source: branches/1.4/gui/scripts/molvisviewer.tcl @ 5174

Last change on this file since 5174 was 5174, checked in by ldelgass, 9 years ago

merge r5158:r5160 from trunk

File size: 73.4 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: molvisviewer - view a molecule in 3D
4#
5#  This widget brings up a 3D representation of a molecule
6#  It connects to the Molvis server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17package require Img
18
19option add *MolvisViewer.width 4i widgetDefault
20option add *MolvisViewer.height 4i widgetDefault
21option add *MolvisViewer.foreground black widgetDefault
22option add *MolvisViewer.font -*-helvetica-medium-r-normal-*-12-* widgetDefault
23
24# must use this name -- plugs into Rappture::resources::load
25proc MolvisViewer_init_resources {} {
26    Rappture::resources::register \
27        molvis_server Rappture::MolvisViewer::SetServerList
28}
29
30set debug 0
31proc debug { args } {
32    global debug
33    if { $debug } {
34        puts stderr "[info level -1]: $args"
35    }
36}
37
38itcl::class Rappture::MolvisViewer {
39    inherit Rappture::VisViewer
40
41    itk_option define -device device Device ""
42
43    private variable _icon 0
44    private variable _getimage 0
45    private variable _mevent;           # info used for mouse event operations
46    private variable _rocker;           # info used for rock operations
47    private variable _dlist "";         # list of dataobj objects
48    private variable _dataobjs;         # data objects on server
49    private variable _dobj2transparency;# maps dataobj => transparency
50    private variable _dobj2raise;       # maps dataobj => raise flag 0/1
51
52    private variable _active;           # array of active models.
53    private variable _obj2models;       # array containing list of models
54                                        # for each data object.
55    private variable _view
56    private variable _click
57
58    private variable _model
59    private variable _mlist
60    private variable _mrep "ballnstick"
61
62    private variable _imagecache
63    private variable _state
64    private variable _labels "default"
65    private variable _cacheid ""
66    private variable _cacheimage ""
67    private variable _first ""
68
69    private common _settings  ;         # Array of settings for all known
70                                        # widgets
71    private variable _initialized
72
73    private common _downloadPopup;      # Download options from popup
74    private variable _pdbdata;          # PDB data from run file sent to pymol
75    private common _hardcopy
76    private variable _nextToken 0
77    private variable _resizePending 0;
78    private variable _updatePending 0;
79    private variable _rotatePending 0;
80    private variable _width
81    private variable _height
82    private variable _reset 1;          # Restore camera settings
83    private variable _cell 0;           # Restore camera settings
84
85    constructor { servers args } {
86        Rappture::VisViewer::constructor $servers
87    } {
88        # defined below
89    }
90    destructor {
91        # defined below
92    }
93    public proc SetServerList { namelist } {
94        Rappture::VisViewer::SetServerList "pymol" $namelist
95    }
96    private method BuildSettingsTab {}
97    private method DoResize {}
98    private method DoRotate {}
99    private method DoUpdate {}
100    private method EventuallyResize { w h }
101    private method EventuallyRotate { a b c }
102    private method EventuallyChangeSettings { args }
103    private method GetImage { widget }
104    private method ReceiveImage { size cacheid frame rock }
105    private method WaitIcon { option widget }
106    private method AddImageControls { frame widget }
107    private method SetWaitVariable { value } {
108        set _getimage $value
109    }
110    private method WaitForResponse {} {
111        tkwait variable [itcl::scope _getimage]
112        return $_getimage
113    }
114    protected method Map {}
115    protected method Pan {option x y}
116    protected method Rebuild { }
117    protected method Rotate {option x y}
118    protected method SendCmd { string }
119    protected method Unmap {}
120    protected method Vmouse  {option b m x y}
121    protected method Vmouse2 {option b m x y}
122    protected method Zoom {option {factor 10}}
123
124    public method Connect {}
125    public method Disconnect {}
126    public method ResetView {}
127    public method add {dataobj {options ""}}
128    public method delete {args}
129    public method download {option args}
130    public method get {}
131    public method isconnected {}
132    public method labels {option {model "all"}}
133    public method parameters {title args} {
134        # do nothing
135    }
136
137    private method UpdateState { args }
138
139    public method snap { w h }
140    private method Opacity {option}
141    private method SphereScale {option {models "all"} }
142    private method StickRadius {option {models "all"} }
143    private method OrthoProjection {option}
144    private method Representation { {option ""} }
145    private method CartoonTrace {option {model "all"}}
146    private method ComputeParallelepipedVertices { dataobj }
147    private method Cell {option}
148    private method Rock {option}
149}
150
151itk::usual MolvisViewer {
152    keep -background -foreground -cursor -font
153}
154
155# ----------------------------------------------------------------------
156# CONSTRUCTOR
157# ----------------------------------------------------------------------
158itcl::body Rappture::MolvisViewer::constructor {servers args} {
159    set _serverType "pymol"
160
161    # Register events to the dispatcher.  Base class expects !rebuild
162    # event to be registered.
163
164    # Rebuild
165    $_dispatcher register !rebuild
166    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
167
168    # Resize event
169    $_dispatcher register !resize
170    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
171
172    # Update state event
173    $_dispatcher register !update
174    $_dispatcher dispatch $this !update "[itcl::code $this DoUpdate]; list"
175
176    # Rotate event
177    $_dispatcher register !rotate
178    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
179
180    # Rocker
181    $_dispatcher register !rocker
182    $_dispatcher dispatch $this !rocker "[itcl::code $this Rock step]; list"
183    # Mouse Event
184    $_dispatcher register !mevent
185    $_dispatcher dispatch $this !mevent "[itcl::code $this _mevent]; list"
186    $_dispatcher register !pngtimeout
187    $_dispatcher register !waiticon
188
189    array set _downloadPopup {
190        format draft
191    }
192
193    # Populate the slave interpreter with commands to handle responses from
194    # the visualization server.
195    $_parser alias image [itcl::code $this ReceiveImage]
196
197    set _rocker(dir) 1
198    set _rocker(client) 0
199    set _rocker(server) 0
200    set _rocker(on) 0
201    set _state(server) 1
202    set _state(client) 1
203    set _reset 1
204
205    array set _view {
206        theta   45
207        phi     45
208        psi     0
209        vx      0
210        vy      0
211        vz      0
212        zoom    0
213        mx      0
214        my      0
215        mz      0
216        x       0
217        y       0
218        z       0
219        width   0
220        height  0
221    }
222
223    # Setup default settings for widget.
224    array set _settings [subst {
225        $this-spherescale 0.25
226        $this-stickradius 0.14
227        $this-cartoontrace no
228        $this-model     ballnstick
229        $this-modelimg  [Rappture::icon ballnstick]
230        $this-opacity   1.0
231        $this-ortho     no
232        $this-rock      no
233        $this-showlabels no
234        $this-showcell  yes
235        $this-showlabels-initialized no
236    }]
237
238    itk_component add 3dview {
239        label $itk_component(plotarea).view -image $_image(plot) \
240            -highlightthickness 0 -borderwidth 0
241    } {
242        usual
243        ignore -highlightthickness -borderwidth  -background
244    }
245    bind $itk_component(3dview) <Control-F1> [itcl::code $this ToggleConsole]
246
247    set f [$itk_component(main) component controls]
248    itk_component add reset {
249        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
250            -highlightthickness 0 \
251            -image [Rappture::icon reset-view] \
252            -command [itcl::code $this ResetView]
253    } {
254        usual
255        ignore -highlightthickness
256    }
257    pack $itk_component(reset) -padx 1 -pady 2
258    Rappture::Tooltip::for $itk_component(reset) \
259        "Reset the view to the default zoom level"
260
261    itk_component add zoomin {
262        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
263            -highlightthickness 0 \
264            -image [Rappture::icon zoom-in] \
265            -command [itcl::code $this Zoom in]
266    } {
267        usual
268        ignore -highlightthickness
269    }
270    pack $itk_component(zoomin) -padx 2 -pady 2
271    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
272
273    itk_component add zoomout {
274        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
275            -highlightthickness 0 \
276            -image [Rappture::icon zoom-out] \
277            -command [itcl::code $this Zoom out]
278    } {
279        usual
280        ignore -highlightthickness
281    }
282    pack $itk_component(zoomout) -padx 2 -pady 2
283    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
284
285    itk_component add labels {
286        Rappture::PushButton $f.labels \
287            -onimage [Rappture::icon molvis-labels-view] \
288            -offimage [Rappture::icon molvis-labels-view] \
289            -command [itcl::code $this labels update] \
290            -variable [itcl::scope _settings($this-showlabels)]
291    }
292    $itk_component(labels) deselect
293    Rappture::Tooltip::for $itk_component(labels) \
294        "Show/hide the labels on atoms"
295    pack $itk_component(labels) -padx 2 -pady {6 2}
296
297    itk_component add rock {
298        Rappture::PushButton $f.rock \
299            -onimage [Rappture::icon molvis-rock-view] \
300            -offimage [Rappture::icon molvis-rock-view] \
301            -command [itcl::code $this Rock toggle] \
302            -variable [itcl::scope _settings($this-rock)]
303    }
304    pack $itk_component(rock) -padx 2 -pady 2
305    Rappture::Tooltip::for $itk_component(rock) "Rock model back and forth"
306
307    itk_component add ortho {
308        label $f.ortho -borderwidth 1 -padx 1 -pady 1 \
309            -relief "raised" -image [Rappture::icon molvis-3dpers]
310    }
311    pack $itk_component(ortho) -padx 2 -pady 2 -ipadx 1 -ipady 1
312    Rappture::Tooltip::for $itk_component(ortho) \
313        "Use orthoscopic projection"
314
315    bind $itk_component(ortho) <ButtonPress> \
316        [itcl::code $this OrthoProjection toggle]
317
318    BuildSettingsTab
319
320    # HACK ALERT. Initially force a requested width of the 3dview label.
321
322    # It's a chicken-and-the-egg problem.  The size of the 3dview label is set
323    # from the size of the image retrieved from the server.  But the size of
324    # the image is specified by the viewport which is the size of the label.
325    # The fly-in-the-ointment is that it takes a non-trival amount of time to
326    # get the first image back from the server.  In the meantime the idletasks
327    # have already kicked in.  We end up with a 1x1 viewport and image.
328
329    # So the idea is to force a ridiculously big requested width on the label
330    # (that's why we're using the blt::table to manage the geometry).  It has
331    # to be big, because we don't know how big the user may want to stretch
332    # the window.  This at least forces the sidebarframe to give the 3dview
333    # the maximum size available, which is perfect for an initially closed
334    # sidebar.
335
336    blt::table $itk_component(plotarea) \
337        0,0 $itk_component(3dview) -fill both -reqwidth 10000
338    #
339    # RENDERING AREA
340    #
341
342    set _image(id) ""
343
344    # set up bindings for rotation
345    if 0 {
346        bind $itk_component(3dview) <ButtonPress-1> \
347            [itcl::code $this Rotate click %x %y]
348        bind $itk_component(3dview) <B1-Motion> \
349            [itcl::code $this Rotate drag %x %y]
350        bind $itk_component(3dview) <ButtonRelease-1> \
351            [itcl::code $this Rotate release %x %y]
352    } else {
353        bind $itk_component(3dview) <ButtonPress-1> \
354            [itcl::code $this Vmouse click %b %s %x %y]
355        bind $itk_component(3dview) <B1-Motion> \
356            [itcl::code $this Vmouse drag 1 %s %x %y]
357        bind $itk_component(3dview) <ButtonRelease-1> \
358            [itcl::code $this Vmouse release %b %s %x %y]
359    }
360
361    bind $itk_component(3dview) <ButtonPress-2> \
362        [itcl::code $this Pan click %x %y]
363    bind $itk_component(3dview) <B2-Motion> \
364        [itcl::code $this Pan drag %x %y]
365    bind $itk_component(3dview) <ButtonRelease-2> \
366        [itcl::code $this Pan release %x %y]
367
368    bind $itk_component(3dview) <KeyPress-Left> \
369        [itcl::code $this Pan set -10 0]
370    bind $itk_component(3dview) <KeyPress-Right> \
371        [itcl::code $this Pan set 10 0]
372    bind $itk_component(3dview) <KeyPress-Up> \
373        [itcl::code $this Pan set 0 -10]
374    bind $itk_component(3dview) <KeyPress-Down> \
375        [itcl::code $this Pan set 0 10]
376    bind $itk_component(3dview) <Shift-KeyPress-Left> \
377        [itcl::code $this Pan set -50 0]
378    bind $itk_component(3dview) <Shift-KeyPress-Right> \
379        [itcl::code $this Pan set 50 0]
380    bind $itk_component(3dview) <Shift-KeyPress-Up> \
381        [itcl::code $this Pan set 0 -50]
382    bind $itk_component(3dview) <Shift-KeyPress-Down> \
383        [itcl::code $this Pan set 0 50]
384    bind $itk_component(3dview) <KeyPress-Prior> \
385        [itcl::code $this Zoom out 2]
386    bind $itk_component(3dview) <KeyPress-Next> \
387        [itcl::code $this Zoom in 2]
388
389    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
390
391
392    if {[string equal "x11" [tk windowingsystem]]} {
393        bind $itk_component(3dview) <4> [itcl::code $this Zoom out 2]
394        bind $itk_component(3dview) <5> [itcl::code $this Zoom in 2]
395    }
396
397    # set up bindings to bridge mouse events to server
398    #bind $itk_component(3dview) <ButtonPress> \
399    #   [itcl::code $this Vmouse2 click %b %s %x %y]
400    #bind $itk_component(3dview) <ButtonRelease> \
401    #    [itcl::code $this Vmouse2 release %b %s %x %y]
402    #bind $itk_component(3dview) <B1-Motion> \
403    #    [itcl::code $this Vmouse2 drag 1 %s %x %y]
404    #bind $itk_component(3dview) <B2-Motion> \
405    #    [itcl::code $this Vmouse2 drag 2 %s %x %y]
406    #bind $itk_component(3dview) <B3-Motion> \
407    #    [itcl::code $this Vmouse2 drag 3 %s %x %y]
408    #bind $itk_component(3dview) <Motion> \
409    #    [itcl::code $this Vmouse2 move 0 %s %x %y]
410
411    bind $itk_component(3dview) <Configure> \
412        [itcl::code $this EventuallyResize %w %h]
413    bind $itk_component(3dview) <Unmap> \
414        [itcl::code $this Unmap]
415    bind $itk_component(3dview) <Map> \
416        [itcl::code $this Map]
417
418    eval itk_initialize $args
419    Connect
420}
421
422# ----------------------------------------------------------------------
423# DESTRUCTOR
424# ----------------------------------------------------------------------
425itcl::body Rappture::MolvisViewer::destructor {} {
426    VisViewer::Disconnect
427
428    image delete $_image(plot)
429    array unset _settings $this-*
430}
431
432
433# ----------------------------------------------------------------------
434# USAGE: add <dataobj> ?<settings>?
435#
436# Clients use this to add a data object to the plot.  The optional
437# <settings> are used to configure the plot.  Allowed settings are
438# -color, -brightness, -width, -linestyle, and -raise. Only
439# -brightness and -raise do anything.
440# ----------------------------------------------------------------------
441itcl::body Rappture::MolvisViewer::add { dataobj {options ""}} {
442    array set params {
443        -color          auto
444        -brightness     0
445        -width          1
446        -raise          0
447        -linestyle      solid
448        -description    ""
449        -param          ""
450    }
451    array set params $options
452
453    set pos [lsearch -exact $_dlist $dataobj]
454
455    if {$pos < 0} {
456        if {![Rappture::library isvalid $dataobj]} {
457            error "bad value \"$dataobj\": should be Rappture::library object"
458        }
459
460        if { !$_settings($this-showlabels-initialized) } {
461            set showlabels [$dataobj get components.molecule.about.emblems]
462            if { $showlabels != "" && [string is boolean $showlabels] } {
463                set _settings($this-showlabels) $showlabels
464            }
465        }
466
467        lappend _dlist $dataobj
468        if { $params(-brightness) >= 0.5 } {
469            set _dobj2transparency($dataobj) "ghost"
470        } else {
471            set _dobj2transparency($dataobj) "normal"
472        }
473        set _dobj2raise($dataobj) $params(-raise)
474        debug "setting parameters for $dataobj\n"
475
476        if { [isconnected] } {
477            $_dispatcher event -idle !rebuild
478        }
479    }
480}
481
482# ----------------------------------------------------------------------
483# USAGE: delete ?<dataobj> <dataobj> ...?
484#
485# Clients use this to delete a dataobj from the plot. If no dataobjs
486# are specified, then all dataobjs are deleted.
487# ----------------------------------------------------------------------
488itcl::body Rappture::MolvisViewer::delete { args } {
489    if {[llength $args] == 0} {
490        set args $_dlist
491    }
492
493    # delete all specified dataobjs
494    set changed 0
495    foreach dataobj $args {
496        set pos [lsearch -exact $_dlist $dataobj]
497        if {$pos >= 0} {
498            set _dlist [lreplace $_dlist $pos $pos]
499            if { [info exists _obj2models($dataobj)] } {
500                foreach model $_obj2models($dataobj) {
501                    array unset _active $model
502                }
503            }
504            array unset _obj2models $dataobj
505            array unset _dobj2transparency $dataobj
506            array unset _dobj2color $dataobj
507            array unset _dobj2width $dataobj
508            array unset _dobj2dashes $dataobj
509            array unset _dobj2raise $dataobj
510            set changed 1
511        }
512    }
513
514    # if anything changed, then rebuild the plot
515    if {$changed} {
516        if { [isconnected] } {
517            $_dispatcher event -idle !rebuild
518        }
519    }
520}
521
522# ----------------------------------------------------------------------
523# USAGE: get
524#
525# Clients use this to query the list of objects being plotted, in
526# order from bottom to top of this result.
527# ----------------------------------------------------------------------
528itcl::body Rappture::MolvisViewer::get {} {
529    # put the dataobj list in order according to -raise options
530    set dlist $_dlist
531    foreach obj $dlist {
532        if {[info exists _dobj2raise($obj)] && $_dobj2raise($obj)} {
533            set i [lsearch -exact $dlist $obj]
534            if {$i >= 0} {
535                set dlist [lreplace $dlist $i $i]
536                lappend dlist $obj
537            }
538        }
539    }
540    return $dlist
541}
542
543# ----------------------------------------------------------------------
544# USAGE: download coming
545# USAGE: download controls <downloadCommand>
546# USAGE: download now
547#
548# Clients use this method to create a downloadable representation
549# of the plot.  Returns a list of the form {ext string}, where
550# "ext" is the file extension (indicating the type of data) and
551# "string" is the data itself.
552# ----------------------------------------------------------------------
553itcl::body Rappture::MolvisViewer::download {option args} {
554    switch $option {
555        coming {}
556        controls {
557            set popup .molvisviewerdownload
558            if {![winfo exists $popup]} {
559                # if we haven't created the popup yet, do it now
560                Rappture::Balloon $popup \
561                    -title "[Rappture::filexfer::label downloadWord] as..."
562                set inner [$popup component inner]
563                label $inner.summary -text "" -anchor w
564                radiobutton $inner.pdb \
565                    -text "PDB Protein Data Bank Format File" \
566                    -variable [itcl::scope _downloadPopup(format)] \
567                    -font "Arial 10 " \
568                    -value pdb
569                Rappture::Tooltip::for $inner.pdb \
570                    "Save as PDB Protein Data Bank format file."
571                radiobutton $inner.image -text "Image (PNG/JPEG/GIF)" \
572                    -variable [itcl::scope _downloadPopup(format)] \
573                    -font "Arial 10 " \
574                    -value image
575                Rappture::Tooltip::for $inner.image \
576                    "Save as image."
577                set f [frame $inner.frame]
578                button $f.ok -text "Save" \
579                    -highlightthickness 0 -pady 3 -padx 3 \
580                    -command [lindex $args 0] \
581                    -compound left \
582                    -image [Rappture::icon download]
583                button $f.cancel -text "Cancel" \
584                    -highlightthickness 0 -pady 3 -padx 3 \
585                    -command [list $popup deactivate] \
586                    -compound left \
587                    -image [Rappture::icon cancel]
588                blt::table $f \
589                    0,0 $f.ok \
590                    0,1 $f.cancel
591                blt::table $inner \
592                    0,0 $inner.summary -anchor w \
593                    1,0 $inner.pdb -anchor w \
594                    2,0 $inner.image -anchor w \
595                    3,0 $f -fill x -pady 4
596                $inner.pdb select
597            } else {
598                set inner [$popup component inner]
599            }
600            set num [llength [get]]
601            set num [expr {($num == 1) ? "1 result" : "$num results"}]
602            set word [Rappture::filexfer::label downloadWord]
603            $inner.summary configure -text "$word $num in the following format:"
604            update idletasks ;          # Fix initial sizes
605            return $popup
606        }
607        now {
608            set popup .molvisviewerdownload
609            if {[winfo exists $popup]} {
610                $popup deactivate
611            }
612            switch -- $_downloadPopup(format) {
613                "pdb" {
614                    return [list .pdb $_pdbdata]
615                }
616                "image" {
617                    set popup .molvisviewerimage
618                    if { ![winfo exists $popup] } {
619                        # Create the balloon popup and and the print image
620                        # dialog widget to it.
621                        Rappture::Balloon $popup -title "Save as image..." \
622                            -deactivatecommand \
623                            [itcl::code $this SetWaitVariable 0]
624                        set inner [$popup component inner]
625                        # Add image controls to the ballon popup
626                        AddImageControls $inner [lindex $args 0]
627                    } else {
628                        set inner [$popup component inner]
629                    }
630                    update
631                    # Activate the popup and call for the output.
632                    foreach { widget toolName plotName } $args break
633                    SetWaitVariable 0
634                    $popup activate $widget left
635                    set bool [WaitForResponse]
636                    $popup deactivate
637                    if { $bool } {
638                        return [GetImage $widget]
639                    }
640                    return ""
641                }
642            }
643        }
644        default {
645            error "bad option \"$option\": should be coming, controls, now"
646        }
647    }
648}
649
650#
651# isconnected --
652#
653#       Indicates if we are currently connected to the visualization server.
654#
655itcl::body Rappture::MolvisViewer::isconnected {} {
656    return [VisViewer::IsConnected]
657}
658
659
660#
661# Connect --
662#
663#       Establishes a connection to a new visualization server.
664#
665itcl::body Rappture::MolvisViewer::Connect {} {
666    global readyForNextFrame
667    set readyForNextFrame 1
668    if { [isconnected] } {
669        return 1
670    }
671    set hosts [GetServerList "pymol"]
672    if { "" == $hosts } {
673        return 0
674    }
675    set _reset 1
676    set result [VisViewer::Connect $hosts]
677    if { $result } {
678        if { $_reportClientInfo }  {
679            # Tell the server the viewer, hub, user and session.
680            # Do this immediately on connect before buffering any commands
681            global env
682
683            set info {}
684            set user "???"
685            if { [info exists env(USER)] } {
686                set user $env(USER)
687            }
688            set session "???"
689            if { [info exists env(SESSION)] } {
690                set session $env(SESSION)
691            }
692            lappend info "version" "$Rappture::version"
693            lappend info "build" "$Rappture::build"
694            lappend info "svnurl" "$Rappture::svnurl"
695            lappend info "installdir" "$Rappture::installdir"
696            lappend info "hub" [exec hostname]
697            lappend info "client" "molvisviewer"
698            lappend info "user" $user
699            lappend info "session" $session
700            SendCmd "clientinfo [list $info]"
701        }
702
703        $_dispatcher event -idle !rebuild
704    }
705    return $result
706}
707
708#
709# Disconnect --
710#
711#       Clients use this method to disconnect from the current rendering
712#       server.
713#
714itcl::body Rappture::MolvisViewer::Disconnect {} {
715    VisViewer::Disconnect
716
717    # disconnected -- no more data sitting on server
718    catch { after cancel $_rocker(afterid) }
719    catch { after cancel $_mevent(afterid) }
720    array unset _dataobjs
721    array unset _model
722    array unset _mlist
723    array unset _imagecache
724
725    set _state(server) 1
726    set _state(client) 1
727    global readyForNextFrame
728    set readyForNextFrame 1
729    set _reset 1
730}
731
732itcl::body Rappture::MolvisViewer::SendCmd { cmd } {
733    debug "in SendCmd ($cmd)\n"
734
735    if { $_state(server) != $_state(client) } {
736        VisViewer::SendCmd "frame -defer $_state(client)"
737        set _state(server) $_state(client)
738    }
739    if { $_rocker(server) != $_rocker(client) } {
740        VisViewer::SendCmd "rock -defer $_rocker(client)"
741        set _rocker(server) $_rocker(client)
742    }
743    VisViewer::SendCmd "$cmd"
744}
745
746#
747# ReceiveImage -bytes <size>
748#
749#     Invoked automatically whenever the "image" command comes in from
750#     the rendering server.  Indicates that binary image data with the
751#     specified <size> will follow.
752#
753set count 0
754itcl::body Rappture::MolvisViewer::ReceiveImage { size cacheid frame rock } {
755    global readyForNextFrame
756    set readyForNextFrame 1
757    set tag "$frame,$rock"
758    global count
759    incr count
760    if { $cacheid != $_cacheid } {
761        array unset _imagecache
762        set _cacheid $cacheid
763    }
764    set data [ReceiveBytes $size]
765    #debug "success: reading $size bytes from proxy\n"
766    if { [string match "print*" $cacheid] } {
767        # $frame is the token that we sent to the proxy.
768        set _hardcopy($this-$cacheid) $data
769        puts stderr "setting _hardcopy($this-$cacheid)"
770    } else {
771        set _imagecache($tag) $data
772        #debug "CACHED: $tag,$cacheid"
773        $_image(plot) configure -data $data
774        set _image(id) $tag
775    }
776}
777
778itcl::body Rappture::MolvisViewer::BuildSettingsTab {} {
779    set fg [option get $itk_component(hull) font Font]
780
781    set inner [$itk_component(main) insert end \
782        -title "Settings" \
783        -icon [Rappture::icon wrench]]
784    $inner configure -borderwidth 4
785
786    label $inner.pict -image $_settings($this-modelimg)
787
788    label $inner.rep_l -text "Molecule Representation" \
789        -font "Arial 9"
790
791    itk_component add representation {
792        Rappture::Combobox $inner.rep -width 20 -editable no
793    }
794    $inner.rep choices insert end \
795        "ballnstick"  "ball and stick" \
796        "spheres"     "spheres"         \
797        "sticks"      "sticks"          \
798        "lines"       "lines"           \
799        "cartoon"     "cartoon"
800
801    bind $inner.rep <<Value>> [itcl::code $this Representation]
802    $inner.rep value "ball and stick"
803
804    scale $inner.spherescale -width 10 -font "Arial 9" \
805        -from 0.1 -to 2.0 -resolution 0.05 -label "Sphere Scale" \
806        -showvalue true -orient horizontal \
807        -command [itcl::code $this EventuallyChangeSettings] \
808        -variable Rappture::MolvisViewer::_settings($this-spherescale)
809    $inner.spherescale set $_settings($this-spherescale)
810    Rappture::Tooltip::for $inner.spherescale \
811        "Adjust scale of atoms (spheres or balls). 1.0 is the full VDW radius."
812
813    scale $inner.stickradius -width 10 -font "Arial 9" \
814        -from 0.1 -to 1.0 -resolution 0.025 -label "Stick Radius" \
815        -showvalue true -orient horizontal \
816        -command [itcl::code $this EventuallyChangeSettings] \
817        -variable Rappture::MolvisViewer::_settings($this-stickradius)
818    Rappture::Tooltip::for $inner.stickradius \
819        "Adjust scale of bonds (sticks)."
820    $inner.stickradius set $_settings($this-stickradius)
821
822    checkbutton $inner.labels -text "Show labels on atoms" \
823        -command [itcl::code $this labels update] \
824        -variable [itcl::scope _settings($this-showlabels)] \
825        -font "Arial 9"
826    Rappture::Tooltip::for $inner.labels \
827        "Display atom symbol and serial number."
828
829    checkbutton $inner.rock -text "Rock model back and forth" \
830        -command [itcl::code $this Rock toggle] \
831        -variable Rappture::MolvisViewer::_settings($this-rock) \
832        -font "Arial 9"
833    Rappture::Tooltip::for $inner.rock \
834        "Rotate the object back and forth around the y-axis."
835
836    checkbutton $inner.ortho -text "Orthoscopic projection" \
837        -command [itcl::code $this OrthoProjection update] \
838        -variable Rappture::MolvisViewer::_settings($this-ortho) \
839         -font "Arial 9"
840    Rappture::Tooltip::for $inner.ortho \
841        "Toggle between orthoscopic/perspective projection modes."
842
843    checkbutton $inner.cartoontrace -text "Cartoon Trace" \
844        -command [itcl::code $this CartoonTrace update] \
845        -variable [itcl::scope _settings($this-cartoontrace)] \
846        -font "Arial 9"
847    Rappture::Tooltip::for $inner.cartoontrace \
848        "Set cartoon representation of bonds (sticks)."
849
850    checkbutton $inner.cell -text "Parallelepiped" \
851        -command [itcl::code $this Cell toggle] \
852        -font "Arial 9"
853    $inner.cell select
854
855    label $inner.spacer
856    blt::table $inner \
857        0,0 $inner.labels -anchor w -pady {1 0} \
858        1,0 $inner.rock -anchor w -pady {1 0} \
859        2,0 $inner.ortho -anchor w -pady {1 0} \
860        3,0 $inner.cartoontrace -anchor w -pady {1 0} \
861        4,0 $inner.cell -anchor w  -pady {1 0} \
862        5,0 $inner.rep_l -anchor w -pady { 2 0 } \
863        6,0 $inner.rep -anchor w  \
864        7,0 $inner.spherescale -fill x -pady {3 0} \
865        8,0 $inner.stickradius -fill x -pady {1 0} \
866
867    blt::table configure $inner r* -resize none
868    blt::table configure $inner r10 -resize expand
869}
870
871# ----------------------------------------------------------------------
872# USAGE: Rebuild
873#
874# Called automatically whenever something changes that affects the
875# data in the widget.  Clears any existing data and rebuilds the
876# widget to display new data.
877# ----------------------------------------------------------------------
878itcl::body Rappture::MolvisViewer::Rebuild {} {
879    debug "in rebuild"
880    set changed 0
881
882    # Turn on buffering of commands to the server.  We don't want to
883    # be preempted by a server disconnect/reconnect (that automatically
884    # generates a new call to Rebuild).
885    StartBufferingCommands
886    set _cell 0
887
888    if { $_reset } {
889        set _rocker(server) 0
890        set _cacheid 0
891
892        SendCmd "raw -defer {set auto_color,0}"
893        SendCmd "raw -defer {set auto_show_lines,0}"
894    }
895    set _first ""
896    set dlist [get]
897    foreach dataobj $dlist {
898        if { $_first == "" } {
899            set _first $dataobj
900        }
901        set model [$dataobj get components.molecule.model]
902        if {"" == $model } {
903            set model "molecule"
904            scan $dataobj "::libraryObj%d" suffix
905            set model $model$suffix
906        }
907        lappend _obj2models($dataobj) $model
908        set state [$dataobj get components.molecule.state]
909        if {"" == $state} {
910            set state $_state(server)
911        }
912        if { ![info exists _mlist($model)] } {  # new, turn on
913            set _mlist($model) 2
914        } elseif { $_mlist($model) == 1 } {     # on, leave on
915            set _mlist($model) 3
916        } elseif { $_mlist($model) == 0 } {     # off, turn on
917            set _mlist($model) 2
918        }
919        if { ![info exists _dataobjs($model-$state)] } {
920            set data1      ""
921            set serial    1
922
923            if { $_reportClientInfo }  {
924                set parent [$dataobj parent -as object]
925                while { $parent != "" } {
926                    set xmlobj $parent
927                    set parent [$parent parent -as object]
928                }
929                set info {}
930                lappend info "tool_id"      [$xmlobj get tool.id]
931                lappend info "tool_name"    [$xmlobj get tool.name]
932                lappend info "tool_title"   [$xmlobj get tool.title]
933                lappend info "tool_command" [$xmlobj get tool.execute]
934                lappend info "tool_revision" \
935                    [$xmlobj get tool.version.application.revision]
936                SendCmd "clientinfo [list $info]"
937            }
938            foreach _atom [$dataobj children -type atom components.molecule] {
939                set symbol [$dataobj get components.molecule.$_atom.symbol]
940                set xyz [$dataobj get components.molecule.$_atom.xyz]
941                regsub {,} $xyz {} xyz
942                scan $xyz "%f %f %f" x y z
943                set recname  "ATOM  "
944                set altLoc   ""
945                set resName  ""
946                set chainID  ""
947                set Seqno    ""
948                set occupancy  1
949                set tempFactor 0
950                set recID      ""
951                set segID      ""
952                set element    ""
953                set charge     ""
954                set atom $symbol
955                set line [format "%6s%5d %4s%1s%3s %1s%5s   %8.3f%8.3f%8.3f%6.2f%6.2f%8s\n" $recname $serial $atom $altLoc $resName $chainID $Seqno $x $y $z $occupancy $tempFactor $recID]
956                append data1 $line
957                incr serial
958            }
959            if {"" != $data1} {
960                # Save the PDB data in case the user wants to later save it.
961                set _pdbdata $data1
962                set numBytes [string length $data1]
963
964                # We know we're buffered here, so append the "loadpdb" command
965                # with the data payload immediately afterwards.
966                SendCmd "loadpdb -defer follows $model $state $numBytes"
967                SendData $data1
968                set _dataobjs($model-$state)  1
969            }
970            # note that pdb files always overwrite xyz files
971            set data2 [$dataobj get components.molecule.pdb]
972            if {"" != $data2} {
973                # Save the PDB data in case the user wants to later save it.
974                set _pdbdata $data2
975                set numBytes [string length $data2]
976
977                # We know we're buffered here, so append the "loadpdb" command
978                # with the data payload immediately afterwards.
979                SendCmd "loadpdb -defer follows $model $state $numBytes"
980                SendData $data2
981                set _dataobjs($model-$state)  1
982            }
983            # lammps dump file overwrites pdb file (change this?)
984            set lammpstypemap [$dataobj get components.molecule.lammpstypemap]
985            set lammpsdata [$dataobj get components.molecule.lammps]
986            if {"" != $lammpsdata} {
987                set data3 ""
988                set modelcount 0
989                foreach lammpsline [split $lammpsdata "\n"] {
990                    if {[scan $lammpsline "%d %d %f %f %f" id type x y z] == 5} {
991                        set recname  "ATOM  "
992                        set altLoc   ""
993                        set resName  ""
994                        set chainID  ""
995                        set Seqno    ""
996                        set occupancy  1
997                        set tempFactor 0
998                        set recID      ""
999                        set segID      ""
1000                        set element    ""
1001                        set charge     ""
1002                        if { "" == $lammpstypemap} {
1003                            set atom $type
1004                        } else {
1005                            set atom [lindex $lammpstypemap [expr {$type - 1}]]
1006                            if { "" == $atom} {
1007                              set atom $type
1008                            }
1009                        }
1010                        set pdbline [format "%6s%5d %4s%1s%3s %1s%5s   %8.3f%8.3f%8.3f%6.2f%6.2f%8s\n" $recname $id $atom $altLoc $resName $chainID $Seqno $x $y $z $occupancy $tempFactor $recID]
1011                        append data3 $pdbline
1012                    }
1013                    # only read first model
1014                    if {[regexp "^ITEM: ATOMS" $lammpsline]} {
1015                      incr modelcount
1016                      if {$modelcount > 1} {
1017                        break
1018                      }
1019                    }
1020                }
1021                if {"" != $data3} {
1022                    # Save the PDB data in case the user wants to later save it.
1023                    set _pdbdata $data3
1024                    set numBytes [string length $data3]
1025
1026                    # We know we're buffered here, so append the "loadpdb"
1027                    # command with the data payload immediately afterwards.
1028                    SendCmd "loadpdb -defer follows $model $state $numBytes"
1029                    SendData $data3
1030                }
1031                set _dataobjs($model-$state) 1
1032            }
1033        }
1034        if { ![info exists _model($model-transparency)] } {
1035            set _model($model-transparency) ""
1036        }
1037        if { ![info exists _model($model-rep)] } {
1038            set _model($model-rep) ""
1039            set _model($model-newrep) $_mrep
1040        }
1041        if { $_model($model-transparency) != $_dobj2transparency($dataobj) } {
1042            set _model($model-newtransparency) $_dobj2transparency($dataobj)
1043        }
1044        if { $_dobj2transparency($dataobj) == "ghost"} {
1045            array unset _active $model
1046        } else {
1047            set _active($model) $dataobj
1048        }
1049        set vector [$dataobj get components.parallelepiped.vector]
1050        if { $vector != "" } {
1051            set vertices [ComputeParallelepipedVertices $dataobj]
1052            SendCmd "raw -defer {verts = \[$vertices\]\n}"
1053            SendCmd "raw -defer {run \$PYMOL_SITE_PATH/rappture/box.py\n}"
1054            SendCmd "raw -defer {draw_box(verts)\n}"
1055            set _cell 1
1056        }
1057    }
1058
1059    # enable/disable models as required (0=off->off, 1=on->off, 2=off->on,
1060    # 3=on->on)
1061
1062    foreach model [array names _mlist] {
1063        if { $_mlist($model) == 1 } {
1064            SendCmd "disable -defer $model"
1065            set _mlist($model) 0
1066            set changed 1
1067        } elseif { $_mlist($model) == 2 } {
1068            set _mlist($model) 1
1069            SendCmd "enable -defer $model"
1070            set changed 1
1071        } elseif { $_mlist($model) == 3 } {
1072            set _mlist($model) 1
1073        }
1074        if { $_mlist($model) == 1 } {
1075            if {  [info exists _model($model-newtransparency)] ||
1076                  [info exists _model($model-newrep)] } {
1077                if { ![info exists _model($model-newrep)] } {
1078                    set _model($model-newrep) $_model($model-rep)
1079                }
1080                if { ![info exists _model($model-newtransparency)] } {
1081                    set _model($model-newtransparency) $_model($model-transparency)
1082                }
1083                set rep $_model($model-newrep)
1084                set transp $_model($model-newtransparency)
1085                SendCmd "representation -defer -model $model $rep"
1086                set changed 1
1087                set _model($model-transparency) $_model($model-newtransparency)
1088                set _model($model-rep) $_model($model-newrep)
1089                catch {
1090                    unset _model($model-newtransparency)
1091                    unset _model($model-newrep)
1092                }
1093            }
1094        }
1095
1096    }
1097
1098    if { $changed } {
1099        array unset _imagecache
1100    }
1101    if { $dlist == "" } {
1102        set _state(server) 1
1103        set _state(client) 1
1104        SendCmd "frame 1"
1105        set flush 1
1106    } elseif { ![info exists _imagecache($state,$_rocker(client))] } {
1107        set _state(server) $state
1108        set _state(client) $state
1109        SendCmd "frame $state"
1110        set flush 1
1111    } else {
1112        set _state(client) $state
1113        UpdateState
1114        set flush 0
1115    }
1116    if { $_reset } {
1117        # Set or restore viewing parameters.  We do this for the first
1118        # model and assume this works for everything else.
1119        set w  [winfo width $itk_component(3dview)]
1120        set h  [winfo height $itk_component(3dview)]
1121        SendCmd "reset"
1122        SendCmd "screen $w $h"
1123        SendCmd "rotate $_view(mx) $_view(my) $_view(mz)"
1124        SendCmd "pan $_view(x) $_view(y)"
1125        SendCmd "zoom $_view(zoom)"
1126        debug "rebuild: rotate $_view(mx) $_view(my) $_view(mz)"
1127
1128        SendCmd "raw -defer {zoom complete=1}"
1129        set _reset 0
1130    }
1131    if { $changed } {
1132        # Default settings for all models.
1133        SphereScale update
1134        StickRadius update
1135        labels update
1136        Opacity update
1137        CartoonTrace update
1138        Cell update
1139        OrthoProjection update
1140        Representation update
1141    }
1142    set inner [$itk_component(main) panel "Settings"]
1143    if { $_cell } {
1144        $inner.cell configure -state normal
1145    } else {
1146        $inner.cell configure -state disabled
1147    }
1148    if { $flush } {
1149        global readyForNextFrame
1150        set readyForNextFrame 0;        # Don't advance to the next frame
1151                                        # until we get an image.
1152        #SendCmd "ppm";                 # Flush the results.
1153    }
1154    blt::busy hold $itk_component(hull)
1155    StopBufferingCommands
1156    blt::busy release $itk_component(hull)
1157
1158    debug "exiting rebuild"
1159}
1160
1161itcl::body Rappture::MolvisViewer::Unmap { } {
1162    # Pause rocking loop while unmapped (saves CPU time)
1163    Rock pause
1164
1165    # Blank image, mark current image dirty
1166    # This will force reload from cache, or remain blank if cache is cleared
1167    # This prevents old image from briefly appearing when a new result is added
1168    # by result viewer
1169
1170    #$_image(plot) blank
1171    set _image(id) ""
1172}
1173
1174itcl::body Rappture::MolvisViewer::Map { } {
1175    if { [isconnected] } {
1176        # Resume rocking loop if it was on
1177        Rock unpause
1178        # Rebuild image if modified, or redisplay cached image if not
1179        $_dispatcher event -idle !rebuild
1180    }
1181}
1182
1183itcl::body Rappture::MolvisViewer::DoResize { } {
1184    SendCmd "screen $_width $_height"
1185    $_image(plot) configure -width $_width -height $_height
1186    # Immediately invalidate cache, defer update until mapped
1187    array unset _imagecache
1188    set _resizePending 0
1189}
1190
1191itcl::body Rappture::MolvisViewer::EventuallyResize { w h } {
1192    set _width $w
1193    set _height $h
1194    if { !$_resizePending } {
1195        $_dispatcher event -after 400 !resize
1196        set _resizePending 1
1197    }
1198}
1199
1200itcl::body Rappture::MolvisViewer::DoRotate {} {
1201    SendCmd "rotate $_view(a) $_view(b) $_view(c)"
1202    array unset _imagecache
1203    set _rotatePending 0
1204}
1205
1206itcl::body Rappture::MolvisViewer::EventuallyRotate { a b c } {
1207    set _view(a) $a
1208    set _view(b) $b
1209    set _view(c) $c
1210    if { !$_rotatePending } {
1211        $_dispatcher event -after 100 !rotate
1212        set _rotatePending 1
1213    }
1214}
1215
1216itcl::body Rappture::MolvisViewer::DoUpdate { } {
1217    array unset _imagecache
1218    set models [array names _mlist]
1219    SphereScale $_settings($this-spherescale) $models
1220    StickRadius $_settings($this-stickradius) $models
1221    set _updatePending 0
1222}
1223
1224itcl::body Rappture::MolvisViewer::EventuallyChangeSettings { args } {
1225    if { !$_updatePending } {
1226        $_dispatcher event -after 400 !update
1227        set _updatePending 1
1228    }
1229}
1230
1231# ----------------------------------------------------------------------
1232# USAGE: $this Pan click x y
1233#        $this Pan drag x y
1234#        $this Pan release x y
1235#
1236# Called automatically when the user clicks on one of the zoom
1237# controls for this widget.  Changes the zoom for the current view.
1238# ----------------------------------------------------------------------
1239itcl::body Rappture::MolvisViewer::Pan {option x y} {
1240    if { $option == "set" } {
1241        set dx $x
1242        set dy $y
1243        set _view(x) [expr $_view(x) + $dx]
1244        set _view(y) [expr $_view(y) + $dy]
1245        array unset _imagecache
1246        SendCmd "pan $dx $dy"
1247        return
1248    }
1249    if { ![info exists _mevent(x)] } {
1250        set option "click"
1251    }
1252    if { $option == "click" } {
1253        $itk_component(3dview) configure -cursor hand1
1254    }
1255    if { $option == "drag" || $option == "release" } {
1256        set dx [expr $x - $_mevent(x)]
1257        set dy [expr $y - $_mevent(y)]
1258        set _view(x) [expr $_view(x) + $dx]
1259        set _view(y) [expr $_view(y) + $dy]
1260        array unset _imagecache
1261        SendCmd "pan $dx $dy"
1262    }
1263    set _mevent(x) $x
1264    set _mevent(y) $y
1265    if { $option == "release" } {
1266        $itk_component(3dview) configure -cursor ""
1267    }
1268}
1269
1270# ----------------------------------------------------------------------
1271# USAGE: Zoom in
1272# USAGE: Zoom out
1273# USAGE: Zoom reset
1274#
1275# Called automatically when the user clicks on one of the zoom
1276# controls for this widget.  Changes the zoom for the current view.
1277# ----------------------------------------------------------------------
1278itcl::body Rappture::MolvisViewer::Zoom {option {factor 10}} {
1279    switch -- $option {
1280        "in" {
1281            set _view(zoom) [expr $_view(zoom) + $factor]
1282            SendCmd "zoom $factor"
1283        }
1284        "out" {
1285            set _view(zoom) [expr $_view(zoom) - $factor]
1286            SendCmd "zoom -$factor"
1287        }
1288        "reset" {
1289            set _view(zoom) 0
1290            SendCmd "reset"
1291        }
1292    }
1293    array unset _imagecache
1294}
1295
1296itcl::body Rappture::MolvisViewer::UpdateState { args } {
1297    set tag "$_state(client),$_rocker(client)"
1298    if { $_image(id) != "$tag" } {
1299        if { [info exists _imagecache($tag)] } {
1300            $_image(plot) configure -data $_imagecache($tag)
1301            set _image(id) "$tag"
1302        }
1303    }
1304}
1305
1306# ----------------------------------------------------------------------
1307# USAGE: Rock on|off|toggle
1308# USAGE: Rock pause|unpause|step
1309#
1310# Used to control the "rocking" model for the molecule being displayed.
1311# Clients should use only the on/off/toggle options; the rest are for
1312# internal control of the rocking motion.
1313# ----------------------------------------------------------------------
1314itcl::body Rappture::MolvisViewer::Rock { option } {
1315    # cancel any pending rocks
1316    if { [info exists _rocker(afterid)] } {
1317        after cancel $_rocker(afterid)
1318        unset _rocker(afterid)
1319    }
1320    if { ![winfo viewable $itk_component(3dview)] } {
1321        return
1322    }
1323    set _rocker(on) $_settings($this-rock)
1324    if { $option == "step"} {
1325        if { $_rocker(client) >= 10 } {
1326            set _rocker(dir) -1
1327        } elseif { $_rocker(client) <= -10 } {
1328            set _rocker(dir) 1
1329        }
1330        set _rocker(client) [expr {$_rocker(client) + $_rocker(dir)}]
1331        if { ![info exists _imagecache($_state(server),$_rocker(client))] } {
1332            set _rocker(server) $_rocker(client)
1333            SendCmd "rock $_rocker(client)"
1334        }
1335        UpdateState
1336    }
1337    if { $_rocker(on) && $option != "pause" } {
1338         set _rocker(afterid) [after 200 [itcl::code $this Rock step]]
1339    }
1340}
1341
1342
1343itcl::body Rappture::MolvisViewer::Vmouse2 {option b m x y} {
1344    set now [clock clicks -milliseconds]
1345    set vButton [expr $b - 1]
1346    set vModifier 0
1347    set vState 1
1348
1349    if { $m & 1 }      { set vModifier [expr $vModifier | 1 ] }
1350    if { $m & 4 }      { set vModifier [expr $vModifier | 2 ] }
1351    if { $m & 131072 } { set vModifier [expr $vModifier | 4 ] }
1352
1353    if { $option == "click"   } { set vState 0 }
1354    if { $option == "release" } { set vState 1 }
1355    if { $option == "drag"    } { set vState 2 }
1356    if { $option == "move"    } { set vState 3 }
1357
1358    if { $vState == 2 || $vState == 3} {
1359        set diff 0
1360
1361        catch { set diff [expr $now - $_mevent(time)] }
1362        if {$diff < 75} { # 75ms between motion updates
1363            return
1364        }
1365    }
1366    SendCmd "vmouse $vButton $vModifier $vState $x $y"
1367    set _mevent(time) $now
1368}
1369
1370itcl::body Rappture::MolvisViewer::Vmouse {option b m x y} {
1371    set now  [clock clicks -milliseconds]
1372    # cancel any pending delayed dragging events
1373    if { [info exists _mevent(afterid)] } {
1374        after cancel $_mevent(afterid)
1375        unset _mevent(afterid)
1376    }
1377
1378    if { ![info exists _mevent(x)] } {
1379        set option "click"
1380    }
1381    if { $option == "click" } {
1382        $itk_component(3dview) configure -cursor fleur
1383    }
1384    if { $option == "drag" || $option == "release" } {
1385        set diff 0
1386         catch { set diff [expr $now - $_mevent(time) ] }
1387         if {$diff < 25 && $option == "drag" } { # 75ms between motion updates
1388             set _mevent(afterid) [after [expr 25 - $diff] [itcl::code $this Vmouse drag $b $m $x $y]]
1389             return
1390         }
1391        set w [winfo width $itk_component(3dview)]
1392        set h [winfo height $itk_component(3dview)]
1393        if {$w <= 0 || $h <= 0} {
1394            return
1395        }
1396        set x1 [expr double($w) / 3]
1397        set x2 [expr $x1 * 2]
1398        set y1 [expr double($h) / 3]
1399        set y2 [expr $y1 * 2]
1400        set dx [expr $x - $_mevent(x)]
1401        set dy [expr $y - $_mevent(y)]
1402        set mx 0
1403        set my 0
1404        set mz 0
1405
1406        if { $_mevent(x) < $x1 } {
1407            set mz $dy
1408        } elseif { $_mevent(x) < $x2 } {
1409            set mx $dy
1410        } else {
1411            set mz [expr -$dy]
1412        }
1413
1414        if { $_mevent(y) < $y1 } {
1415            set mz [expr -$dx]
1416        } elseif { $_mevent(y) < $y2 } {
1417            set my $dx
1418        } else {
1419            set mz $dx
1420        }
1421        # Accumlate movements
1422        set _view(mx) [expr {$_view(mx) + $mx}]
1423        set _view(my) [expr {$_view(my) + $my}]
1424        set _view(mz) [expr {$_view(mz) + $mz}]
1425        #SendCmd "rotate $mx $my $mz"
1426        EventuallyRotate $mx $my $mz
1427        debug "_vmmouse: rotate $_view(mx) $_view(my) $_view(mz)"
1428    }
1429    set _mevent(x) $x
1430    set _mevent(y) $y
1431    set _mevent(time) $now
1432    if { $option == "release" } {
1433        $itk_component(3dview) configure -cursor ""
1434    }
1435}
1436
1437# ----------------------------------------------------------------------
1438# USAGE: Rotate click <x> <y>
1439# USAGE: Rotate drag <x> <y>
1440# USAGE: Rotate release <x> <y>
1441#
1442# Called automatically when the user clicks/drags/releases in the
1443# plot area.  Moves the plot according to the user's actions.
1444# ----------------------------------------------------------------------
1445itcl::body Rappture::MolvisViewer::Rotate {option x y} {
1446    set now  [clock clicks -milliseconds]
1447    #update idletasks
1448    # cancel any pending delayed dragging events
1449    if { [info exists _mevent(afterid)] } {
1450        after cancel $_mevent(afterid)
1451        unset _mevent(afterid)
1452    }
1453    switch -- $option {
1454        click {
1455            $itk_component(3dview) configure -cursor fleur
1456            set _click(x) $x
1457            set _click(y) $y
1458            set _click(theta) $_view(theta)
1459            set _click(phi) $_view(phi)
1460        }
1461        drag {
1462            if {[array size _click] == 0} {
1463                Rotate click $x $y
1464            } else {
1465                set w [winfo width $itk_component(3dview)]
1466                set h [winfo height $itk_component(3dview)]
1467                if {$w <= 0 || $h <= 0} {
1468                    return
1469                }
1470#         set diff 0
1471#          catch { set diff [expr $now - $_mevent(time) ] }
1472#          if {$diff < 175 && $option == "drag" } { # 75ms between motion updates
1473#              set _mevent(afterid) [after [expr 175 - $diff] [itcl::code $this Rotate drag $x $y]]
1474#              return
1475#          }
1476
1477                if {[catch {
1478                    # this fails sometimes for no apparent reason
1479                    set dx [expr {double($x-$_click(x))/$w}]
1480                    set dy [expr {double($y-$_click(y))/$h}]
1481                }]} {
1482                    return
1483                }
1484
1485                #
1486                # Rotate the camera in 3D
1487                #
1488                if {$_view(psi) > 90 || $_view(psi) < -90} {
1489                    # when psi is flipped around, theta moves backwards
1490                    set dy [expr {-$dy}]
1491                }
1492                set theta [expr {$_view(theta) - $dy*180}]
1493                while {$theta < 0} { set theta [expr {$theta+180}] }
1494                while {$theta > 180} { set theta [expr {$theta-180}] }
1495
1496                if {abs($theta) >= 30 && abs($theta) <= 160} {
1497                    set phi [expr {$_view(phi) - $dx*360}]
1498                    while {$phi < 0} { set phi [expr {$phi+360}] }
1499                    while {$phi > 360} { set phi [expr {$phi-360}] }
1500                    set psi $_view(psi)
1501                } else {
1502                    set phi $_view(phi)
1503                    set psi [expr {$_view(psi) - $dx*360}]
1504                    while {$psi < -180} { set psi [expr {$psi+360}] }
1505                    while {$psi > 180} { set psi [expr {$psi-360}] }
1506                }
1507                array set _view [subst {
1508                    theta $theta
1509                    phi $phi
1510                    psi $psi
1511                }]
1512                foreach { vx vy vz } [Euler2XYZ $theta $phi $psi] break
1513                set a [expr $vx - $_view(vx)]
1514                set a [expr -$a]
1515                set b [expr $vy - $_view(vy)]
1516                set c [expr $vz - $_view(vz)]
1517                array set _view [subst {
1518                    vx $vx
1519                    vy $vy
1520                    vz $vz
1521                }]
1522                EventuallyRotate $a $b $c
1523                #SendCmd "rotate $a $b $c"
1524                debug "Rotate $x $y: rotate $_view(vx) $_view(vy) $_view(vz)"
1525                set _click(x) $x
1526                set _click(y) $y
1527            }
1528        }
1529        release {
1530            Rotate drag $x $y
1531            $itk_component(3dview) configure -cursor ""
1532            catch {unset _click}
1533        }
1534        default {
1535            error "bad option \"$option\": should be click, drag, release"
1536        }
1537    }
1538    set _mevent(time) $now
1539}
1540
1541# ----------------------------------------------------------------------
1542# USAGE: Representation spheres|ballnstick|lines|sticks
1543#
1544# Used internally to change the molecular representation used to render
1545# our scene.
1546# ----------------------------------------------------------------------
1547itcl::body Rappture::MolvisViewer::Representation { { option "" } } {
1548    if { $option == "" } {
1549        set value [$itk_component(representation) value]
1550        set option [$itk_component(representation) translate $value]
1551    }
1552    if { $option == $_mrep } {
1553        return
1554    }
1555    if { $option == "update" } {
1556        set option $_settings($this-model)
1557    }
1558    array unset _imagecache
1559    if { $option == "sticks" } {
1560        set _settings($this-modelimg) [Rappture::icon lines]
1561    }  else {
1562        set _settings($this-modelimg) [Rappture::icon $option]
1563    }
1564    set inner [$itk_component(main) panel "Settings"]
1565    $inner.pict configure -image $_settings($this-modelimg)
1566
1567    # Save the current option to set all radiobuttons -- just in case.
1568    # This method gets called without the user clicking on a radiobutton.
1569    set _settings($this-model) $option
1570    set _mrep $option
1571
1572    foreach model [array names _mlist] {
1573        if { [info exists _model($model-rep)] } {
1574            if { $_model($model-rep) != $option } {
1575                set _model($model-newrep) $option
1576            } else {
1577                catch { unset _model($model-newrep) }
1578            }
1579        }
1580    }
1581    if { [isconnected] } {
1582        SendCmd "representation -model $model $option"
1583        #$_dispatcher event -idle !rebuild
1584    }
1585}
1586
1587
1588# ----------------------------------------------------------------------
1589# USAGE: OrthoProjection on|off|toggle
1590# USAGE: OrthoProjection update
1591#
1592# Used internally to turn labels associated with atoms on/off, and to
1593# update the positions of the labels so they sit on top of each atom.
1594# ----------------------------------------------------------------------
1595itcl::body Rappture::MolvisViewer::OrthoProjection {option} {
1596    array unset _imagecache
1597    switch -- $option {
1598        "orthoscopic" {
1599            set ortho 1
1600        }
1601        "perspective" {
1602            set ortho 0
1603        }
1604        "toggle" {
1605            set ortho [expr {$_settings($this-ortho) == 0}]
1606        }
1607        "update" {
1608            set ortho $_settings($this-ortho)
1609        }
1610        default {
1611            error "bad option \"$option\": should be on, off, toggle, or update"
1612        }
1613    }
1614    if { $ortho == $_settings($this-ortho) && $option != "update"} {
1615        # nothing to do
1616        return
1617    }
1618    if { $ortho } {
1619        $itk_component(ortho) configure -image [Rappture::icon molvis-3dorth]
1620        Rappture::Tooltip::for $itk_component(ortho) \
1621            "Use perspective projection"
1622        set _settings($this-ortho) 1
1623        SendCmd "orthoscopic on"
1624    } else {
1625        $itk_component(ortho) configure -image [Rappture::icon molvis-3dpers]
1626        Rappture::Tooltip::for $itk_component(ortho) \
1627            "Use orthoscopic projection"
1628        set _settings($this-ortho) 0
1629        SendCmd "orthoscopic off"
1630    }
1631}
1632
1633# ----------------------------------------------------------------------
1634# USAGE: Cell on|off|toggle
1635#
1636# Used internally to turn labels associated with atoms on/off, and to
1637# update the positions of the labels so they sit on top of each atom.
1638# ----------------------------------------------------------------------
1639itcl::body Rappture::MolvisViewer::Cell {option} {
1640    switch -- $option {
1641        "on" - "off" {
1642            set cell $option
1643        }
1644        "toggle" {
1645            set cell [expr {$_settings($this-showcell) == 0}]
1646        }
1647        "update" {
1648            set cell $_settings($this-showcell)
1649        }
1650        default {
1651            error "bad option \"$option\": should be on, off, toggle, or update"
1652        }
1653    }
1654    if { $cell == $_settings($this-showcell) && $option != "update"} {
1655        # nothing to do
1656        return
1657    }
1658    array unset _imagecache
1659    if { $cell } {
1660        Rappture::Tooltip::for $itk_component(ortho) \
1661            "Hide the cell."
1662        set _settings($this-showcell) 1
1663        SendCmd "raw {show everything,unitcell}"
1664    } else {
1665        Rappture::Tooltip::for $itk_component(ortho) \
1666            "Show the cell."
1667        set _settings($this-showcell) 0
1668        SendCmd "raw {hide everything,unitcell}"
1669    }
1670}
1671
1672
1673#
1674# ResetView
1675#
1676itcl::body Rappture::MolvisViewer::ResetView {} {
1677    array set _view {
1678        theta   45
1679        phi     45
1680        psi     0
1681        mx      0
1682        my      0
1683        mz      0
1684        x       0
1685        y       0
1686        z       0
1687        zoom    0
1688        width   0
1689        height  0
1690    }
1691    SendCmd "reset"
1692    DoResize
1693    SendCmd "rotate $_view(mx) $_view(my) $_view(mz)"
1694    debug "ResetView: rotate $_view(mx) $_view(my) $_view(mz)"
1695    SendCmd "pan $_view(x) $_view(y)"
1696    SendCmd "zoom $_view(zoom)"
1697}
1698
1699
1700itcl::body Rappture::MolvisViewer::WaitIcon  { option widget } {
1701    switch -- $option {
1702        "start" {
1703            $_dispatcher dispatch $this !waiticon \
1704                "[itcl::code $this WaitIcon "next" $widget] ; list"
1705            set _icon 0
1706            $widget configure -image [Rappture::icon bigroller${_icon}]
1707            $_dispatcher event -after 100 !waiticon
1708        }
1709        "next" {
1710            incr _icon
1711            if { $_icon >= 8 } {
1712                set _icon 0
1713            }
1714            $widget configure -image [Rappture::icon bigroller${_icon}]
1715            $_dispatcher event -after 100 !waiticon
1716        }
1717        "stop" {
1718            $_dispatcher cancel !waiticon
1719        }
1720    }
1721}
1722
1723itcl::body Rappture::MolvisViewer::GetImage { widget } {
1724    set token "print[incr _nextToken]"
1725    set var ::Rappture::MolvisViewer::_hardcopy($this-$token)
1726    set $var ""
1727
1728    set controls $_downloadPopup(image_controls)
1729    set combo $controls.size
1730    set size [$combo translate [$combo value]]
1731    switch -- $size {
1732        "standard" {
1733            set width 1200
1734            set height 1200
1735        }
1736        "highquality" {
1737            set width 2400
1738            set height 2400
1739        }
1740        "draft" {
1741            set width 400
1742            set height 400
1743        }
1744        default {
1745            error "unknown image size [$combo value]"
1746        }
1747    }
1748    # Setup an automatic timeout procedure.
1749    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
1750
1751    set popup .molvisviewerimagedownload
1752    if { ![winfo exists $popup] } {
1753        Rappture::Balloon $popup -title "Generating file..."
1754        set inner [$popup component inner]
1755        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
1756        label $inner.please -text "This may take a minute." -font "Arial 10"
1757        label $inner.icon -image [Rappture::icon bigroller0]
1758        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
1759            -command [list set $var ""]
1760        blt::table $inner \
1761            0,0 $inner.title -cspan 2 \
1762            1,0 $inner.please -anchor w \
1763            1,1 $inner.icon -anchor e  \
1764            2,0 $inner.cancel -cspan 2
1765        blt::table configure $inner r0 -pady 4
1766        blt::table configure $inner r2 -pady 4
1767        bind $inner.cancel <Return> [list $inner.cancel invoke]
1768        bind $inner.cancel <KP_Enter> [list $inner.cancel invoke]
1769    } else {
1770        set inner [$popup component inner]
1771    }
1772    set combo $controls.bgcolor
1773    set bgcolor [$combo translate [$combo value]]
1774
1775    $_dispatcher event -after 60000 !pngtimeout
1776    WaitIcon start $inner.icon
1777    grab set $inner
1778    focus $inner.cancel
1779
1780    SendCmd "print $token $width $height $bgcolor"
1781
1782    $popup activate $widget below
1783    # We wait here for either
1784    #  1) the png to be delivered or
1785    #  2) timeout or
1786    #  3) user cancels the operation.
1787    tkwait variable $var
1788
1789    # Clean up.
1790    $_dispatcher cancel !pngtimeout
1791    WaitIcon stop $inner.icon
1792    grab release $inner
1793    $popup deactivate
1794    update
1795
1796    if { $_hardcopy($this-$token) != "" } {
1797        set combo $controls.format
1798        set fmt [$combo translate [$combo value]]
1799        switch -- $fmt {
1800            "jpg" {
1801                set img [image create photo -data $_hardcopy($this-$token)]
1802                set bytes [$img data -format "jpeg -quality 100"]
1803                set bytes [Rappture::encoding::decode -as b64 $bytes]
1804                return [list .jpg $bytes]
1805            }
1806            "gif" {
1807                set img [image create photo -data $_hardcopy($this-$token)]
1808                set bytes [$img data -format "gif"]
1809                set bytes [Rappture::encoding::decode -as b64 $bytes]
1810                return [list .gif $bytes]
1811            }
1812            "png" {
1813                return [list .png $_hardcopy($this-$token)]
1814            }
1815        }
1816    }
1817    return ""
1818}
1819
1820# ----------------------------------------------------------------------
1821# USAGE: SphereScale radius ?model?
1822#        SphereScale update ?model?
1823#
1824# Used internally to change the molecular atom scale used to render
1825# our scene.
1826#
1827# Note: Only sets the specified radius for active models.  If the model
1828#       is inactive, then it overridden with the value "0.1".
1829# ----------------------------------------------------------------------
1830
1831itcl::body Rappture::MolvisViewer::SphereScale { option {models "all"} } {
1832    if { $option == "update" } {
1833        set radius $_settings($this-spherescale)
1834    } elseif { [string is double $option] } {
1835        set radius $option
1836        if { ($radius < 0.1) || ($radius > 2.0) } {
1837            error "bad atom size \"$radius\""
1838        }
1839    } else {
1840        error "bad option \"$option\""
1841    }
1842    set _settings($this-spherescale) $radius
1843    if { $models == "all" } {
1844        SendCmd "spherescale -model all $radius"
1845        return
1846    }
1847    set overrideradius [expr $radius * 0.8]
1848    SendCmd "spherescale -model all $overrideradius"
1849    foreach model $models {
1850        if { [info exists _active($model)] } {
1851            SendCmd "spherescale -model $model $radius"
1852        }
1853    }
1854}
1855
1856# ----------------------------------------------------------------------
1857# USAGE: StickRadius radius ?models?
1858#        StickRadius update ?models?
1859#
1860# Used internally to change the stick radius used to render
1861# our scene.
1862#
1863# Note: Only sets the specified radius for active models.  If the model
1864#       is inactive, then it overridden with the value "0.25".
1865# ----------------------------------------------------------------------
1866
1867itcl::body Rappture::MolvisViewer::StickRadius { option {models "all"} } {
1868    if { $option == "update" } {
1869        set radius $_settings($this-stickradius)
1870    } elseif { [string is double $option] } {
1871        set radius $option
1872        if { ($radius < 0.1) || ($radius > 2.0) } {
1873            error "bad stick radius \"$radius\""
1874        }
1875    } else {
1876        error "bad option \"$option\""
1877    }
1878    set _settings($this-stickradius) $radius
1879    if { $models == "all" } {
1880        SendCmd "stickradius -model all $radius"
1881        return
1882    }
1883    set overrideradius [expr $radius * 0.8]
1884    SendCmd "stickradius -model all $overrideradius"
1885    foreach model $models {
1886        if { [info exists _active($model)] } {
1887            SendCmd "stickradius -model $model $radius"
1888        }
1889    }
1890}
1891
1892# ----------------------------------------------------------------------
1893# USAGE: Opacity value ?models?
1894#        Opacity update ?models?
1895#
1896# Used internally to change the opacity (transparency) used to render
1897# our scene.
1898#
1899# Note: Only sets the specified transparency for active models.  If the model
1900#       is inactive, then it overridden with the value "0.75".
1901# ----------------------------------------------------------------------
1902
1903itcl::body Rappture::MolvisViewer::Opacity { option } {
1904    array unset _imagecache
1905    if { $option == "update" } {
1906        set opacity $_settings($this-opacity)
1907    } elseif { [string is double $option] } {
1908        set opacity $option
1909        if { ($opacity < 0.0) || ($opacity > 1.0) } {
1910            error "bad opacity \"$opacity\""
1911        }
1912    } else {
1913        error "bad option \"$option\""
1914    }
1915    set _settings($this-opacity) $opacity
1916    set transparency [expr 1.0 - $opacity]
1917    set models [array names _active]
1918    if { [llength $models] == 0 } {
1919        SendCmd "transparency -model all $transparency"
1920        return
1921    }
1922    set overridetransparency 0.60
1923    SendCmd "transparency -model all $overridetransparency"
1924    foreach model $models {
1925        SendCmd "transparency -model $model $transparency"
1926    }
1927}
1928
1929# ----------------------------------------------------------------------
1930# USAGE: labels on|off|toggle
1931# USAGE: labels update
1932#
1933# Used internally to turn labels associated with atoms on/off, and to
1934# update the positions of the labels so they sit on top of each atom.
1935# ----------------------------------------------------------------------
1936itcl::body Rappture::MolvisViewer::labels {option {models "all"}} {
1937    set showlabels $_settings($this-showlabels)
1938    if { $option == "update" } {
1939        set showlabels $_settings($this-showlabels)
1940    } elseif { [string is boolean $option] } {
1941        set showlabels $option
1942    } else {
1943        error "bad option \"$option\""
1944    }
1945    # Clear the image cache
1946    array unset _imagecache
1947    set _settings($this-showlabels) $showlabels
1948    if { $models == "all" } {
1949        SendCmd "label -model all $showlabels"
1950        return
1951    }
1952    SendCmd "label -model all off"
1953    if { $showlabels } {
1954        foreach model $models {
1955            if { [info exists _active($model)] } {
1956                SendCmd "label -model $model $showlabels"
1957            }
1958        }
1959    }
1960}
1961
1962# ----------------------------------------------------------------------
1963# USAGE: CartoonTrace on|off|toggle
1964# USAGE: CartoonTrace update
1965#
1966# Used internally to turn labels associated with atoms on/off, and to
1967# update the positions of the labels so they sit on top of each atom.
1968# ----------------------------------------------------------------------
1969itcl::body Rappture::MolvisViewer::CartoonTrace {option {models "all"}} {
1970    array unset _imagecache
1971    set trace $_settings($this-cartoontrace)
1972    if { $option == "update" } {
1973        set trace $_settings($this-cartoontrace)
1974    } elseif { [string is boolean $option] } {
1975        set trace $option
1976    } else {
1977        error "bad option \"$option\""
1978    }
1979    set _settings($this-cartoontrace) $trace
1980    if { $models == "all" } {
1981        SendCmd "cartoontrace -model all $trace"
1982        return
1983    }
1984    SendCmd "cartoontrace -model all off"
1985    if { $trace } {
1986        foreach model $models {
1987            if { [info exists _active($model)] } {
1988                SendCmd "cartoontrace -model $model $trace"
1989            }
1990        }
1991    }
1992}
1993
1994itcl::body Rappture::MolvisViewer::AddImageControls { inner widget } {
1995    label $inner.size_l -text "Size:" -font "Arial 9"
1996    set _downloadPopup(image_controls) $inner
1997    set img $_image(plot)
1998    set res "[image width $img]x[image height $img]"
1999    Rappture::Combobox $inner.size -width 30 -editable no
2000    $inner.size choices insert end \
2001        "draft"  "Draft (400x400)"         \
2002        "standard"  "Standard (1200x1200)"          \
2003        "highquality"  "High Quality (2400x2400)"
2004
2005    label $inner.bgcolor_l -text "Background:" -font "Arial 9"
2006    Rappture::Combobox $inner.bgcolor -width 30 -editable no
2007    $inner.bgcolor choices insert end \
2008        "black"  "Black" \
2009        "white"  "White" \
2010        "none"  "Transparent (PNG only)"
2011
2012    label $inner.format_l -text "Format:" -font "Arial 9"
2013    Rappture::Combobox $inner.format -width 30 -editable no
2014    $inner.format choices insert end \
2015        "png"  "PNG (Portable Network Graphics format)" \
2016        "jpg"  "JPEG (Joint Photographic Experts Group format)" \
2017        "gif"  "GIF (GIF Graphics Interchange Format)"
2018
2019    set f [frame $inner.frame]
2020    button $f.ok -text "Save" \
2021        -highlightthickness 0 -pady 3 -padx 3 \
2022        -command [itcl::code $this SetWaitVariable 1] \
2023        -compound left \
2024        -image [Rappture::icon download
2025]
2026    button $f.cancel -text "Cancel" \
2027        -highlightthickness 0 -pady 3 -padx 3 \
2028        -command [itcl::code $this SetWaitVariable 0] \
2029        -compound left \
2030        -image [Rappture::icon cancel]
2031    blt::table $f \
2032        0,0 $f.ok  \
2033        0,1 $f.cancel
2034
2035    blt::table $inner \
2036        0,0 $inner.format_l -anchor e \
2037        0,1 $inner.format -anchor w -fill x  \
2038        1,0 $inner.size_l -anchor e \
2039        1,1 $inner.size -anchor w -fill x \
2040        2,0 $inner.bgcolor_l -anchor e \
2041        2,1 $inner.bgcolor -anchor w -fill x \
2042        3,0 $f -cspan 2 -fill x
2043    blt::table configure $inner r0 r1 r2 r3 -pady { 4 0 }
2044    blt::table configure $inner r3 -pady { 4 4 }
2045    $inner.bgcolor value "Black"
2046    $inner.size value "Draft (400x400)"
2047    $inner.format value  "PNG (Portable Network Graphics format)"
2048}
2049
2050itcl::body Rappture::MolvisViewer::snap { w h } {
2051    if { $w <= 0 || $h <= 0 } {
2052        set w [image width $_image(plot)]
2053        set h [image height $_image(plot)]
2054    }
2055    set tag "$_state(client),$_rocker(client)"
2056    if { $_image(id) != "$tag" } {
2057        while { ![info exists _imagecache($tag)] } {
2058            update idletasks
2059            update
2060            after 100
2061        }
2062        if { [info exists _imagecache($tag)] } {
2063            $_image(plot) configure -data $_imagecache($tag)
2064            set _image(id) "$tag"
2065        }
2066    }
2067    set img [image create picture -width $w -height $h]
2068    $img resample $_image(plot)
2069    return $img
2070}
2071
2072# FIXME: Handle 2D vectors
2073itcl::body Rappture::MolvisViewer::ComputeParallelepipedVertices { dataobj } {
2074    # Create a vector for every 3D point
2075    blt::vector point0(3) point1(3) point2(3) point3(3) point4(3) point5(3) \
2076        point6(3) point7(3) origin(3) scale(3)
2077
2078    set count 0
2079    set parent [$dataobj element -as object "components.parallelepiped"]
2080    foreach child [$parent children] {
2081        if { ![string match "vector*" $child] } {
2082            continue
2083        }
2084        incr count
2085        set values [$parent get $child]
2086        regexp -all {,} $values { } values
2087        point$count set $values
2088    }
2089    itcl::delete object $parent
2090    if { $count < 1 || $count > 3 } {
2091        error "bad number of vectors supplied to parallelepiped"
2092    }
2093    point0 set { 0.0 0.0 0.0 }
2094    point4 expr {point2 + point1}
2095    point5 expr {point4 + point3}
2096    point6 expr {point2 + point3}
2097    point7 expr {point1 + point3}
2098
2099    set values [$dataobj get components.parallelepiped.scale]
2100    set n [llength $values]
2101    scale set { 1.0 1.0 1.0 }
2102    if { $n == 1 } {
2103        set scale(0:2) [lindex $values 0]
2104    } elseif { $n == 2 } {
2105        set scale(0:1) [lindex $values 0]
2106    } elseif { $n == 3 } {
2107        scale set $values
2108    }
2109    set values [$dataobj get components.parallelepiped.origin]
2110    set n [llength $values]
2111    origin set { 0.0 0.0 0.0 }
2112    if { $n == 1 } {
2113        set origin(0) [lindex $values 0]
2114    } elseif { $n == 2 } {
2115        set origin(0) [lindex $values 0]
2116        set origin(1) [lindex $values 1]
2117    } elseif { $n == 3 } {
2118        origin set $values
2119    }
2120
2121    # Scale and translate points
2122    for { set i 0 } { $i < 8 } { incr i } {
2123        point${i} expr "(point${i} * scale) + origin"
2124    }
2125
2126    # Generate vertices as a string for PyMOL
2127    set vertices ""
2128    foreach n { 0 1 0 2 0 3 1 4 2 4 2 6 1 7 3 7 5 7 4 5 3 6 5 } {
2129        set values [point${n} range 0 end]
2130        append vertices "\[ [join $values {, }] \], \\\n"
2131    }
2132    set values [point6 range 0 end]
2133    append vertices "\[ [join $values {, }] \]  \\\n"
2134    blt::vector destroy point0 point1 point2 point3 point4 point5 point6 \
2135        point7 origin scale
2136    return $vertices
2137}
2138
2139
2140# ----------------------------------------------------------------------
2141# OPTION: -device
2142# ----------------------------------------------------------------------
2143itcl::configbody Rappture::MolvisViewer::device {
2144    if {$itk_option(-device) != "" } {
2145        if {![Rappture::library isvalid $itk_option(-device)]} {
2146            error "bad value \"$itk_option(-device)\": should be Rappture::library object"
2147        }
2148        $this delete
2149        $this add $itk_option(-device)
2150    } else {
2151        $this delete
2152    }
2153
2154    if { [isconnected] } {
2155        $_dispatcher event -idle !rebuild
2156    }
2157}
2158
Note: See TracBrowser for help on using the repository browser.