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

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

merge r4749 from trunk

File size: 76.8 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                set units [lindex $_fields($_curFldName) 1]
1033            } else {
1034                set units [$_first hints ${axis}units]
1035            }
1036            if { $units != "" } {
1037                # May be a space in the axis units.
1038                SendCmd [list axis units $axis $units]
1039            }
1040        }
1041        #
1042        # Reset the camera and other view parameters
1043        #
1044        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1045        $_arcball quaternion $q
1046        if {$_settings(view3D) } {
1047            if { $_view(ortho)} {
1048                SendCmd "camera mode ortho"
1049            } else {
1050                SendCmd "camera mode persp"
1051            }
1052            DoRotate
1053            SendCmd "camera reset"
1054        }
1055        PanCamera
1056        InitSettings axisXGrid axisYGrid axisZGrid \
1057            axisVisible axisLabels field view3D
1058        if { [array size _fields] < 2 } {
1059            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1060        }
1061        RequestLegend
1062        set _reset 0
1063    }
1064    global readyForNextFrame
1065    set readyForNextFrame 0;            # Don't advance to the next frame
1066
1067    # Actually write the commands to the server socket.  If it fails, we don't
1068    # care.  We're finished here.
1069    blt::busy hold $itk_component(hull)
1070    StopBufferingCommands
1071    blt::busy release $itk_component(hull)
1072}
1073
1074# ----------------------------------------------------------------------
1075# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1076#
1077# Returns a list of server IDs for the current datasets being displayed.  This
1078# is normally a single ID, but it might be a list of IDs if the current data
1079# object has multiple components.
1080# ----------------------------------------------------------------------
1081itcl::body Rappture::VtkImageViewer::CurrentDatasets {args} {
1082    set flag [lindex $args 0]
1083    switch -- $flag {
1084        "-all" {
1085            if { [llength $args] > 1 } {
1086                error "CurrentDatasets: can't specify dataobj after \"-all\""
1087            }
1088            set dlist [get -objects]
1089        }
1090        "-visible" {
1091            if { [llength $args] > 1 } {
1092                set dlist {}
1093                set args [lrange $args 1 end]
1094                foreach dataobj $args {
1095                    if { [info exists _obj2ovride($dataobj-raise)] } {
1096                        lappend dlist $dataobj
1097                    }
1098                }
1099            } else {
1100                set dlist [get -visible]
1101            }
1102        }           
1103        default {
1104            set dlist $args
1105        }
1106    }
1107    set rlist ""
1108    foreach dataobj $dlist {
1109        foreach comp [$dataobj components] {
1110            set tag $dataobj-$comp
1111            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1112                lappend rlist $tag
1113            }
1114        }
1115    }
1116    return $rlist
1117}
1118
1119# ----------------------------------------------------------------------
1120# USAGE: Zoom in
1121# USAGE: Zoom out
1122# USAGE: Zoom reset
1123#
1124# Called automatically when the user clicks on one of the zoom
1125# controls for this widget.  Changes the zoom for the current view.
1126# ----------------------------------------------------------------------
1127itcl::body Rappture::VtkImageViewer::Zoom {option} {
1128    switch -- $option {
1129        "in" {
1130            set _view(zoom) [expr {$_view(zoom)*1.25}]
1131            SendCmd "camera zoom $_view(zoom)"
1132        }
1133        "out" {
1134            set _view(zoom) [expr {$_view(zoom)*0.8}]
1135            SendCmd "camera zoom $_view(zoom)"
1136        }
1137        "reset" {
1138            array set _view {
1139                qw      0.36
1140                qx      0.25
1141                qy      0.50
1142                qz      0.70
1143                zoom    1.0
1144                xpan    0
1145                ypan    0
1146            }
1147            if { $_first != "" } {
1148                set location [$_first hints camera]
1149                if { $location != "" } {
1150                    array set _view $location
1151                }
1152            }
1153            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1154            $_arcball quaternion $q
1155            if {$_settings(view3D) } {
1156                DoRotate
1157            }
1158            SendCmd "camera reset"
1159        }
1160    }
1161}
1162
1163itcl::body Rappture::VtkImageViewer::PanCamera {} {
1164    set x $_view(xpan)
1165    set y $_view(ypan)
1166    SendCmd "camera pan $x $y"
1167}
1168
1169
1170# ----------------------------------------------------------------------
1171# USAGE: Rotate click <x> <y>
1172# USAGE: Rotate drag <x> <y>
1173# USAGE: Rotate release <x> <y>
1174#
1175# Called automatically when the user clicks/drags/releases in the
1176# plot area.  Moves the plot according to the user's actions.
1177# ----------------------------------------------------------------------
1178itcl::body Rappture::VtkImageViewer::Rotate {option x y} {
1179    switch -- $option {
1180        "click" {
1181            $itk_component(view) configure -cursor fleur
1182            set _click(x) $x
1183            set _click(y) $y
1184        }
1185        "drag" {
1186            if {[array size _click] == 0} {
1187                Rotate click $x $y
1188            } else {
1189                set w [winfo width $itk_component(view)]
1190                set h [winfo height $itk_component(view)]
1191                if {$w <= 0 || $h <= 0} {
1192                    return
1193                }
1194
1195                if {[catch {
1196                    # this fails sometimes for no apparent reason
1197                    set dx [expr {double($x-$_click(x))/$w}]
1198                    set dy [expr {double($y-$_click(y))/$h}]
1199                }]} {
1200                    return
1201                }
1202                if { $dx == 0 && $dy == 0 } {
1203                    return
1204                }
1205                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1206                EventuallyRotate $q
1207                set _click(x) $x
1208                set _click(y) $y
1209            }
1210        }
1211        "release" {
1212            Rotate drag $x $y
1213            $itk_component(view) configure -cursor ""
1214            catch {unset _click}
1215        }
1216        default {
1217            error "bad option \"$option\": should be click, drag, release"
1218        }
1219    }
1220}
1221
1222itcl::body Rappture::VtkImageViewer::Pick {x y} {
1223    foreach tag [CurrentDatasets -visible] {
1224        SendCmd "dataset getscalar pixel $x $y $tag"
1225    }
1226}
1227
1228# ----------------------------------------------------------------------
1229# USAGE: $this Pan click x y
1230#        $this Pan drag x y
1231#        $this Pan release x y
1232#
1233# Called automatically when the user clicks on one of the zoom
1234# controls for this widget.  Changes the zoom for the current view.
1235# ----------------------------------------------------------------------
1236itcl::body Rappture::VtkImageViewer::Pan {option x y} {
1237    switch -- $option {
1238        "set" {
1239            set w [winfo width $itk_component(view)]
1240            set h [winfo height $itk_component(view)]
1241            set x [expr $x / double($w)]
1242            set y [expr $y / double($h)]
1243            set _view(xpan) [expr $_view(xpan) + $x]
1244            set _view(ypan) [expr $_view(ypan) + $y]
1245            PanCamera
1246            return
1247        }
1248        "click" {
1249            set _click(x) $x
1250            set _click(y) $y
1251            $itk_component(view) configure -cursor hand1
1252        }
1253        "drag" {
1254            if { ![info exists _click(x)] } {
1255                set _click(x) $x
1256            }
1257            if { ![info exists _click(y)] } {
1258                set _click(y) $y
1259            }
1260            set w [winfo width $itk_component(view)]
1261            set h [winfo height $itk_component(view)]
1262            set dx [expr ($_click(x) - $x)/double($w)]
1263            set dy [expr ($_click(y) - $y)/double($h)]
1264            set _click(x) $x
1265            set _click(y) $y
1266            set _view(xpan) [expr $_view(xpan) - $dx]
1267            set _view(ypan) [expr $_view(ypan) - $dy]
1268            PanCamera
1269        }
1270        "release" {
1271            Pan drag $x $y
1272            $itk_component(view) configure -cursor ""
1273        }
1274        default {
1275            error "unknown option \"$option\": should set, click, drag, or release"
1276        }
1277    }
1278}
1279
1280# ----------------------------------------------------------------------
1281# USAGE: InitSettings <what> ?<value>?
1282#
1283# Used internally to update rendering settings whenever parameters
1284# change in the popup settings panel.  Sends the new settings off
1285# to the back end.
1286# ----------------------------------------------------------------------
1287itcl::body Rappture::VtkImageViewer::InitSettings { args } {
1288    foreach spec $args {
1289        if { [info exists _settings($_first-$spec)] } {
1290            # Reset global setting with dataobj specific setting
1291            set _settings($spec) $_settings($_first-$spec)
1292        }
1293        AdjustSetting $spec
1294    }
1295}
1296
1297#
1298# AdjustSetting --
1299#
1300#       Changes/updates a specific setting in the widget.  There are
1301#       usually user-setable option.  Commands are sent to the render
1302#       server.
1303#
1304itcl::body Rappture::VtkImageViewer::AdjustSetting {what {value ""}} {
1305    if { $_beforeConnect } {
1306        return
1307    }
1308    switch -- $what {
1309        "axisFlymode" {
1310            set mode [$itk_component(axisflymode) value]
1311            set mode [$itk_component(axisflymode) translate $mode]
1312            set _settings($what) $mode
1313            SendCmd "axis flymode $mode"
1314        }
1315        "axisLabels" {
1316            set bool $_settings($what)
1317            SendCmd "axis labels all $bool"
1318        }
1319        "axisMinorTicks" {
1320            set bool $_settings($what)
1321            SendCmd "axis minticks all $bool"
1322        }
1323        "axisVisible" {
1324            set bool $_settings($what)
1325            SendCmd "axis visible all $bool"
1326        }
1327        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1328            set axis [string tolower [string range $what 4 4]]
1329            set bool $_settings($what)
1330            SendCmd "axis grid $axis $bool"
1331        }
1332        "background" {
1333            set bg [$itk_component(background) value]
1334            array set fgcolors {
1335                "black" "white"
1336                "white" "black"
1337                "grey"  "black"
1338            }
1339            set fg $fgcolors($bg)
1340            configure -plotbackground $bg -plotforeground $fg
1341            $itk_component(view) delete "legend"
1342            SendCmd "screen bgcolor [Color2RGB $bg]"
1343            SendCmd "outline color [Color2RGB $fg]"
1344            SendCmd "axis color all [Color2RGB $fg]"
1345            DrawLegend
1346        }
1347        "backingColor" {
1348            set color [$itk_component(backingcolor) value]
1349            if { $color == "none" } {
1350                if { $_settings(backingVisible) } {
1351                    SendCmd "image backing 0"
1352                    set _settings(backingVisible) 0
1353                }
1354            } else {
1355                if { !$_settings(backingVisible) } {
1356                    SendCmd "image backing 1"
1357                    set _settings(backingVisible) 1
1358                }
1359                SendCmd "image color [Color2RGB $color]"
1360            }
1361        }
1362        "backingVisible" {
1363            set bool $_settings($what)
1364            SendCmd "image backing $bool"
1365        }
1366        "colormap" {
1367            set _changed($what) 1
1368            StartBufferingCommands
1369            set color [$itk_component(colormap) value]
1370            set _settings($what) $color
1371            SetCurrentColormap $color
1372            if {$_settings(colormapDiscrete)} {
1373                 SendCmd "colormap res $_settings(numColors) $color"
1374            }
1375            StopBufferingCommands
1376            EventuallyRequestLegend
1377        }
1378        "colormapDiscrete" {
1379            set bool $_settings($what)
1380            StartBufferingCommands
1381            if {$bool} {
1382                SendCmd "colormap res $_settings(numColors)"
1383            } else {
1384                SendCmd "colormap res default"
1385            }
1386            StopBufferingCommands
1387            EventuallyRequestLegend
1388        }
1389        "field" {
1390            set label [$itk_component(field) value]
1391            set fname [$itk_component(field) translate $label]
1392            set _settings($what) $fname
1393            if { [info exists _fields($fname)] } {
1394                foreach { label units components } $_fields($fname) break
1395                if { $components > 1 } {
1396                    set _colorMode vmag
1397                } else {
1398                    set _colorMode scalar
1399                }
1400                set _curFldName $fname
1401                set _curFldLabel $label
1402            } else {
1403                puts stderr "unknown field \"$fname\""
1404                return
1405            }
1406
1407            # Get the new limits because the field changed.
1408            SendCmd "dataset scalar $_curFldName"
1409            #SendCmd "image colormode scalar $_curFldName"
1410            SendCmd "camera reset"
1411            DrawLegend
1412        }
1413        "view3D" {
1414            set bool $_settings($what)
1415            set c $itk_component(view)
1416            StartBufferingCommands
1417            # Fix image scale: 0 for contours, 1 for images.
1418            if { $bool } {
1419                set _settings(opacity) $_settings(saveOpacity)
1420            } else {
1421                set _settings(opacity) 100
1422            }
1423            AdjustSetting opacity
1424            if { $bool } {
1425                $itk_component(opacity) configure -state normal
1426                $itk_component(opacity_l) configure -state normal
1427                if {$_view(ortho)} {
1428                    SendCmd "camera mode ortho"
1429                } else {
1430                    SendCmd "camera mode persp"
1431                }
1432                SendCmd "camera aspect native"
1433            } else {
1434                $itk_component(opacity) configure -state disabled
1435                $itk_component(opacity_l) configure -state disabled
1436                SendCmd "camera mode image"
1437                if {$_settings(stretchToFit)} {
1438                    SendCmd "camera aspect window"
1439                }
1440            }
1441            if { $bool } {
1442                set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1443                $_arcball quaternion $q
1444                SendCmd "camera orient $q"
1445            } else {
1446                bind $c <ButtonPress-1> {}
1447                bind $c <B1-Motion> {}
1448                bind $c <ButtonRelease-1> {}
1449            }
1450            SendCmd "camera reset"
1451            # Fix the mouse bindings for rotation/panning and the
1452            # camera mode. Ideally we'd create a bindtag for these.
1453            if { $bool } {
1454                # Bindings for rotation via mouse
1455                bind $c <ButtonPress-1> \
1456                    [itcl::code $this Rotate click %x %y]
1457                bind $c <B1-Motion> \
1458                    [itcl::code $this Rotate drag %x %y]
1459                bind $c <ButtonRelease-1> \
1460                    [itcl::code $this Rotate release %x %y]
1461            }
1462            StopBufferingCommands
1463        }
1464        "window" {
1465            set val $_settings($what)
1466            SendCmd "image window $val"
1467        }
1468        "level" {
1469            set val $_settings($what)
1470            SendCmd "image level $val"
1471        }
1472        "legendVisible" {
1473            if { !$_settings($what) } {
1474                $itk_component(view) delete legend
1475            }
1476            DrawLegend
1477        }
1478        "opacity" {
1479            set _changed($what) 1
1480            if { $_settings(view3D) } {
1481                set _settings(saveOpacity) $_settings($what)
1482                set val [expr $_settings($what) * 0.01]
1483                SendCmd "image opacity $val"
1484            } else {
1485                SendCmd "image opacity 1.0"
1486            }
1487        }
1488        "outline" {
1489            set bool $_settings($what)
1490            SendCmd "outline visible $bool"
1491        }
1492        "stretchToFit" {
1493            set bool $_settings($what)
1494            if { $bool } {
1495                if { $_settings(view3D) } {
1496                    SendCmd "camera aspect native"
1497                } else {
1498                    SendCmd "camera aspect window"
1499                }
1500            } else {
1501                SendCmd "camera aspect native"
1502            }
1503        }
1504        default {
1505            error "don't know how to fix $what"
1506        }
1507    }
1508}
1509
1510#
1511# RequestLegend --
1512#
1513#       Request a new legend from the server.  The size of the legend
1514#       is determined from the height of the canvas. 
1515#
1516# This should be called when
1517#       1.  A new current colormap is set.
1518#       2.  Window is resized.
1519#       3.  The limits of the data have changed.  (Just need a redraw).
1520#       4.  Number of isolines have changed. (Just need a redraw).
1521#       5.  Legend becomes visible (Just need a redraw).
1522#
1523itcl::body Rappture::VtkImageViewer::RequestLegend {} {
1524    set _legendPending 0
1525    set font "Arial 8"
1526    set w 12
1527    set lineht [font metrics $font -linespace]
1528    # color ramp height = (canvas height) - (min and max value lines) - 2
1529    set h [expr {$_height - 2 * ($lineht + 2)}]
1530    set _legendHeight $h
1531
1532    set fname $_curFldName
1533    if { [string match "component*" $fname] } {
1534        set title ""
1535    } else {
1536        if { [info exists _fields($fname)] } {
1537            foreach { title units } $_fields($fname) break
1538            if { $units != "" } {
1539                set title [format "%s (%s)" $title $units]
1540            }
1541        } else {
1542            set title $fname
1543        }
1544    }
1545    # If there's a title too, substract one more line
1546    if { $title != "" } {
1547        incr h -$lineht
1548    }
1549    if { $h < 1 } {
1550        return
1551    }
1552    # Set the legend on the first image dataset.
1553    if { $_currentColormap != "" && $_currentColormap != "none" } {
1554        SendCmd "legend $_currentColormap scalar $_curFldName {} $w $h 0"
1555    }
1556}
1557
1558#
1559# SetCurrentColormap --
1560#
1561itcl::body Rappture::VtkImageViewer::SetCurrentColormap { name } {
1562    # Keep track of the colormaps that we build.
1563    if { $name != "none" && ![info exists _colormaps($name)] } {
1564        BuildColormap $name
1565        set _colormaps($name) 1
1566    }
1567    set _currentColormap $name
1568    SendCmd "image colormap $_currentColormap"
1569}
1570
1571
1572#
1573# BuildColormap --
1574#
1575#       Build the designated colormap on the server.
1576#
1577itcl::body Rappture::VtkImageViewer::BuildColormap { name } {
1578    set cmap [ColorsToColormap $name]
1579    if { [llength $cmap] == 0 } {
1580        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1581    }
1582    set wmap "0.0 1.0 1.0 1.0"
1583    SendCmd "colormap add $name { $cmap } { $wmap }"
1584}
1585
1586# ----------------------------------------------------------------------
1587# CONFIGURATION OPTION: -mode
1588# ----------------------------------------------------------------------
1589itcl::configbody Rappture::VtkImageViewer::mode {
1590    switch -- $itk_option(-mode) {
1591        "volume" {
1592            set _settings(view3D) 1
1593        }
1594        "vtkimage" {
1595            set _settings(view3D) 0
1596        }
1597        default {
1598            error "unknown mode settings \"$itk_option(-mode)\""
1599        }
1600    }
1601    if { !$_reset } {
1602        AdjustSetting view3D
1603    }
1604}
1605
1606# ----------------------------------------------------------------------
1607# CONFIGURATION OPTION: -plotbackground
1608# ----------------------------------------------------------------------
1609itcl::configbody Rappture::VtkImageViewer::plotbackground {
1610    if { [isconnected] } {
1611        set rgb [Color2RGB $itk_option(-plotbackground)]
1612        if { !$_reset } {
1613            SendCmd "screen bgcolor $rgb"
1614        }
1615        $itk_component(view) configure -background $itk_option(-plotbackground)
1616    }
1617}
1618
1619# ----------------------------------------------------------------------
1620# CONFIGURATION OPTION: -plotforeground
1621# ----------------------------------------------------------------------
1622itcl::configbody Rappture::VtkImageViewer::plotforeground {
1623    if { [isconnected] } {
1624        set rgb [Color2RGB $itk_option(-plotforeground)]
1625        if { !$_reset } {
1626            SendCmd "outline color $rgb"
1627            SendCmd "axis color all $rgb"
1628        }
1629    }
1630}
1631
1632itcl::body Rappture::VtkImageViewer::BuildImageTab {} {
1633
1634    set fg [option get $itk_component(hull) font Font]
1635    #set bfg [option get $itk_component(hull) boldFont Font]
1636
1637    set inner [$itk_component(main) insert end \
1638        -title "Image Settings" \
1639        -icon [Rappture::icon contour2]]
1640    $inner configure -borderwidth 4
1641
1642    checkbutton $inner.legend \
1643        -text "Legend" \
1644        -variable [itcl::scope _settings(legendVisible)] \
1645        -command [itcl::code $this AdjustSetting legendVisible] \
1646        -font "Arial 9"
1647
1648    checkbutton $inner.outline \
1649        -text "Outline" \
1650        -variable [itcl::scope _settings(outline)] \
1651        -command [itcl::code $this AdjustSetting outline] \
1652        -font "Arial 9"
1653
1654    checkbutton $inner.backing \
1655        -text "Backing" \
1656        -variable [itcl::scope _settings(backingVisible)] \
1657        -command [itcl::code $this AdjustSetting backingVisible] \
1658        -font "Arial 9"
1659
1660    checkbutton $inner.stretch \
1661        -text "Stretch to fit" \
1662        -variable [itcl::scope _settings(stretchToFit)] \
1663        -command [itcl::code $this AdjustSetting stretchToFit] \
1664        -font "Arial 9"
1665
1666    checkbutton $inner.colormapDiscrete \
1667        -text "Discrete Colormap" \
1668        -variable [itcl::scope _settings(colormapDiscrete)] \
1669        -command [itcl::code $this AdjustSetting colormapDiscrete] \
1670        -font "Arial 9"
1671
1672    itk_component add field_l {
1673        label $inner.field_l -text "Field" -font "Arial 9"
1674    } {
1675        ignore -font
1676    }
1677    itk_component add field {
1678        Rappture::Combobox $inner.field -width 10 -editable no
1679    }
1680    bind $inner.field <<Value>> \
1681        [itcl::code $this AdjustSetting field]
1682
1683    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1684    itk_component add colormap {
1685        Rappture::Combobox $inner.colormap -width 10 -editable no
1686    }
1687    $inner.colormap choices insert end [GetColormapList -includeNone]
1688
1689    $itk_component(colormap) value "BCGYR"
1690    bind $inner.colormap <<Value>> \
1691        [itcl::code $this AdjustSetting colormap]
1692
1693    label $inner.backingcolor_l -text "Backing Color" -font "Arial 9"
1694    itk_component add backingcolor {
1695        Rappture::Combobox $inner.backingcolor -width 10 -editable no
1696    }
1697    $inner.backingcolor choices insert end \
1698        "black"              "black"            \
1699        "blue"               "blue"             \
1700        "cyan"               "cyan"             \
1701        "green"              "green"            \
1702        "grey"               "grey"             \
1703        "magenta"            "magenta"          \
1704        "orange"             "orange"           \
1705        "red"                "red"              \
1706        "white"              "white"            \
1707        "none"               "none"
1708
1709    $itk_component(backingcolor) value "white"
1710    bind $inner.backingcolor <<Value>> \
1711        [itcl::code $this AdjustSetting backingColor]
1712
1713    label $inner.background_l -text "Background Color" -font "Arial 9"
1714    itk_component add background {
1715        Rappture::Combobox $inner.background -width 10 -editable no
1716    }
1717    $inner.background choices insert end \
1718        "black"              "black"            \
1719        "white"              "white"            \
1720        "grey"               "grey"             
1721
1722    $itk_component(background) value "white"
1723    bind $inner.background <<Value>> [itcl::code $this AdjustSetting background]
1724
1725    itk_component add opacity_l {
1726        label $inner.opacity_l -text "Opacity" -font "Arial 9"
1727    } {
1728        ignore -font
1729    }
1730    itk_component add opacity {
1731        ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1732            -variable [itcl::scope _settings(opacity)] \
1733            -showvalue off \
1734            -command [itcl::code $this AdjustSetting opacity]
1735    }
1736
1737    itk_component add window_l {
1738        label $inner.window_l -text "Window" -font "Arial 9"
1739    } {
1740        ignore -font
1741    }
1742    itk_component add window {
1743        ::scale $inner.window -from 0 -to 255 -orient horizontal \
1744            -variable [itcl::scope _settings(window)] \
1745            -showvalue off \
1746            -command [itcl::code $this AdjustSetting window]
1747    }
1748    itk_component add level_l {
1749        label $inner.level_l -text "Level" -font "Arial 9"
1750    } {
1751        ignore -font
1752    }
1753    itk_component add level {
1754        ::scale $inner.level -from 0 -to 255 -orient horizontal \
1755            -variable [itcl::scope _settings(level)] \
1756            -showvalue off \
1757            -command [itcl::code $this AdjustSetting level]
1758    }
1759
1760    frame $inner.separator1 -height 2 -relief sunken -bd 1
1761    frame $inner.separator2 -height 2 -relief sunken -bd 1
1762
1763    blt::table $inner \
1764        0,0 $inner.field_l -anchor w -pady 2 \
1765        0,1 $inner.field -anchor w -pady 2 -fill x \
1766        1,0 $inner.colormap_l -anchor w -pady 2  \
1767        1,1 $inner.colormap   -anchor w -pady 2 -fill x  \
1768        2,0 $inner.backingcolor_l  -anchor w -pady 2  \
1769        2,1 $inner.backingcolor    -anchor w -pady 2 -fill x  \
1770        3,0 $inner.background_l -anchor w -pady 2 \
1771        3,1 $inner.background -anchor w -pady 2  -fill x \
1772        4,0 $inner.backing -anchor w -pady 2 -cspan 2 \
1773        5,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
1774        7,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1775        8,0 $inner.colormapDiscrete -anchor w -pady 2 -cspan 2 \
1776        11,0 $inner.separator1 -padx 2 -fill x -cspan 2 \
1777        12,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
1778        13,0 $inner.separator2 -padx 2 -fill x -cspan 2 \
1779        15,0 $inner.opacity_l -anchor w -pady 2 \
1780        15,1 $inner.opacity   -fill x   -pady 2 \
1781        16,0 $inner.window_l -anchor w -pady 2 \
1782        16,1 $inner.window   -fill x   -pady 2 \
1783        17,0 $inner.level_l -anchor w -pady 2 \
1784        17,1 $inner.level   -fill x   -pady 2
1785
1786    blt::table configure $inner r* c* -resize none
1787    blt::table configure $inner r19 c1 -resize expand
1788}
1789
1790itcl::body Rappture::VtkImageViewer::BuildAxisTab {} {
1791
1792    set fg [option get $itk_component(hull) font Font]
1793    #set bfg [option get $itk_component(hull) boldFont Font]
1794
1795    set inner [$itk_component(main) insert end \
1796        -title "Axis Settings" \
1797        -icon [Rappture::icon axis2]]
1798    $inner configure -borderwidth 4
1799
1800    checkbutton $inner.visible \
1801        -text "Axes" \
1802        -variable [itcl::scope _settings(axisVisible)] \
1803        -command [itcl::code $this AdjustSetting axisVisible] \
1804        -font "Arial 9"
1805    checkbutton $inner.labels \
1806        -text "Axis Labels" \
1807        -variable [itcl::scope _settings(axisLabels)] \
1808        -command [itcl::code $this AdjustSetting axisLabels] \
1809        -font "Arial 9"
1810    label $inner.grid_l -text "Grid" -font "Arial 9"
1811    checkbutton $inner.xgrid \
1812        -text "X" \
1813        -variable [itcl::scope _settings(axisXGrid)] \
1814        -command [itcl::code $this AdjustSetting axisXGrid] \
1815        -font "Arial 9"
1816    checkbutton $inner.ygrid \
1817        -text "Y" \
1818        -variable [itcl::scope _settings(axisYGrid)] \
1819        -command [itcl::code $this AdjustSetting axisYGrid] \
1820        -font "Arial 9"
1821    checkbutton $inner.zgrid \
1822        -text "Z" \
1823        -variable [itcl::scope _settings(axisZGrid)] \
1824        -command [itcl::code $this AdjustSetting axisZGrid] \
1825        -font "Arial 9"
1826    checkbutton $inner.minorticks \
1827        -text "Minor Ticks" \
1828        -variable [itcl::scope _settings(axisMinorTicks)] \
1829        -command [itcl::code $this AdjustSetting axisMinorTicks] \
1830        -font "Arial 9"
1831
1832    label $inner.mode_l -text "Mode" -font "Arial 9"
1833
1834    itk_component add axisflymode {
1835        Rappture::Combobox $inner.mode -width 10 -editable no
1836    }
1837    $inner.mode choices insert end \
1838        "static_triad"    "static" \
1839        "closest_triad"   "closest" \
1840        "furthest_triad"  "farthest" \
1841        "outer_edges"     "outer"         
1842    $itk_component(axisflymode) value "static"
1843    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisFlymode]
1844
1845    blt::table $inner \
1846        0,0 $inner.visible -anchor w -cspan 4 \
1847        1,0 $inner.labels  -anchor w -cspan 4 \
1848        2,0 $inner.minorticks  -anchor w -cspan 4 \
1849        4,0 $inner.grid_l  -anchor w \
1850        4,1 $inner.xgrid   -anchor w \
1851        4,2 $inner.ygrid   -anchor w \
1852        4,3 $inner.zgrid   -anchor w \
1853        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1854        5,1 $inner.mode    -fill x -cspan 3
1855
1856    blt::table configure $inner r* c* -resize none
1857    blt::table configure $inner r7 c6 -resize expand
1858    blt::table configure $inner r3 -height 0.125i
1859}
1860
1861
1862itcl::body Rappture::VtkImageViewer::BuildCameraTab {} {
1863    set inner [$itk_component(main) insert end \
1864        -title "Camera Settings" \
1865        -icon [Rappture::icon camera]]
1866    $inner configure -borderwidth 4
1867
1868    label $inner.view_l -text "view" -font "Arial 9"
1869    set f [frame $inner.view]
1870    foreach side { front back left right top bottom } {
1871        button $f.$side  -image [Rappture::icon view$side] \
1872            -command [itcl::code $this SetOrientation $side]
1873        Rappture::Tooltip::for $f.$side "Change the view to $side"
1874        pack $f.$side -side left
1875    }
1876
1877    blt::table $inner \
1878        0,0 $inner.view_l -anchor e -pady 2 \
1879        0,1 $inner.view -anchor w -pady 2
1880
1881    set labels { qx qy qz qw xpan ypan zoom }
1882    set row 1
1883    foreach tag $labels {
1884        label $inner.${tag}label -text $tag -font "Arial 9"
1885        entry $inner.${tag} -font "Arial 9"  -bg white \
1886            -textvariable [itcl::scope _view($tag)]
1887        bind $inner.${tag} <Return> \
1888            [itcl::code $this camera set ${tag}]
1889        bind $inner.${tag} <KP_Enter> \
1890            [itcl::code $this camera set ${tag}]
1891        blt::table $inner \
1892            $row,0 $inner.${tag}label -anchor e -pady 2 \
1893            $row,1 $inner.${tag} -anchor w -pady 2
1894        blt::table configure $inner r$row -resize none
1895        incr row
1896    }
1897    checkbutton $inner.ortho \
1898        -text "Orthographic Projection" \
1899        -variable [itcl::scope _view(ortho)] \
1900        -command [itcl::code $this camera set ortho] \
1901        -font "Arial 9"
1902    blt::table $inner \
1903            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1904    blt::table configure $inner r$row -resize none
1905    incr row
1906
1907    blt::table configure $inner c* r* -resize none
1908    blt::table configure $inner c2 -resize expand
1909    blt::table configure $inner r$row -resize expand
1910}
1911
1912#
1913#  camera --
1914#
1915itcl::body Rappture::VtkImageViewer::camera {option args} {
1916    switch -- $option {
1917        "show" {
1918            puts [array get _view]
1919        }
1920        "set" {
1921            set who [lindex $args 0]
1922            set x $_view($who)
1923            set code [catch { string is double $x } result]
1924            if { $code != 0 || !$result } {
1925                return
1926            }
1927            switch -- $who {
1928                "ortho" {
1929                    if {$_view(ortho)} {
1930                        SendCmd "camera mode ortho"
1931                    } else {
1932                        SendCmd "camera mode persp"
1933                    }
1934                }
1935                "xpan" - "ypan" {
1936                    PanCamera
1937                }
1938                "qx" - "qy" - "qz" - "qw" {
1939                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1940                    $_arcball quaternion $q
1941                    EventuallyRotate $q
1942                }
1943                "zoom" {
1944                    SendCmd "camera zoom $_view(zoom)"
1945                }
1946            }
1947        }
1948    }
1949}
1950
1951itcl::body Rappture::VtkImageViewer::GetVtkData { args } {
1952    set bytes ""
1953    foreach dataobj [get] {
1954        foreach comp [$dataobj components] {
1955            set tag $dataobj-$comp
1956            set contents [$dataobj vtkdata $comp]
1957            append bytes "$contents\n"
1958        }
1959    }
1960    return [list .vtk $bytes]
1961}
1962
1963itcl::body Rappture::VtkImageViewer::GetImage { args } {
1964    if { [image width $_image(download)] > 0 &&
1965         [image height $_image(download)] > 0 } {
1966        set bytes [$_image(download) data -format "jpeg -quality 100"]
1967        set bytes [Rappture::encoding::decode -as b64 $bytes]
1968        return [list .jpg $bytes]
1969    }
1970    return ""
1971}
1972
1973itcl::body Rappture::VtkImageViewer::BuildDownloadPopup { popup command } {
1974    Rappture::Balloon $popup \
1975        -title "[Rappture::filexfer::label downloadWord] as..."
1976    set inner [$popup component inner]
1977    label $inner.summary -text "" -anchor w
1978    radiobutton $inner.vtk_button -text "VTK data file" \
1979        -variable [itcl::scope _downloadPopup(format)] \
1980        -font "Arial 9 " \
1981        -value vtk 
1982    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
1983    radiobutton $inner.image_button -text "Image File" \
1984        -variable [itcl::scope _downloadPopup(format)] \
1985        -font "Arial 9 " \
1986        -value image
1987    Rappture::Tooltip::for $inner.image_button \
1988        "Save as digital image."
1989
1990    button $inner.ok -text "Save" \
1991        -highlightthickness 0 -pady 2 -padx 3 \
1992        -command $command \
1993        -compound left \
1994        -image [Rappture::icon download]
1995
1996    button $inner.cancel -text "Cancel" \
1997        -highlightthickness 0 -pady 2 -padx 3 \
1998        -command [list $popup deactivate] \
1999        -compound left \
2000        -image [Rappture::icon cancel]
2001
2002    blt::table $inner \
2003        0,0 $inner.summary -cspan 2  \
2004        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2005        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2006        4,1 $inner.cancel -width .9i -fill y \
2007        4,0 $inner.ok -padx 2 -width .9i -fill y
2008    blt::table configure $inner r3 -height 4
2009    blt::table configure $inner r4 -pady 4
2010    raise $inner.image_button
2011    $inner.vtk_button invoke
2012    return $inner
2013}
2014
2015#
2016# SetObjectStyle --
2017#
2018#       Set the style of the image/contour object.  This gets calls
2019#       for each dataset once as it is loaded.  It can overridden by
2020#       the user controls.
2021#
2022#
2023itcl::body Rappture::VtkImageViewer::SetObjectStyle { dataobj comp } {
2024    # Parse style string.
2025    set tag $dataobj-$comp
2026    array set style {
2027        -color none
2028        -opacity 1.0
2029    }
2030    set stylelist [$dataobj style $comp]
2031    if { $stylelist != "" } {
2032        array set style $stylelist
2033    }
2034    # This is too complicated.  We want to set the colormap, number of
2035    # isolines and opacity for the dataset.  They can be the default values,
2036    # the style hints loaded with the dataset, or set by user controls.  As
2037    # datasets get loaded, they first use the defaults that are overidden
2038    # by the style hints.  If the user changes the global controls, then that
2039    # overrides everything else.  I don't know what it means when global
2040    # controls are specified as style hints by each dataset.  It complicates
2041    # the code to handle aberrant cases.
2042
2043    if { $_changed(opacity) } {
2044        set style(-opacity) [expr $_settings(opacity) * 0.01]
2045    }
2046    if { $_changed(colormap) } {
2047        set style(-color) $_settings(colormap)
2048    }
2049    if { $_currentColormap == "" } {
2050        $itk_component(colormap) value $style(-color)
2051    }
2052    if { [info exists style(-stretchtofit)] } {
2053        set _settings(stretchToFit) $style(-stretchtofit)
2054        AdjustSetting stretchToFit
2055    }
2056    SendCmd "outline add $tag"
2057    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2058    SendCmd "outline visible $_settings(outline) $tag"
2059    SendCmd "image add $tag"
2060    SetCurrentColormap $style(-color)
2061    set color [$itk_component(backingcolor) value]
2062    SendCmd "image color [Color2RGB $color] $tag"
2063    SendCmd "image opacity $style(-opacity) $tag"
2064    set _settings(opacity) [expr $style(-opacity) * 100.0]
2065}
2066
2067itcl::body Rappture::VtkImageViewer::IsValidObject { dataobj } {
2068    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2069        return 0
2070    }
2071    return 1
2072}
2073
2074# ----------------------------------------------------------------------
2075# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2076#
2077# Invoked automatically whenever the "legend" command comes in from
2078# the rendering server.  Indicates that binary image data with the
2079# specified <size> will follow.
2080# ----------------------------------------------------------------------
2081itcl::body Rappture::VtkImageViewer::ReceiveLegend { colormap title min max size } {
2082    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2083    if { [isconnected] } {
2084        set bytes [ReceiveBytes $size]
2085        if { ![info exists _image(legend)] } {
2086            set _image(legend) [image create photo]
2087        }
2088        $_image(legend) configure -data $bytes
2089        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2090        if { [catch {DrawLegend} errs] != 0 } {
2091            global errorInfo
2092            puts stderr "errs=$errs errorInfo=$errorInfo"
2093        }
2094    }
2095}
2096
2097#
2098# DrawLegend --
2099#
2100#       Draws the legend in the own canvas on the right side of the plot area.
2101#
2102itcl::body Rappture::VtkImageViewer::DrawLegend {} {
2103    set fname $_curFldName
2104    set c $itk_component(view)
2105    set w [winfo width $c]
2106    set h [winfo height $c]
2107    set font "Arial 8"
2108    set lineht [font metrics $font -linespace]
2109   
2110    if { [string match "component*" $fname] } {
2111        set title ""
2112    } else {
2113        if { [info exists _fields($fname)] } {
2114            foreach { title units } $_fields($fname) break
2115            if { $units != "" } {
2116                set title [format "%s (%s)" $title $units]
2117            }
2118        } else {
2119            set title $fname
2120        }
2121    }
2122    set x [expr $w - 2]
2123    if { !$_settings(legendVisible) } {
2124        $c delete legend
2125        return
2126    }
2127    if { [$c find withtag "legend"] == "" } {
2128        set y 2
2129        # If there's a legend title, create a text item for the title.
2130        $c create text $x $y \
2131            -anchor ne \
2132            -fill $itk_option(-plotforeground) -tags "title legend" \
2133            -font $font
2134        if { $title != "" } {
2135            incr y $lineht
2136        }
2137        $c create text $x $y \
2138            -anchor ne \
2139            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2140            -font $font
2141        incr y $lineht
2142        $c create image $x $y \
2143            -anchor ne \
2144            -image $_image(legend) -tags "colormap legend"
2145        $c create rectangle $x $y 1 1 \
2146            -fill "" -outline "" -tags "sensor legend"
2147        $c create text $x [expr {$h-2}] \
2148            -anchor se \
2149            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2150            -font $font
2151        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2152        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2153        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2154    }
2155
2156    set x2 $x
2157    set iw [image width $_image(legend)]
2158    set ih [image height $_image(legend)]
2159    set x1 [expr $x2 - ($iw*12)/10]
2160
2161    $c bind title <ButtonPress> [itcl::code $this Combo post]
2162    $c bind title <Enter> [itcl::code $this Combo activate]
2163    $c bind title <Leave> [itcl::code $this Combo deactivate]
2164    # Reset the item coordinates according the current size of the plot.
2165    if { [info exists _limits($_curFldName)] } {
2166        foreach { vmin vmax } $_limits($_curFldName) break
2167        $c itemconfigure vmin -text [format %g $vmin]
2168        $c itemconfigure vmax -text [format %g $vmax]
2169    }
2170    set y 2
2171    # If there's a legend title, move the title to the correct position
2172    if { $title != "" } {
2173        $c itemconfigure title -text $title
2174        $c coords title $x $y
2175        incr y $lineht
2176    }
2177    $c coords vmax $x $y
2178    incr y $lineht
2179    $c coords colormap $x $y
2180    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2181    $c raise sensor
2182    $c coords vmin $x [expr {$h - 2}]
2183}
2184
2185#
2186# EnterLegend --
2187#
2188itcl::body Rappture::VtkImageViewer::EnterLegend { x y } {
2189    SetLegendTip $x $y
2190}
2191
2192#
2193# MotionLegend --
2194#
2195itcl::body Rappture::VtkImageViewer::MotionLegend { x y } {
2196    Rappture::Tooltip::tooltip cancel
2197    set c $itk_component(view)
2198    set cw [winfo width $c]
2199    set ch [winfo height $c]
2200    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2201        SetLegendTip $x $y
2202    }
2203}
2204
2205#
2206# LeaveLegend --
2207#
2208itcl::body Rappture::VtkImageViewer::LeaveLegend { } {
2209    Rappture::Tooltip::tooltip cancel
2210    .rappturetooltip configure -icon ""
2211}
2212
2213#
2214# SetLegendTip --
2215#
2216itcl::body Rappture::VtkImageViewer::SetLegendTip { x y } {
2217    set fname $_curFldName
2218    set c $itk_component(view)
2219    set w [winfo width $c]
2220    set h [winfo height $c]
2221    set font "Arial 8"
2222    set lineht [font metrics $font -linespace]
2223   
2224    set ih [image height $_image(legend)]
2225    # Subtract off the offset of the color ramp from the top of the canvas
2226    set iy [expr $y - ($lineht + 2)]
2227
2228    if { [string match "component*" $fname] } {
2229        set title ""
2230    } else {
2231        if { [info exists _fields($fname)] } {
2232            foreach { title units } $_fields($fname) break
2233            if { $units != "" } {
2234                set title [format "%s (%s)" $title $units]
2235            }
2236        } else {
2237            set title $fname
2238        }
2239    }
2240    # If there's a legend title, increase the offset by the line height.
2241    if { $title != "" } {
2242        incr iy -$lineht
2243    }
2244
2245    # Make a swatch of the selected color
2246    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2247        return
2248    }
2249
2250    if { ![info exists _image(swatch)] } {
2251        set _image(swatch) [image create photo -width 24 -height 24]
2252    }
2253    set color [eval format "\#%02x%02x%02x" $pixel]
2254    $_image(swatch) put black  -to 0 0 23 23
2255    $_image(swatch) put $color -to 1 1 22 22
2256
2257    # Compute the value of the point
2258    if { [info exists _limits($fname)] } {
2259        foreach { vmin vmax } $_limits($fname) break
2260        set t [expr 1.0 - (double($iy) / double($ih-1))]
2261        set value [expr $t * ($vmax - $vmin) + $vmin]
2262    } else {
2263        set value 0.0
2264    }
2265    set tipx [expr $x + 15]
2266    set tipy [expr $y - 5]
2267    .rappturetooltip configure -icon $_image(swatch)
2268    if { [info exists _isolines($y)] } {
2269        Rappture::Tooltip::text $c [format "$title %g (isoline)" $_isolines($y)]
2270    } else {
2271        Rappture::Tooltip::text $c [format "$title %g" $value]
2272    }
2273    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2274}
2275
2276# ----------------------------------------------------------------------
2277# USAGE: _dropdown post
2278# USAGE: _dropdown unpost
2279# USAGE: _dropdown select
2280#
2281# Used internally to handle the dropdown list for this combobox.  The
2282# post/unpost options are invoked when the list is posted or unposted
2283# to manage the relief of the controlling button.  The select option
2284# is invoked whenever there is a selection from the list, to assign
2285# the value back to the gauge.
2286# ----------------------------------------------------------------------
2287itcl::body Rappture::VtkImageViewer::Combo {option} {
2288    set c $itk_component(view)
2289    switch -- $option {
2290        post {
2291            foreach { x1 y1 x2 y2 } [$c bbox title] break
2292            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2293            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2294            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2295            tk_popup $itk_component(fieldmenu) $x $y
2296        }
2297        activate {
2298            $c itemconfigure title -fill red
2299        }
2300        deactivate {
2301            $c itemconfigure title -fill $itk_option(-plotforeground)
2302        }
2303        invoke {
2304            $itk_component(field) value $_curFldLabel
2305            AdjustSetting field
2306        }
2307        default {
2308            error "bad option \"$option\": should be post, unpost, select"
2309        }
2310    }
2311}
2312
2313itcl::body Rappture::VtkImageViewer::SetOrientation { side } {
2314    array set positions {
2315        front  "0.707107 0.707107 0 0"
2316        back   "0 0 0.707107 0.707107"
2317        left   "0.5 0.5 -0.5 -0.5"
2318        right  "0.5 0.5 0.5 0.5"
2319        top    "1 0 0 0"
2320        bottom "0 1 0 0"
2321    }
2322    foreach name { qw qx qy qz } value $positions($side) {
2323        set _view($name) $value
2324    }
2325    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2326    $_arcball quaternion $q
2327    SendCmd "camera orient $q"
2328    SendCmd "camera reset"
2329    set _view(xpan) 0
2330    set _view(ypan) 0
2331    set _view(zoom) 1.0
2332}
Note: See TracBrowser for help on using the repository browser.