source: branches/1.3/gui/scripts/vtkimageviewer.tcl @ 4706

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

merge r4699 from trunk

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