source: branches/1.3/gui/scripts/vtkimageviewer.tcl @ 4759

Last change on this file since 4759 was 4759, checked in by ldelgass, 6 years ago

merge r4756:4758 from trunk

File size: 76.9 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkimageviewer - Vtk image viewer
4#
5#  It connects to the Vtk server running on a rendering farm,
6#  transmits data, and displays the results.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2014  HUBzero Foundation, LLC
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16#package require Img
17
18option add *VtkImageViewer.width 4i widgetDefault
19option add *VtkImageViewer*cursor crosshair widgetDefault
20option add *VtkImageViewer.height 4i widgetDefault
21option add *VtkImageViewer.foreground black widgetDefault
22option add *VtkImageViewer.controlBackground gray widgetDefault
23option add *VtkImageViewer.controlDarkBackground #999999 widgetDefault
24option add *VtkImageViewer.plotBackground black widgetDefault
25option add *VtkImageViewer.plotForeground white widgetDefault
26option add *VtkImageViewer.font \
27    -*-helvetica-medium-r-normal-*-12-* widgetDefault
28
29# must use this name -- plugs into Rappture::resources::load
30proc VtkImageViewer_init_resources {} {
31    Rappture::resources::register \
32        vtkvis_server Rappture::VtkImageViewer::SetServerList
33}
34
35itcl::class Rappture::VtkImageViewer {
36    inherit Rappture::VisViewer
37
38    itk_option define -plotforeground plotForeground Foreground ""
39    itk_option define -plotbackground plotBackground Background ""
40    itk_option define -mode mode Mode "vtkimage"
41
42    constructor { hostlist args } {
43        Rappture::VisViewer::constructor $hostlist
44    } {
45        # defined below
46    }
47    destructor {
48        # defined below
49    }
50    public proc SetServerList { namelist } {
51        Rappture::VisViewer::SetServerList "vtkvis" $namelist
52    }
53    public method add {dataobj {settings ""}}
54    public method camera {option args}
55    public method delete {args}
56    public method disconnect {}
57    public method download {option args}
58    public method get {args}
59    public method isconnected {}
60    public method parameters {title args} {
61        # do nothing
62    }
63    public method scale {args}
64
65    protected method Connect {}
66    protected method CurrentDatasets {args}
67    protected method Disconnect {}
68    protected method DoResize {}
69    protected method DoRotate {}
70    protected method AdjustSetting {what {value ""}}
71    protected method AdjustMode {}
72    protected method InitSettings { args  }
73    protected method Pan {option x y}
74    protected method Pick {x y}
75    protected method Rebuild {}
76    protected method ReceiveDataset { args }
77    protected method ReceiveImage { args }
78    protected method ReceiveLegend { colormap title min max size }
79    protected method Rotate {option x y}
80    protected method Zoom {option}
81
82    # The following methods are only used by this class.
83    private method BuildAxisTab {}
84    private method BuildCameraTab {}
85    private method BuildColormap { name }
86    private method BuildImageTab {}
87    private method BuildDownloadPopup { widget command }
88    private method Combo { option }
89    private method DrawLegend {}
90    private method EnterLegend { x y }
91    private method EventuallyRequestLegend {}
92    private method EventuallyResize { w h }
93    private method EventuallyRotate { q }
94    private method GetImage { args }
95    private method GetVtkData { args }
96    private method IsValidObject { dataobj }
97    private method LeaveLegend {}
98    private method MotionLegend { x y }
99    private method PanCamera {}
100    private method RequestLegend {}
101    private method SetCurrentColormap { color }
102    private method SetLegendTip { x y }
103    private method SetObjectStyle { dataobj comp }
104    private method SetOrientation { side }
105
106    private variable _arcball ""
107    private variable _dlist ""     ;    # list of data objects
108    private variable _obj2datasets
109    private variable _obj2ovride   ;    # maps dataobj => style override
110    private variable _datasets     ;    # contains all the dataobj-component
111                                   ;    # datasets in the server
112    private variable _colormaps    ;    # contains all the colormaps
113                                   ;    # in the server.
114
115    # The name of the current colormap used.  The colormap is global to all
116    # images displayed.
117    private variable _currentColormap ""
118    private variable _currentNumIsolines -1
119
120    private variable _maxScale 100;     # This is the # of times the x-axis
121                                        # and y-axis ranges can differ before
122                                        # automatically turning on
123                                        # -stretchtofit
124
125    private variable _click        ;    # info used for rotate operations
126    private variable _limits       ;    # Holds overall limits for all dataobjs
127                                        # using the viewer.
128    private variable _view         ;    # view params for 3D view
129    private variable _settings
130    private variable _changed
131    private variable _initialStyle "";  # First found style in dataobjects.
132    private variable _reset 1;          # Indicates if camera needs to be reset
133                                        # to starting position.
134    private variable _beforeConnect 1;  # Indicates if camera needs to be reset
135                                        # to starting position.
136
137    private variable _first ""     ;    # This is the topmost dataset.
138    private variable _start 0
139    private variable _isolines
140    private variable _contourList ""
141
142    common _downloadPopup;              # download options from popup
143    private common _hardcopy
144    private variable _width 0
145    private variable _height 0
146    private variable _legendWidth 0
147    private variable _legendHeight 0
148    private variable _resizePending 0
149    private variable _rotatePending 0
150    private variable _legendPending 0
151    private variable _fieldNames {}
152    private variable _fields
153    private variable _curFldName ""
154    private variable _curFldLabel ""
155    private variable _colorMode "scalar";#  Mode of colormap (vmag or scalar)
156}
157
158itk::usual VtkImageViewer {
159    keep -background -foreground -cursor -font
160    keep -plotbackground -plotforeground -mode
161}
162
163# ----------------------------------------------------------------------
164# CONSTRUCTOR
165# ----------------------------------------------------------------------
166itcl::body Rappture::VtkImageViewer::constructor {hostlist args} {
167    set _serverType "vtkvis"
168
169    EnableWaitDialog 900
170    # Rebuild event
171    $_dispatcher register !rebuild
172    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
173
174    # Resize event
175    $_dispatcher register !resize
176    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
177
178    # Rotate event
179    $_dispatcher register !rotate
180    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
181
182    # Legend event
183    $_dispatcher register !legend
184    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
185
186    #
187    # Populate parser with commands handle incoming requests
188    #
189    $_parser alias image [itcl::code $this ReceiveImage]
190    $_parser alias dataset [itcl::code $this ReceiveDataset]
191    $_parser alias legend [itcl::code $this ReceiveLegend]
192
193    # Create image for legend colorbar.
194    set _image(legend) [image create photo]
195
196    # Initialize the view to some default parameters.
197    array set _view {
198        qw      0.36
199        qx      0.25
200        qy      0.50
201        qz      0.70
202        zoom    1.0
203        xpan    0
204        ypan    0
205        ortho   0
206    }
207    set _arcball [blt::arcball create 100 100]
208    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
209    $_arcball quaternion $q
210
211    array set _settings {
212        axisFlymode             "static"
213        axisLabels              1
214        axisMinorTicks          1
215        axisVisible             1
216        axisXGrid               0
217        axisYGrid               0
218        axisZGrid               0
219        backingColor            white
220        backingVisible          1
221        colormapDiscrete        0
222        field                   "Default"
223        legendVisible           0
224        level                   127.5
225        numColors               256
226        opacity                 100
227        outline                 0
228        saveOpacity             100
229        stretchToFit            0
230        view3D                  0
231        window                  255.0
232    }
233    array set _changed {
234        opacity                 0
235        colormap                0
236    }
237    itk_component add view {
238        canvas $itk_component(plotarea).view \
239            -highlightthickness 0 -borderwidth 0
240    } {
241        usual
242        ignore -highlightthickness -borderwidth -background
243    }
244
245    itk_component add fieldmenu {
246        menu $itk_component(plotarea).menu \
247            -relief flat \
248            -tearoff no
249    } {
250        usual
251        ignore -background -foreground -relief -tearoff
252    }
253    set c $itk_component(view)
254    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
255    bind $c <4> [itcl::code $this Zoom in 0.25]
256    bind $c <5> [itcl::code $this Zoom out 0.25]
257    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
258    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
259    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
260    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
261    bind $c <Enter> "focus %W"
262    bind $c <Control-F1> [itcl::code $this ToggleConsole]
263
264    # Fix the scrollregion in case we go off screen
265    $c configure -scrollregion [$c bbox all]
266
267    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
268    set _map(cwidth) -1
269    set _map(cheight) -1
270    set _map(zoom) 1.0
271    set _map(original) ""
272
273    set f [$itk_component(main) component controls]
274    itk_component add reset {
275        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
276            -highlightthickness 0 \
277            -image [Rappture::icon reset-view] \
278            -command [itcl::code $this Zoom reset]
279    } {
280        usual
281        ignore -highlightthickness
282    }
283    pack $itk_component(reset) -side top -padx 2 -pady { 2 0 }
284    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
285
286    itk_component add zoomin {
287        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
288            -highlightthickness 0 \
289            -image [Rappture::icon zoom-in] \
290            -command [itcl::code $this Zoom in]
291    } {
292        usual
293        ignore -highlightthickness
294    }
295    pack $itk_component(zoomin) -side top -padx 2 -pady { 2 0 }
296    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
297
298    itk_component add zoomout {
299        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
300            -highlightthickness 0 \
301            -image [Rappture::icon zoom-out] \
302            -command [itcl::code $this Zoom out]
303    } {
304        usual
305        ignore -highlightthickness
306    }
307    pack $itk_component(zoomout) -side top -padx 2 -pady { 2 0 }
308    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
309
310    itk_component add mode {
311        Rappture::PushButton $f.mode \
312            -onimage [Rappture::icon surface] \
313            -offimage [Rappture::icon surface] \
314            -variable [itcl::scope _settings(view3D)] \
315            -command [itcl::code $this AdjustSetting view3D] \
316    }
317    Rappture::Tooltip::for $itk_component(mode) \
318        "Toggle the surface/contour on/off"
319    pack $itk_component(mode) -padx 2 -pady { 2 0 }
320
321    itk_component add stretchtofit {
322        Rappture::PushButton $f.stretchtofit \
323            -onimage [Rappture::icon stretchtofit] \
324            -offimage [Rappture::icon stretchtofit] \
325            -variable [itcl::scope _settings(stretchToFit)] \
326            -command [itcl::code $this AdjustSetting stretchToFit] \
327    }
328    Rappture::Tooltip::for $itk_component(stretchtofit) \
329        "Stretch plot to fit window on/off"
330    pack $itk_component(stretchtofit) -padx 2 -pady 2
331
332    if { [catch {
333        BuildImageTab
334        BuildAxisTab
335        BuildCameraTab
336    } errs] != 0 } {
337        global errorInfo
338        puts stderr "errs=$errs errorInfo=$errorInfo"
339    }
340
341    # Hack around the Tk panewindow.  The problem is that the requested
342    # size of the 3d view isn't set until an image is retrieved from
343    # the server.  So the panewindow uses the tiny size.
344    set w 10000
345    pack forget $itk_component(view)
346    blt::table $itk_component(plotarea) \
347        0,0 $itk_component(view) -fill both -reqwidth $w
348    blt::table configure $itk_component(plotarea) c1 -resize none
349
350    # Bindings for panning via mouse
351    bind $itk_component(view) <ButtonPress-2> \
352        [itcl::code $this Pan click %x %y]
353    bind $itk_component(view) <B2-Motion> \
354        [itcl::code $this Pan drag %x %y]
355    bind $itk_component(view) <ButtonRelease-2> \
356        [itcl::code $this Pan release %x %y]
357
358    #bind $itk_component(view) <ButtonRelease-3> \
359    #    [itcl::code $this Pick %x %y]
360
361    # Bindings for panning via keyboard
362    bind $itk_component(view) <KeyPress-Left> \
363        [itcl::code $this Pan set -10 0]
364    bind $itk_component(view) <KeyPress-Right> \
365        [itcl::code $this Pan set 10 0]
366    bind $itk_component(view) <KeyPress-Up> \
367        [itcl::code $this Pan set 0 -10]
368    bind $itk_component(view) <KeyPress-Down> \
369        [itcl::code $this Pan set 0 10]
370    bind $itk_component(view) <Shift-KeyPress-Left> \
371        [itcl::code $this Pan set -2 0]
372    bind $itk_component(view) <Shift-KeyPress-Right> \
373        [itcl::code $this Pan set 2 0]
374    bind $itk_component(view) <Shift-KeyPress-Up> \
375        [itcl::code $this Pan set 0 -2]
376    bind $itk_component(view) <Shift-KeyPress-Down> \
377        [itcl::code $this Pan set 0 2]
378
379    # Bindings for zoom via keyboard
380    bind $itk_component(view) <KeyPress-Prior> \
381        [itcl::code $this Zoom out]
382    bind $itk_component(view) <KeyPress-Next> \
383        [itcl::code $this Zoom in]
384
385    bind $itk_component(view) <Enter> "focus $itk_component(view)"
386
387    if {[string equal "x11" [tk windowingsystem]]} {
388        # Bindings for zoom via mouse
389        bind $itk_component(view) <4> [itcl::code $this Zoom out]
390        bind $itk_component(view) <5> [itcl::code $this Zoom in]
391    }
392
393    set _image(download) [image create photo]
394    eval itk_initialize $args
395    Connect
396    set _beforeConnect 0
397}
398
399# ----------------------------------------------------------------------
400# DESTRUCTOR
401# ----------------------------------------------------------------------
402itcl::body Rappture::VtkImageViewer::destructor {} {
403    Disconnect
404    image delete $_image(plot)
405    image delete $_image(download)
406    catch { blt::arcball destroy $_arcball }
407}
408
409itcl::body Rappture::VtkImageViewer::DoResize {} {
410    if { $_width < 2 } {
411        set _width 500
412    }
413    if { $_height < 2 } {
414        set _height 500
415    }
416    set _start [clock clicks -milliseconds]
417    SendCmd "screen size [expr $_width - 20] $_height"
418
419    set font "Arial 8"
420    set lh [font metrics $font -linespace]
421    set h [expr {$_height - 2 * ($lh + 2)}]
422    if { $h != $_legendHeight } {
423        EventuallyRequestLegend
424    } else {
425        DrawLegend
426    }
427    set _resizePending 0
428}
429
430itcl::body Rappture::VtkImageViewer::DoRotate {} {
431    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
432    SendCmd "camera orient $q"
433    set _rotatePending 0
434}
435
436itcl::body Rappture::VtkImageViewer::EventuallyRequestLegend {} {
437    if { !$_legendPending } {
438        set _legendPending 1
439        $_dispatcher event -idle !legend
440    }
441}
442
443itcl::body Rappture::VtkImageViewer::EventuallyResize { w h } {
444    set _width $w
445    set _height $h
446    $_arcball resize $w $h
447    if { !$_resizePending } {
448        set _resizePending 1
449        $_dispatcher event -after 250 !resize
450    }
451}
452
453set rotate_delay 100
454
455itcl::body Rappture::VtkImageViewer::EventuallyRotate { q } {
456    foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
457    if { !$_rotatePending } {
458        set _rotatePending 1
459        global rotate_delay
460        $_dispatcher event -after $rotate_delay !rotate
461    }
462}
463
464# ----------------------------------------------------------------------
465# USAGE: add <dataobj> ?<settings>?
466#
467# Clients use this to add a data object to the plot.  The optional
468# <settings> are used to configure the plot.  Allowed settings are
469# -color, -brightness, -width, -linestyle, and -raise.
470# ----------------------------------------------------------------------
471itcl::body Rappture::VtkImageViewer::add {dataobj {settings ""}} {
472    if { ![$dataobj isvalid] } {
473        return;                         # Object doesn't contain valid data.
474    }
475    array set params {
476        -color auto
477        -width 1
478        -linestyle solid
479        -brightness 0
480        -raise 0
481        -description ""
482        -param ""
483        -type ""
484    }
485    array set params $settings
486    set params(-description) ""
487    set params(-param) ""
488    array set params $settings
489
490    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
491        # can't handle -autocolors yet
492        set params(-color) white
493    }
494    set pos [lsearch -exact $_dlist $dataobj]
495    if {$pos < 0} {
496        lappend _dlist $dataobj
497    }
498    set _obj2ovride($dataobj-color) $params(-color)
499    set _obj2ovride($dataobj-width) $params(-width)
500    set _obj2ovride($dataobj-raise) $params(-raise)
501    $_dispatcher event -idle !rebuild
502}
503
504
505# ----------------------------------------------------------------------
506# USAGE: delete ?<dataobj1> <dataobj2> ...?
507#
508#       Clients use this to delete a dataobj from the plot.  If no dataobjs
509#       are specified, then all dataobjs are deleted.  No data objects are
510#       deleted.  They are only removed from the display list.
511#
512# ----------------------------------------------------------------------
513itcl::body Rappture::VtkImageViewer::delete {args} {
514    if { [llength $args] == 0} {
515        set args $_dlist
516    }
517    # Delete all specified dataobjs
518    set changed 0
519    foreach dataobj $args {
520        set pos [lsearch -exact $_dlist $dataobj]
521        if { $pos < 0 } {
522            continue;                   # Don't know anything about it.
523        }
524        # Remove it from the dataobj list.
525        set _dlist [lreplace $_dlist $pos $pos]
526        array unset _obj2ovride $dataobj-*
527        array unset _settings $dataobj-*
528        set changed 1
529    }
530    # If anything changed, then rebuild the plot
531    if { $changed } {
532        $_dispatcher event -idle !rebuild
533    }
534}
535
536# ----------------------------------------------------------------------
537# USAGE: get ?-objects?
538# USAGE: get ?-visible?
539# USAGE: get ?-image view?
540#
541# Clients use this to query the list of objects being plotted, in
542# order from bottom to top of this result.  The optional "-image"
543# flag can also request the internal images being shown.
544# ----------------------------------------------------------------------
545itcl::body Rappture::VtkImageViewer::get {args} {
546    if {[llength $args] == 0} {
547        set args "-objects"
548    }
549    set op [lindex $args 0]
550    switch -- $op {
551        "-objects" {
552            # put the dataobj list in order according to -raise options
553            set dlist {}
554            foreach dataobj $_dlist {
555                if { ![IsValidObject $dataobj] } {
556                    continue
557                }
558                if {[info exists _obj2ovride($dataobj-raise)] &&
559                    $_obj2ovride($dataobj-raise)} {
560                    set dlist [linsert $dlist 0 $dataobj]
561                } else {
562                    lappend dlist $dataobj
563                }
564            }
565            return $dlist
566        }
567        "-visible" {
568            set dlist {}
569            foreach dataobj $_dlist {
570                if { ![IsValidObject $dataobj] } {
571                    continue
572                }
573                if { ![info exists _obj2ovride($dataobj-raise)] } {
574                    # No setting indicates that the object isn't visible.
575                    continue
576                }
577                # Otherwise use the -raise parameter to put the object to
578                # the front of the list.
579                if { $_obj2ovride($dataobj-raise) } {
580                    set dlist [linsert $dlist 0 $dataobj]
581                } else {
582                    lappend dlist $dataobj
583                }
584            }
585            return $dlist
586        }           
587        -image {
588            if {[llength $args] != 2} {
589                error "wrong # args: should be \"get -image view\""
590            }
591            switch -- [lindex $args end] {
592                view {
593                    return $_image(plot)
594                }
595                default {
596                    error "bad image name \"[lindex $args end]\": should be view"
597                }
598            }
599        }
600        default {
601            error "bad option \"$op\": should be -objects or -image"
602        }
603    }
604}
605
606#
607# scale  --
608#
609#       This gets called either incrementally as new simulations are
610#       added or all at once as a sequence of images.
611#       This  accounts for all objects--even those not showing on the
612#       screen.  Because of this, the limits are appropriate for all
613#       objects as the user scans through data in the ResultSet viewer.
614#
615itcl::body Rappture::VtkImageViewer::scale {args} {
616    foreach dataobj $args {
617        if { ![$dataobj isvalid] } {
618            continue;                   # Object doesn't contain valid data.
619        }
620        foreach axis { x y } {
621            set lim [$dataobj limits $axis]
622            if { ![info exists _limits($axis)] } {
623                set _limits($axis) $lim
624                continue
625            }
626            foreach {min max} $lim break
627            foreach {amin amax} $_limits($axis) break
628            if { $amin > $min } {
629                set amin $min
630            }
631            if { $amax < $max } {
632                set amax $max
633            }
634            set _limits($axis) [list $amin $amax]
635            set units [$dataobj hints ${axis}units]
636            set found($units) 1
637        }
638        foreach { fname lim } [$dataobj fieldlimits] {
639            if { ![info exists _limits($fname)] } {
640                set _limits($fname) $lim
641                continue
642            }
643            foreach {min max} $lim break
644            foreach {fmin fmax} $_limits($fname) break
645            if { $fmin > $min } {
646                set fmin $min
647            }
648            if { $fmax < $max } {
649                set fmax $max
650            }
651            set _limits($fname) [list $fmin $fmax]
652        }
653    }
654    if { [array size found] > 1 } {
655        set _settings(stretchToFit) 1
656    } else {
657        # Check if the range of the x and y axes requires that we stretch
658        # the contour to fit the plotting area.  This can happen when the
659        # x and y scales differ greatly (> 100x)
660        foreach {xmin xmax} $_limits(x) break
661        foreach {ymin ymax} $_limits(y) break
662        if { (($xmax - $xmin) > (($ymax -$ymin) * $_maxScale)) ||
663             ((($xmax - $xmin) * $_maxScale) < ($ymax -$ymin)) } {
664            set _settings(stretchToFit) 1
665        }
666    }
667}
668
669# ----------------------------------------------------------------------
670# USAGE: download coming
671# USAGE: download controls <downloadCommand>
672# USAGE: download now
673#
674# Clients use this method to create a downloadable representation
675# of the plot.  Returns a list of the form {ext string}, where
676# "ext" is the file extension (indicating the type of data) and
677# "string" is the data itself.
678# ----------------------------------------------------------------------
679itcl::body Rappture::VtkImageViewer::download {option args} {
680    switch $option {
681        coming {
682            if {[catch {
683                blt::winop snap $itk_component(plotarea) $_image(download)
684            }]} {
685                $_image(download) configure -width 1 -height 1
686                $_image(download) put #000000
687            }
688        }
689        controls {
690            set popup .vtkviewerdownload
691            if { ![winfo exists .vtkviewerdownload] } {
692                set inner [BuildDownloadPopup $popup [lindex $args 0]]
693            } else {
694                set inner [$popup component inner]
695            }
696            set _downloadPopup(image_controls) $inner.image_frame
697            set num [llength [get]]
698            set num [expr {($num == 1) ? "1 result" : "$num results"}]
699            set word [Rappture::filexfer::label downloadWord]
700            $inner.summary configure -text "$word $num in the following format:"
701            update idletasks            ;# Fix initial sizes
702            return $popup
703        }
704        now {
705            set popup .vtkviewerdownload
706            if {[winfo exists .vtkviewerdownload]} {
707                $popup deactivate
708            }
709            switch -- $_downloadPopup(format) {
710                "image" {
711                    return [$this GetImage [lindex $args 0]]
712                }
713                "vtk" {
714                    return [$this GetVtkData [lindex $args 0]]
715                }
716            }
717            return ""
718        }
719        default {
720            error "bad option \"$option\": should be coming, controls, now"
721        }
722    }
723}
724
725# ----------------------------------------------------------------------
726# USAGE: Connect ?<host:port>,<host:port>...?
727#
728# Clients use this method to establish a connection to a new
729# server, or to reestablish a connection to the previous server.
730# Any existing connection is automatically closed.
731# ----------------------------------------------------------------------
732itcl::body Rappture::VtkImageViewer::Connect {} {
733    global readyForNextFrame
734    set readyForNextFrame 1
735    set _reset 1
736    set _hosts [GetServerList "vtkvis"]
737    if { "" == $_hosts } {
738        return 0
739    }
740    set result [VisViewer::Connect $_hosts]
741    if { $result } {
742        if { $_reportClientInfo }  {
743            # Tell the server the viewer, hub, user and session.
744            # Do this immediately on connect before buffering any commands
745            global env
746
747            set info {}
748            set user "???"
749            if { [info exists env(USER)] } {
750                set user $env(USER)
751            }
752            set session "???"
753            if { [info exists env(SESSION)] } {
754                set session $env(SESSION)
755            }
756            lappend info "version" "$Rappture::version"
757            lappend info "build" "$Rappture::build"
758            lappend info "svnurl" "$Rappture::svnurl"
759            lappend info "installdir" "$Rappture::installdir"
760            lappend info "hub" [exec hostname]
761            lappend info "client" "vtkimageviewer"
762            lappend info "user" $user
763            lappend info "session" $session
764            SendCmd "clientinfo [list $info]"
765        }
766        set w [winfo width $itk_component(view)]
767        set h [winfo height $itk_component(view)]
768        EventuallyResize $w $h
769    }
770    return $result
771}
772
773#
774# isconnected --
775#
776#       Indicates if we are currently connected to the visualization server.
777#
778itcl::body Rappture::VtkImageViewer::isconnected {} {
779    return [VisViewer::IsConnected]
780}
781
782#
783# disconnect --
784#
785itcl::body Rappture::VtkImageViewer::disconnect {} {
786    Disconnect
787    set _reset 1
788}
789
790#
791# Disconnect --
792#
793#       Clients use this method to disconnect from the current rendering
794#       server.
795#
796itcl::body Rappture::VtkImageViewer::Disconnect {} {
797    VisViewer::Disconnect
798
799    $_dispatcher cancel !rebuild
800    $_dispatcher cancel !resize
801    $_dispatcher cancel !rotate
802    $_dispatcher cancel !legend
803    # disconnected -- no more data sitting on server
804    array unset _datasets
805    array unset _data
806    array unset _colormaps
807    array unset _obj2datasets
808    global readyForNextFrame
809    set readyForNextFrame 1
810}
811
812# ----------------------------------------------------------------------
813# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
814#
815# Invoked automatically whenever the "image" command comes in from
816# the rendering server.  Indicates that binary image data with the
817# specified <size> will follow.
818# ----------------------------------------------------------------------
819itcl::body Rappture::VtkImageViewer::ReceiveImage { args } {
820    global readyForNextFrame
821    set readyForNextFrame 1
822    array set info {
823        -token "???"
824        -bytes 0
825        -type image
826    }
827    array set info $args
828    set bytes [ReceiveBytes $info(-bytes)]
829    if { $info(-type) == "image" } {
830        if 0 {
831            set f [open "last.ppm" "w"]
832            puts $f $bytes
833            close $f
834        }
835        $_image(plot) configure -data $bytes
836        set time [clock seconds]
837        set date [clock format $time]
838        #puts stderr "$date: received image [image width $_image(plot)]x[image height $_image(plot)] image>"       
839        if { $_start > 0 } {
840            set finish [clock clicks -milliseconds]
841            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
842            set _start 0
843        }
844    } elseif { $info(type) == "print" } {
845        set tag $this-print-$info(-token)
846        set _hardcopy($tag) $bytes
847    }
848}
849
850#
851# ReceiveDataset --
852#
853itcl::body Rappture::VtkImageViewer::ReceiveDataset { args } {
854    if { ![isconnected] } {
855        return
856    }
857    set option [lindex $args 0]
858    switch -- $option {
859        "scalar" {
860            set option [lindex $args 1]
861            switch -- $option {
862                "world" {
863                    foreach { x y z value tag } [lrange $args 2 end] break
864                }
865                "pixel" {
866                    foreach { x y value tag } [lrange $args 2 end] break
867                }
868            }
869        }
870        "vector" {
871            set option [lindex $args 1]
872            switch -- $option {
873                "world" {
874                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
875                }
876                "pixel" {
877                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
878                }
879            }
880        }
881        "names" {
882            foreach { name } [lindex $args 1] {
883                #puts stderr "Dataset: $name"
884            }
885        }
886        default {
887            error "unknown dataset option \"$option\" from server"
888        }
889    }
890}
891
892# ----------------------------------------------------------------------
893# USAGE: Rebuild
894#
895# Called automatically whenever something changes that affects the
896# data in the widget.  Clears any existing data and rebuilds the
897# widget to display new data.
898# ----------------------------------------------------------------------
899itcl::body Rappture::VtkImageViewer::Rebuild {} {
900    set w [winfo width $itk_component(view)]
901    set h [winfo height $itk_component(view)]
902    if { $w < 2 || $h < 2 } {
903        $_dispatcher event -idle !rebuild
904        return
905    }
906
907    # Turn on buffering of commands to the server.  We don't want to
908    # be preempted by a server disconnect/reconnect (which automatically
909    # generates a new call to Rebuild).   
910    StartBufferingCommands
911
912    if { $_width != $w || $_height != $h || $_reset } {
913        set _width $w
914        set _height $h
915        $_arcball resize $w $h
916        DoResize
917        if { $_settings(stretchToFit) } {
918            AdjustSetting stretchToFit
919        }
920    }
921    if { $_reset } {
922        #
923        # Reset the camera and other view parameters
924        #
925        InitSettings view3D background
926
927        SendCmd "axis lrot z 90"
928        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
929        $_arcball quaternion $q
930        if {$_settings(view3D) } {
931            if { $_view(ortho)} {
932                SendCmd "camera mode ortho"
933            } else {
934                SendCmd "camera mode persp"
935            }
936            DoRotate
937            SendCmd "camera reset"
938        }
939        PanCamera
940        StopBufferingCommands
941        SendCmd "imgflush"
942        StartBufferingCommands
943    }
944
945    set _first ""
946    # Start off with no datasets are visible.
947    SendCmd "dataset visible 0"
948    foreach dataobj [get -objects] {
949        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
950            set _first $dataobj
951        }
952        set _obj2datasets($dataobj) ""
953        foreach comp [$dataobj components] {
954            set tag $dataobj-$comp
955            if { ![info exists _datasets($tag)] } {
956                set bytes [$dataobj vtkdata $comp]
957                if 0 {
958                    set f [open /tmp/vtkimage.vtk "w"]
959                    puts $f $bytes
960                    close $f
961                }
962                set length [string length $bytes]
963                if { $_reportClientInfo }  {
964                    set info {}
965                    lappend info "tool_id"       [$dataobj hints toolid]
966                    lappend info "tool_name"     [$dataobj hints toolname]
967                    lappend info "tool_title"    [$dataobj hints tooltitle]
968                    lappend info "tool_command"  [$dataobj hints toolcommand]
969                    lappend info "tool_revision" [$dataobj hints toolrevision]
970                    lappend info "dataset_label" [$dataobj hints label]
971                    lappend info "dataset_size"  $length
972                    lappend info "dataset_tag"   $tag
973                    SendCmd [list "clientinfo" $info]
974                }
975                SendCmd "dataset add $tag data follows $length"
976                append _outbuf $bytes
977                set _datasets($tag) 1
978                SetObjectStyle $dataobj $comp
979            }
980            lappend _obj2datasets($dataobj) $tag
981            if { [info exists _obj2ovride($dataobj-raise)] } {
982                # Setting dataset visible enables outline
983                # and image
984                SendCmd "dataset visible 1 $tag"
985            }
986        }
987    }
988    if { $_first != ""  } {
989        $itk_component(field) choices delete 0 end
990        $itk_component(fieldmenu) delete 0 end
991        array unset _fields
992        set _curFldName ""
993        foreach cname [$_first components] {
994            foreach fname [$_first fieldnames $cname] {
995                if { [info exists _fields($fname)] } {
996                    continue
997                }
998                foreach { label units components } \
999                    [$_first fieldinfo $fname] break
1000                $itk_component(field) choices insert end "$fname" "$label"
1001                $itk_component(fieldmenu) add radiobutton -label "$label" \
1002                    -value $label -variable [itcl::scope _curFldLabel] \
1003                    -selectcolor red \
1004                    -activebackground $itk_option(-plotbackground) \
1005                    -activeforeground $itk_option(-plotforeground) \
1006                    -font "Arial 8" \
1007                    -command [itcl::code $this Combo invoke]
1008                set _fields($fname) [list $label $units $components]
1009                if { $_curFldName == "" } {
1010                    set _curFldName $fname
1011                    set _curFldLabel $label
1012                }
1013            }
1014        }
1015        $itk_component(field) value $_curFldLabel
1016    }
1017    InitSettings stretchToFit outline
1018
1019    if { $_reset } {
1020        SendCmd "axis tickpos outside"
1021        #SendCmd "axis lformat all %g"
1022       
1023        foreach axis { x y z } {
1024            set label [$_first hints ${axis}label]
1025            if { $label == "" } {
1026                set label [string toupper $axis]
1027            }
1028            # May be a space in the axis label.
1029            SendCmd [list axis name $axis $label]
1030
1031            if {$axis == "z" && [$_first hints ${axis}units] == ""} {
1032                if {$_curFldName != ""} {
1033                    set units [lindex $_fields($_curFldName) 1]
1034                }
1035            } else {
1036                set units [$_first hints ${axis}units]
1037            }
1038            if { $units != "" } {
1039                # May be a space in the axis units.
1040                SendCmd [list axis units $axis $units]
1041            }
1042        }
1043        #
1044        # Reset the camera and other view parameters
1045        #
1046        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1047        $_arcball quaternion $q
1048        if {$_settings(view3D) } {
1049            if { $_view(ortho)} {
1050                SendCmd "camera mode ortho"
1051            } else {
1052                SendCmd "camera mode persp"
1053            }
1054            DoRotate
1055            SendCmd "camera reset"
1056        }
1057        PanCamera
1058        InitSettings axisXGrid axisYGrid axisZGrid \
1059            axisVisible axisLabels field view3D
1060        if { [array size _fields] < 2 } {
1061            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1062        }
1063        RequestLegend
1064        set _reset 0
1065    }
1066    global readyForNextFrame
1067    set readyForNextFrame 0;            # Don't advance to the next frame
1068
1069    # Actually write the commands to the server socket.  If it fails, we don't
1070    # care.  We're finished here.
1071    blt::busy hold $itk_component(hull)
1072    StopBufferingCommands
1073    blt::busy release $itk_component(hull)
1074}
1075
1076# ----------------------------------------------------------------------
1077# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1078#
1079# Returns a list of server IDs for the current datasets being displayed.  This
1080# is normally a single ID, but it might be a list of IDs if the current data
1081# object has multiple components.
1082# ----------------------------------------------------------------------
1083itcl::body Rappture::VtkImageViewer::CurrentDatasets {args} {
1084    set flag [lindex $args 0]
1085    switch -- $flag {
1086        "-all" {
1087            if { [llength $args] > 1 } {
1088                error "CurrentDatasets: can't specify dataobj after \"-all\""
1089            }
1090            set dlist [get -objects]
1091        }
1092        "-visible" {
1093            if { [llength $args] > 1 } {
1094                set dlist {}
1095                set args [lrange $args 1 end]
1096                foreach dataobj $args {
1097                    if { [info exists _obj2ovride($dataobj-raise)] } {
1098                        lappend dlist $dataobj
1099                    }
1100                }
1101            } else {
1102                set dlist [get -visible]
1103            }
1104        }           
1105        default {
1106            set dlist $args
1107        }
1108    }
1109    set rlist ""
1110    foreach dataobj $dlist {
1111        foreach comp [$dataobj components] {
1112            set tag $dataobj-$comp
1113            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1114                lappend rlist $tag
1115            }
1116        }
1117    }
1118    return $rlist
1119}
1120
1121# ----------------------------------------------------------------------
1122# USAGE: Zoom in
1123# USAGE: Zoom out
1124# USAGE: Zoom reset
1125#
1126# Called automatically when the user clicks on one of the zoom
1127# controls for this widget.  Changes the zoom for the current view.
1128# ----------------------------------------------------------------------
1129itcl::body Rappture::VtkImageViewer::Zoom {option} {
1130    switch -- $option {
1131        "in" {
1132            set _view(zoom) [expr {$_view(zoom)*1.25}]
1133            SendCmd "camera zoom $_view(zoom)"
1134        }
1135        "out" {
1136            set _view(zoom) [expr {$_view(zoom)*0.8}]
1137            SendCmd "camera zoom $_view(zoom)"
1138        }
1139        "reset" {
1140            array set _view {
1141                qw      0.36
1142                qx      0.25
1143                qy      0.50
1144                qz      0.70
1145                zoom    1.0
1146                xpan    0
1147                ypan    0
1148            }
1149            if { $_first != "" } {
1150                set location [$_first hints camera]
1151                if { $location != "" } {
1152                    array set _view $location
1153                }
1154            }
1155            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1156            $_arcball quaternion $q
1157            if {$_settings(view3D) } {
1158                DoRotate
1159            }
1160            SendCmd "camera reset"
1161        }
1162    }
1163}
1164
1165itcl::body Rappture::VtkImageViewer::PanCamera {} {
1166    set x $_view(xpan)
1167    set y $_view(ypan)
1168    SendCmd "camera pan $x $y"
1169}
1170
1171
1172# ----------------------------------------------------------------------
1173# USAGE: Rotate click <x> <y>
1174# USAGE: Rotate drag <x> <y>
1175# USAGE: Rotate release <x> <y>
1176#
1177# Called automatically when the user clicks/drags/releases in the
1178# plot area.  Moves the plot according to the user's actions.
1179# ----------------------------------------------------------------------
1180itcl::body Rappture::VtkImageViewer::Rotate {option x y} {
1181    switch -- $option {
1182        "click" {
1183            $itk_component(view) configure -cursor fleur
1184            set _click(x) $x
1185            set _click(y) $y
1186        }
1187        "drag" {
1188            if {[array size _click] == 0} {
1189                Rotate click $x $y
1190            } else {
1191                set w [winfo width $itk_component(view)]
1192                set h [winfo height $itk_component(view)]
1193                if {$w <= 0 || $h <= 0} {
1194                    return
1195                }
1196
1197                if {[catch {
1198                    # this fails sometimes for no apparent reason
1199                    set dx [expr {double($x-$_click(x))/$w}]
1200                    set dy [expr {double($y-$_click(y))/$h}]
1201                }]} {
1202                    return
1203                }
1204                if { $dx == 0 && $dy == 0 } {
1205                    return
1206                }
1207                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1208                EventuallyRotate $q
1209                set _click(x) $x
1210                set _click(y) $y
1211            }
1212        }
1213        "release" {
1214            Rotate drag $x $y
1215            $itk_component(view) configure -cursor ""
1216            catch {unset _click}
1217        }
1218        default {
1219            error "bad option \"$option\": should be click, drag, release"
1220        }
1221    }
1222}
1223
1224itcl::body Rappture::VtkImageViewer::Pick {x y} {
1225    foreach tag [CurrentDatasets -visible] {
1226        SendCmd "dataset getscalar pixel $x $y $tag"
1227    }
1228}
1229
1230# ----------------------------------------------------------------------
1231# USAGE: $this Pan click x y
1232#        $this Pan drag x y
1233#        $this Pan release x y
1234#
1235# Called automatically when the user clicks on one of the zoom
1236# controls for this widget.  Changes the zoom for the current view.
1237# ----------------------------------------------------------------------
1238itcl::body Rappture::VtkImageViewer::Pan {option x y} {
1239    switch -- $option {
1240        "set" {
1241            set w [winfo width $itk_component(view)]
1242            set h [winfo height $itk_component(view)]
1243            set x [expr $x / double($w)]
1244            set y [expr $y / double($h)]
1245            set _view(xpan) [expr $_view(xpan) + $x]
1246            set _view(ypan) [expr $_view(ypan) + $y]
1247            PanCamera
1248            return
1249        }
1250        "click" {
1251            set _click(x) $x
1252            set _click(y) $y
1253            $itk_component(view) configure -cursor hand1
1254        }
1255        "drag" {
1256            if { ![info exists _click(x)] } {
1257                set _click(x) $x
1258            }
1259            if { ![info exists _click(y)] } {
1260                set _click(y) $y
1261            }
1262            set w [winfo width $itk_component(view)]
1263            set h [winfo height $itk_component(view)]
1264            set dx [expr ($_click(x) - $x)/double($w)]
1265            set dy [expr ($_click(y) - $y)/double($h)]
1266            set _click(x) $x
1267            set _click(y) $y
1268            set _view(xpan) [expr $_view(xpan) - $dx]
1269            set _view(ypan) [expr $_view(ypan) - $dy]
1270            PanCamera
1271        }
1272        "release" {
1273            Pan drag $x $y
1274            $itk_component(view) configure -cursor ""
1275        }
1276        default {
1277            error "unknown option \"$option\": should set, click, drag, or release"
1278        }
1279    }
1280}
1281
1282# ----------------------------------------------------------------------
1283# USAGE: InitSettings <what> ?<value>?
1284#
1285# Used internally to update rendering settings whenever parameters
1286# change in the popup settings panel.  Sends the new settings off
1287# to the back end.
1288# ----------------------------------------------------------------------
1289itcl::body Rappture::VtkImageViewer::InitSettings { args } {
1290    foreach spec $args {
1291        if { [info exists _settings($_first-$spec)] } {
1292            # Reset global setting with dataobj specific setting
1293            set _settings($spec) $_settings($_first-$spec)
1294        }
1295        AdjustSetting $spec
1296    }
1297}
1298
1299#
1300# AdjustSetting --
1301#
1302#       Changes/updates a specific setting in the widget.  There are
1303#       usually user-setable option.  Commands are sent to the render
1304#       server.
1305#
1306itcl::body Rappture::VtkImageViewer::AdjustSetting {what {value ""}} {
1307    if { $_beforeConnect } {
1308        return
1309    }
1310    switch -- $what {
1311        "axisFlymode" {
1312            set mode [$itk_component(axisflymode) value]
1313            set mode [$itk_component(axisflymode) translate $mode]
1314            set _settings($what) $mode
1315            SendCmd "axis flymode $mode"
1316        }
1317        "axisLabels" {
1318            set bool $_settings($what)
1319            SendCmd "axis labels all $bool"
1320        }
1321        "axisMinorTicks" {
1322            set bool $_settings($what)
1323            SendCmd "axis minticks all $bool"
1324        }
1325        "axisVisible" {
1326            set bool $_settings($what)
1327            SendCmd "axis visible all $bool"
1328        }
1329        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1330            set axis [string tolower [string range $what 4 4]]
1331            set bool $_settings($what)
1332            SendCmd "axis grid $axis $bool"
1333        }
1334        "background" {
1335            set bg [$itk_component(background) value]
1336            array set fgcolors {
1337                "black" "white"
1338                "white" "black"
1339                "grey"  "black"
1340            }
1341            set fg $fgcolors($bg)
1342            configure -plotbackground $bg -plotforeground $fg
1343            $itk_component(view) delete "legend"
1344            SendCmd "screen bgcolor [Color2RGB $bg]"
1345            SendCmd "outline color [Color2RGB $fg]"
1346            SendCmd "axis color all [Color2RGB $fg]"
1347            DrawLegend
1348        }
1349        "backingColor" {
1350            set color [$itk_component(backingcolor) value]
1351            if { $color == "none" } {
1352                if { $_settings(backingVisible) } {
1353                    SendCmd "image backing 0"
1354                    set _settings(backingVisible) 0
1355                }
1356            } else {
1357                if { !$_settings(backingVisible) } {
1358                    SendCmd "image backing 1"
1359                    set _settings(backingVisible) 1
1360                }
1361                SendCmd "image color [Color2RGB $color]"
1362            }
1363        }
1364        "backingVisible" {
1365            set bool $_settings($what)
1366            SendCmd "image backing $bool"
1367        }
1368        "colormap" {
1369            set _changed($what) 1
1370            StartBufferingCommands
1371            set color [$itk_component(colormap) value]
1372            set _settings($what) $color
1373            SetCurrentColormap $color
1374            if {$_settings(colormapDiscrete)} {
1375                 SendCmd "colormap res $_settings(numColors) $color"
1376            }
1377            StopBufferingCommands
1378            EventuallyRequestLegend
1379        }
1380        "colormapDiscrete" {
1381            set bool $_settings($what)
1382            StartBufferingCommands
1383            if {$bool} {
1384                SendCmd "colormap res $_settings(numColors)"
1385            } else {
1386                SendCmd "colormap res default"
1387            }
1388            StopBufferingCommands
1389            EventuallyRequestLegend
1390        }
1391        "field" {
1392            set label [$itk_component(field) value]
1393            set fname [$itk_component(field) translate $label]
1394            set _settings($what) $fname
1395            if { [info exists _fields($fname)] } {
1396                foreach { label units components } $_fields($fname) break
1397                if { $components > 1 } {
1398                    set _colorMode vmag
1399                } else {
1400                    set _colorMode scalar
1401                }
1402                set _curFldName $fname
1403                set _curFldLabel $label
1404            } else {
1405                puts stderr "unknown field \"$fname\""
1406                return
1407            }
1408
1409            # Get the new limits because the field changed.
1410            SendCmd "dataset scalar $_curFldName"
1411            #SendCmd "image colormode scalar $_curFldName"
1412            SendCmd "camera reset"
1413            DrawLegend
1414        }
1415        "view3D" {
1416            set bool $_settings($what)
1417            set c $itk_component(view)
1418            StartBufferingCommands
1419            # Fix image scale: 0 for contours, 1 for images.
1420            if { $bool } {
1421                set _settings(opacity) $_settings(saveOpacity)
1422            } else {
1423                set _settings(opacity) 100
1424            }
1425            AdjustSetting opacity
1426            if { $bool } {
1427                $itk_component(opacity) configure -state normal
1428                $itk_component(opacity_l) configure -state normal
1429                if {$_view(ortho)} {
1430                    SendCmd "camera mode ortho"
1431                } else {
1432                    SendCmd "camera mode persp"
1433                }
1434                SendCmd "camera aspect native"
1435            } else {
1436                $itk_component(opacity) configure -state disabled
1437                $itk_component(opacity_l) configure -state disabled
1438                SendCmd "camera mode image"
1439                if {$_settings(stretchToFit)} {
1440                    SendCmd "camera aspect window"
1441                }
1442            }
1443            if { $bool } {
1444                set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1445                $_arcball quaternion $q
1446                SendCmd "camera orient $q"
1447            } else {
1448                bind $c <ButtonPress-1> {}
1449                bind $c <B1-Motion> {}
1450                bind $c <ButtonRelease-1> {}
1451            }
1452            SendCmd "camera reset"
1453            # Fix the mouse bindings for rotation/panning and the
1454            # camera mode. Ideally we'd create a bindtag for these.
1455            if { $bool } {
1456                # Bindings for rotation via mouse
1457                bind $c <ButtonPress-1> \
1458                    [itcl::code $this Rotate click %x %y]
1459                bind $c <B1-Motion> \
1460                    [itcl::code $this Rotate drag %x %y]
1461                bind $c <ButtonRelease-1> \
1462                    [itcl::code $this Rotate release %x %y]
1463            }
1464            StopBufferingCommands
1465        }
1466        "window" {
1467            set val $_settings($what)
1468            SendCmd "image window $val"
1469        }
1470        "level" {
1471            set val $_settings($what)
1472            SendCmd "image level $val"
1473        }
1474        "legendVisible" {
1475            if { !$_settings($what) } {
1476                $itk_component(view) delete legend
1477            }
1478            DrawLegend
1479        }
1480        "opacity" {
1481            set _changed($what) 1
1482            if { $_settings(view3D) } {
1483                set _settings(saveOpacity) $_settings($what)
1484                set val [expr $_settings($what) * 0.01]
1485                SendCmd "image opacity $val"
1486            } else {
1487                SendCmd "image opacity 1.0"
1488            }
1489        }
1490        "outline" {
1491            set bool $_settings($what)
1492            SendCmd "outline visible $bool"
1493        }
1494        "stretchToFit" {
1495            set bool $_settings($what)
1496            if { $bool } {
1497                if { $_settings(view3D) } {
1498                    SendCmd "camera aspect native"
1499                } else {
1500                    SendCmd "camera aspect window"
1501                }
1502            } else {
1503                SendCmd "camera aspect native"
1504            }
1505        }
1506        default {
1507            error "don't know how to fix $what"
1508        }
1509    }
1510}
1511
1512#
1513# RequestLegend --
1514#
1515#       Request a new legend from the server.  The size of the legend
1516#       is determined from the height of the canvas. 
1517#
1518# This should be called when
1519#       1.  A new current colormap is set.
1520#       2.  Window is resized.
1521#       3.  The limits of the data have changed.  (Just need a redraw).
1522#       4.  Number of isolines have changed. (Just need a redraw).
1523#       5.  Legend becomes visible (Just need a redraw).
1524#
1525itcl::body Rappture::VtkImageViewer::RequestLegend {} {
1526    set _legendPending 0
1527    set font "Arial 8"
1528    set w 12
1529    set lineht [font metrics $font -linespace]
1530    # color ramp height = (canvas height) - (min and max value lines) - 2
1531    set h [expr {$_height - 2 * ($lineht + 2)}]
1532    set _legendHeight $h
1533
1534    set fname $_curFldName
1535    if { [string match "component*" $fname] } {
1536        set title ""
1537    } else {
1538        if { [info exists _fields($fname)] } {
1539            foreach { title units } $_fields($fname) break
1540            if { $units != "" } {
1541                set title [format "%s (%s)" $title $units]
1542            }
1543        } else {
1544            set title $fname
1545        }
1546    }
1547    # If there's a title too, substract one more line
1548    if { $title != "" } {
1549        incr h -$lineht
1550    }
1551    if { $h < 1 } {
1552        return
1553    }
1554    # Set the legend on the first image dataset.
1555    if { $_currentColormap != "" && $_currentColormap != "none" } {
1556        #SendCmd "legend $_currentColormap scalar $_curFldName {} $w $h 0"
1557        SendCmd "legend2 $_currentColormap $w $h"
1558    }
1559}
1560
1561#
1562# SetCurrentColormap --
1563#
1564itcl::body Rappture::VtkImageViewer::SetCurrentColormap { name } {
1565    # Keep track of the colormaps that we build.
1566    if { $name != "none" && ![info exists _colormaps($name)] } {
1567        BuildColormap $name
1568        set _colormaps($name) 1
1569    }
1570    set _currentColormap $name
1571    SendCmd "image colormap $_currentColormap"
1572}
1573
1574
1575#
1576# BuildColormap --
1577#
1578#       Build the designated colormap on the server.
1579#
1580itcl::body Rappture::VtkImageViewer::BuildColormap { name } {
1581    set cmap [ColorsToColormap $name]
1582    if { [llength $cmap] == 0 } {
1583        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1584    }
1585    set wmap "0.0 1.0 1.0 1.0"
1586    SendCmd "colormap add $name { $cmap } { $wmap }"
1587}
1588
1589# ----------------------------------------------------------------------
1590# CONFIGURATION OPTION: -mode
1591# ----------------------------------------------------------------------
1592itcl::configbody Rappture::VtkImageViewer::mode {
1593    switch -- $itk_option(-mode) {
1594        "volume" {
1595            set _settings(view3D) 1
1596        }
1597        "vtkimage" {
1598            set _settings(view3D) 0
1599        }
1600        default {
1601            error "unknown mode settings \"$itk_option(-mode)\""
1602        }
1603    }
1604    if { !$_reset } {
1605        AdjustSetting view3D
1606    }
1607}
1608
1609# ----------------------------------------------------------------------
1610# CONFIGURATION OPTION: -plotbackground
1611# ----------------------------------------------------------------------
1612itcl::configbody Rappture::VtkImageViewer::plotbackground {
1613    if { [isconnected] } {
1614        set rgb [Color2RGB $itk_option(-plotbackground)]
1615        if { !$_reset } {
1616            SendCmd "screen bgcolor $rgb"
1617        }
1618        $itk_component(view) configure -background $itk_option(-plotbackground)
1619    }
1620}
1621
1622# ----------------------------------------------------------------------
1623# CONFIGURATION OPTION: -plotforeground
1624# ----------------------------------------------------------------------
1625itcl::configbody Rappture::VtkImageViewer::plotforeground {
1626    if { [isconnected] } {
1627        set rgb [Color2RGB $itk_option(-plotforeground)]
1628        if { !$_reset } {
1629            SendCmd "outline color $rgb"
1630            SendCmd "axis color all $rgb"
1631        }
1632    }
1633}
1634
1635itcl::body Rappture::VtkImageViewer::BuildImageTab {} {
1636
1637    set fg [option get $itk_component(hull) font Font]
1638    #set bfg [option get $itk_component(hull) boldFont Font]
1639
1640    set inner [$itk_component(main) insert end \
1641        -title "Image Settings" \
1642        -icon [Rappture::icon contour2]]
1643    $inner configure -borderwidth 4
1644
1645    checkbutton $inner.legend \
1646        -text "Legend" \
1647        -variable [itcl::scope _settings(legendVisible)] \
1648        -command [itcl::code $this AdjustSetting legendVisible] \
1649        -font "Arial 9"
1650
1651    checkbutton $inner.outline \
1652        -text "Outline" \
1653        -variable [itcl::scope _settings(outline)] \
1654        -command [itcl::code $this AdjustSetting outline] \
1655        -font "Arial 9"
1656
1657    checkbutton $inner.backing \
1658        -text "Backing" \
1659        -variable [itcl::scope _settings(backingVisible)] \
1660        -command [itcl::code $this AdjustSetting backingVisible] \
1661        -font "Arial 9"
1662
1663    checkbutton $inner.stretch \
1664        -text "Stretch to fit" \
1665        -variable [itcl::scope _settings(stretchToFit)] \
1666        -command [itcl::code $this AdjustSetting stretchToFit] \
1667        -font "Arial 9"
1668
1669    checkbutton $inner.colormapDiscrete \
1670        -text "Discrete Colormap" \
1671        -variable [itcl::scope _settings(colormapDiscrete)] \
1672        -command [itcl::code $this AdjustSetting colormapDiscrete] \
1673        -font "Arial 9"
1674
1675    itk_component add field_l {
1676        label $inner.field_l -text "Field" -font "Arial 9"
1677    } {
1678        ignore -font
1679    }
1680    itk_component add field {
1681        Rappture::Combobox $inner.field -width 10 -editable no
1682    }
1683    bind $inner.field <<Value>> \
1684        [itcl::code $this AdjustSetting field]
1685
1686    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1687    itk_component add colormap {
1688        Rappture::Combobox $inner.colormap -width 10 -editable no
1689    }
1690    $inner.colormap choices insert end [GetColormapList -includeNone]
1691
1692    $itk_component(colormap) value "BCGYR"
1693    bind $inner.colormap <<Value>> \
1694        [itcl::code $this AdjustSetting colormap]
1695
1696    label $inner.backingcolor_l -text "Backing Color" -font "Arial 9"
1697    itk_component add backingcolor {
1698        Rappture::Combobox $inner.backingcolor -width 10 -editable no
1699    }
1700    $inner.backingcolor choices insert end \
1701        "black"              "black"            \
1702        "blue"               "blue"             \
1703        "cyan"               "cyan"             \
1704        "green"              "green"            \
1705        "grey"               "grey"             \
1706        "magenta"            "magenta"          \
1707        "orange"             "orange"           \
1708        "red"                "red"              \
1709        "white"              "white"            \
1710        "none"               "none"
1711
1712    $itk_component(backingcolor) value "white"
1713    bind $inner.backingcolor <<Value>> \
1714        [itcl::code $this AdjustSetting backingColor]
1715
1716    label $inner.background_l -text "Background Color" -font "Arial 9"
1717    itk_component add background {
1718        Rappture::Combobox $inner.background -width 10 -editable no
1719    }
1720    $inner.background choices insert end \
1721        "black"              "black"            \
1722        "white"              "white"            \
1723        "grey"               "grey"             
1724
1725    $itk_component(background) value "white"
1726    bind $inner.background <<Value>> [itcl::code $this AdjustSetting background]
1727
1728    itk_component add opacity_l {
1729        label $inner.opacity_l -text "Opacity" -font "Arial 9"
1730    } {
1731        ignore -font
1732    }
1733    itk_component add opacity {
1734        ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1735            -variable [itcl::scope _settings(opacity)] \
1736            -showvalue off \
1737            -command [itcl::code $this AdjustSetting opacity]
1738    }
1739
1740    itk_component add window_l {
1741        label $inner.window_l -text "Window" -font "Arial 9"
1742    } {
1743        ignore -font
1744    }
1745    itk_component add window {
1746        ::scale $inner.window -from 0 -to 255 -orient horizontal \
1747            -variable [itcl::scope _settings(window)] \
1748            -showvalue off \
1749            -command [itcl::code $this AdjustSetting window]
1750    }
1751    itk_component add level_l {
1752        label $inner.level_l -text "Level" -font "Arial 9"
1753    } {
1754        ignore -font
1755    }
1756    itk_component add level {
1757        ::scale $inner.level -from 0 -to 255 -orient horizontal \
1758            -variable [itcl::scope _settings(level)] \
1759            -showvalue off \
1760            -command [itcl::code $this AdjustSetting level]
1761    }
1762
1763    frame $inner.separator1 -height 2 -relief sunken -bd 1
1764    frame $inner.separator2 -height 2 -relief sunken -bd 1
1765
1766    blt::table $inner \
1767        0,0 $inner.field_l -anchor w -pady 2 \
1768        0,1 $inner.field -anchor w -pady 2 -fill x \
1769        1,0 $inner.colormap_l -anchor w -pady 2  \
1770        1,1 $inner.colormap   -anchor w -pady 2 -fill x  \
1771        2,0 $inner.backingcolor_l  -anchor w -pady 2  \
1772        2,1 $inner.backingcolor    -anchor w -pady 2 -fill x  \
1773        3,0 $inner.background_l -anchor w -pady 2 \
1774        3,1 $inner.background -anchor w -pady 2  -fill x \
1775        4,0 $inner.backing -anchor w -pady 2 -cspan 2 \
1776        5,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
1777        7,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1778        8,0 $inner.colormapDiscrete -anchor w -pady 2 -cspan 2 \
1779        11,0 $inner.separator1 -padx 2 -fill x -cspan 2 \
1780        12,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
1781        13,0 $inner.separator2 -padx 2 -fill x -cspan 2 \
1782        15,0 $inner.opacity_l -anchor w -pady 2 \
1783        15,1 $inner.opacity   -fill x   -pady 2 \
1784        16,0 $inner.window_l -anchor w -pady 2 \
1785        16,1 $inner.window   -fill x   -pady 2 \
1786        17,0 $inner.level_l -anchor w -pady 2 \
1787        17,1 $inner.level   -fill x   -pady 2
1788
1789    blt::table configure $inner r* c* -resize none
1790    blt::table configure $inner r19 c1 -resize expand
1791}
1792
1793itcl::body Rappture::VtkImageViewer::BuildAxisTab {} {
1794
1795    set fg [option get $itk_component(hull) font Font]
1796    #set bfg [option get $itk_component(hull) boldFont Font]
1797
1798    set inner [$itk_component(main) insert end \
1799        -title "Axis Settings" \
1800        -icon [Rappture::icon axis2]]
1801    $inner configure -borderwidth 4
1802
1803    checkbutton $inner.visible \
1804        -text "Axes" \
1805        -variable [itcl::scope _settings(axisVisible)] \
1806        -command [itcl::code $this AdjustSetting axisVisible] \
1807        -font "Arial 9"
1808    checkbutton $inner.labels \
1809        -text "Axis Labels" \
1810        -variable [itcl::scope _settings(axisLabels)] \
1811        -command [itcl::code $this AdjustSetting axisLabels] \
1812        -font "Arial 9"
1813    label $inner.grid_l -text "Grid" -font "Arial 9"
1814    checkbutton $inner.xgrid \
1815        -text "X" \
1816        -variable [itcl::scope _settings(axisXGrid)] \
1817        -command [itcl::code $this AdjustSetting axisXGrid] \
1818        -font "Arial 9"
1819    checkbutton $inner.ygrid \
1820        -text "Y" \
1821        -variable [itcl::scope _settings(axisYGrid)] \
1822        -command [itcl::code $this AdjustSetting axisYGrid] \
1823        -font "Arial 9"
1824    checkbutton $inner.zgrid \
1825        -text "Z" \
1826        -variable [itcl::scope _settings(axisZGrid)] \
1827        -command [itcl::code $this AdjustSetting axisZGrid] \
1828        -font "Arial 9"
1829    checkbutton $inner.minorticks \
1830        -text "Minor Ticks" \
1831        -variable [itcl::scope _settings(axisMinorTicks)] \
1832        -command [itcl::code $this AdjustSetting axisMinorTicks] \
1833        -font "Arial 9"
1834
1835    label $inner.mode_l -text "Mode" -font "Arial 9"
1836
1837    itk_component add axisflymode {
1838        Rappture::Combobox $inner.mode -width 10 -editable no
1839    }
1840    $inner.mode choices insert end \
1841        "static_triad"    "static" \
1842        "closest_triad"   "closest" \
1843        "furthest_triad"  "farthest" \
1844        "outer_edges"     "outer"         
1845    $itk_component(axisflymode) value "static"
1846    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisFlymode]
1847
1848    blt::table $inner \
1849        0,0 $inner.visible -anchor w -cspan 4 \
1850        1,0 $inner.labels  -anchor w -cspan 4 \
1851        2,0 $inner.minorticks  -anchor w -cspan 4 \
1852        4,0 $inner.grid_l  -anchor w \
1853        4,1 $inner.xgrid   -anchor w \
1854        4,2 $inner.ygrid   -anchor w \
1855        4,3 $inner.zgrid   -anchor w \
1856        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1857        5,1 $inner.mode    -fill x -cspan 3
1858
1859    blt::table configure $inner r* c* -resize none
1860    blt::table configure $inner r7 c6 -resize expand
1861    blt::table configure $inner r3 -height 0.125i
1862}
1863
1864
1865itcl::body Rappture::VtkImageViewer::BuildCameraTab {} {
1866    set inner [$itk_component(main) insert end \
1867        -title "Camera Settings" \
1868        -icon [Rappture::icon camera]]
1869    $inner configure -borderwidth 4
1870
1871    label $inner.view_l -text "view" -font "Arial 9"
1872    set f [frame $inner.view]
1873    foreach side { front back left right top bottom } {
1874        button $f.$side  -image [Rappture::icon view$side] \
1875            -command [itcl::code $this SetOrientation $side]
1876        Rappture::Tooltip::for $f.$side "Change the view to $side"
1877        pack $f.$side -side left
1878    }
1879
1880    blt::table $inner \
1881        0,0 $inner.view_l -anchor e -pady 2 \
1882        0,1 $inner.view -anchor w -pady 2
1883
1884    set labels { qx qy qz qw xpan ypan zoom }
1885    set row 1
1886    foreach tag $labels {
1887        label $inner.${tag}label -text $tag -font "Arial 9"
1888        entry $inner.${tag} -font "Arial 9"  -bg white \
1889            -textvariable [itcl::scope _view($tag)]
1890        bind $inner.${tag} <Return> \
1891            [itcl::code $this camera set ${tag}]
1892        bind $inner.${tag} <KP_Enter> \
1893            [itcl::code $this camera set ${tag}]
1894        blt::table $inner \
1895            $row,0 $inner.${tag}label -anchor e -pady 2 \
1896            $row,1 $inner.${tag} -anchor w -pady 2
1897        blt::table configure $inner r$row -resize none
1898        incr row
1899    }
1900    checkbutton $inner.ortho \
1901        -text "Orthographic Projection" \
1902        -variable [itcl::scope _view(ortho)] \
1903        -command [itcl::code $this camera set ortho] \
1904        -font "Arial 9"
1905    blt::table $inner \
1906            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1907    blt::table configure $inner r$row -resize none
1908    incr row
1909
1910    blt::table configure $inner c* r* -resize none
1911    blt::table configure $inner c2 -resize expand
1912    blt::table configure $inner r$row -resize expand
1913}
1914
1915#
1916#  camera --
1917#
1918itcl::body Rappture::VtkImageViewer::camera {option args} {
1919    switch -- $option {
1920        "show" {
1921            puts [array get _view]
1922        }
1923        "set" {
1924            set who [lindex $args 0]
1925            set x $_view($who)
1926            set code [catch { string is double $x } result]
1927            if { $code != 0 || !$result } {
1928                return
1929            }
1930            switch -- $who {
1931                "ortho" {
1932                    if {$_view(ortho)} {
1933                        SendCmd "camera mode ortho"
1934                    } else {
1935                        SendCmd "camera mode persp"
1936                    }
1937                }
1938                "xpan" - "ypan" {
1939                    PanCamera
1940                }
1941                "qx" - "qy" - "qz" - "qw" {
1942                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1943                    $_arcball quaternion $q
1944                    EventuallyRotate $q
1945                }
1946                "zoom" {
1947                    SendCmd "camera zoom $_view(zoom)"
1948                }
1949            }
1950        }
1951    }
1952}
1953
1954itcl::body Rappture::VtkImageViewer::GetVtkData { args } {
1955    set bytes ""
1956    foreach dataobj [get] {
1957        foreach comp [$dataobj components] {
1958            set tag $dataobj-$comp
1959            set contents [$dataobj vtkdata $comp]
1960            append bytes "$contents\n"
1961        }
1962    }
1963    return [list .vtk $bytes]
1964}
1965
1966itcl::body Rappture::VtkImageViewer::GetImage { args } {
1967    if { [image width $_image(download)] > 0 &&
1968         [image height $_image(download)] > 0 } {
1969        set bytes [$_image(download) data -format "jpeg -quality 100"]
1970        set bytes [Rappture::encoding::decode -as b64 $bytes]
1971        return [list .jpg $bytes]
1972    }
1973    return ""
1974}
1975
1976itcl::body Rappture::VtkImageViewer::BuildDownloadPopup { popup command } {
1977    Rappture::Balloon $popup \
1978        -title "[Rappture::filexfer::label downloadWord] as..."
1979    set inner [$popup component inner]
1980    label $inner.summary -text "" -anchor w
1981    radiobutton $inner.vtk_button -text "VTK data file" \
1982        -variable [itcl::scope _downloadPopup(format)] \
1983        -font "Arial 9 " \
1984        -value vtk 
1985    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
1986    radiobutton $inner.image_button -text "Image File" \
1987        -variable [itcl::scope _downloadPopup(format)] \
1988        -font "Arial 9 " \
1989        -value image
1990    Rappture::Tooltip::for $inner.image_button \
1991        "Save as digital image."
1992
1993    button $inner.ok -text "Save" \
1994        -highlightthickness 0 -pady 2 -padx 3 \
1995        -command $command \
1996        -compound left \
1997        -image [Rappture::icon download]
1998
1999    button $inner.cancel -text "Cancel" \
2000        -highlightthickness 0 -pady 2 -padx 3 \
2001        -command [list $popup deactivate] \
2002        -compound left \
2003        -image [Rappture::icon cancel]
2004
2005    blt::table $inner \
2006        0,0 $inner.summary -cspan 2  \
2007        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2008        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2009        4,1 $inner.cancel -width .9i -fill y \
2010        4,0 $inner.ok -padx 2 -width .9i -fill y
2011    blt::table configure $inner r3 -height 4
2012    blt::table configure $inner r4 -pady 4
2013    raise $inner.image_button
2014    $inner.vtk_button invoke
2015    return $inner
2016}
2017
2018#
2019# SetObjectStyle --
2020#
2021#       Set the style of the image/contour object.  This gets calls
2022#       for each dataset once as it is loaded.  It can overridden by
2023#       the user controls.
2024#
2025#
2026itcl::body Rappture::VtkImageViewer::SetObjectStyle { dataobj comp } {
2027    # Parse style string.
2028    set tag $dataobj-$comp
2029    array set style {
2030        -color none
2031        -opacity 1.0
2032    }
2033    set stylelist [$dataobj style $comp]
2034    if { $stylelist != "" } {
2035        array set style $stylelist
2036    }
2037    # This is too complicated.  We want to set the colormap, number of
2038    # isolines and opacity for the dataset.  They can be the default values,
2039    # the style hints loaded with the dataset, or set by user controls.  As
2040    # datasets get loaded, they first use the defaults that are overidden
2041    # by the style hints.  If the user changes the global controls, then that
2042    # overrides everything else.  I don't know what it means when global
2043    # controls are specified as style hints by each dataset.  It complicates
2044    # the code to handle aberrant cases.
2045
2046    if { $_changed(opacity) } {
2047        set style(-opacity) [expr $_settings(opacity) * 0.01]
2048    }
2049    if { $_changed(colormap) } {
2050        set style(-color) $_settings(colormap)
2051    }
2052    if { $_currentColormap == "" } {
2053        $itk_component(colormap) value $style(-color)
2054    }
2055    if { [info exists style(-stretchtofit)] } {
2056        set _settings(stretchToFit) $style(-stretchtofit)
2057        AdjustSetting stretchToFit
2058    }
2059    SendCmd "outline add $tag"
2060    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2061    SendCmd "outline visible $_settings(outline) $tag"
2062    SendCmd "image add $tag"
2063    SetCurrentColormap $style(-color)
2064    set color [$itk_component(backingcolor) value]
2065    SendCmd "image color [Color2RGB $color] $tag"
2066    SendCmd "image opacity $style(-opacity) $tag"
2067    set _settings(opacity) [expr $style(-opacity) * 100.0]
2068}
2069
2070itcl::body Rappture::VtkImageViewer::IsValidObject { dataobj } {
2071    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2072        return 0
2073    }
2074    return 1
2075}
2076
2077# ----------------------------------------------------------------------
2078# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2079#
2080# Invoked automatically whenever the "legend" command comes in from
2081# the rendering server.  Indicates that binary image data with the
2082# specified <size> will follow.
2083# ----------------------------------------------------------------------
2084itcl::body Rappture::VtkImageViewer::ReceiveLegend { colormap title min max size } {
2085    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2086    if { [isconnected] } {
2087        set bytes [ReceiveBytes $size]
2088        if { ![info exists _image(legend)] } {
2089            set _image(legend) [image create photo]
2090        }
2091        $_image(legend) configure -data $bytes
2092        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2093        if { [catch {DrawLegend} errs] != 0 } {
2094            global errorInfo
2095            puts stderr "errs=$errs errorInfo=$errorInfo"
2096        }
2097    }
2098}
2099
2100#
2101# DrawLegend --
2102#
2103#       Draws the legend in the own canvas on the right side of the plot area.
2104#
2105itcl::body Rappture::VtkImageViewer::DrawLegend {} {
2106    set fname $_curFldName
2107    set c $itk_component(view)
2108    set w [winfo width $c]
2109    set h [winfo height $c]
2110    set font "Arial 8"
2111    set lineht [font metrics $font -linespace]
2112   
2113    if { [string match "component*" $fname] } {
2114        set title ""
2115    } else {
2116        if { [info exists _fields($fname)] } {
2117            foreach { title units } $_fields($fname) break
2118            if { $units != "" } {
2119                set title [format "%s (%s)" $title $units]
2120            }
2121        } else {
2122            set title $fname
2123        }
2124    }
2125    set x [expr $w - 2]
2126    if { !$_settings(legendVisible) } {
2127        $c delete legend
2128        return
2129    }
2130    if { [$c find withtag "legend"] == "" } {
2131        set y 2
2132        # If there's a legend title, create a text item for the title.
2133        $c create text $x $y \
2134            -anchor ne \
2135            -fill $itk_option(-plotforeground) -tags "title legend" \
2136            -font $font
2137        if { $title != "" } {
2138            incr y $lineht
2139        }
2140        $c create text $x $y \
2141            -anchor ne \
2142            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2143            -font $font
2144        incr y $lineht
2145        $c create image $x $y \
2146            -anchor ne \
2147            -image $_image(legend) -tags "colormap legend"
2148        $c create rectangle $x $y 1 1 \
2149            -fill "" -outline "" -tags "sensor legend"
2150        $c create text $x [expr {$h-2}] \
2151            -anchor se \
2152            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2153            -font $font
2154        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2155        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2156        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2157    }
2158
2159    set x2 $x
2160    set iw [image width $_image(legend)]
2161    set ih [image height $_image(legend)]
2162    set x1 [expr $x2 - ($iw*12)/10]
2163
2164    $c bind title <ButtonPress> [itcl::code $this Combo post]
2165    $c bind title <Enter> [itcl::code $this Combo activate]
2166    $c bind title <Leave> [itcl::code $this Combo deactivate]
2167    # Reset the item coordinates according the current size of the plot.
2168    if { [info exists _limits($_curFldName)] } {
2169        foreach { vmin vmax } $_limits($_curFldName) break
2170        $c itemconfigure vmin -text [format %g $vmin]
2171        $c itemconfigure vmax -text [format %g $vmax]
2172    }
2173    set y 2
2174    # If there's a legend title, move the title to the correct position
2175    if { $title != "" } {
2176        $c itemconfigure title -text $title
2177        $c coords title $x $y
2178        incr y $lineht
2179    }
2180    $c coords vmax $x $y
2181    incr y $lineht
2182    $c coords colormap $x $y
2183    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2184    $c raise sensor
2185    $c coords vmin $x [expr {$h - 2}]
2186}
2187
2188#
2189# EnterLegend --
2190#
2191itcl::body Rappture::VtkImageViewer::EnterLegend { x y } {
2192    SetLegendTip $x $y
2193}
2194
2195#
2196# MotionLegend --
2197#
2198itcl::body Rappture::VtkImageViewer::MotionLegend { x y } {
2199    Rappture::Tooltip::tooltip cancel
2200    set c $itk_component(view)
2201    set cw [winfo width $c]
2202    set ch [winfo height $c]
2203    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2204        SetLegendTip $x $y
2205    }
2206}
2207
2208#
2209# LeaveLegend --
2210#
2211itcl::body Rappture::VtkImageViewer::LeaveLegend { } {
2212    Rappture::Tooltip::tooltip cancel
2213    .rappturetooltip configure -icon ""
2214}
2215
2216#
2217# SetLegendTip --
2218#
2219itcl::body Rappture::VtkImageViewer::SetLegendTip { x y } {
2220    set fname $_curFldName
2221    set c $itk_component(view)
2222    set w [winfo width $c]
2223    set h [winfo height $c]
2224    set font "Arial 8"
2225    set lineht [font metrics $font -linespace]
2226   
2227    set ih [image height $_image(legend)]
2228    # Subtract off the offset of the color ramp from the top of the canvas
2229    set iy [expr $y - ($lineht + 2)]
2230
2231    if { [string match "component*" $fname] } {
2232        set title ""
2233    } else {
2234        if { [info exists _fields($fname)] } {
2235            foreach { title units } $_fields($fname) break
2236            if { $units != "" } {
2237                set title [format "%s (%s)" $title $units]
2238            }
2239        } else {
2240            set title $fname
2241        }
2242    }
2243    # If there's a legend title, increase the offset by the line height.
2244    if { $title != "" } {
2245        incr iy -$lineht
2246    }
2247
2248    # Make a swatch of the selected color
2249    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2250        return
2251    }
2252
2253    if { ![info exists _image(swatch)] } {
2254        set _image(swatch) [image create photo -width 24 -height 24]
2255    }
2256    set color [eval format "\#%02x%02x%02x" $pixel]
2257    $_image(swatch) put black  -to 0 0 23 23
2258    $_image(swatch) put $color -to 1 1 22 22
2259
2260    # Compute the value of the point
2261    if { [info exists _limits($fname)] } {
2262        foreach { vmin vmax } $_limits($fname) break
2263        set t [expr 1.0 - (double($iy) / double($ih-1))]
2264        set value [expr $t * ($vmax - $vmin) + $vmin]
2265    } else {
2266        set value 0.0
2267    }
2268    set tipx [expr $x + 15]
2269    set tipy [expr $y - 5]
2270    .rappturetooltip configure -icon $_image(swatch)
2271    if { [info exists _isolines($y)] } {
2272        Rappture::Tooltip::text $c [format "$title %g (isoline)" $_isolines($y)]
2273    } else {
2274        Rappture::Tooltip::text $c [format "$title %g" $value]
2275    }
2276    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2277}
2278
2279# ----------------------------------------------------------------------
2280# USAGE: _dropdown post
2281# USAGE: _dropdown unpost
2282# USAGE: _dropdown select
2283#
2284# Used internally to handle the dropdown list for this combobox.  The
2285# post/unpost options are invoked when the list is posted or unposted
2286# to manage the relief of the controlling button.  The select option
2287# is invoked whenever there is a selection from the list, to assign
2288# the value back to the gauge.
2289# ----------------------------------------------------------------------
2290itcl::body Rappture::VtkImageViewer::Combo {option} {
2291    set c $itk_component(view)
2292    switch -- $option {
2293        post {
2294            foreach { x1 y1 x2 y2 } [$c bbox title] break
2295            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2296            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2297            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2298            tk_popup $itk_component(fieldmenu) $x $y
2299        }
2300        activate {
2301            $c itemconfigure title -fill red
2302        }
2303        deactivate {
2304            $c itemconfigure title -fill $itk_option(-plotforeground)
2305        }
2306        invoke {
2307            $itk_component(field) value $_curFldLabel
2308            AdjustSetting field
2309        }
2310        default {
2311            error "bad option \"$option\": should be post, unpost, select"
2312        }
2313    }
2314}
2315
2316itcl::body Rappture::VtkImageViewer::SetOrientation { side } {
2317    array set positions {
2318        front  "0.707107 0.707107 0 0"
2319        back   "0 0 0.707107 0.707107"
2320        left   "0.5 0.5 -0.5 -0.5"
2321        right  "0.5 0.5 0.5 0.5"
2322        top    "1 0 0 0"
2323        bottom "0 1 0 0"
2324    }
2325    foreach name { qw qx qy qz } value $positions($side) {
2326        set _view($name) $value
2327    }
2328    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2329    $_arcball quaternion $q
2330    SendCmd "camera orient $q"
2331    SendCmd "camera reset"
2332    set _view(xpan) 0
2333    set _view(ypan) 0
2334    set _view(zoom) 1.0
2335}
Note: See TracBrowser for help on using the repository browser.