source: branches/1.4/gui/scripts/vtkimageviewer.tcl @ 5172

Last change on this file since 5172 was 5172, checked in by ldelgass, 10 years ago

merge r5156 from trunk

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