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

Last change on this file since 4768 was 4768, checked in by ldelgass, 6 years ago

merge r4767 from trunk

File size: 77.0 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            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 axisXGrid axisYGrid axisZGrid \
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        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1331            set axis [string tolower [string range $what 4 4]]
1332            set bool $_settings($what)
1333            SendCmd "axis grid $axis $bool"
1334        }
1335        "background" {
1336            set bg [$itk_component(background) value]
1337            array set fgcolors {
1338                "black" "white"
1339                "white" "black"
1340                "grey"  "black"
1341            }
1342            set fg $fgcolors($bg)
1343            configure -plotbackground $bg -plotforeground $fg
1344            $itk_component(view) delete "legend"
1345            SendCmd "screen bgcolor [Color2RGB $bg]"
1346            SendCmd "outline color [Color2RGB $fg]"
1347            SendCmd "axis color all [Color2RGB $fg]"
1348            DrawLegend
1349        }
1350        "backingColor" {
1351            set color [$itk_component(backingcolor) value]
1352            if { $color == "none" } {
1353                if { $_settings(backingVisible) } {
1354                    SendCmd "image backing 0"
1355                    set _settings(backingVisible) 0
1356                }
1357            } else {
1358                if { !$_settings(backingVisible) } {
1359                    SendCmd "image backing 1"
1360                    set _settings(backingVisible) 1
1361                }
1362                SendCmd "image color [Color2RGB $color]"
1363            }
1364        }
1365        "backingVisible" {
1366            set bool $_settings($what)
1367            SendCmd "image backing $bool"
1368        }
1369        "colormap" {
1370            set _changed($what) 1
1371            StartBufferingCommands
1372            set color [$itk_component(colormap) value]
1373            set _settings($what) $color
1374            SetCurrentColormap $color
1375            if {$_settings(colormapDiscrete)} {
1376                 SendCmd "colormap res $_settings(numColors) $color"
1377            }
1378            StopBufferingCommands
1379            EventuallyRequestLegend
1380        }
1381        "colormapDiscrete" {
1382            set bool $_settings($what)
1383            StartBufferingCommands
1384            if {$bool} {
1385                SendCmd "colormap res $_settings(numColors)"
1386            } else {
1387                SendCmd "colormap res default"
1388            }
1389            StopBufferingCommands
1390            EventuallyRequestLegend
1391        }
1392        "field" {
1393            set label [$itk_component(field) value]
1394            set fname [$itk_component(field) translate $label]
1395            set _settings($what) $fname
1396            if { [info exists _fields($fname)] } {
1397                foreach { label units components } $_fields($fname) break
1398                if { $components > 1 } {
1399                    set _colorMode vmag
1400                } else {
1401                    set _colorMode scalar
1402                }
1403                set _curFldName $fname
1404                set _curFldLabel $label
1405            } else {
1406                puts stderr "unknown field \"$fname\""
1407                return
1408            }
1409
1410            # Get the new limits because the field changed.
1411            SendCmd "dataset scalar $_curFldName"
1412            #SendCmd "image colormode scalar $_curFldName"
1413            SendCmd "camera reset"
1414            DrawLegend
1415        }
1416        "view3D" {
1417            set bool $_settings($what)
1418            set c $itk_component(view)
1419            StartBufferingCommands
1420            # Fix image scale: 0 for contours, 1 for images.
1421            if { $bool } {
1422                set _settings(opacity) $_settings(saveOpacity)
1423            } else {
1424                set _settings(opacity) 100
1425            }
1426            AdjustSetting opacity
1427            if { $bool } {
1428                $itk_component(opacity) configure -state normal
1429                $itk_component(opacity_l) configure -state normal
1430                if {$_view(-ortho)} {
1431                    SendCmd "camera mode ortho"
1432                } else {
1433                    SendCmd "camera mode persp"
1434                }
1435                SendCmd "camera aspect native"
1436            } else {
1437                $itk_component(opacity) configure -state disabled
1438                $itk_component(opacity_l) configure -state disabled
1439                SendCmd "camera mode image"
1440                if {$_settings(stretchToFit)} {
1441                    SendCmd "camera aspect window"
1442                }
1443            }
1444            if { $bool } {
1445                set q [ViewToQuaternion]
1446                $_arcball quaternion $q
1447                SendCmd "camera orient $q"
1448            } else {
1449                bind $c <ButtonPress-1> {}
1450                bind $c <B1-Motion> {}
1451                bind $c <ButtonRelease-1> {}
1452            }
1453            SendCmd "camera reset"
1454            # Fix the mouse bindings for rotation/panning and the
1455            # camera mode. Ideally we'd create a bindtag for these.
1456            if { $bool } {
1457                # Bindings for rotation via mouse
1458                bind $c <ButtonPress-1> \
1459                    [itcl::code $this Rotate click %x %y]
1460                bind $c <B1-Motion> \
1461                    [itcl::code $this Rotate drag %x %y]
1462                bind $c <ButtonRelease-1> \
1463                    [itcl::code $this Rotate release %x %y]
1464            }
1465            StopBufferingCommands
1466        }
1467        "window" {
1468            set val $_settings($what)
1469            SendCmd "image window $val"
1470        }
1471        "level" {
1472            set val $_settings($what)
1473            SendCmd "image level $val"
1474        }
1475        "legendVisible" {
1476            if { !$_settings($what) } {
1477                $itk_component(view) delete legend
1478            }
1479            DrawLegend
1480        }
1481        "opacity" {
1482            set _changed($what) 1
1483            if { $_settings(view3D) } {
1484                set _settings(saveOpacity) $_settings($what)
1485                set val [expr $_settings($what) * 0.01]
1486                SendCmd "image opacity $val"
1487            } else {
1488                SendCmd "image opacity 1.0"
1489            }
1490        }
1491        "outline" {
1492            set bool $_settings($what)
1493            SendCmd "outline visible $bool"
1494        }
1495        "stretchToFit" {
1496            set bool $_settings($what)
1497            if { $bool } {
1498                if { $_settings(view3D) } {
1499                    SendCmd "camera aspect native"
1500                } else {
1501                    SendCmd "camera aspect window"
1502                }
1503            } else {
1504                SendCmd "camera aspect native"
1505            }
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 "white"
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>> [itcl::code $this AdjustSetting background]
1728
1729    itk_component add opacity_l {
1730        label $inner.opacity_l -text "Opacity" -font "Arial 9"
1731    } {
1732        ignore -font
1733    }
1734    itk_component add opacity {
1735        ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1736            -variable [itcl::scope _settings(opacity)] \
1737            -showvalue off \
1738            -command [itcl::code $this AdjustSetting opacity]
1739    }
1740
1741    itk_component add window_l {
1742        label $inner.window_l -text "Window" -font "Arial 9"
1743    } {
1744        ignore -font
1745    }
1746    itk_component add window {
1747        ::scale $inner.window -from 0 -to 255 -orient horizontal \
1748            -variable [itcl::scope _settings(window)] \
1749            -showvalue off \
1750            -command [itcl::code $this AdjustSetting window]
1751    }
1752    itk_component add level_l {
1753        label $inner.level_l -text "Level" -font "Arial 9"
1754    } {
1755        ignore -font
1756    }
1757    itk_component add level {
1758        ::scale $inner.level -from 0 -to 255 -orient horizontal \
1759            -variable [itcl::scope _settings(level)] \
1760            -showvalue off \
1761            -command [itcl::code $this AdjustSetting level]
1762    }
1763
1764    frame $inner.separator1 -height 2 -relief sunken -bd 1
1765    frame $inner.separator2 -height 2 -relief sunken -bd 1
1766
1767    blt::table $inner \
1768        0,0 $inner.field_l -anchor w -pady 2 \
1769        0,1 $inner.field -anchor w -pady 2 -fill x \
1770        1,0 $inner.colormap_l -anchor w -pady 2  \
1771        1,1 $inner.colormap   -anchor w -pady 2 -fill x  \
1772        2,0 $inner.backingcolor_l  -anchor w -pady 2  \
1773        2,1 $inner.backingcolor    -anchor w -pady 2 -fill x  \
1774        3,0 $inner.background_l -anchor w -pady 2 \
1775        3,1 $inner.background -anchor w -pady 2  -fill x \
1776        4,0 $inner.backing -anchor w -pady 2 -cspan 2 \
1777        5,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
1778        7,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1779        8,0 $inner.colormapDiscrete -anchor w -pady 2 -cspan 2 \
1780        11,0 $inner.separator1 -padx 2 -fill x -cspan 2 \
1781        12,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
1782        13,0 $inner.separator2 -padx 2 -fill x -cspan 2 \
1783        15,0 $inner.opacity_l -anchor w -pady 2 \
1784        15,1 $inner.opacity   -fill x   -pady 2 \
1785        16,0 $inner.window_l -anchor w -pady 2 \
1786        16,1 $inner.window   -fill x   -pady 2 \
1787        17,0 $inner.level_l -anchor w -pady 2 \
1788        17,1 $inner.level   -fill x   -pady 2
1789
1790    blt::table configure $inner r* c* -resize none
1791    blt::table configure $inner r19 c1 -resize expand
1792}
1793
1794itcl::body Rappture::VtkImageViewer::BuildAxisTab {} {
1795
1796    set fg [option get $itk_component(hull) font Font]
1797    #set bfg [option get $itk_component(hull) boldFont Font]
1798
1799    set inner [$itk_component(main) insert end \
1800        -title "Axis Settings" \
1801        -icon [Rappture::icon axis2]]
1802    $inner configure -borderwidth 4
1803
1804    checkbutton $inner.visible \
1805        -text "Axes" \
1806        -variable [itcl::scope _settings(axisVisible)] \
1807        -command [itcl::code $this AdjustSetting axisVisible] \
1808        -font "Arial 9"
1809    checkbutton $inner.labels \
1810        -text "Axis Labels" \
1811        -variable [itcl::scope _settings(axisLabels)] \
1812        -command [itcl::code $this AdjustSetting axisLabels] \
1813        -font "Arial 9"
1814    label $inner.grid_l -text "Grid" -font "Arial 9"
1815    checkbutton $inner.xgrid \
1816        -text "X" \
1817        -variable [itcl::scope _settings(axisXGrid)] \
1818        -command [itcl::code $this AdjustSetting axisXGrid] \
1819        -font "Arial 9"
1820    checkbutton $inner.ygrid \
1821        -text "Y" \
1822        -variable [itcl::scope _settings(axisYGrid)] \
1823        -command [itcl::code $this AdjustSetting axisYGrid] \
1824        -font "Arial 9"
1825    checkbutton $inner.zgrid \
1826        -text "Z" \
1827        -variable [itcl::scope _settings(axisZGrid)] \
1828        -command [itcl::code $this AdjustSetting axisZGrid] \
1829        -font "Arial 9"
1830    checkbutton $inner.minorticks \
1831        -text "Minor Ticks" \
1832        -variable [itcl::scope _settings(axisMinorTicks)] \
1833        -command [itcl::code $this AdjustSetting axisMinorTicks] \
1834        -font "Arial 9"
1835
1836    label $inner.mode_l -text "Mode" -font "Arial 9"
1837
1838    itk_component add axisflymode {
1839        Rappture::Combobox $inner.mode -width 10 -editable no
1840    }
1841    $inner.mode choices insert end \
1842        "static_triad"    "static" \
1843        "closest_triad"   "closest" \
1844        "furthest_triad"  "farthest" \
1845        "outer_edges"     "outer"         
1846    $itk_component(axisflymode) value "static"
1847    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisFlymode]
1848
1849    blt::table $inner \
1850        0,0 $inner.visible -anchor w -cspan 4 \
1851        1,0 $inner.labels  -anchor w -cspan 4 \
1852        2,0 $inner.minorticks  -anchor w -cspan 4 \
1853        4,0 $inner.grid_l  -anchor w \
1854        4,1 $inner.xgrid   -anchor w \
1855        4,2 $inner.ygrid   -anchor w \
1856        4,3 $inner.zgrid   -anchor w \
1857        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1858        5,1 $inner.mode    -fill x -cspan 3
1859
1860    blt::table configure $inner r* c* -resize none
1861    blt::table configure $inner r7 c6 -resize expand
1862    blt::table configure $inner r3 -height 0.125i
1863}
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
1885    set labels { qx qy qz qw xpan ypan zoom }
1886    set row 1
1887    foreach tag $labels {
1888        label $inner.${tag}label -text $tag -font "Arial 9"
1889        entry $inner.${tag} -font "Arial 9"  -bg white \
1890            -textvariable [itcl::scope _view(-$tag)]
1891        bind $inner.${tag} <Return> \
1892            [itcl::code $this camera set -${tag}]
1893        bind $inner.${tag} <KP_Enter> \
1894            [itcl::code $this camera set -${tag}]
1895        blt::table $inner \
1896            $row,0 $inner.${tag}label -anchor e -pady 2 \
1897            $row,1 $inner.${tag} -anchor w -pady 2
1898        blt::table configure $inner r$row -resize none
1899        incr row
1900    }
1901    checkbutton $inner.ortho \
1902        -text "Orthographic Projection" \
1903        -variable [itcl::scope _view(-ortho)] \
1904        -command [itcl::code $this camera set -ortho] \
1905        -font "Arial 9"
1906    blt::table $inner \
1907            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1908    blt::table configure $inner r$row -resize none
1909    incr row
1910
1911    blt::table configure $inner c* r* -resize none
1912    blt::table configure $inner c2 -resize expand
1913    blt::table configure $inner r$row -resize expand
1914}
1915
1916#
1917#  camera --
1918#
1919itcl::body Rappture::VtkImageViewer::camera {option args} {
1920    switch -- $option {
1921        "show" {
1922            puts [array get _view]
1923        }
1924        "set" {
1925            set what [lindex $args 0]
1926            set x $_view($what)
1927            set code [catch { string is double $x } result]
1928            if { $code != 0 || !$result } {
1929                return
1930            }
1931            switch -- $what {
1932                "-ortho" {
1933                    if {$_view($what)} {
1934                        SendCmd "camera mode ortho"
1935                    } else {
1936                        SendCmd "camera mode persp"
1937                    }
1938                }
1939                "-xpan" - "-ypan" {
1940                    PanCamera
1941                }
1942                "-qx" - "-qy" - "-qz" - "-qw" {
1943                    set q [ViewToQuaternion]
1944                    $_arcball quaternion $q
1945                    EventuallyRotate $q
1946                }
1947                "-zoom" {
1948                    SendCmd "camera zoom $_view($what)"
1949                }
1950            }
1951        }
1952    }
1953}
1954
1955itcl::body Rappture::VtkImageViewer::GetVtkData { args } {
1956    set bytes ""
1957    foreach dataobj [get] {
1958        foreach comp [$dataobj components] {
1959            set tag $dataobj-$comp
1960            set contents [$dataobj vtkdata $comp]
1961            append bytes "$contents\n"
1962        }
1963    }
1964    return [list .vtk $bytes]
1965}
1966
1967itcl::body Rappture::VtkImageViewer::GetImage { args } {
1968    if { [image width $_image(download)] > 0 &&
1969         [image height $_image(download)] > 0 } {
1970        set bytes [$_image(download) data -format "jpeg -quality 100"]
1971        set bytes [Rappture::encoding::decode -as b64 $bytes]
1972        return [list .jpg $bytes]
1973    }
1974    return ""
1975}
1976
1977itcl::body Rappture::VtkImageViewer::BuildDownloadPopup { popup command } {
1978    Rappture::Balloon $popup \
1979        -title "[Rappture::filexfer::label downloadWord] as..."
1980    set inner [$popup component inner]
1981    label $inner.summary -text "" -anchor w
1982    radiobutton $inner.vtk_button -text "VTK data file" \
1983        -variable [itcl::scope _downloadPopup(format)] \
1984        -font "Arial 9 " \
1985        -value vtk 
1986    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
1987    radiobutton $inner.image_button -text "Image File" \
1988        -variable [itcl::scope _downloadPopup(format)] \
1989        -font "Arial 9 " \
1990        -value image
1991    Rappture::Tooltip::for $inner.image_button \
1992        "Save as digital image."
1993
1994    button $inner.ok -text "Save" \
1995        -highlightthickness 0 -pady 2 -padx 3 \
1996        -command $command \
1997        -compound left \
1998        -image [Rappture::icon download]
1999
2000    button $inner.cancel -text "Cancel" \
2001        -highlightthickness 0 -pady 2 -padx 3 \
2002        -command [list $popup deactivate] \
2003        -compound left \
2004        -image [Rappture::icon cancel]
2005
2006    blt::table $inner \
2007        0,0 $inner.summary -cspan 2  \
2008        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2009        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2010        4,1 $inner.cancel -width .9i -fill y \
2011        4,0 $inner.ok -padx 2 -width .9i -fill y
2012    blt::table configure $inner r3 -height 4
2013    blt::table configure $inner r4 -pady 4
2014    raise $inner.image_button
2015    $inner.vtk_button invoke
2016    return $inner
2017}
2018
2019#
2020# SetObjectStyle --
2021#
2022#       Set the style of the image/contour object.  This gets calls
2023#       for each dataset once as it is loaded.  It can overridden by
2024#       the user controls.
2025#
2026#
2027itcl::body Rappture::VtkImageViewer::SetObjectStyle { dataobj comp } {
2028    # Parse style string.
2029    set tag $dataobj-$comp
2030    array set style {
2031        -color none
2032        -opacity 1.0
2033    }
2034    set stylelist [$dataobj style $comp]
2035    if { $stylelist != "" } {
2036        array set style $stylelist
2037    }
2038    # This is too complicated.  We want to set the colormap, number of
2039    # isolines and opacity for the dataset.  They can be the default values,
2040    # the style hints loaded with the dataset, or set by user controls.  As
2041    # datasets get loaded, they first use the defaults that are overidden
2042    # by the style hints.  If the user changes the global controls, then that
2043    # overrides everything else.  I don't know what it means when global
2044    # controls are specified as style hints by each dataset.  It complicates
2045    # the code to handle aberrant cases.
2046
2047    if { $_changed(opacity) } {
2048        set style(-opacity) [expr $_settings(opacity) * 0.01]
2049    }
2050    if { $_changed(colormap) } {
2051        set style(-color) $_settings(colormap)
2052    }
2053    if { $_currentColormap == "" } {
2054        $itk_component(colormap) value $style(-color)
2055    }
2056    if { [info exists style(-stretchtofit)] } {
2057        set _settings(stretchToFit) $style(-stretchtofit)
2058        AdjustSetting stretchToFit
2059    }
2060    SendCmd "outline add $tag"
2061    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2062    SendCmd "outline visible $_settings(outline) $tag"
2063    SendCmd "image add $tag"
2064    SetCurrentColormap $style(-color)
2065    set color [$itk_component(backingcolor) value]
2066    SendCmd "image color [Color2RGB $color] $tag"
2067    SendCmd "image opacity $style(-opacity) $tag"
2068    set _settings(opacity) [expr $style(-opacity) * 100.0]
2069}
2070
2071itcl::body Rappture::VtkImageViewer::IsValidObject { dataobj } {
2072    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2073        return 0
2074    }
2075    return 1
2076}
2077
2078# ----------------------------------------------------------------------
2079# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2080#
2081# Invoked automatically whenever the "legend" command comes in from
2082# the rendering server.  Indicates that binary image data with the
2083# specified <size> will follow.
2084# ----------------------------------------------------------------------
2085itcl::body Rappture::VtkImageViewer::ReceiveLegend { colormap title min max size } {
2086    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2087    if { [isconnected] } {
2088        set bytes [ReceiveBytes $size]
2089        if { ![info exists _image(legend)] } {
2090            set _image(legend) [image create photo]
2091        }
2092        $_image(legend) configure -data $bytes
2093        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2094        if { [catch {DrawLegend} errs] != 0 } {
2095            global errorInfo
2096            puts stderr "errs=$errs errorInfo=$errorInfo"
2097        }
2098    }
2099}
2100
2101#
2102# DrawLegend --
2103#
2104#       Draws the legend in the own canvas on the right side of the plot area.
2105#
2106itcl::body Rappture::VtkImageViewer::DrawLegend {} {
2107    set fname $_curFldName
2108    set c $itk_component(view)
2109    set w [winfo width $c]
2110    set h [winfo height $c]
2111    set font "Arial 8"
2112    set lineht [font metrics $font -linespace]
2113   
2114    if { [string match "component*" $fname] } {
2115        set title ""
2116    } else {
2117        if { [info exists _fields($fname)] } {
2118            foreach { title units } $_fields($fname) break
2119            if { $units != "" } {
2120                set title [format "%s (%s)" $title $units]
2121            }
2122        } else {
2123            set title $fname
2124        }
2125    }
2126    set x [expr $w - 2]
2127    if { !$_settings(legendVisible) } {
2128        $c delete legend
2129        return
2130    }
2131    if { [$c find withtag "legend"] == "" } {
2132        set y 2
2133        # If there's a legend title, create a text item for the title.
2134        $c create text $x $y \
2135            -anchor ne \
2136            -fill $itk_option(-plotforeground) -tags "title legend" \
2137            -font $font
2138        if { $title != "" } {
2139            incr y $lineht
2140        }
2141        $c create text $x $y \
2142            -anchor ne \
2143            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2144            -font $font
2145        incr y $lineht
2146        $c create image $x $y \
2147            -anchor ne \
2148            -image $_image(legend) -tags "colormap legend"
2149        $c create rectangle $x $y 1 1 \
2150            -fill "" -outline "" -tags "sensor legend"
2151        $c create text $x [expr {$h-2}] \
2152            -anchor se \
2153            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2154            -font $font
2155        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2156        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2157        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2158    }
2159
2160    set x2 $x
2161    set iw [image width $_image(legend)]
2162    set ih [image height $_image(legend)]
2163    set x1 [expr $x2 - ($iw*12)/10]
2164
2165    $c bind title <ButtonPress> [itcl::code $this Combo post]
2166    $c bind title <Enter> [itcl::code $this Combo activate]
2167    $c bind title <Leave> [itcl::code $this Combo deactivate]
2168    # Reset the item coordinates according the current size of the plot.
2169    if { [info exists _limits($_curFldName)] } {
2170        foreach { vmin vmax } $_limits($_curFldName) break
2171        $c itemconfigure vmin -text [format %g $vmin]
2172        $c itemconfigure vmax -text [format %g $vmax]
2173    }
2174    set y 2
2175    # If there's a legend title, move the title to the correct position
2176    if { $title != "" } {
2177        $c itemconfigure title -text $title
2178        $c coords title $x $y
2179        incr y $lineht
2180    }
2181    $c coords vmax $x $y
2182    incr y $lineht
2183    $c coords colormap $x $y
2184    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2185    $c raise sensor
2186    $c coords vmin $x [expr {$h - 2}]
2187}
2188
2189#
2190# EnterLegend --
2191#
2192itcl::body Rappture::VtkImageViewer::EnterLegend { x y } {
2193    SetLegendTip $x $y
2194}
2195
2196#
2197# MotionLegend --
2198#
2199itcl::body Rappture::VtkImageViewer::MotionLegend { x y } {
2200    Rappture::Tooltip::tooltip cancel
2201    set c $itk_component(view)
2202    set cw [winfo width $c]
2203    set ch [winfo height $c]
2204    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2205        SetLegendTip $x $y
2206    }
2207}
2208
2209#
2210# LeaveLegend --
2211#
2212itcl::body Rappture::VtkImageViewer::LeaveLegend { } {
2213    Rappture::Tooltip::tooltip cancel
2214    .rappturetooltip configure -icon ""
2215}
2216
2217#
2218# SetLegendTip --
2219#
2220itcl::body Rappture::VtkImageViewer::SetLegendTip { x y } {
2221    set fname $_curFldName
2222    set c $itk_component(view)
2223    set w [winfo width $c]
2224    set h [winfo height $c]
2225    set font "Arial 8"
2226    set lineht [font metrics $font -linespace]
2227   
2228    set ih [image height $_image(legend)]
2229    # Subtract off the offset of the color ramp from the top of the canvas
2230    set iy [expr $y - ($lineht + 2)]
2231
2232    if { [string match "component*" $fname] } {
2233        set title ""
2234    } else {
2235        if { [info exists _fields($fname)] } {
2236            foreach { title units } $_fields($fname) break
2237            if { $units != "" } {
2238                set title [format "%s (%s)" $title $units]
2239            }
2240        } else {
2241            set title $fname
2242        }
2243    }
2244    # If there's a legend title, increase the offset by the line height.
2245    if { $title != "" } {
2246        incr iy -$lineht
2247    }
2248
2249    # Make a swatch of the selected color
2250    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2251        return
2252    }
2253
2254    if { ![info exists _image(swatch)] } {
2255        set _image(swatch) [image create photo -width 24 -height 24]
2256    }
2257    set color [eval format "\#%02x%02x%02x" $pixel]
2258    $_image(swatch) put black  -to 0 0 23 23
2259    $_image(swatch) put $color -to 1 1 22 22
2260
2261    # Compute the value of the point
2262    if { [info exists _limits($fname)] } {
2263        foreach { vmin vmax } $_limits($fname) break
2264        set t [expr 1.0 - (double($iy) / double($ih-1))]
2265        set value [expr $t * ($vmax - $vmin) + $vmin]
2266    } else {
2267        set value 0.0
2268    }
2269    set tipx [expr $x + 15]
2270    set tipy [expr $y - 5]
2271    .rappturetooltip configure -icon $_image(swatch)
2272    if { [info exists _isolines($y)] } {
2273        Rappture::Tooltip::text $c [format "$title %g (isoline)" $_isolines($y)]
2274    } else {
2275        Rappture::Tooltip::text $c [format "$title %g" $value]
2276    }
2277    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2278}
2279
2280# ----------------------------------------------------------------------
2281# USAGE: _dropdown post
2282# USAGE: _dropdown unpost
2283# USAGE: _dropdown select
2284#
2285# Used internally to handle the dropdown list for this combobox.  The
2286# post/unpost options are invoked when the list is posted or unposted
2287# to manage the relief of the controlling button.  The select option
2288# is invoked whenever there is a selection from the list, to assign
2289# the value back to the gauge.
2290# ----------------------------------------------------------------------
2291itcl::body Rappture::VtkImageViewer::Combo {option} {
2292    set c $itk_component(view)
2293    switch -- $option {
2294        post {
2295            foreach { x1 y1 x2 y2 } [$c bbox title] break
2296            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2297            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2298            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2299            tk_popup $itk_component(fieldmenu) $x $y
2300        }
2301        activate {
2302            $c itemconfigure title -fill red
2303        }
2304        deactivate {
2305            $c itemconfigure title -fill $itk_option(-plotforeground)
2306        }
2307        invoke {
2308            $itk_component(field) value $_curFldLabel
2309            AdjustSetting field
2310        }
2311        default {
2312            error "bad option \"$option\": should be post, unpost, select"
2313        }
2314    }
2315}
2316
2317itcl::body Rappture::VtkImageViewer::SetOrientation { side } {
2318    array set positions {
2319        front  "0.707107 0.707107 0 0"
2320        back   "0 0 0.707107 0.707107"
2321        left   "0.5 0.5 -0.5 -0.5"
2322        right  "0.5 0.5 0.5 0.5"
2323        top    "1 0 0 0"
2324        bottom "0 1 0 0"
2325    }
2326    foreach name { -qw -qx -qy -qz } value $positions($side) {
2327        set _view($name) $value
2328    }
2329    set q [ViewToQuaternion]
2330    $_arcball quaternion $q
2331    SendCmd "camera orient $q"
2332    SendCmd "camera reset"
2333    set _view(-xpan) 0
2334    set _view(-ypan) 0
2335    set _view(-zoom) 1.0
2336}
Note: See TracBrowser for help on using the repository browser.