source: trunk/gui/scripts/vtkimageviewer.tcl @ 4344

Last change on this file since 4344 was 4344, checked in by ldelgass, 7 years ago

Add VTK surface viewer for viewing colormapped surfaces from any field.

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