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

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

Enable the wait animation in all nanovis and vtkvis viewers

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