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

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

merge r4765 from trunk

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