source: branches/1.3/gui/scripts/visviewer.tcl @ 4487

Last change on this file since 4487 was 4479, checked in by ldelgass, 10 years ago

merge r4448 from trunk

File size: 38.5 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2
3# ----------------------------------------------------------------------
4#  VisViewer -
5#
6#  This class is the base class for the various visualization viewers
7#  that use the nanoserver render farm.
8#
9# ======================================================================
10#  AUTHOR:  Michael McLennan, Purdue University
11#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
12#
13#  See the file "license.terms" for information on usage and
14#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
15# ======================================================================
16
17itcl::class ::Rappture::VisViewer {
18    inherit itk::Widget
19
20    itk_option define -sendcommand sendCommand SendCommand ""
21    itk_option define -receivecommand receiveCommand ReceiveCommand ""
22
23    private common _servers         ;# array of visualization server lists
24    set _servers(geovis)  "localhost:2015"
25    set _servers(nanovis) "localhost:2000"
26    set _servers(pymol)   "localhost:2020"
27    set _servers(vmdmds)  "localhost:2018"
28    set _servers(vtkvis)  "localhost:2010"
29
30    protected variable _serverType "???";# Type of server.
31    protected variable _sid ""      ;   # socket connection to server
32    private common _done            ;   # Used to indicate status of send.
33    private variable _buffer        ;   # buffer for incoming/outgoing commands
34    private variable _initialized
35    private variable _isOpen 0
36    private variable _afterId -1
37    private variable _icon 0
38
39    # Number of milliseconds to wait before idle timeout.  If greater than 0,
40    # automatically disconnect from the visualization server when idle timeout
41    # is reached.
42    private variable _idleTimeout 43200000; # 12 hours
43    #private variable _idleTimeout 5000;    # 5 seconds
44    #private variable _idleTimeout 0;       # No timeout
45
46    protected variable _maxConnects 100
47    protected variable _outbuf       ;    # buffer for outgoing commands
48    protected variable _buffering 0
49
50    private variable _logging 0
51
52    protected variable _dispatcher "";  # dispatcher for !events
53    protected variable _hosts ""    ;   # list of hosts for server
54    protected variable _parser ""   ;   # interpreter for incoming commands
55    protected variable _image
56    protected variable _hostname
57    protected variable _numConnectTries 0
58    protected variable _debugConsole 0
59    protected variable _reportClientInfo 1
60    protected variable _waitTimeout 0
61
62    constructor { servers args } {
63        # defined below
64    }
65    destructor {
66        # defined below
67    }
68    # Used internally only.
69    private method Shuffle { servers }
70    private method ReceiveHelper {}
71    private method ServerDown {}
72    private method SendHelper {}
73    private method SendHelper.old {}
74    private method WaitDialog { state }
75
76    protected method ToggleConsole {}
77    private method DebugConsole {}
78    private method BuildConsole {}
79    private method HideConsole {}
80    private method TraceComm { channel {data {}} }
81    private method SendDebugCommand {}
82
83    protected method CheckConnection {}
84    protected method Color2RGB { color }
85    protected method ColorsToColormap { colors }
86    protected method Connect { servers }
87    protected method Disconnect {}
88    protected method EnableWaitDialog { timeout }
89    protected method Euler2XYZ { theta phi psi }
90    protected method Flush {}
91    protected method GetColormapList { args }
92    protected method HandleError { args }
93    protected method HandleOk { args }
94    protected method IsConnected {}
95    protected method ReceiveBytes { nbytes }
96    protected method ReceiveEcho { channel {data ""} }
97    protected method SendBytes { bytes }
98    protected method SendCmd {string}
99    protected method SendCmdNoWait {string}
100    protected method SendEcho { channel {data ""} }
101    protected method StartBufferingCommands {}
102    protected method StartWaiting {}
103    protected method StopBufferingCommands {}
104    protected method StopWaiting {}
105
106    private method Waiting { option widget }
107
108    private proc CheckNameList { namelist }  {
109        foreach host $namelist {
110            set pattern {^[a-zA-Z0-9\.]+:[0-9]}
111            if { ![regexp $pattern $host match] } {
112                error "bad visualization server address \"$host\": should be host:port,host:port,..."
113            }
114        }
115    }
116    public proc GetServerList { type } {
117        return $_servers($type)
118    }
119    public proc SetServerList { type namelist } {
120        # Convert the comma separated list into a Tcl list.  OGRE also adds
121        # a trailing comma that we want to ignore.
122        regsub -all "," $namelist " " namelist
123        CheckNameList $namelist
124        set _servers($type) $namelist
125    }
126    public proc RemoveServerFromList { type server } {
127        if { ![info exists _servers($type)] } {
128            error "unknown server type \"$type\""
129        }
130        set i [lsearch $_servers($type) $server]
131        if { $i < 0 } {
132            return
133        }
134        set _servers($type) [lreplace $_servers($type) $i $i]
135    }
136    public proc SetPymolServerList { namelist } {
137        SetServerList "pymol" $namelist
138    }
139    public proc SetNanovisServerList { namelist } {
140        SetServerList "nanovis" $namelist
141    }
142    public proc SetVtkServerList { namelist } {
143        SetServerList "vtk" $namelist
144    }
145}
146
147itk::usual Panedwindow {
148    keep -background -cursor
149}
150
151# ----------------------------------------------------------------------
152# CONSTRUCTOR
153# ----------------------------------------------------------------------
154itcl::body Rappture::VisViewer::constructor { servers args } {
155
156    Rappture::dispatcher _dispatcher
157    $_dispatcher register !serverDown
158    $_dispatcher dispatch $this !serverDown "[itcl::code $this ServerDown]; list"
159    $_dispatcher register !timeout
160    $_dispatcher dispatch $this !timeout "[itcl::code $this Disconnect]; list"
161
162    $_dispatcher register !waiting
163
164    CheckNameList $servers
165    set _buffer(in) ""
166    set _buffer(out) ""
167    #
168    # Create a parser to handle incoming requests
169    #
170    set _parser [interp create -safe]
171    foreach cmd [$_parser eval {info commands}] {
172        $_parser hide $cmd
173    }
174    # Add default handlers for "ok" acknowledgement and server errors.
175    $_parser alias ok       [itcl::code $this HandleOk]
176    $_parser alias viserror [itcl::code $this HandleError]
177
178    #
179    # Set up the widgets in the main body
180    #
181    option add hull.width hull.height
182    pack propagate $itk_component(hull) no
183
184    itk_component add main {
185        Rappture::SidebarFrame $itk_interior.main -resizeframe 1
186    }
187    pack $itk_component(main) -expand yes -fill both
188    set f [$itk_component(main) component frame]
189
190    itk_component add plotarea {
191        frame $f.plotarea -highlightthickness 0 -background black
192    } {
193        ignore -background
194    }
195    pack $itk_component(plotarea) -fill both -expand yes
196    set _image(plot) [image create photo]
197
198    global env
199    if { [info exists env(VISRECORDER)] } {
200        set _logging 1
201        if { [file exists /tmp/recording.log] } {
202            file delete /tmp/recording.log
203        }
204    }
205    eval itk_initialize $args
206}
207
208#
209# destructor --
210#
211itcl::body Rappture::VisViewer::destructor {} {
212    $_dispatcher cancel !timeout
213    interp delete $_parser
214    array unset _done $this
215}
216
217#
218# Shuffle --
219#
220#   Shuffle the list of server hosts.
221#
222itcl::body Rappture::VisViewer::Shuffle { hosts } {
223    set randomHosts {}
224    set ticks [clock clicks]
225    expr {srand($ticks)}
226    for { set i [llength $hosts] } { $i > 0 } { incr i -1 } {
227        set index [expr {round(rand()*$i - 0.5)}]
228        if { $index == $i } {
229            set index [expr $i - 1]
230        }
231        lappend randomHosts [lindex $hosts $index]
232        set hosts [lreplace $hosts $index $index]
233    }
234    return $randomHosts
235}
236
237#
238# ServerDown --
239#
240#    Used internally to let the user know when the connection to the
241#    visualization server has been lost.  Puts up a tip encouraging the
242#    user to press any control to reconnect.
243#
244itcl::body Rappture::VisViewer::ServerDown {} {
245    if { [info exists itk_component(plotarea)] } {
246        set x [expr {[winfo rootx $itk_component(plotarea)]+10}]
247        set y [expr {[winfo rooty $itk_component(plotarea)]+10}]
248    } else {
249        set x 0; set y 0
250    }
251    Rappture::Tooltip::cue @$x,$y "Lost connection to visualization server.  This happens sometimes when there are too many users and the system runs out of memory.\n\nTo reconnect, reset the view or press any other control.  Your picture should come right back up."
252}
253
254#
255# Connect --
256#
257#    Connect to the visualization server (e.g. nanovis, pymolproxy).
258#    Creates an event callback that is triggered when we are idle
259#    (no I/O with the server) for some specified time.
260#
261itcl::body Rappture::VisViewer::Connect { servers } {
262    blt::busy hold $itk_component(hull) -cursor watch
263
264    if { $_numConnectTries > $_maxConnects } {
265        blt::busy release $itk_component(hull)
266        set x [expr {[winfo rootx $itk_component(hull)]+10}]
267        set y [expr {[winfo rooty $itk_component(hull)]+10}]
268        Rappture::Tooltip::cue @$x,$y "Exceeded maximum number of connection attmepts to any $_serverType visualization server. Please contact support."
269        return 0;
270    }
271    foreach server [Shuffle $servers] {
272        puts stderr "connecting to $server..."
273        foreach {hostname port} [split $server ":"] break
274        if { [catch {socket $hostname $port} _sid] != 0 } {
275            set _sid ""
276            RemoveServerFromList $_serverType $server
277            continue
278        }
279        incr _numConnectTries
280        set _hostname $server
281        fconfigure $_sid -translation binary -encoding binary
282       
283        # Read back the server identification string.
284        if { [gets $_sid data] <= 0 } {
285            set _sid ""
286            puts stderr "reading from server"
287            RemoveServerFromList $_serverType $server
288            continue
289        }
290        puts stderr "Render server is $data"
291        # We're connected. Cancel any pending serverDown events and
292        # release the busy window over the hull.
293        $_dispatcher cancel !serverDown
294        if { $_idleTimeout > 0 } {
295            $_dispatcher event -after $_idleTimeout !timeout
296        }
297        blt::busy release $itk_component(hull)
298        fconfigure $_sid -buffering line
299        fileevent $_sid readable [itcl::code $this ReceiveHelper]
300        return 1
301    }
302    blt::busy release $itk_component(hull)
303    set x [expr {[winfo rootx $itk_component(hull)]+10}]
304    set y [expr {[winfo rooty $itk_component(hull)]+10}]
305    Rappture::Tooltip::cue @$x,$y "Can't connect to any $_serverType visualization server.  This may be a network problem.  Wait a few moments and try resetting the view."
306    return 0
307}
308
309#
310# Disconnect --
311#
312#    Clients use this method to disconnect from the current rendering
313#    server.  Cancel any pending idle timeout events.
314#
315itcl::body Rappture::VisViewer::Disconnect {} {
316    after cancel $_afterId
317    $_dispatcher cancel !timeout
318    catch {close $_sid}
319    set _sid ""
320    set _buffer(in) ""
321    set _outbuf ""
322}
323
324#
325# IsConnected --
326#
327#    Indicates if we are currently connected to a server.
328#
329itcl::body Rappture::VisViewer::IsConnected {} {
330    if { $_sid == "" } {
331        return 0
332    }
333    if { [eof $_sid] } {
334        set _sid ""
335        return 0
336    }
337    return 1
338}
339
340#
341# CheckConection --
342#
343#   This routine is called whenever we're about to send/receive data on
344#   the socket connection to the visualization server.  If we're connected,
345#   then reset the timeout event.  Otherwise try to reconnect to the
346#   visualization server.
347#
348itcl::body Rappture::VisViewer::CheckConnection {} {
349    $_dispatcher cancel !timeout
350    if { $_idleTimeout > 0 } {
351        $_dispatcher event -after $_idleTimeout !timeout
352    }
353    if { [IsConnected] } {
354        return 1
355    }
356    if { $_sid != "" } {
357        fileevent $_sid writable ""
358    }
359    # If we aren't connected, assume it's because the connection to the
360    # visualization server broke. Try to open a connection and trigger a
361    # rebuild.
362    $_dispatcher cancel !serverDown
363    set x [expr {[winfo rootx $itk_component(plotarea)]+10}]
364    set y [expr {[winfo rooty $itk_component(plotarea)]+10}]
365    Rappture::Tooltip::cue @$x,$y "Connecting..."
366    set code [catch { Connect } ok]
367    if { $code == 0 && $ok} {
368        $_dispatcher event -idle !rebuild
369        Rappture::Tooltip::cue hide
370    } else {
371        Rappture::Tooltip::cue @$x,$y "Can't connect to any $_serverType visualization server.  This may be a network problem.  Wait a few moments and try resetting the view."
372        return 0
373    }
374    return 1
375}
376
377#
378# Flush --
379#
380#    Flushes the socket.
381#
382itcl::body Rappture::VisViewer::Flush {} {
383    if { [CheckConnection] } {
384        flush $_sid
385    }
386}
387
388
389#
390# SendHelper --
391#
392#   Helper routine called from a file event to send data when the
393#   connection is writable (i.e. not blocked).  Sets a magic variable
394#   _done($this) when we're done.
395#
396itcl::body Rappture::VisViewer::SendHelper {} {
397    if { ![CheckConnection] } {
398        return 0
399    }
400    puts -nonewline $_sid $_buffer(out)
401    flush $_sid
402    set _done($this) 1;                 # Success
403}
404
405#
406# SendHelper.old --
407#
408#   Helper routine called from a file event to send data when the
409#   connection is writable (i.e. not blocked).  Sends data in chunks of 8k
410#   (or less).  Sets magic variable _done($this) to indicate that we're
411#   either finished (success) or could not send bytes to the server
412#   (failure).
413#
414itcl::body Rappture::VisViewer::SendHelper.old {} {
415    if { ![CheckConnection] } {
416        return 0
417    }
418    set bytesLeft [string length $_buffer(out)]
419    if { $bytesLeft > 0} {
420        set chunk [string range $_buffer(out) 0 8095]
421        set _buffer(out)  [string range $_buffer(out) 8096 end]
422        incr bytesLeft -8096
423        set code [catch {
424            if { $bytesLeft > 0 } {
425                puts -nonewline $_sid $chunk
426            } else {
427                puts $_sid $chunk
428            }
429        } err]
430        if { $code != 0 } {
431            puts stderr "error sending data to $_sid: $err"
432            Disconnect
433            set _done($this) 0;     # Failure
434        }
435    } else {
436        set _done($this) 1;     # Success
437    }
438}
439
440#
441# SendBytes --
442#
443#   Send a a string to the visualization server.
444#
445itcl::body Rappture::VisViewer::SendBytes { bytes } {
446    SendEcho >>line $bytes
447    if { ![CheckConnection] } {
448        return 0
449    }
450    StartWaiting
451    # Even though the data is sent in only 1 "puts", we need to verify that
452    # the server is ready first.  Wait for the socket to become writable
453    # before sending anything.
454    set _done($this) 1
455    set _buffer(out) $bytes
456    fileevent $_sid writable [itcl::code $this SendHelper]
457    tkwait variable ::Rappture::VisViewer::_done($this)
458    set _buffer(out) ""
459    if { [IsConnected] } {
460        # The connection may have closed while we were writing to the server.
461        # This can happen if what we sent the server caused it to barf.
462        fileevent $_sid writable ""
463        flush $_sid
464    }
465    return $_done($this)
466}
467
468#
469# StartWaiting --
470#
471#    Read some number of bytes from the visualization server.
472#
473
474itcl::body Rappture::VisViewer::StartWaiting {} {
475    if { $_waitTimeout > 0 } {
476        after cancel $_afterId
477        set _afterId [after $_waitTimeout [itcl::code $this WaitDialog on]]
478    }
479}
480
481itcl::body Rappture::VisViewer::StopWaiting {} {
482    if { $_waitTimeout > 0 } {
483        WaitDialog off
484    }
485}
486
487itcl::body Rappture::VisViewer::EnableWaitDialog { value } {
488    set _waitTimeout $value
489}
490
491#
492# ReceiveBytes --
493#
494#    Read some number of bytes from the visualization server.
495#
496itcl::body Rappture::VisViewer::ReceiveBytes { size } {
497    if { ![CheckConnection] } {
498        return 0
499    }
500    set bytes [read $_sid $size]
501    ReceiveEcho <<line "<read $size bytes"
502    StopWaiting
503    return $bytes
504}
505
506#
507# ReceiveHelper --
508#
509#   Helper routine called from a file event when the connection is readable
510#   (i.e. a command response has been sent by the rendering server.  Reads
511#   the incoming command and executes it in a safe interpreter to handle the
512#   action.
513#
514#       Note: This routine currently only handles command responses from
515#         the visualization server.  It doesn't handle non-blocking
516#         reads from the visualization server.
517#
518#       nv>image -bytes 100000      yes
519#       ...following 100000 bytes...    no
520#
521#   Note: All commands from the render server are on one line.
522#         This is because the render server can send anything
523#         as an error message (restricted again to one line).
524#
525itcl::body Rappture::VisViewer::ReceiveHelper {} {
526    if { ![CheckConnection] } {
527        return 0
528    }
529    set n [gets $_sid line]
530
531    if { $n < 0 } {
532        Disconnect
533        return 0
534    }
535    set line [string trim $line]
536    if { $line == "" } {
537        return
538    }
539    if { [string compare -length 3 $line "nv>"] == 0 } {
540        ReceiveEcho <<line $line
541        append _buffer(in) [string range $line 3 end]
542        append _buffer(in) "\n"
543        if {[info complete $_buffer(in)]} {
544            set request $_buffer(in)
545            set _buffer(in) ""
546            if { [catch {$_parser eval $request} err]  != 0 } {
547                global errorInfo
548                puts stderr "err=$err errorInfo=$errorInfo"
549            }
550        }
551    } elseif { [string compare -length 21 $line "NanoVis Server Error:"] == 0 ||
552               [string compare -length 20 $line "VtkVis Server Error:"] == 0} {
553        # this shows errors coming back from the engine
554        ReceiveEcho <<error $line
555        puts stderr "Render Server Error: $line\n"
556    } else {
557        # this shows errors coming back from the engine
558        ReceiveEcho <<error $line
559        puts stderr "Garbled message: $line\n"
560    }
561}
562
563#
564# Color2RGB --
565#
566#   Converts a color name to a list of r,g,b values needed for the engine.
567#   Each r/g/b component is scaled in the # range 0-1.
568#
569itcl::body Rappture::VisViewer::Color2RGB {color} {
570    foreach {r g b} [winfo rgb $itk_component(hull) $color] break
571    set r [expr {$r/65535.0}]
572    set g [expr {$g/65535.0}]
573    set b [expr {$b/65535.0}]
574    return [list $r $g $b]
575}
576
577#
578# Euler2XYZ --
579#
580#   Converts euler angles for the camera placement the to angles of
581#   rotation about the x/y/z axes, used by the engine.  Returns a list:
582#   {xangle, yangle, zangle}.
583#
584itcl::body Rappture::VisViewer::Euler2XYZ {theta phi psi} {
585    set xangle [expr {$theta-90.0}]
586    set yangle [expr {180.0-$phi}]
587    set zangle $psi
588    return [list $xangle $yangle $zangle]
589}
590
591#
592# SendEcho --
593#
594#     Used internally to echo sent data to clients interested in this widget.
595#     If the -sendcommand option is set, then it is invoked in the global scope
596#     with the <channel> and <data> values as arguments.  Otherwise, this does
597#     nothing.
598#
599itcl::body Rappture::VisViewer::SendEcho {channel {data ""}} {
600    if { $_logging }  {
601        set f [open "/tmp/recording.log" "a"]
602        puts $f $data
603        close $f
604    }
605    #puts stderr ">>($data)"
606    if {[string length $itk_option(-sendcommand)] > 0} {
607        uplevel #0 $itk_option(-sendcommand) [list $channel $data]
608    }
609}
610
611#
612# ReceiveEcho --
613#
614#     Echoes received data to clients interested in this widget.  If the
615#     -receivecommand option is set, then it is invoked in the global scope
616#     with the <channel> and <data> values as arguments.  Otherwise, this
617#     does nothing.
618#
619itcl::body Rappture::VisViewer::ReceiveEcho {channel {data ""}} {
620    #puts stderr "<<line $data"
621    if {[string length $itk_option(-receivecommand)] > 0} {
622        uplevel #0 $itk_option(-receivecommand) [list $channel $data]
623    }
624}
625
626itcl::body Rappture::VisViewer::WaitDialog { state } {
627    after cancel $_afterId
628    set _afterId -1
629    if { $state } {
630        if { [winfo exists $itk_component(plotarea).view.splash] } {
631            return
632        }
633        set inner [frame $itk_component(plotarea).view.splash]
634        $inner configure -relief raised -bd 2
635        label $inner.text1 -text "Working...\nPlease wait." \
636            -font "Arial 10"
637        label $inner.icon
638        pack $inner -expand yes -anchor c
639        blt::table $inner \
640            0,0 $inner.text1 -anchor w \
641            0,1 $inner.icon
642        Waiting start $inner.icon
643    } else {
644        if { ![winfo exists $itk_component(plotarea).view.splash] } {
645            return
646        }
647        Waiting stop $itk_component(plotarea).view.splash
648        destroy $itk_component(plotarea).view.splash
649    }
650}
651
652itcl::body Rappture::VisViewer::Waiting { option widget } {
653    switch -- $option {
654        "start" {
655            $_dispatcher dispatch $this !waiting \
656                "[itcl::code $this Waiting "next" $widget] ; list"
657            set _icon 0
658            $widget configure -image [Rappture::icon bigroller${_icon}]
659            $_dispatcher event -after 150 !waiting
660        }
661        "next" {
662            incr _icon
663            if { $_icon >= 8 } {
664                set _icon 0
665            }
666            $widget configure -image [Rappture::icon bigroller${_icon}]
667            $_dispatcher event -after 150 !waiting
668        }
669        "stop" {
670            $_dispatcher cancel !waiting
671        }
672    }
673}
674
675#
676# HideConsole --
677#
678#    Hide the debug console by withdrawing its toplevel window.
679#
680itcl::body Rappture::VisViewer::HideConsole {} {
681    set _debugConsole 0
682    DebugConsole
683}
684
685#
686# BuildConsole --
687#
688#    Create and pack the widgets that make up the debug console: a text
689#    widget to display the communication and an entry widget to type
690#    in commands to send to the render server.
691#
692itcl::body Rappture::VisViewer::BuildConsole {} {
693    toplevel .renderconsole
694    wm protocol .renderconsole WM_DELETE_WINDOW [itcl::code $this HideConsole]
695    set f .renderconsole
696    frame $f.send
697    pack $f.send -side bottom -fill x
698    label $f.send.l -text "Send:"
699    pack $f.send.l -side left
700    itk_component add command {
701        entry $f.send.e -background white
702    } {
703        ignore -background
704    }
705    pack $f.send.e -side left -expand yes -fill x
706    bind $f.send.e <Return> [itcl::code $this SendDebugCommand]
707    bind $f.send.e <KP_Enter> [itcl::code $this SendDebugCommand]
708    scrollbar $f.sb -orient vertical -command "$f.comm yview"
709    pack $f.sb -side right -fill y
710    itk_component add trace {
711        text $f.comm -wrap char -yscrollcommand "$f.sb set" -background white
712    } {
713        ignore -background
714    }
715    pack $f.comm -expand yes -fill both
716    bind $f.comm <Control-F1> [itcl::code $this ToggleConsole]
717    bind $f.comm <Enter> [list focus %W]
718    bind $f.send.e <Control-F1> [itcl::code $this ToggleConsole]
719
720    $itk_component(trace) tag configure error -foreground red \
721        -font -*-courier-medium-o-normal-*-*-120-*
722    $itk_component(trace) tag configure incoming -foreground blue
723}
724
725#
726# ToggleConsole --
727#
728#    This is used by derived classes to turn on/off debuging.  It's
729#    up the to derived class to decide how to turn on/off debugging.
730#
731itcl::body Rappture::VisViewer::ToggleConsole {} {
732    if { $_debugConsole } {
733        set _debugConsole 0
734    } else {
735        set _debugConsole 1
736    }
737    DebugConsole
738}
739
740#
741# DebugConsole --
742#
743#    Based on the value of the variable _debugConsole, turns on/off
744#    debugging. This is done by setting/unsetting a procedure that
745#    is called whenever new characters are received or sent on the
746#    socket to the render server.  Additionally, the debug console
747#    is created if necessary and hidden/shown.
748#
749itcl::body Rappture::VisViewer::DebugConsole {} {
750    if { ![winfo exists .renderconsole] } {
751        BuildConsole
752    }
753    if { $_debugConsole } {
754        $this configure -sendcommand [itcl::code $this TraceComm]
755        $this configure -receivecommand [itcl::code $this TraceComm]
756        wm deiconify .renderconsole
757    } else {
758        $this configure -sendcommand ""
759        $this configure -receivecommand ""
760        wm withdraw .renderconsole
761    }
762}
763
764# ----------------------------------------------------------------------
765# USAGE: TraceComm <channel> <data>
766#
767# Invoked automatically whenever there is communication between
768# the rendering widget and the server.  Eavesdrops on the communication
769# and posts the commands in a text viewer.
770# ----------------------------------------------------------------------
771itcl::body Rappture::VisViewer::TraceComm {channel {data ""}} {
772    $itk_component(trace) configure -state normal
773    switch -- $channel {
774        closed {
775            $itk_component(trace) insert end "--CLOSED--\n" error
776        }
777        <<line {
778            $itk_component(trace) insert end $data incoming "\n" incoming
779        }
780        >>line {
781            $itk_component(trace) insert end $data outgoing "\n" outgoing
782        }
783        error {
784            $itk_component(trace) insert end $data error "\n" error
785        }
786        default {
787            $itk_component(trace) insert end "$data\n"
788        }
789    }
790    $itk_component(trace) configure -state disabled
791    $itk_component(trace) see end
792}
793
794# ----------------------------------------------------------------------
795# USAGE: SendDebugCommand
796#
797# Invoked automatically whenever the user enters a command and
798# presses <Return>.  Sends the command along to the rendering
799# widget.
800# ----------------------------------------------------------------------
801itcl::body Rappture::VisViewer::SendDebugCommand {} {
802    set cmd [$itk_component(command) get]
803    append cmd "\n"
804    SendBytes $cmd
805    $itk_component(command) delete 0 end
806}
807
808#
809# HandleOk --
810#
811#       This handles the "ok" response from the server that acknowledges
812#       the reception of a server command, but does not produce an image.
813#       It may pass an argument such as "-token 9" that could be used to
814#       determine how many commands have been processed by the server.
815#
816itcl::body Rappture::VisViewer::HandleOk { args } {
817    if { $_waitTimeout > 0 } {
818        StopWaiting
819    }
820}
821
822#
823# HandleError --
824#
825#       This handles the "viserror" response from the server that reports
826#       that a client-initiated error has occurred on the server.
827#
828itcl::body Rappture::VisViewer::HandleError { args } {
829    array set info {
830        -token "???"
831        -bytes 0
832        -type "???"
833    }
834    array set info $args
835    set bytes [ReceiveBytes $info(-bytes)]
836    if { $info(-type) == "error" } {
837        set popup $itk_component(hull).error
838        if { ![winfo exists $popup] } {
839            Rappture::Balloon $popup \
840                -title "Render Server Error"
841            set inner [$popup component inner]
842            label $inner.summary -text "" -anchor w
843
844            Rappture::Scroller $inner.scrl \
845                -xscrollmode auto -yscrollmode auto
846            text $inner.scrl.text \
847                -font "Arial 9 " -background white -relief sunken -bd 1 \
848                -height 5 -wrap word -width 60
849            $inner.scrl contents $inner.scrl.text
850            button $inner.ok -text "Dismiss" -command [list $popup deactivate] \
851                -font "Arial 9"
852            blt::table $inner \
853                0,0 $inner.scrl -fill both \
854                1,0 $inner.ok
855            $inner.scrl.text tag configure normal -font "Arial 9"
856            $inner.scrl.text tag configure italic -font "Arial 9 italic"
857            $inner.scrl.text tag configure bold -font "Arial 10 bold"
858            $inner.scrl.text tag configure code -font "Courier 10 bold"
859        } else {
860            $popup deactivate
861        }
862        update
863        set inner [$popup component inner]
864        $inner.scrl.text delete 0.0 end
865       
866        $inner.scrl.text configure -state normal
867        $inner.scrl.text insert end "The following error was reported by the render server:\n\n" bold
868        $inner.scrl.text insert end $bytes code
869        $inner.scrl.text configure -state disabled
870        update
871        $popup activate $itk_component(hull) below
872    } else {
873        ReceiveEcho <<error $bytes
874        puts stderr "Render server error:\n$bytes"
875    }
876}
877
878itcl::body Rappture::VisViewer::GetColormapList { args } {
879    array set opts {
880        -includeDefault 0
881        -includeElementDefault 0
882        -includeNone 0
883    }
884    if {[llength $args] > 0} {
885        foreach opt $args {
886            set opts($opt) 1
887        }
888    }
889    set colormaps [list]
890    if {$opts(-includeDefault)} {
891        lappend colormaps "default" "default"
892    }
893    if {$opts(-includeElementDefault)} {
894        lappend colormaps "elementDefault" "elementDefault"
895    }
896    lappend colormaps \
897        "BCGYR"              "BCGYR"            \
898        "BGYOR"              "BGYOR"            \
899        "blue-to-brown"      "blue-to-brown"    \
900        "blue-to-orange"     "blue-to-orange"   \
901        "blue-to-grey"       "blue-to-grey"     \
902        "green-to-magenta"   "green-to-magenta" \
903        "greyscale"          "greyscale"        \
904        "nanohub"            "nanohub"          \
905        "rainbow"            "rainbow"          \
906        "spectral"           "spectral"         \
907        "ROYGB"              "ROYGB"            \
908        "RYGCB"              "RYGCB"            \
909        "white-to-blue"      "white-to-blue"    \
910        "brown-to-blue"      "brown-to-blue"    \
911        "grey-to-blue"       "grey-to-blue"     \
912        "orange-to-blue"     "orange-to-blue"
913    if {$opts(-includeNone)} {
914        lappend colormaps "none" "none"
915    }
916    return $colormaps
917}
918
919itcl::body Rappture::VisViewer::ColorsToColormap { colors } {
920    switch -- $colors {
921        "grey-to-blue" {
922            return {
923                0.0                      0.200 0.200 0.200
924                0.14285714285714285      0.400 0.400 0.400
925                0.2857142857142857       0.600 0.600 0.600
926                0.42857142857142855      0.900 0.900 0.900
927                0.5714285714285714       0.800 1.000 1.000
928                0.7142857142857143       0.600 1.000 1.000
929                0.8571428571428571       0.400 0.900 1.000
930                1.0                      0.000 0.600 0.800
931            }
932        }
933        "blue-to-grey" {
934            return {
935                0.0                     0.000 0.600 0.800
936                0.14285714285714285     0.400 0.900 1.000
937                0.2857142857142857      0.600 1.000 1.000
938                0.42857142857142855     0.800 1.000 1.000
939                0.5714285714285714      0.900 0.900 0.900
940                0.7142857142857143      0.600 0.600 0.600
941                0.8571428571428571      0.400 0.400 0.400
942                1.0                     0.200 0.200 0.200
943            }
944        }
945        "white-to-blue" {
946            return {
947                0.0                     0.900 1.000 1.000
948                0.1111111111111111      0.800 0.983 1.000
949                0.2222222222222222      0.700 0.950 1.000
950                0.3333333333333333      0.600 0.900 1.000
951                0.4444444444444444      0.500 0.833 1.000
952                0.5555555555555556      0.400 0.750 1.000
953                0.6666666666666666      0.300 0.650 1.000
954                0.7777777777777778      0.200 0.533 1.000
955                0.8888888888888888      0.100 0.400 1.000
956                1.0                     0.000 0.250 1.000
957            }
958        }
959        "brown-to-blue" {
960            return {
961                0.0                             0.200   0.100   0.000
962                0.09090909090909091             0.400   0.187   0.000
963                0.18181818181818182             0.600   0.379   0.210
964                0.2727272727272727              0.800   0.608   0.480
965                0.36363636363636365             0.850   0.688   0.595
966                0.45454545454545453             0.950   0.855   0.808
967                0.5454545454545454              0.800   0.993   1.000
968                0.6363636363636364              0.600   0.973   1.000
969                0.7272727272727273              0.400   0.940   1.000
970                0.8181818181818182              0.200   0.893   1.000
971                0.9090909090909091              0.000   0.667   0.800
972                1.0                             0.000   0.480   0.600
973            }
974        }
975        "blue-to-brown" {
976            return {
977                0.0                             0.000   0.480   0.600
978                0.09090909090909091             0.000   0.667   0.800
979                0.18181818181818182             0.200   0.893   1.000
980                0.2727272727272727              0.400   0.940   1.000
981                0.36363636363636365             0.600   0.973   1.000
982                0.45454545454545453             0.800   0.993   1.000
983                0.5454545454545454              0.950   0.855   0.808
984                0.6363636363636364              0.850   0.688   0.595
985                0.7272727272727273              0.800   0.608   0.480
986                0.8181818181818182              0.600   0.379   0.210
987                0.9090909090909091              0.400   0.187   0.000
988                1.0                             0.200   0.100   0.000
989            }
990        }
991        "blue-to-orange" {
992            return {
993                0.0                             0.000   0.167   1.000
994                0.09090909090909091             0.100   0.400   1.000
995                0.18181818181818182             0.200   0.600   1.000
996                0.2727272727272727              0.400   0.800   1.000
997                0.36363636363636365             0.600   0.933   1.000
998                0.45454545454545453             0.800   1.000   1.000
999                0.5454545454545454              1.000   1.000   0.800
1000                0.6363636363636364              1.000   0.933   0.600
1001                0.7272727272727273              1.000   0.800   0.400
1002                0.8181818181818182              1.000   0.600   0.200
1003                0.9090909090909091              1.000   0.400   0.100
1004                1.0                             1.000   0.167   0.000
1005            }
1006        }
1007        "orange-to-blue" {
1008            return {
1009                0.0                             1.000   0.167   0.000
1010                0.09090909090909091             1.000   0.400   0.100
1011                0.18181818181818182             1.000   0.600   0.200
1012                0.2727272727272727              1.000   0.800   0.400
1013                0.36363636363636365             1.000   0.933   0.600
1014                0.45454545454545453             1.000   1.000   0.800
1015                0.5454545454545454              0.800   1.000   1.000
1016                0.6363636363636364              0.600   0.933   1.000
1017                0.7272727272727273              0.400   0.800   1.000
1018                0.8181818181818182              0.200   0.600   1.000
1019                0.9090909090909091              0.100   0.400   1.000
1020                1.0                             0.000   0.167   1.000
1021            }
1022        }
1023        "rainbow" {
1024            set clist {
1025                "#EE82EE"
1026                "#4B0082"
1027                "blue"
1028                "#008000"
1029                "yellow"
1030                "#FFA500"
1031                "red"
1032            }
1033        }
1034        "BGYOR" {
1035            set clist {
1036                "blue"
1037                "#008000"
1038                "yellow"
1039                "#FFA500"
1040                "red"
1041            }
1042        }
1043        "ROYGB" {
1044            set clist {
1045                "red"
1046                "#FFA500"
1047                "yellow"
1048                "#008000"
1049                "blue"
1050            }
1051        }
1052        "RYGCB" {
1053            set clist {
1054                "red"
1055                "yellow"
1056                "green"
1057                "cyan"
1058                "blue"
1059            }
1060        }
1061        "BCGYR" {
1062            set clist {
1063                "blue"
1064                "cyan"
1065                "green"
1066                "yellow"
1067                "red"
1068            }
1069        }
1070        "spectral" {
1071            return {
1072                0.0 0.150 0.300 1.000
1073                0.1 0.250 0.630 1.000
1074                0.2 0.450 0.850 1.000
1075                0.3 0.670 0.970 1.000
1076                0.4 0.880 1.000 1.000
1077                0.5 1.000 1.000 0.750
1078                0.6 1.000 0.880 0.600
1079                0.7 1.000 0.680 0.450
1080                0.8 0.970 0.430 0.370
1081                0.9 0.850 0.150 0.196
1082                1.0 0.650 0.000 0.130
1083            }
1084        }
1085        "green-to-magenta" {
1086            return {
1087                0.0 0.000 0.316 0.000
1088                0.06666666666666667 0.000 0.526 0.000
1089                0.13333333333333333 0.000 0.737 0.000
1090                0.2 0.000 0.947 0.000
1091                0.26666666666666666 0.316 1.000 0.316
1092                0.3333333333333333 0.526 1.000 0.526
1093                0.4 0.737 1.000 0.737
1094                0.4666666666666667 1.000 1.000 1.000
1095                0.5333333333333333 1.000 0.947 1.000
1096                0.6 1.000 0.737 1.000
1097                0.6666666666666666 1.000 0.526 1.000
1098                0.7333333333333333 1.000 0.316 1.000
1099                0.8 0.947 0.000 0.947
1100                0.8666666666666667 0.737 0.000 0.737
1101                0.9333333333333333 0.526 0.000 0.526
1102                1.0 0.316 0.000 0.316
1103            }
1104        }
1105        "greyscale" {
1106            return {
1107                0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
1108            }
1109        }
1110        "nanohub" {
1111            set clist "white yellow green cyan blue magenta"
1112        }
1113        default {
1114            set clist [split $colors ":"]
1115        }
1116    }
1117    set cmap {}
1118    if { [llength $clist] == 1 } {
1119        set rgb [Color2RGB $clist]
1120        append cmap "0.0 $rgb 1.0 $rgb"
1121    } else {
1122        for {set i 0} {$i < [llength $clist]} {incr i} {
1123            set x [expr {double($i)/([llength $clist]-1)}]
1124            set color [lindex $clist $i]
1125            append cmap "$x [Color2RGB $color] "
1126        }
1127    }
1128    return $cmap
1129}
1130
1131
1132#
1133# StartBufferingCommands --
1134#
1135itcl::body Rappture::VisViewer::StartBufferingCommands { } {
1136    incr _buffering
1137    if { $_buffering == 1 } {
1138        set _outbuf ""
1139    }
1140}
1141
1142#
1143# StopBufferingCommands --
1144#
1145#       This gets called when we want to stop buffering the commands for
1146#       the server and actually send then to the server.  Note that there's
1147#       a reference count on buffering.  This is so that you can can
1148#       Start/Stop multiple times without worrying about the current state.
1149#
1150itcl::body Rappture::VisViewer::StopBufferingCommands { } {
1151    incr _buffering -1
1152    if { $_buffering == 0 } {
1153        SendBytes $_outbuf
1154        set _outbuf ""
1155    }
1156}
1157
1158#
1159# SendCmd
1160#
1161#       Send commands off to the rendering server.  If we're currently
1162#       sending data objects to the server, buffer the commands to be
1163#       sent later.
1164#
1165itcl::body Rappture::VisViewer::SendCmd {string} {
1166    if { $_buffering } {
1167        append _outbuf $string "\n"
1168    } else {
1169        SendBytes "$string\n"
1170    }
1171}
1172
1173#
1174# SendCmdNoWait
1175#
1176#       Send commands off to the rendering server.  If we're currently
1177#       sending data objects to the server, buffer the commands to be
1178#       sent later.
1179#
1180itcl::body Rappture::VisViewer::SendCmdNoWait {string} {
1181    if { $_buffering } {
1182        append _outbuf $string "\n"
1183    } else {
1184        SendBytes "$string\n"
1185    }
1186}
Note: See TracBrowser for help on using the repository browser.