source: branches/1.4/gui/scripts/vtkimageviewer.tcl @ 5187

Last change on this file since 5187 was 5187, checked in by ldelgass, 8 years ago

s/styles/style/ (for code consistency), remove unused member variables

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