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

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

Add build info to clientinfo command

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