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

Last change on this file since 6052 was 6052, checked in by ldelgass, 9 years ago

Remove unused server list in viewer constructors. The server list is obtained
from the VisViewer? internal server list which can be modified with the
Get/SetServerList? "static" procs (and which is called while evaluating the
session resources file if present).

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