source: branches/1.7/gui/scripts/vtkimageviewer.tcl @ 6306

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

merge fixes from trunk

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