source: trunk/gui/scripts/controls.tcl @ 3074

Last change on this file since 3074 was 2992, checked in by gah, 13 years ago

Migrated drawing controls from branch

File size: 26.2 KB
Line 
1# ----------------------------------------------------------------------
2#  COMPONENT: controls - a container for various Rappture controls
3#
4#  This widget is a smart frame acting as a container for controls.
5#  Controls are added to this panel, and the panel itself decides
6#  how to arrange them given available space.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2005  Purdue Research Foundation
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16
17option add *Controls.padding 4 widgetDefault
18option add *Controls.labelFont \
19    -*-helvetica-medium-r-normal-*-12-* widgetDefault
20
21itcl::class Rappture::Controls {
22    inherit itk::Widget
23
24    itk_option define -padding padding Padding 0
25
26    constructor {owner args} { # defined below }
27    destructor { # defined below }
28
29    public method insert {pos path}
30    public method delete {first {last ""}}
31    public method index {name}
32    public method control {args}
33    public method refresh {}
34
35    protected method _layout {}
36    protected method _monitor {name state}
37    protected method _controlChanged {name}
38    protected method _controlValue {path {units ""}}
39    protected method _formatLabel {str}
40    protected method _changeTabs {}
41    protected method _resize {}
42
43    private variable _owner ""       ;# controls belong to this owner
44    private variable _tabs ""        ;# optional tabset for groups
45    private variable _frame ""       ;# pack controls into this frame
46    private variable _counter 0      ;# counter for control names
47    private variable _dispatcher ""  ;# dispatcher for !events
48    private variable _controls ""    ;# list of known controls
49    private variable _showing ""     ;# list of enabled (showing) controls
50    private variable _name2info      ;# maps control name => info
51    private variable _scheme ""      ;# layout scheme (tabs/hlabels)
52}
53                                                                               
54itk::usual Controls {
55}
56
57# ----------------------------------------------------------------------
58# CONSTRUCTOR
59# ----------------------------------------------------------------------
60itcl::body Rappture::Controls::constructor {owner args} {
61    Rappture::dispatcher _dispatcher
62    $_dispatcher register !layout
63    $_dispatcher dispatch $this !layout "[itcl::code $this _layout]; list"
64    $_dispatcher register !resize
65    $_dispatcher dispatch $this !resize "[itcl::code $this _resize]; list"
66
67    set _owner $owner
68
69    Rappture::Scroller $itk_interior.sc -xscrollmode none -yscrollmode auto
70    pack $itk_interior.sc -expand yes -fill both
71    set f [$itk_interior.sc contents frame]
72
73    set _tabs [blt::tabset $f.tabs -borderwidth 0 -relief flat \
74        -side top -tearoff 0 -highlightthickness 0 \
75        -selectbackground $itk_option(-background) \
76        -selectcommand [itcl::code $this _changeTabs]]
77
78    set _frame [frame $f.inner]
79    pack $_frame -expand yes -fill both
80
81    #
82    # Put this frame in whenever the control frame is empty.
83    # It forces the size to contract back now when controls are deleted.
84    #
85    frame $_frame.empty -width 1 -height 1
86
87    #
88    # Set up a binding that all inserted widgets will use so that
89    # we can monitor their size changes.
90    #
91    bind Controls-$this <Configure> \
92        [list $_dispatcher event -idle !resize]
93
94    eval itk_initialize $args
95}
96
97# ----------------------------------------------------------------------
98# DESTRUCTOR
99# ----------------------------------------------------------------------
100itcl::body Rappture::Controls::destructor {} {
101    delete 0 end
102}
103
104# ----------------------------------------------------------------------
105# USAGE: insert <pos> <path>
106#
107# Clients use this to insert a control into this panel.  The control
108# is inserted into the list at position <pos>, which can be an integer
109# starting from 0 or the keyword "end".  Information about the control
110# is taken from the specified <path>.
111#
112# Returns a name that can be used to identify the control in other
113# methods.
114# ----------------------------------------------------------------------
115itcl::body Rappture::Controls::insert {pos path} {
116    if {"end" == $pos} {
117        set pos [llength $_controls]
118    } elseif {![string is integer $pos]} {
119        error "bad index \"$pos\": should be integer or \"end\""
120    }
121
122    incr _counter
123    set name "control$_counter"
124    set path [$_owner xml element -as path $path]
125
126    set _name2info($name-path) $path
127    set _name2info($name-label) ""
128    set _name2info($name-type) ""
129    set _name2info($name-value) [set w $_frame.v$name]
130    set _name2info($name-enable) "yes"
131    set _name2info($name-disablestyle) "greyout"
132
133    set type [$_owner xml element -as type $path]
134    set _name2info($name-type) $type
135    switch -- $type {
136        choice {
137            Rappture::ChoiceEntry $w $_owner $path
138            bind $w <<Value>> [itcl::code $this _controlChanged $name]
139        }
140        group {
141            Rappture::GroupEntry $w $_owner $path
142        }
143        loader {
144            Rappture::Loader $w $_owner $path -tool [$_owner tool]
145            bind $w <<Value>> [itcl::code $this _controlChanged $name]
146        }
147        number {
148            Rappture::NumberEntry $w $_owner $path
149            bind $w <<Value>> [itcl::code $this _controlChanged $name]
150        }
151        integer {
152            Rappture::IntegerEntry $w $_owner $path
153            bind $w <<Value>> [itcl::code $this _controlChanged $name]
154        }
155        boolean {
156            Rappture::BooleanEntry $w $_owner $path
157            bind $w <<Value>> [itcl::code $this _controlChanged $name]
158        }
159        string {
160            Rappture::TextEntry $w $_owner $path
161            bind $w <<Value>> [itcl::code $this _controlChanged $name]
162        }
163        drawing {
164            Rappture::DrawingEntry $w $_owner $path
165        }
166        image {
167            Rappture::ImageEntry $w $_owner $path
168        }
169        control {
170            set label [$_owner xml get $path.label]
171            if {"" == $label} { set label "Simulate" }
172            set service [$_owner xml get $path.service]
173            button $w -text $label -command [list $service run]
174        }
175        separator {
176            # no widget to create
177            set _name2info($name-value) "--"
178        }
179        note {
180            Rappture::Note $w $_owner $path
181        }
182        periodicelement {
183            Rappture::PeriodicElementEntry $w $_owner $path
184            bind $w <<Value>> [itcl::code $this _controlChanged $name]
185        }
186        default {
187            error "don't know how to add control type \"$type\""
188        }
189    }
190
191    #
192    # If this element has an <enable> expression, then register
193    # its controlling widget here.
194    #
195    set notify [string trim [$_owner xml get $path.about.notify]]
196
197    set disablestyle [string trim [$_owner xml get $path.about.disablestyle]]
198    if { $disablestyle != "" } {
199        set _name2info($name-disablestyle) $disablestyle
200    }
201    #
202    # If this element has an <enable> expression, then register
203    # its controlling widget here.
204    #
205    set enable [string trim [$_owner xml get $path.about.enable]]
206    if {"" == $enable} {
207        set enable yes
208    }
209    if {![string is boolean $enable]} {
210        set re {([a-zA-Z_]+[0-9]*|\([^\(\)]+\)|[a-zA-Z_]+[0-9]*\([^\(\)]+\))(\.([a-zA-Z_]+[0-9]*|\([^\(\)]+\)|[a-zA-Z_]+[0-9]*\([^\(\)]+\)))*(:[-a-zA-Z0-9/]+)?}
211        set rest $enable
212        set enable ""
213        set deps ""
214        while {1} {
215            if {[regexp -indices $re $rest match]} {
216                foreach {s0 s1} $match break
217
218                if {[string index $rest [expr {$s0-1}]] == "\""
219                      && [string index $rest [expr {$s1+1}]] == "\""} {
220                    # string in ""'s? then leave it alone
221                    append enable [string range $rest 0 $s1]
222                    set rest [string range $rest [expr {$s1+1}] end]
223                } else {
224                    #
225                    # This is a symbol which should be substituted
226                    # it can be either:
227                    #   input.foo.bar
228                    #   input.foo.bar:units
229                    #
230                    set cpath [string range $rest $s0 $s1]
231                    set parts [split $cpath :]
232                    set ccpath [lindex $parts 0]
233                    set units [lindex $parts 1]
234
235                    # make sure we have the standard path notation
236                    set stdpath [$_owner regularize $ccpath]
237                    if {"" == $stdpath} {
238                        puts stderr "WARNING: don't recognize parameter $cpath in <enable> expression for $path.  This may be buried in a structure that is not yet loaded."
239                        set stdpath $ccpath
240                    }
241                    # substitute [_controlValue ...] call in place of path
242                    append enable [string range $rest 0 [expr {$s0-1}]]
243                    append enable [format {[_controlValue %s %s]} $stdpath $units]
244                    lappend deps $stdpath
245                    set rest [string range $rest [expr {$s1+1}] end]
246                }
247            } else {
248                append enable $rest
249                break
250            }
251        }
252
253        foreach cpath $deps {
254            $_owner dependenciesfor $cpath $path
255        }
256    }
257    set _name2info($name-enable) $enable
258
259    set hidden [$_owner xml get $_name2info($name-path).hide]
260    if { $hidden != "" } {
261        set _name2info($name-enable) [expr !$hidden]
262    }
263    $_owner widgetfor $path $w
264
265    if {[lsearch {control group separator note} $type] < 0} {
266        # make a label for this control
267        set label [$w label]
268        if {"" != $label} {
269            set _name2info($name-label) $_frame.l$name
270            set font [option get $itk_component(hull) labelFont Font]
271            label $_name2info($name-label) -text [_formatLabel $label] \
272                -font $font
273        }
274
275        # register the tooltip for this control
276        set tip [$w tooltip]
277        if {"" != $tip} {
278            Rappture::Tooltip::for $w $tip
279
280            # add the tooltip to the label too, if there is one
281            if {$_name2info($name-label) != ""} {
282                Rappture::Tooltip::for $_name2info($name-label) $tip
283            }
284        }
285    }
286
287    # insert the new control onto the known list
288    set _controls [linsert $_controls $pos $name]
289    _monitor $name on
290
291    # now that we have a new control, we should fix the layout
292    $_dispatcher event -idle !layout
293    _controlChanged $name
294
295    return $name
296}
297
298# ----------------------------------------------------------------------
299# USAGE: delete <first> ?<last>?
300#
301# Clients use this to delete one or more controls from this widget.
302# The <first> and <last> represent the integer index of the desired
303# control.  You can use the "index" method to convert a control name to
304# its integer index.  If only <first> is specified, then that one
305# control is deleted.  If <last> is specified, then all controls in the
306# range <first> to <last> are deleted.
307# ----------------------------------------------------------------------
308itcl::body Rappture::Controls::delete {first {last ""}} {
309    if {$last == ""} {
310        set last $first
311    }
312    if {![regexp {^[0-9]+|end$} $first]} {
313        error "bad index \"$first\": should be integer or \"end\""
314    }
315    if {![regexp {^[0-9]+|end$} $last]} {
316        error "bad index \"$last\": should be integer or \"end\""
317    }
318
319    foreach name [lrange $_controls $first $last] {
320        _monitor $name off
321
322        if {"" != $_name2info($name-label)} {
323            destroy $_name2info($name-label)
324        }
325        if {"" != $_name2info($name-value)} {
326            destroy $_name2info($name-value)
327        }
328        $_owner widgetfor $_name2info($name-path) ""
329        array unset _name2info $name-*
330    }
331    set _controls [lreplace $_controls $first $last]
332
333    $_dispatcher event -idle !layout
334}
335
336# ----------------------------------------------------------------------
337# USAGE: index <name>|@n
338#
339# Clients use this to convert a control <name> into its corresponding
340# integer index.  Returns an error if the <name> is not recognized.
341# ----------------------------------------------------------------------
342itcl::body Rappture::Controls::index {name} {
343    set i [lsearch $_controls $name]
344    if {$i >= 0} {
345        return $i
346    }
347    if {[regexp {^@([0-9]+)$} $name match i]} {
348        return $i
349    }
350    if {$name == "end"} {
351        return [expr {[llength $_controls]-1}]
352    }
353    error "bad control name \"$name\": should be @int or one of [join [lsort $_controls] {, }]"
354}
355
356# ----------------------------------------------------------------------
357# USAGE: control ?-label|-value|-path|-enable? ?<name>|@n?
358#
359# Clients use this to get information about controls.  With no args, it
360# returns a list of all control names.  Otherwise, it returns the frame
361# associated with a control name.  The -label option requests the label
362# widget instead of the value widget.  The -path option requests the
363# path within the XML that the control affects.  The -enable option
364# requests the enabling condition for this control.
365# ----------------------------------------------------------------------
366itcl::body Rappture::Controls::control {args} {
367    if {[llength $args] == 0} {
368        return $_controls
369    }
370    Rappture::getopts args params {
371        flag switch -value default
372        flag switch -label
373        flag switch -path
374        flag switch -enable
375        flag switch -disablestyle
376    }
377    if {[llength $args] == 0} {
378        error "missing control name"
379    }
380    set i [index [lindex $args 0]]
381    set name [lindex $_controls $i]
382
383    set opt $params(switch)
384    return $_name2info($name$opt)
385}
386
387# ----------------------------------------------------------------------
388# USAGE: refresh
389#
390# Clients use this to refresh the layout of the control panel
391# whenever a widget within the panel changes visibility state.
392# ----------------------------------------------------------------------
393itcl::body Rappture::Controls::refresh {} {
394    $_dispatcher event -idle !layout
395}
396
397# ----------------------------------------------------------------------
398# USAGE: _layout
399#
400# Used internally to fix the layout of controls whenever controls
401# are added or deleted, or when the control arrangement changes.
402# There are a lot of heuristics here trying to achieve a "good"
403# arrangement of controls.
404# ----------------------------------------------------------------------
405itcl::body Rappture::Controls::_layout {} {
406    #
407    # Clear any existing layout
408    #
409    foreach name $_controls {
410        foreach elem {label value} {
411            set w $_name2info($name-$elem)
412            if {$w != "" && [winfo exists $w]} {
413                grid forget $w
414            }
415        }
416    }
417    if {[$_tabs size] > 0} {
418        $_tabs delete 0 end
419    }
420    grid forget $_frame.empty
421
422    #
423    # Decide which widgets should be shown and which should be hidden.
424    #
425    set hidden ""
426    set showing ""
427    foreach name $_controls {
428        set show 1
429        set cond $_name2info($name-enable)
430        if {[string is boolean $cond] && !$cond} {
431            # hard-coded "off" -- ignore completely
432        } elseif {[catch {expr $cond} show] == 0} {
433            set type $_name2info($name-type)
434            set disablestyle $_name2info($name-disablestyle)
435            set lwidget $_name2info($name-label)
436            set vwidget $_name2info($name-value)
437            if {[lsearch -exact {group image structure} $type] >= 0 ||
438                $disablestyle == "hide" } {
439                if {$show ne "" && $show} {
440                    lappend showing $name
441                } else {
442                    lappend hidden $name
443                }
444            } else {
445                # show other objects, but enable/disable them
446                lappend showing $name
447                if {$show ne "" && $show} {
448                    if {[winfo exists $vwidget]} {
449                        $vwidget configure -state normal
450                    }
451                    if {[winfo exists $lwidget]} {
452                        $lwidget configure -foreground \
453                            [lindex [$lwidget configure -foreground] 3]
454                    }
455                } else {
456                    if {[winfo exists $vwidget]} {
457                        $vwidget configure -state disabled
458                    }
459                    if {[winfo exists $lwidget]} {
460                        $lwidget configure -foreground gray
461                    }
462                }
463            }
464        } else {
465            bgerror "Error in <enable> expression for \"$_name2info($name-path)\":\n  $show"
466        }
467    }
468
469    # store the showing tabs in the object so it can be used in _changeTabs
470    set _showing $showing
471
472    #
473    # Decide on a layout scheme:
474    #   tabs ...... best if all elements within are groups
475    #   hlabels ... horizontal labels (label: value)
476    #
477    if {[llength $showing] >= 2} {
478        # assume tabs for multiple groups
479        set _scheme tabs
480        foreach name $showing {
481            set w $_name2info($name-value)
482
483            if {$w == "--" || [winfo class $w] != "GroupEntry"} {
484                # something other than a group? then fall back on hlabels
485                set _scheme hlabels
486                break
487            }
488        }
489    } else {
490        set _scheme hlabels
491    }
492
493    switch -- $_scheme {
494      tabs {
495        #
496        # SCHEME: tabs
497        # put a series of groups into a tabbed notebook
498        #
499
500        # use inner frame within tabs to show current group
501        pack $_tabs -before $_frame -fill x
502
503        set gn 1
504        foreach name $showing {
505            set wv $_name2info($name-value)
506            $wv configure -heading no
507
508            set label [$wv component heading cget -text]
509            if {"" == $label} {
510                set label "Group #$gn"
511            }
512            set _name2info($name-label) $label
513
514            $_tabs insert end $label \
515                -activebackground $itk_option(-background)
516
517            incr gn
518        }
519
520        # compute the overall size
521        # BE CAREFUL: do this after setting "-heading no" above
522        $_dispatcher event -now !resize
523
524        grid propagate $_frame off
525        grid columnconfigure $_frame 0 -weight 1
526        grid rowconfigure $_frame 0 -weight 1
527
528        $_tabs select 0; _changeTabs
529      }
530
531      hlabels {
532        #
533        # SCHEME: hlabels
534        # simple "Label: Value" layout
535        #
536        pack forget $_tabs
537        grid propagate $_frame on
538        grid columnconfigure $_frame 0 -weight 0
539        grid rowconfigure $_frame 0 -weight 0
540
541        set expand 0  ;# most controls float to top
542        set row 0
543        foreach name $showing {
544            set wl $_name2info($name-label)
545            if {$wl != "" && [winfo exists $wl]} {
546                grid $wl -row $row -column 0 -sticky e
547            }
548
549            set wv $_name2info($name-value)
550            if {$wv != "" && [winfo exists $wv]} {
551                if {$wl != ""} {
552                    grid $wv -row $row -column 1 -sticky ew
553                } else {
554                    grid $wv -row $row -column 0 -columnspan 2 -sticky ew
555                }
556
557                grid rowconfigure $_frame $row -weight 0
558
559                switch -- [winfo class $wv] {
560                    TextEntry {
561                        if {[regexp {[0-9]+x[0-9]+} [$wv size]]} {
562                            grid $wl -sticky n -pady 4
563                            grid $wv -sticky nsew
564                            grid rowconfigure $_frame $row -weight 1
565                            grid columnconfigure $_frame 1 -weight 1
566                            set expand 1
567                        }
568                    }
569                    GroupEntry {
570                        $wv configure -heading yes
571
572                        #
573                        # Scan through all children in this group
574                        # and see if any demand more space.  If the
575                        # group contains a structure or a note, then
576                        # make sure that the group itself is set to
577                        # expand/fill.
578                        #
579                        set queue [winfo children $wv]
580                        set expandgroup 0
581                        while {[llength $queue] > 0} {
582                            set w [lindex $queue 0]
583                            set queue [lrange $queue 1 end]
584                            set c [winfo class $w]
585                            if {[lsearch {DeviceEditor Note} $c] >= 0} {
586                                set expandgroup 1
587                                break
588                            }
589                            eval lappend queue [winfo children $w]
590                        }
591                        if {$expandgroup} {
592                            set expand 1
593                            grid $wv -sticky nsew
594                            grid rowconfigure $_frame $row -weight 1
595                        }
596                    }
597                    Note {
598                        grid $wv -sticky nsew
599                        grid rowconfigure $_frame $row -weight 1
600                        set expand 1
601                    }
602                }
603                grid columnconfigure $_frame 1 -weight 1
604            } elseif {$wv == "--"} {
605                grid rowconfigure $_frame $row -minsize 10
606            }
607
608            incr row
609            grid rowconfigure $_frame $row -minsize $itk_option(-padding)
610            incr row
611        }
612        grid $_frame.empty -row $row
613
614        #
615        # If there are any hidden items, then make the bottom of
616        # this form fill up any extra space, so the form floats
617        # to the top.  Otherwise, it will jitter around as the
618        # hidden items come and go.
619        #
620        if {[llength $hidden] > 0 && !$expand} {
621            grid rowconfigure $_frame 99 -weight 1
622        } else {
623            grid rowconfigure $_frame 99 -weight 0
624        }
625      }
626    }
627}
628
629# ----------------------------------------------------------------------
630# USAGE: _monitor <name> <state>
631#
632# Used internally to add/remove bindings that cause the widget
633# associated with <name> to notify this controls widget of size
634# changes.  Whenever there is a size change, this controls widget
635# should fix its layout.
636# ----------------------------------------------------------------------
637itcl::body Rappture::Controls::_monitor {name state} {
638    set tag "Controls-$this"
639    set wv $_name2info($name-value)
640    if {$wv == "--" || [catch {bindtags $wv} btags]} {
641        return
642    }
643    set i [lsearch $btags $tag]
644
645    if {$state} {
646        if {$i < 0} {
647            bindtags $wv [linsert $btags 0 $tag]
648        }
649    } else {
650        if {$i >= 0} {
651            bindtags $wv [lreplace $btags $i $i]
652        }
653    }
654}
655
656# ----------------------------------------------------------------------
657# USAGE: _controlChanged <name>
658#
659# Invoked automatically whenever the value for a control changes.
660# Sends a notification along to the tool controlling this panel.
661# ----------------------------------------------------------------------
662itcl::body Rappture::Controls::_controlChanged {name} {
663    set path $_name2info($name-path)
664
665    #
666    # Let the owner know that this control changed.
667    #
668    if {"" != $_owner} {
669        $_owner changed $path
670    }
671}
672
673# ----------------------------------------------------------------------
674# USAGE: _controlValue <path> ?<units>?
675#
676# Used internally to get the value of a control with the specified
677# <path>.  Returns the current value for the control.
678# ----------------------------------------------------------------------
679itcl::body Rappture::Controls::_controlValue {path {units ""}} {
680    if {"" != $_owner} {
681        set val [$_owner valuefor $path]
682        if {"" != $units} {
683            set val [Rappture::Units::convert $val -to $units -units off]
684        }
685        return $val
686    }
687    return ""
688}
689
690# ----------------------------------------------------------------------
691# USAGE: _formatLabel <string>
692#
693# Used internally to format a label <string>.  Trims any excess
694# white space and adds a ":" to the end.  That way, all labels
695# have a uniform look.
696# ----------------------------------------------------------------------
697itcl::body Rappture::Controls::_formatLabel {str} {
698    set str [string trim $str]
699    if {"" != $str && [string index $str end] != ":"} {
700        append str ":"
701    }
702    return $str
703}
704
705# ----------------------------------------------------------------------
706# USAGE: _changeTabs
707#
708# Used internally to change tabs when the user clicks on a tab
709# in the "tabs" layout mode.  This mode is used when the widget
710# contains nothing but groups, as a compact way of representing
711# the groups.
712# ----------------------------------------------------------------------
713itcl::body Rappture::Controls::_changeTabs {} {
714    set i [$_tabs index select]
715    # we use _showing here instead of _controls because sometimes tabs
716    # are disabled, and the index of the choosen tab always matches
717    # _showing, even if tabs are disabled.
718    set name [lindex $_showing $i]
719    if {"" != $name} {
720        foreach w [grid slaves $_frame] {
721            grid forget $w
722        }
723
724        set wv $_name2info($name-value)
725        grid $wv -row 0 -column 0 -sticky new
726    }
727}
728
729# ----------------------------------------------------------------------
730# USAGE: _resize
731#
732# Used internally to resize the widget when its contents change.
733# ----------------------------------------------------------------------
734itcl::body Rappture::Controls::_resize {} {
735    switch -- $_scheme {
736        tabs {
737            # compute the overall size
738            # BE CAREFUL: do this after setting "-heading no" above
739            set maxw 0
740            set maxh 0
741            update idletasks
742            foreach name $_controls {
743                set wv $_name2info($name-value)
744                set w [winfo reqwidth $wv]
745                if {$w > $maxw} { set maxw $w }
746                set h [winfo reqheight $wv]
747                if {$h > $maxh} { set maxh $h }
748            }
749            $_frame configure -width $maxw -height $maxh
750        }
751        hlabels {
752            # do nothing
753        }
754    }
755}
756
757# ----------------------------------------------------------------------
758# OPTION: -padding
759# ----------------------------------------------------------------------
760itcl::configbody Rappture::Controls::padding {
761    $_dispatcher event -idle !layout
762}
Note: See TracBrowser for help on using the repository browser.