source: trunk/gui/scripts/vtkimageviewer.tcl @ 5347

Last change on this file since 5347 was 5347, checked in by ldelgass, 5 years ago

set _downloadPopup to private access

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