source: branches/1.7/gui/scripts/vtkimageviewer.tcl @ 6266

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

merge r6265 from 1.6 branch

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