source: branches/uiuc_vtk_viewers/gui/scripts/vtkimageviewer.tcl @ 5033

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

sync up heightmap and image viewers

File size: 77.3 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        -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        -xgrid                  0
233        -ygrid                  0
234        -zgrid                  0
235    }
236    array set _changed {
237        -colormap               0
238        -opacity                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            fconfigure $f -encoding binary
835            puts -nonewline $f $bytes
836            close $f
837        }
838        $_image(plot) configure -data $bytes
839        set time [clock seconds]
840        set date [clock format $time]
841        #puts stderr "$date: received image [image width $_image(plot)]x[image height $_image(plot)] image>"       
842        if { $_start > 0 } {
843            set finish [clock clicks -milliseconds]
844            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
845            set _start 0
846        }
847    } elseif { $info(type) == "print" } {
848        set tag $this-print-$info(-token)
849        set _hardcopy($tag) $bytes
850    }
851}
852
853#
854# ReceiveDataset --
855#
856itcl::body Rappture::VtkImageViewer::ReceiveDataset { args } {
857    if { ![isconnected] } {
858        return
859    }
860    set option [lindex $args 0]
861    switch -- $option {
862        "scalar" {
863            set option [lindex $args 1]
864            switch -- $option {
865                "world" {
866                    foreach { x y z value tag } [lrange $args 2 end] break
867                }
868                "pixel" {
869                    foreach { x y value tag } [lrange $args 2 end] break
870                }
871            }
872        }
873        "vector" {
874            set option [lindex $args 1]
875            switch -- $option {
876                "world" {
877                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
878                }
879                "pixel" {
880                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
881                }
882            }
883        }
884        "names" {
885            foreach { name } [lindex $args 1] {
886                #puts stderr "Dataset: $name"
887            }
888        }
889        default {
890            error "unknown dataset option \"$option\" from server"
891        }
892    }
893}
894
895# ----------------------------------------------------------------------
896# USAGE: Rebuild
897#
898# Called automatically whenever something changes that affects the
899# data in the widget.  Clears any existing data and rebuilds the
900# widget to display new data.
901# ----------------------------------------------------------------------
902itcl::body Rappture::VtkImageViewer::Rebuild {} {
903    set w [winfo width $itk_component(view)]
904    set h [winfo height $itk_component(view)]
905    if { $w < 2 || $h < 2 } {
906        $_dispatcher event -idle !rebuild
907        return
908    }
909
910    # Turn on buffering of commands to the server.  We don't want to
911    # be preempted by a server disconnect/reconnect (which automatically
912    # generates a new call to Rebuild).   
913    StartBufferingCommands
914
915    if { $_width != $w || $_height != $h || $_reset } {
916        set _width $w
917        set _height $h
918        $_arcball resize $w $h
919        DoResize
920        if { $_settings(-stretchtofit) } {
921            AdjustSetting -stretchToFit
922        }
923    }
924    if { $_reset } {
925        #
926        # Reset the camera and other view parameters
927        #
928        InitSettings -view3d -background
929
930        SendCmd "axis lrot z 90"
931        $_arcball quaternion [ViewToQuaternion]
932        if {$_settings(-view3d) } {
933            if { $_view(-ortho)} {
934                SendCmd "camera mode ortho"
935            } else {
936                SendCmd "camera mode persp"
937            }
938            DoRotate
939            SendCmd "camera reset"
940        }
941        PanCamera
942        StopBufferingCommands
943        SendCmd "imgflush"
944        StartBufferingCommands
945    }
946
947    set _first ""
948    # Start off with no datasets are visible.
949    SendCmd "dataset visible 0"
950    foreach dataobj [get -objects] {
951        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
952            set _first $dataobj
953        }
954        set _obj2datasets($dataobj) ""
955        foreach comp [$dataobj components] {
956            set tag $dataobj-$comp
957            if { ![info exists _datasets($tag)] } {
958                set bytes [$dataobj vtkdata $comp]
959                if 0 {
960                    set f [open /tmp/vtkimage.vtk "w"]
961                    fconfigure $f -translation binary -encoding binary
962                    puts -nonewline $f $bytes
963                    close $f
964                }
965                set length [string length $bytes]
966                if { $_reportClientInfo }  {
967                    set info {}
968                    lappend info "tool_id"       [$dataobj hints toolid]
969                    lappend info "tool_name"     [$dataobj hints toolname]
970                    lappend info "tool_title"    [$dataobj hints tooltitle]
971                    lappend info "tool_command"  [$dataobj hints toolcommand]
972                    lappend info "tool_revision" [$dataobj hints toolrevision]
973                    lappend info "dataset_label" [$dataobj hints label]
974                    lappend info "dataset_size"  $length
975                    lappend info "dataset_tag"   $tag
976                    SendCmd "clientinfo [list $info]"
977                }
978                SendCmd "dataset add $tag data follows $length"
979                append _outbuf $bytes
980                set _datasets($tag) 1
981                SetObjectStyle $dataobj $comp
982            }
983            lappend _obj2datasets($dataobj) $tag
984            if { [info exists _obj2ovride($dataobj-raise)] } {
985                # Setting dataset visible enables outline
986                # and image
987                SendCmd "dataset visible 1 $tag"
988            }
989        }
990    }
991    if { $_first != ""  } {
992        $itk_component(field) choices delete 0 end
993        $itk_component(fieldmenu) delete 0 end
994        array unset _fields
995        set _curFldName ""
996        foreach cname [$_first components] {
997            foreach fname [$_first fieldnames $cname] {
998                if { [info exists _fields($fname)] } {
999                    continue
1000                }
1001                foreach { label units components } \
1002                    [$_first fieldinfo $fname] break
1003                $itk_component(field) choices insert end "$fname" "$label"
1004                $itk_component(fieldmenu) add radiobutton -label "$label" \
1005                    -value $label -variable [itcl::scope _curFldLabel] \
1006                    -selectcolor red \
1007                    -activebackground $itk_option(-plotbackground) \
1008                    -activeforeground $itk_option(-plotforeground) \
1009                    -font "Arial 8" \
1010                    -command [itcl::code $this Combo invoke]
1011                set _fields($fname) [list $label $units $components]
1012                if { $_curFldName == "" } {
1013                    set _curFldName $fname
1014                    set _curFldLabel $label
1015                }
1016            }
1017        }
1018        $itk_component(field) value $_curFldLabel
1019    }
1020    InitSettings -stretchtofit -outline
1021
1022    if { $_reset } {
1023        SendCmd "axis tickpos outside"
1024        #SendCmd "axis lformat all %g"
1025       
1026        foreach axis { x y z } {
1027            set label [$_first hints ${axis}label]
1028            if { $label == "" } {
1029                set label [string toupper $axis]
1030            }
1031            # May be a space in the axis label.
1032            SendCmd [list axis name $axis $label]
1033
1034            if {$axis == "z" && [$_first hints ${axis}units] == ""} {
1035                if {$_curFldName != ""} {
1036                    set units [lindex $_fields($_curFldName) 1]
1037                }
1038            } else {
1039                set units [$_first hints ${axis}units]
1040            }
1041            if { $units != "" } {
1042                # May be a space in the axis units.
1043                SendCmd [list axis units $axis $units]
1044            }
1045        }
1046        #
1047        # Reset the camera and other view parameters
1048        #
1049        $_arcball quaternion [ViewToQuaternion]
1050        if {$_settings(-view3d) } {
1051            if { $_view(-ortho)} {
1052                SendCmd "camera mode ortho"
1053            } else {
1054                SendCmd "camera mode persp"
1055            }
1056            DoRotate
1057            SendCmd "camera reset"
1058        }
1059        PanCamera
1060        InitSettings -xgrid -ygrid -zgrid \
1061            -axisvisible -axislabels -field -view3d
1062        if { [array size _fields] < 2 } {
1063            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1064        }
1065        RequestLegend
1066        set _reset 0
1067    }
1068    global readyForNextFrame
1069    set readyForNextFrame 0;            # Don't advance to the next frame
1070
1071    # Actually write the commands to the server socket.  If it fails, we don't
1072    # care.  We're finished here.
1073    blt::busy hold $itk_component(hull)
1074    StopBufferingCommands
1075    blt::busy release $itk_component(hull)
1076}
1077
1078# ----------------------------------------------------------------------
1079# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1080#
1081# Returns a list of server IDs for the current datasets being displayed.  This
1082# is normally a single ID, but it might be a list of IDs if the current data
1083# object has multiple components.
1084# ----------------------------------------------------------------------
1085itcl::body Rappture::VtkImageViewer::CurrentDatasets {args} {
1086    set flag [lindex $args 0]
1087    switch -- $flag {
1088        "-all" {
1089            if { [llength $args] > 1 } {
1090                error "CurrentDatasets: can't specify dataobj after \"-all\""
1091            }
1092            set dlist [get -objects]
1093        }
1094        "-visible" {
1095            if { [llength $args] > 1 } {
1096                set dlist {}
1097                set args [lrange $args 1 end]
1098                foreach dataobj $args {
1099                    if { [info exists _obj2ovride($dataobj-raise)] } {
1100                        lappend dlist $dataobj
1101                    }
1102                }
1103            } else {
1104                set dlist [get -visible]
1105            }
1106        }           
1107        default {
1108            set dlist $args
1109        }
1110    }
1111    set rlist ""
1112    foreach dataobj $dlist {
1113        foreach comp [$dataobj components] {
1114            set tag $dataobj-$comp
1115            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1116                lappend rlist $tag
1117            }
1118        }
1119    }
1120    return $rlist
1121}
1122
1123# ----------------------------------------------------------------------
1124# USAGE: Zoom in
1125# USAGE: Zoom out
1126# USAGE: Zoom reset
1127#
1128# Called automatically when the user clicks on one of the zoom
1129# controls for this widget.  Changes the zoom for the current view.
1130# ----------------------------------------------------------------------
1131itcl::body Rappture::VtkImageViewer::Zoom {option} {
1132    switch -- $option {
1133        "in" {
1134            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1135            SendCmd "camera zoom $_view(-zoom)"
1136        }
1137        "out" {
1138            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1139            SendCmd "camera zoom $_view(-zoom)"
1140        }
1141        "reset" {
1142            array set _view {
1143                -qw      0.36
1144                -qx      0.25
1145                -qy      0.50
1146                -qz      0.70
1147                -xpan    0
1148                -ypan    0
1149                -zoom    1.0
1150            }
1151            if { $_first != "" } {
1152                set location [$_first hints camera]
1153                if { $location != "" } {
1154                    array set _view $location
1155                }
1156            }
1157            $_arcball quaternion [ViewToQuaternion]
1158            if {$_settings(-view3d) } {
1159                DoRotate
1160            }
1161            SendCmd "camera reset"
1162        }
1163    }
1164}
1165
1166itcl::body Rappture::VtkImageViewer::PanCamera {} {
1167    set x $_view(-xpan)
1168    set y $_view(-ypan)
1169    SendCmd "camera pan $x $y"
1170}
1171
1172
1173# ----------------------------------------------------------------------
1174# USAGE: Rotate click <x> <y>
1175# USAGE: Rotate drag <x> <y>
1176# USAGE: Rotate release <x> <y>
1177#
1178# Called automatically when the user clicks/drags/releases in the
1179# plot area.  Moves the plot according to the user's actions.
1180# ----------------------------------------------------------------------
1181itcl::body Rappture::VtkImageViewer::Rotate {option x y} {
1182    switch -- $option {
1183        "click" {
1184            $itk_component(view) configure -cursor fleur
1185            set _click(x) $x
1186            set _click(y) $y
1187        }
1188        "drag" {
1189            if {[array size _click] == 0} {
1190                Rotate click $x $y
1191            } else {
1192                set w [winfo width $itk_component(view)]
1193                set h [winfo height $itk_component(view)]
1194                if {$w <= 0 || $h <= 0} {
1195                    return
1196                }
1197
1198                if {[catch {
1199                    # this fails sometimes for no apparent reason
1200                    set dx [expr {double($x-$_click(x))/$w}]
1201                    set dy [expr {double($y-$_click(y))/$h}]
1202                }]} {
1203                    return
1204                }
1205                if { $dx == 0 && $dy == 0 } {
1206                    return
1207                }
1208                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1209                EventuallyRotate $q
1210                set _click(x) $x
1211                set _click(y) $y
1212            }
1213        }
1214        "release" {
1215            Rotate drag $x $y
1216            $itk_component(view) configure -cursor ""
1217            catch {unset _click}
1218        }
1219        default {
1220            error "bad option \"$option\": should be click, drag, release"
1221        }
1222    }
1223}
1224
1225itcl::body Rappture::VtkImageViewer::Pick {x y} {
1226    foreach tag [CurrentDatasets -visible] {
1227        SendCmd "dataset getscalar pixel $x $y $tag"
1228    }
1229}
1230
1231# ----------------------------------------------------------------------
1232# USAGE: $this Pan click x y
1233#        $this Pan drag x y
1234#        $this Pan release x y
1235#
1236# Called automatically when the user clicks on one of the zoom
1237# controls for this widget.  Changes the zoom for the current view.
1238# ----------------------------------------------------------------------
1239itcl::body Rappture::VtkImageViewer::Pan {option x y} {
1240    switch -- $option {
1241        "set" {
1242            set w [winfo width $itk_component(view)]
1243            set h [winfo height $itk_component(view)]
1244            set x [expr $x / double($w)]
1245            set y [expr $y / double($h)]
1246            set _view(-xpan) [expr $_view(-xpan) + $x]
1247            set _view(-ypan) [expr $_view(-ypan) + $y]
1248            PanCamera
1249            return
1250        }
1251        "click" {
1252            set _click(x) $x
1253            set _click(y) $y
1254            $itk_component(view) configure -cursor hand1
1255        }
1256        "drag" {
1257            if { ![info exists _click(x)] } {
1258                set _click(x) $x
1259            }
1260            if { ![info exists _click(y)] } {
1261                set _click(y) $y
1262            }
1263            set w [winfo width $itk_component(view)]
1264            set h [winfo height $itk_component(view)]
1265            set dx [expr ($_click(x) - $x)/double($w)]
1266            set dy [expr ($_click(y) - $y)/double($h)]
1267            set _click(x) $x
1268            set _click(y) $y
1269            set _view(-xpan) [expr $_view(-xpan) - $dx]
1270            set _view(-ypan) [expr $_view(-ypan) - $dy]
1271            PanCamera
1272        }
1273        "release" {
1274            Pan drag $x $y
1275            $itk_component(view) configure -cursor ""
1276        }
1277        default {
1278            error "unknown option \"$option\": should set, click, drag, or release"
1279        }
1280    }
1281}
1282
1283# ----------------------------------------------------------------------
1284# USAGE: InitSettings <what> ?<value>?
1285#
1286# Used internally to update rendering settings whenever parameters
1287# change in the popup settings panel.  Sends the new settings off
1288# to the back end.
1289# ----------------------------------------------------------------------
1290itcl::body Rappture::VtkImageViewer::InitSettings { args } {
1291    foreach spec $args {
1292        if { [info exists _settings($_first${spec})] } {
1293            # Reset global setting with dataobj specific setting
1294            set _settings($spec) $_settings($_first${spec})
1295        }
1296        AdjustSetting $spec
1297    }
1298}
1299
1300#
1301# AdjustSetting --
1302#
1303#       Changes/updates a specific setting in the widget.  There are
1304#       usually user-setable option.  Commands are sent to the render
1305#       server.
1306#
1307itcl::body Rappture::VtkImageViewer::AdjustSetting {what {value ""}} {
1308    if { $_beforeConnect } {
1309        return
1310    }
1311    switch -- $what {
1312        "-axisflymode" {
1313            set mode [$itk_component(axisflymode) value]
1314            set mode [$itk_component(axisflymode) translate $mode]
1315            set _settings($what) $mode
1316            SendCmd "axis flymode $mode"
1317        }
1318        "-axislabels" {
1319            set bool $_settings($what)
1320            SendCmd "axis labels all $bool"
1321        }
1322        "-axisminorticks" {
1323            set bool $_settings($what)
1324            SendCmd "axis minticks all $bool"
1325        }
1326        "-axisvisible" {
1327            set bool $_settings($what)
1328            SendCmd "axis visible all $bool"
1329        }
1330        "-background" {
1331            set bg [$itk_component(background) value]
1332            array set fgcolors {
1333                "black" "white"
1334                "white" "black"
1335                "grey"  "black"
1336            }
1337            set fg $fgcolors($bg)
1338            configure -plotbackground $bg -plotforeground $fg
1339            $itk_component(view) delete "legend"
1340            SendCmd "screen bgcolor [Color2RGB $bg]"
1341            SendCmd "outline color [Color2RGB $fg]"
1342            SendCmd "axis color all [Color2RGB $fg]"
1343            DrawLegend
1344        }
1345        "-backingcolor" {
1346            set color [$itk_component(backingcolor) value]
1347            if { $color == "none" } {
1348                if { $_settings(-backingvisible) } {
1349                    SendCmd "image backing 0"
1350                    set _settings(-backingvisible) 0
1351                }
1352            } else {
1353                if { !$_settings(-backingvisible) } {
1354                    SendCmd "image backing 1"
1355                    set _settings(-backingvisible) 1
1356                }
1357                SendCmd "image color [Color2RGB $color]"
1358            }
1359        }
1360        "-backingvisible" {
1361            set bool $_settings($what)
1362            SendCmd "image backing $bool"
1363        }
1364        "-colormap" {
1365            set _changed($what) 1
1366            StartBufferingCommands
1367            set color [$itk_component(colormap) value]
1368            set _settings($what) $color
1369            SetCurrentColormap $color
1370            if {$_settings(-colormapdiscrete)} {
1371                 SendCmd "colormap res $_settings(-numcolors) $color"
1372            }
1373            StopBufferingCommands
1374            EventuallyRequestLegend
1375        }
1376        "-colormapdiscrete" {
1377            set bool $_settings($what)
1378            StartBufferingCommands
1379            if {$bool} {
1380                SendCmd "colormap res $_settings(-numcolors)"
1381            } else {
1382                SendCmd "colormap res default"
1383            }
1384            StopBufferingCommands
1385            EventuallyRequestLegend
1386        }
1387        "-field" {
1388            set label [$itk_component(field) value]
1389            set fname [$itk_component(field) translate $label]
1390            set _settings($what) $fname
1391            if { [info exists _fields($fname)] } {
1392                foreach { label units components } $_fields($fname) break
1393                if { $components > 1 } {
1394                    set _colorMode vmag
1395                } else {
1396                    set _colorMode scalar
1397                }
1398                set _curFldName $fname
1399                set _curFldLabel $label
1400            } else {
1401                puts stderr "unknown field \"$fname\""
1402                return
1403            }
1404
1405            # Get the new limits because the field changed.
1406            SendCmd "dataset scalar $_curFldName"
1407            #SendCmd "image colormode scalar $_curFldName"
1408            SendCmd "camera reset"
1409            DrawLegend
1410        }
1411        "-view3d" {
1412            set bool $_settings($what)
1413            set c $itk_component(view)
1414            StartBufferingCommands
1415            # Fix image scale: 0 for contours, 1 for images.
1416            if { $bool } {
1417                set _settings(-opacity) $_settings(-saveopacity)
1418            } else {
1419                set _settings(-opacity) 100
1420            }
1421            AdjustSetting -opacity
1422            if { $bool } {
1423                $itk_component(opacity) configure -state normal
1424                $itk_component(opacity_l) configure -state normal
1425                if {$_view(-ortho)} {
1426                    SendCmd "camera mode ortho"
1427                } else {
1428                    SendCmd "camera mode persp"
1429                }
1430                SendCmd "camera aspect native"
1431            } else {
1432                $itk_component(opacity) configure -state disabled
1433                $itk_component(opacity_l) configure -state disabled
1434                SendCmd "camera mode image"
1435                if {$_settings(-stretchtofit)} {
1436                    SendCmd "camera aspect window"
1437                }
1438            }
1439            if { $bool } {
1440                set q [ViewToQuaternion]
1441                $_arcball quaternion $q
1442                SendCmd "camera orient $q"
1443            } else {
1444                bind $c <ButtonPress-1> {}
1445                bind $c <B1-Motion> {}
1446                bind $c <ButtonRelease-1> {}
1447            }
1448            SendCmd "camera reset"
1449            # Fix the mouse bindings for rotation/panning and the
1450            # camera mode. Ideally we'd create a bindtag for these.
1451            if { $bool } {
1452                # Bindings for rotation via mouse
1453                bind $c <ButtonPress-1> \
1454                    [itcl::code $this Rotate click %x %y]
1455                bind $c <B1-Motion> \
1456                    [itcl::code $this Rotate drag %x %y]
1457                bind $c <ButtonRelease-1> \
1458                    [itcl::code $this Rotate release %x %y]
1459            }
1460            StopBufferingCommands
1461        }
1462        "-window" {
1463            set val $_settings($what)
1464            SendCmd "image window $val"
1465        }
1466        "-level" {
1467            set val $_settings($what)
1468            SendCmd "image level $val"
1469        }
1470        "-legendvisible" {
1471            if { !$_settings($what) } {
1472                $itk_component(view) delete legend
1473            }
1474            DrawLegend
1475        }
1476        "-opacity" {
1477            set _changed($what) 1
1478            if { $_settings(-view3d) } {
1479                set _settings(-saveopacity) $_settings($what)
1480                set val [expr $_settings($what) * 0.01]
1481                SendCmd "image opacity $val"
1482            } else {
1483                SendCmd "image opacity 1.0"
1484            }
1485        }
1486        "-outline" {
1487            set bool $_settings($what)
1488            SendCmd "outline visible $bool"
1489        }
1490        "-stretchtofit" {
1491            set bool $_settings($what)
1492            if { $bool } {
1493                if { $_settings(-view3d) } {
1494                    SendCmd "camera aspect native"
1495                } else {
1496                    SendCmd "camera aspect window"
1497                }
1498            } else {
1499                SendCmd "camera aspect native"
1500            }
1501        }
1502        "-xgrid" - "-ygrid" - "-zgrid" {
1503            set axis [string tolower [string range $what 1 1]]
1504            set bool $_settings($what)
1505            SendCmd "axis grid $axis $bool"
1506        }
1507        default {
1508            error "don't know how to fix $what"
1509        }
1510    }
1511}
1512
1513#
1514# RequestLegend --
1515#
1516#       Request a new legend from the server.  The size of the legend
1517#       is determined from the height of the canvas. 
1518#
1519# This should be called when
1520#       1.  A new current colormap is set.
1521#       2.  Window is resized.
1522#       3.  The limits of the data have changed.  (Just need a redraw).
1523#       4.  Number of isolines have changed. (Just need a redraw).
1524#       5.  Legend becomes visible (Just need a redraw).
1525#
1526itcl::body Rappture::VtkImageViewer::RequestLegend {} {
1527    set _legendPending 0
1528    set font "Arial 8"
1529    set w 12
1530    set lineht [font metrics $font -linespace]
1531    # color ramp height = (canvas height) - (min and max value lines) - 2
1532    set h [expr {$_height - 2 * ($lineht + 2)}]
1533    set _legendHeight $h
1534
1535    set fname $_curFldName
1536    if { [string match "component*" $fname] } {
1537        set title ""
1538    } else {
1539        if { [info exists _fields($fname)] } {
1540            foreach { title units } $_fields($fname) break
1541            if { $units != "" } {
1542                set title [format "%s (%s)" $title $units]
1543            }
1544        } else {
1545            set title $fname
1546        }
1547    }
1548    # If there's a title too, substract one more line
1549    if { $title != "" } {
1550        incr h -$lineht
1551    }
1552    if { $h < 1 } {
1553        return
1554    }
1555    # Set the legend on the first image dataset.
1556    if { $_currentColormap != "" && $_currentColormap != "none" } {
1557        #SendCmd "legend $_currentColormap scalar $_curFldName {} $w $h 0"
1558        SendCmd "legend2 $_currentColormap $w $h"
1559    }
1560}
1561
1562#
1563# SetCurrentColormap --
1564#
1565itcl::body Rappture::VtkImageViewer::SetCurrentColormap { name } {
1566    # Keep track of the colormaps that we build.
1567    if { $name != "none" && ![info exists _colormaps($name)] } {
1568        BuildColormap $name
1569        set _colormaps($name) 1
1570    }
1571    set _currentColormap $name
1572    SendCmd "image colormap $_currentColormap"
1573}
1574
1575
1576#
1577# BuildColormap --
1578#
1579#       Build the designated colormap on the server.
1580#
1581itcl::body Rappture::VtkImageViewer::BuildColormap { name } {
1582    set cmap [ColorsToColormap $name]
1583    if { [llength $cmap] == 0 } {
1584        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1585    }
1586    set wmap "0.0 1.0 1.0 1.0"
1587    SendCmd "colormap add $name { $cmap } { $wmap }"
1588}
1589
1590# ----------------------------------------------------------------------
1591# CONFIGURATION OPTION: -mode
1592# ----------------------------------------------------------------------
1593itcl::configbody Rappture::VtkImageViewer::mode {
1594    switch -- $itk_option(-mode) {
1595        "volume" {
1596            set _settings(-view3d) 1
1597        }
1598        "vtkimage" {
1599            set _settings(-view3d) 0
1600        }
1601        default {
1602            error "unknown mode settings \"$itk_option(-mode)\""
1603        }
1604    }
1605    if { !$_reset } {
1606        AdjustSetting -view3d
1607    }
1608}
1609
1610# ----------------------------------------------------------------------
1611# CONFIGURATION OPTION: -plotbackground
1612# ----------------------------------------------------------------------
1613itcl::configbody Rappture::VtkImageViewer::plotbackground {
1614    if { [isconnected] } {
1615        set rgb [Color2RGB $itk_option(-plotbackground)]
1616        if { !$_reset } {
1617            SendCmd "screen bgcolor $rgb"
1618        }
1619        $itk_component(view) configure -background $itk_option(-plotbackground)
1620    }
1621}
1622
1623# ----------------------------------------------------------------------
1624# CONFIGURATION OPTION: -plotforeground
1625# ----------------------------------------------------------------------
1626itcl::configbody Rappture::VtkImageViewer::plotforeground {
1627    if { [isconnected] } {
1628        set rgb [Color2RGB $itk_option(-plotforeground)]
1629        if { !$_reset } {
1630            SendCmd "axis color all $rgb"
1631            SendCmd "outline color $rgb"
1632        }
1633    }
1634}
1635
1636itcl::body Rappture::VtkImageViewer::BuildImageTab {} {
1637
1638    set fg [option get $itk_component(hull) font Font]
1639    #set bfg [option get $itk_component(hull) boldFont Font]
1640
1641    set inner [$itk_component(main) insert end \
1642        -title "Image Settings" \
1643        -icon [Rappture::icon contour2]]
1644    $inner configure -borderwidth 4
1645
1646    checkbutton $inner.legend \
1647        -text "Legend" \
1648        -variable [itcl::scope _settings(-legendvisible)] \
1649        -command [itcl::code $this AdjustSetting -legendvisible] \
1650        -font "Arial 9"
1651
1652    checkbutton $inner.outline \
1653        -text "Outline" \
1654        -variable [itcl::scope _settings(-outline)] \
1655        -command [itcl::code $this AdjustSetting -outline] \
1656        -font "Arial 9"
1657
1658    checkbutton $inner.backing \
1659        -text "Backing" \
1660        -variable [itcl::scope _settings(-backingvisible)] \
1661        -command [itcl::code $this AdjustSetting -backingvisible] \
1662        -font "Arial 9"
1663
1664    checkbutton $inner.stretch \
1665        -text "Stretch to fit" \
1666        -variable [itcl::scope _settings(-stretchtofit)] \
1667        -command [itcl::code $this AdjustSetting -stretchtofit] \
1668        -font "Arial 9"
1669
1670    checkbutton $inner.colormapDiscrete \
1671        -text "Discrete Colormap" \
1672        -variable [itcl::scope _settings(-colormapdiscrete)] \
1673        -command [itcl::code $this AdjustSetting -colormapdiscrete] \
1674        -font "Arial 9"
1675
1676    itk_component add field_l {
1677        label $inner.field_l -text "Field" -font "Arial 9"
1678    } {
1679        ignore -font
1680    }
1681    itk_component add field {
1682        Rappture::Combobox $inner.field -width 10 -editable no
1683    }
1684    bind $inner.field <<Value>> \
1685        [itcl::code $this AdjustSetting -field]
1686
1687    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1688    itk_component add colormap {
1689        Rappture::Combobox $inner.colormap -width 10 -editable no
1690    }
1691    $inner.colormap choices insert end [GetColormapList -includeNone]
1692
1693    $itk_component(colormap) value "BCGYR"
1694    bind $inner.colormap <<Value>> \
1695        [itcl::code $this AdjustSetting -colormap]
1696
1697    label $inner.backingcolor_l -text "Backing Color" -font "Arial 9"
1698    itk_component add backingcolor {
1699        Rappture::Combobox $inner.backingcolor -width 10 -editable no
1700    }
1701    $inner.backingcolor choices insert end \
1702        "black"              "black"            \
1703        "blue"               "blue"             \
1704        "cyan"               "cyan"             \
1705        "green"              "green"            \
1706        "grey"               "grey"             \
1707        "magenta"            "magenta"          \
1708        "orange"             "orange"           \
1709        "red"                "red"              \
1710        "white"              "white"            \
1711        "none"               "none"
1712
1713    $itk_component(backingcolor) value $_settings(-backingcolor)
1714    bind $inner.backingcolor <<Value>> \
1715        [itcl::code $this AdjustSetting -backingcolor]
1716
1717    label $inner.background_l -text "Background Color" -font "Arial 9"
1718    itk_component add background {
1719        Rappture::Combobox $inner.background -width 10 -editable no
1720    }
1721    $inner.background choices insert end \
1722        "black"              "black"            \
1723        "white"              "white"            \
1724        "grey"               "grey"             
1725
1726    $itk_component(background) value "white"
1727    bind $inner.background <<Value>> \
1728        [itcl::code $this AdjustSetting -background]
1729
1730    itk_component add opacity_l {
1731        label $inner.opacity_l -text "Opacity" -font "Arial 9"
1732    } {
1733        ignore -font
1734    }
1735    itk_component add opacity {
1736        ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1737            -variable [itcl::scope _settings(-opacity)] \
1738            -showvalue off \
1739            -command [itcl::code $this AdjustSetting -opacity]
1740    }
1741
1742    itk_component add window_l {
1743        label $inner.window_l -text "Window" -font "Arial 9"
1744    } {
1745        ignore -font
1746    }
1747    itk_component add window {
1748        ::scale $inner.window -from 0 -to 255 -orient horizontal \
1749            -variable [itcl::scope _settings(-window)] \
1750            -showvalue off \
1751            -command [itcl::code $this AdjustSetting -window]
1752    }
1753    itk_component add level_l {
1754        label $inner.level_l -text "Level" -font "Arial 9"
1755    } {
1756        ignore -font
1757    }
1758    itk_component add level {
1759        ::scale $inner.level -from 0 -to 255 -orient horizontal \
1760            -variable [itcl::scope _settings(-level)] \
1761            -showvalue off \
1762            -command [itcl::code $this AdjustSetting -level]
1763    }
1764
1765    frame $inner.separator1 -height 2 -relief sunken -bd 1
1766    frame $inner.separator2 -height 2 -relief sunken -bd 1
1767
1768    blt::table $inner \
1769        0,0 $inner.field_l -anchor w -pady 2 \
1770        0,1 $inner.field -anchor w -pady 2 -fill x \
1771        1,0 $inner.colormap_l -anchor w -pady 2  \
1772        1,1 $inner.colormap   -anchor w -pady 2 -fill x  \
1773        2,0 $inner.backingcolor_l  -anchor w -pady 2  \
1774        2,1 $inner.backingcolor    -anchor w -pady 2 -fill x  \
1775        3,0 $inner.background_l -anchor w -pady 2 \
1776        3,1 $inner.background -anchor w -pady 2  -fill x \
1777        4,0 $inner.backing -anchor w -pady 2 -cspan 2 \
1778        5,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
1779        7,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1780        8,0 $inner.colormapDiscrete -anchor w -pady 2 -cspan 2 \
1781        11,0 $inner.separator1 -padx 2 -fill x -cspan 2 \
1782        12,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
1783        13,0 $inner.separator2 -padx 2 -fill x -cspan 2 \
1784        15,0 $inner.opacity_l -anchor w -pady 2 \
1785        15,1 $inner.opacity   -fill x   -pady 2 \
1786        16,0 $inner.window_l -anchor w -pady 2 \
1787        16,1 $inner.window   -fill x   -pady 2 \
1788        17,0 $inner.level_l -anchor w -pady 2 \
1789        17,1 $inner.level   -fill x   -pady 2
1790
1791    blt::table configure $inner r* c* -resize none
1792    blt::table configure $inner r19 c1 -resize expand
1793}
1794
1795itcl::body Rappture::VtkImageViewer::BuildAxisTab {} {
1796
1797    set fg [option get $itk_component(hull) font Font]
1798    #set bfg [option get $itk_component(hull) boldFont Font]
1799
1800    set inner [$itk_component(main) insert end \
1801        -title "Axis Settings" \
1802        -icon [Rappture::icon axis2]]
1803    $inner configure -borderwidth 4
1804
1805    checkbutton $inner.visible \
1806        -text "Axes" \
1807        -variable [itcl::scope _settings(-axisvisible)] \
1808        -command [itcl::code $this AdjustSetting -axisvisible] \
1809        -font "Arial 9"
1810    checkbutton $inner.labels \
1811        -text "Axis Labels" \
1812        -variable [itcl::scope _settings(-axislabels)] \
1813        -command [itcl::code $this AdjustSetting -axislabels] \
1814        -font "Arial 9"
1815    label $inner.grid_l -text "Grid" -font "Arial 9"
1816    checkbutton $inner.xgrid \
1817        -text "X" \
1818        -variable [itcl::scope _settings(-xgrid)] \
1819        -command [itcl::code $this AdjustSetting -xgrid] \
1820        -font "Arial 9"
1821    checkbutton $inner.ygrid \
1822        -text "Y" \
1823        -variable [itcl::scope _settings(-ygrid)] \
1824        -command [itcl::code $this AdjustSetting -ygrid] \
1825        -font "Arial 9"
1826    checkbutton $inner.zgrid \
1827        -text "Z" \
1828        -variable [itcl::scope _settings(-zgrid)] \
1829        -command [itcl::code $this AdjustSetting -zgrid] \
1830        -font "Arial 9"
1831    checkbutton $inner.minorticks \
1832        -text "Minor Ticks" \
1833        -variable [itcl::scope _settings(-axisminorticks)] \
1834        -command [itcl::code $this AdjustSetting -axisminorticks] \
1835        -font "Arial 9"
1836
1837    label $inner.mode_l -text "Mode" -font "Arial 9"
1838
1839    itk_component add axisflymode {
1840        Rappture::Combobox $inner.mode -width 10 -editable no
1841    }
1842    $inner.mode choices insert end \
1843        "static_triad"    "static" \
1844        "closest_triad"   "closest" \
1845        "furthest_triad"  "farthest" \
1846        "outer_edges"     "outer"         
1847    $itk_component(axisflymode) value $_settings(-axisflymode)
1848    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axisflymode]
1849
1850    blt::table $inner \
1851        0,0 $inner.visible -anchor w -cspan 4 \
1852        1,0 $inner.labels  -anchor w -cspan 4 \
1853        2,0 $inner.minorticks  -anchor w -cspan 4 \
1854        4,0 $inner.grid_l  -anchor w \
1855        4,1 $inner.xgrid   -anchor w \
1856        4,2 $inner.ygrid   -anchor w \
1857        4,3 $inner.zgrid   -anchor w \
1858        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1859        5,1 $inner.mode    -fill x -cspan 3
1860
1861    blt::table configure $inner r* c* -resize none
1862    blt::table configure $inner r7 c6 -resize expand
1863    blt::table configure $inner r3 -height 0.125i
1864}
1865
1866itcl::body Rappture::VtkImageViewer::BuildCameraTab {} {
1867    set inner [$itk_component(main) insert end \
1868        -title "Camera Settings" \
1869        -icon [Rappture::icon camera]]
1870    $inner configure -borderwidth 4
1871
1872    label $inner.view_l -text "view" -font "Arial 9"
1873    set f [frame $inner.view]
1874    foreach side { front back left right top bottom } {
1875        button $f.$side  -image [Rappture::icon view$side] \
1876            -command [itcl::code $this SetOrientation $side]
1877        Rappture::Tooltip::for $f.$side "Change the view to $side"
1878        pack $f.$side -side left
1879    }
1880
1881    blt::table $inner \
1882        0,0 $inner.view_l -anchor e -pady 2 \
1883        0,1 $inner.view -anchor w -pady 2
1884    blt::table configure $inner r0 -resize none
1885
1886    set labels { qx qy qz qw xpan ypan zoom }
1887    set row 1
1888    foreach tag $labels {
1889        label $inner.${tag}label -text $tag -font "Arial 9"
1890        entry $inner.${tag} -font "Arial 9"  -bg white \
1891            -textvariable [itcl::scope _view(-$tag)]
1892        bind $inner.${tag} <Return> \
1893            [itcl::code $this camera set -${tag}]
1894        bind $inner.${tag} <KP_Enter> \
1895            [itcl::code $this camera set -${tag}]
1896        blt::table $inner \
1897            $row,0 $inner.${tag}label -anchor e -pady 2 \
1898            $row,1 $inner.${tag} -anchor w -pady 2
1899        blt::table configure $inner r$row -resize none
1900        incr row
1901    }
1902    checkbutton $inner.ortho \
1903        -text "Orthographic Projection" \
1904        -variable [itcl::scope _view(-ortho)] \
1905        -command [itcl::code $this camera set -ortho] \
1906        -font "Arial 9"
1907    blt::table $inner \
1908            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1909    blt::table configure $inner r$row -resize none
1910    incr row
1911
1912    blt::table configure $inner c* -resize none
1913    blt::table configure $inner c2 -resize expand
1914    blt::table configure $inner r$row -resize expand
1915}
1916
1917#
1918#  camera --
1919#
1920itcl::body Rappture::VtkImageViewer::camera {option args} {
1921    switch -- $option {
1922        "show" {
1923            puts [array get _view]
1924        }
1925        "set" {
1926            set what [lindex $args 0]
1927            set x $_view($what)
1928            set code [catch { string is double $x } result]
1929            if { $code != 0 || !$result } {
1930                return
1931            }
1932            switch -- $what {
1933                "-ortho" {
1934                    if {$_view($what)} {
1935                        SendCmd "camera mode ortho"
1936                    } else {
1937                        SendCmd "camera mode persp"
1938                    }
1939                }
1940                "-xpan" - "-ypan" {
1941                    PanCamera
1942                }
1943                "-qx" - "-qy" - "-qz" - "-qw" {
1944                    set q [ViewToQuaternion]
1945                    $_arcball quaternion $q
1946                    EventuallyRotate $q
1947                }
1948                "-zoom" {
1949                    SendCmd "camera zoom $_view($what)"
1950                }
1951            }
1952        }
1953    }
1954}
1955
1956itcl::body Rappture::VtkImageViewer::GetVtkData { args } {
1957    set bytes ""
1958    foreach dataobj [get] {
1959        foreach comp [$dataobj components] {
1960            set tag $dataobj-$comp
1961            set contents [$dataobj vtkdata $comp]
1962            append bytes "$contents\n"
1963        }
1964    }
1965    return [list .vtk $bytes]
1966}
1967
1968itcl::body Rappture::VtkImageViewer::GetImage { args } {
1969    if { [image width $_image(download)] > 0 &&
1970         [image height $_image(download)] > 0 } {
1971        set bytes [$_image(download) data -format "jpeg -quality 100"]
1972        set bytes [Rappture::encoding::decode -as b64 $bytes]
1973        return [list .jpg $bytes]
1974    }
1975    return ""
1976}
1977
1978itcl::body Rappture::VtkImageViewer::BuildDownloadPopup { popup command } {
1979    Rappture::Balloon $popup \
1980        -title "[Rappture::filexfer::label downloadWord] as..."
1981    set inner [$popup component inner]
1982    label $inner.summary -text "" -anchor w
1983    radiobutton $inner.vtk_button -text "VTK data file" \
1984        -variable [itcl::scope _downloadPopup(format)] \
1985        -font "Arial 9 " \
1986        -value vtk 
1987    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
1988    radiobutton $inner.image_button -text "Image File" \
1989        -variable [itcl::scope _downloadPopup(format)] \
1990        -font "Arial 9 " \
1991        -value image
1992    Rappture::Tooltip::for $inner.image_button \
1993        "Save as digital image."
1994
1995    button $inner.ok -text "Save" \
1996        -highlightthickness 0 -pady 2 -padx 3 \
1997        -command $command \
1998        -compound left \
1999        -image [Rappture::icon download]
2000
2001    button $inner.cancel -text "Cancel" \
2002        -highlightthickness 0 -pady 2 -padx 3 \
2003        -command [list $popup deactivate] \
2004        -compound left \
2005        -image [Rappture::icon cancel]
2006
2007    blt::table $inner \
2008        0,0 $inner.summary -cspan 2  \
2009        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2010        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2011        4,1 $inner.cancel -width .9i -fill y \
2012        4,0 $inner.ok -padx 2 -width .9i -fill y
2013    blt::table configure $inner r3 -height 4
2014    blt::table configure $inner r4 -pady 4
2015    raise $inner.image_button
2016    $inner.vtk_button invoke
2017    return $inner
2018}
2019
2020#
2021# SetObjectStyle --
2022#
2023#       Set the style of the image/contour object.  This gets calls
2024#       for each dataset once as it is loaded.  It can overridden by
2025#       the user controls.
2026#
2027#
2028itcl::body Rappture::VtkImageViewer::SetObjectStyle { dataobj comp } {
2029    # Parse style string.
2030    set tag $dataobj-$comp
2031    array set style {
2032        -color none
2033        -opacity 1.0
2034    }
2035    set stylelist [$dataobj style $comp]
2036    if { $stylelist != "" } {
2037        array set style $stylelist
2038    }
2039    # This is too complicated.  We want to set the colormap, number of
2040    # isolines and opacity for the dataset.  They can be the default values,
2041    # the style hints loaded with the dataset, or set by user controls.  As
2042    # datasets get loaded, they first use the defaults that are overidden
2043    # by the style hints.  If the user changes the global controls, then that
2044    # overrides everything else.  I don't know what it means when global
2045    # controls are specified as style hints by each dataset.  It complicates
2046    # the code to handle aberrant cases.
2047
2048    if { $_changed(-opacity) } {
2049        set style(-opacity) [expr $_settings(-opacity) * 0.01]
2050    }
2051    if { $_changed(-colormap) } {
2052        set style(-color) $_settings(-colormap)
2053    }
2054    if { $_currentColormap == "" } {
2055        $itk_component(colormap) value $style(-color)
2056    }
2057    if { [info exists style(-stretchtofit)] } {
2058        set _settings(-stretchtofit) $style(-stretchtofit)
2059        AdjustSetting -stretchToFit
2060    }
2061    SendCmd "outline add $tag"
2062    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2063    SendCmd "outline visible $_settings(-outline) $tag"
2064    SendCmd "image add $tag"
2065    SetCurrentColormap $style(-color)
2066    set color [$itk_component(backingcolor) value]
2067    SendCmd "image color [Color2RGB $color] $tag"
2068    SendCmd "image opacity $style(-opacity) $tag"
2069    set _settings(-opacity) [expr $style(-opacity) * 100.0]
2070}
2071
2072itcl::body Rappture::VtkImageViewer::IsValidObject { dataobj } {
2073    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2074        return 0
2075    }
2076    return 1
2077}
2078
2079# ----------------------------------------------------------------------
2080# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2081#
2082# Invoked automatically whenever the "legend" command comes in from
2083# the rendering server.  Indicates that binary image data with the
2084# specified <size> will follow.
2085# ----------------------------------------------------------------------
2086itcl::body Rappture::VtkImageViewer::ReceiveLegend { colormap title min max size } {
2087    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2088    if { [isconnected] } {
2089        set bytes [ReceiveBytes $size]
2090        if { ![info exists _image(legend)] } {
2091            set _image(legend) [image create photo]
2092        }
2093        $_image(legend) configure -data $bytes
2094        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2095        if { [catch {DrawLegend} errs] != 0 } {
2096            global errorInfo
2097            puts stderr "errs=$errs errorInfo=$errorInfo"
2098        }
2099    }
2100}
2101
2102#
2103# DrawLegend --
2104#
2105#       Draws the legend in the own canvas on the right side of the plot area.
2106#
2107itcl::body Rappture::VtkImageViewer::DrawLegend {} {
2108    set fname $_curFldName
2109    set c $itk_component(view)
2110    set w [winfo width $c]
2111    set h [winfo height $c]
2112    set font "Arial 8"
2113    set lineht [font metrics $font -linespace]
2114   
2115    if { [string match "component*" $fname] } {
2116        set title ""
2117    } else {
2118        if { [info exists _fields($fname)] } {
2119            foreach { title units } $_fields($fname) break
2120            if { $units != "" } {
2121                set title [format "%s (%s)" $title $units]
2122            }
2123        } else {
2124            set title $fname
2125        }
2126    }
2127    set x [expr $w - 2]
2128    if { !$_settings(-legendvisible) } {
2129        $c delete legend
2130        return
2131    }
2132    if { [$c find withtag "legend"] == "" } {
2133        set y 2
2134        # If there's a legend title, create a text item for the title.
2135        $c create text $x $y \
2136            -anchor ne \
2137            -fill $itk_option(-plotforeground) -tags "title legend" \
2138            -font $font
2139        if { $title != "" } {
2140            incr y $lineht
2141        }
2142        $c create text $x $y \
2143            -anchor ne \
2144            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2145            -font $font
2146        incr y $lineht
2147        $c create image $x $y \
2148            -anchor ne \
2149            -image $_image(legend) -tags "colormap legend"
2150        $c create rectangle $x $y 1 1 \
2151            -fill "" -outline "" -tags "sensor legend"
2152        $c create text $x [expr {$h-2}] \
2153            -anchor se \
2154            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2155            -font $font
2156        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2157        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2158        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2159    }
2160
2161    set x2 $x
2162    set iw [image width $_image(legend)]
2163    set ih [image height $_image(legend)]
2164    set x1 [expr $x2 - ($iw*12)/10]
2165
2166    $c bind title <ButtonPress> [itcl::code $this Combo post]
2167    $c bind title <Enter> [itcl::code $this Combo activate]
2168    $c bind title <Leave> [itcl::code $this Combo deactivate]
2169    # Reset the item coordinates according the current size of the plot.
2170    if { [info exists _limits($_curFldName)] } {
2171        foreach { vmin vmax } $_limits($_curFldName) break
2172        $c itemconfigure vmin -text [format %g $vmin]
2173        $c itemconfigure vmax -text [format %g $vmax]
2174    }
2175    set y 2
2176    # If there's a legend title, move the title to the correct position
2177    if { $title != "" } {
2178        $c itemconfigure title -text $title
2179        $c coords title $x $y
2180        incr y $lineht
2181    }
2182    $c coords vmax $x $y
2183    incr y $lineht
2184    $c coords colormap $x $y
2185    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2186    $c raise sensor
2187    $c coords vmin $x [expr {$h - 2}]
2188}
2189
2190#
2191# EnterLegend --
2192#
2193itcl::body Rappture::VtkImageViewer::EnterLegend { x y } {
2194    SetLegendTip $x $y
2195}
2196
2197#
2198# MotionLegend --
2199#
2200itcl::body Rappture::VtkImageViewer::MotionLegend { x y } {
2201    Rappture::Tooltip::tooltip cancel
2202    set c $itk_component(view)
2203    set cw [winfo width $c]
2204    set ch [winfo height $c]
2205    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2206        SetLegendTip $x $y
2207    }
2208}
2209
2210#
2211# LeaveLegend --
2212#
2213itcl::body Rappture::VtkImageViewer::LeaveLegend { } {
2214    Rappture::Tooltip::tooltip cancel
2215    .rappturetooltip configure -icon ""
2216}
2217
2218#
2219# SetLegendTip --
2220#
2221itcl::body Rappture::VtkImageViewer::SetLegendTip { x y } {
2222    set fname $_curFldName
2223    set c $itk_component(view)
2224    set w [winfo width $c]
2225    set h [winfo height $c]
2226    set font "Arial 8"
2227    set lineht [font metrics $font -linespace]
2228   
2229    set ih [image height $_image(legend)]
2230    # Subtract off the offset of the color ramp from the top of the canvas
2231    set iy [expr $y - ($lineht + 2)]
2232
2233    if { [string match "component*" $fname] } {
2234        set title ""
2235    } else {
2236        if { [info exists _fields($fname)] } {
2237            foreach { title units } $_fields($fname) break
2238            if { $units != "" } {
2239                set title [format "%s (%s)" $title $units]
2240            }
2241        } else {
2242            set title $fname
2243        }
2244    }
2245    # If there's a legend title, increase the offset by the line height.
2246    if { $title != "" } {
2247        incr iy -$lineht
2248    }
2249
2250    # Make a swatch of the selected color
2251    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2252        return
2253    }
2254
2255    if { ![info exists _image(swatch)] } {
2256        set _image(swatch) [image create photo -width 24 -height 24]
2257    }
2258    set color [eval format "\#%02x%02x%02x" $pixel]
2259    $_image(swatch) put black  -to 0 0 23 23
2260    $_image(swatch) put $color -to 1 1 22 22
2261
2262    # Compute the value of the point
2263    if { [info exists _limits($fname)] } {
2264        foreach { vmin vmax } $_limits($fname) break
2265        set t [expr 1.0 - (double($iy) / double($ih-1))]
2266        set value [expr $t * ($vmax - $vmin) + $vmin]
2267    } else {
2268        set value 0.0
2269    }
2270    set tipx [expr $x + 15]
2271    set tipy [expr $y - 5]
2272    .rappturetooltip configure -icon $_image(swatch)
2273    if { [info exists _isolines($y)] } {
2274        Rappture::Tooltip::text $c [format "$title %g (isoline)" $_isolines($y)]
2275    } else {
2276        Rappture::Tooltip::text $c [format "$title %g" $value]
2277    }
2278    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2279}
2280
2281# ----------------------------------------------------------------------
2282# USAGE: _dropdown post
2283# USAGE: _dropdown unpost
2284# USAGE: _dropdown select
2285#
2286# Used internally to handle the dropdown list for this combobox.  The
2287# post/unpost options are invoked when the list is posted or unposted
2288# to manage the relief of the controlling button.  The select option
2289# is invoked whenever there is a selection from the list, to assign
2290# the value back to the gauge.
2291# ----------------------------------------------------------------------
2292itcl::body Rappture::VtkImageViewer::Combo {option} {
2293    set c $itk_component(view)
2294    switch -- $option {
2295        post {
2296            foreach { x1 y1 x2 y2 } [$c bbox title] break
2297            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2298            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2299            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2300            tk_popup $itk_component(fieldmenu) $x $y
2301        }
2302        activate {
2303            $c itemconfigure title -fill red
2304        }
2305        deactivate {
2306            $c itemconfigure title -fill $itk_option(-plotforeground)
2307        }
2308        invoke {
2309            $itk_component(field) value $_curFldLabel
2310            AdjustSetting -field
2311        }
2312        default {
2313            error "bad option \"$option\": should be post, unpost, select"
2314        }
2315    }
2316}
2317
2318itcl::body Rappture::VtkImageViewer::SetOrientation { side } {
2319    array set positions {
2320        front  "0.707107 0.707107 0 0"
2321        back   "0 0 0.707107 0.707107"
2322        left   "0.5 0.5 -0.5 -0.5"
2323        right  "0.5 0.5 0.5 0.5"
2324        top    "1 0 0 0"
2325        bottom "0 1 0 0"
2326    }
2327    foreach name { -qw -qx -qy -qz } value $positions($side) {
2328        set _view($name) $value
2329    }
2330    set q [ViewToQuaternion]
2331    $_arcball quaternion $q
2332    SendCmd "camera orient $q"
2333    SendCmd "camera reset"
2334    set _view(-xpan) 0
2335    set _view(-ypan) 0
2336    set _view(-zoom) 1.0
2337}
Note: See TracBrowser for help on using the repository browser.