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

Last change on this file since 3074 was 3050, checked in by gah, 12 years ago
File size: 25.0 KB
Line 
1# ----------------------------------------------------------------------
2#  COMPONENT: gauge - compact readout for real values
3#
4#  This widget is a readout for a real value.  It has a little glyph
5#  filled with color according to the value, followed by a numeric
6#  representation of the value itself.  The value can be edited, and
7#  a list of predefined values can be associated with a menu that
8#  drops down from the value.
9# ======================================================================
10#  AUTHOR:  Michael McLennan, Purdue University
11#  Copyright (c) 2004-2005  Purdue Research Foundation
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# ======================================================================
16package require Itk
17package require BLT
18
19option add *Gauge.sampleWidth 30 widgetDefault
20option add *Gauge.sampleHeight 20 widgetDefault
21option add *Gauge.valuePosition "right" widgetDefault
22option add *Gauge.textBackground #cccccc widgetDefault
23option add *Gauge.editable yes widgetDefault
24
25itcl::class Rappture::Gauge {
26    inherit itk::Widget
27
28    itk_option define -editable editable Editable ""
29    itk_option define -state state State "normal"
30    itk_option define -spectrum spectrum Spectrum ""
31    itk_option define -type type Type "real"
32    itk_option define -units units Units ""
33    itk_option define -minvalue minValue MinValue ""
34    itk_option define -maxvalue maxValue MaxValue ""
35    itk_option define -presets presets Presets ""
36    itk_option define -valueposition valuePosition ValuePosition ""
37    itk_option define -image image Image ""
38    itk_option define -samplewidth sampleWidth SampleWidth 0
39    itk_option define -sampleheight sampleHeight SampleHeight 0
40
41    constructor {args} { # defined below }
42
43    public method value {args}
44    public method edit {option}
45    public method bump {delta}
46
47    protected method _redraw {}
48    protected method _resize {}
49    protected method _hilite {comp state}
50    protected method _editor {option args}
51    protected method _presets {option}
52    protected method _layout {}
53
54    private variable _value 0  ;# value for this widget
55
56    blt::bitmap define GaugeArrow-up {
57        #define up_width 8
58        #define up_height 4
59        static unsigned char up_bits[] = {
60           0x10, 0x38, 0x7c, 0xfe};
61    }
62    blt::bitmap define GaugeArrow-down {
63        #define arrow_width 8
64        #define arrow_height 4
65        static unsigned char arrow_bits[] = {
66           0xfe, 0x7c, 0x38, 0x10};
67    }
68
69    blt::bitmap define GaugeArrow {
70        #define arrow_width 9
71        #define arrow_height 4
72        static unsigned char arrow_bits[] = {
73           0x7f, 0x00, 0x3e, 0x00, 0x1c, 0x00, 0x08, 0x00};
74    }
75}
76                                                                               
77itk::usual Gauge {
78    keep -cursor -font -foreground -background
79    keep -selectbackground -selectforeground -selectborderwidth
80}
81
82# ----------------------------------------------------------------------
83# CONSTRUCTOR
84# ----------------------------------------------------------------------
85itcl::body Rappture::Gauge::constructor {args} {
86    itk_component add icon {
87        canvas $itk_interior.icon -width 1 -height 1 \
88            -borderwidth 0 -highlightthickness 0
89    } {
90        usual
91        ignore -highlightthickness -highlightbackground -highlightcolor
92    }
93    pack $itk_component(icon) -side left
94    bind $itk_component(icon) <Configure> [itcl::code $this _redraw]
95
96    itk_component add -protected vframe {
97        frame $itk_interior.vframe
98    }
99
100    itk_component add value {
101        label $itk_component(vframe).value -borderwidth 1 -width 7 \
102            -textvariable [itcl::scope _value]
103    } {
104        rename -background -textbackground textBackground Background
105    }
106    pack $itk_component(value) -side left -expand yes -fill both
107
108    bind $itk_component(value) <Enter> [itcl::code $this _hilite value on]
109    bind $itk_component(value) <Leave> [itcl::code $this _hilite value off]
110
111    bind $itk_component(value) <<Cut>> [itcl::code $this edit cut]
112    bind $itk_component(value) <<Copy>> [itcl::code $this edit copy]
113    bind $itk_component(value) <<Paste>> [itcl::code $this edit paste]
114
115    itk_component add emenu {
116        menu $itk_component(value).menu -tearoff 0
117    } {
118        usual
119        ignore -tearoff
120    }
121    $itk_component(emenu) add command -label "Cut" -accelerator "^X" \
122        -command [list event generate $itk_component(value) <<Cut>>]
123    $itk_component(emenu) add command -label "Copy" -accelerator "^C" \
124        -command [list event generate $itk_component(value) <<Copy>>]
125    $itk_component(emenu) add command -label "Paste" -accelerator "^V" \
126        -command [list event generate $itk_component(value) <<Paste>>]
127    bind $itk_component(value) <<PopupMenu>> \
128        [itcl::code $this _editor menu %X %Y]
129
130    itk_component add editor {
131        Rappture::Editor $itk_interior.editor \
132            -activatecommand [itcl::code $this _editor activate] \
133            -validatecommand [itcl::code $this _editor validate] \
134            -applycommand [itcl::code $this _editor apply]
135    }
136    bind $itk_component(value) <ButtonPress> \
137        [itcl::code $this _editor popup]
138
139
140    itk_component add spinner {
141        frame $itk_component(vframe).spinner
142    }
143
144    itk_component add spinup {
145        button $itk_component(spinner).up -bitmap GaugeArrow-up \
146            -borderwidth 1 -relief raised -highlightthickness 0 \
147            -command [itcl::code $this bump 1]
148    } {
149        usual
150        ignore -borderwidth -highlightthickness
151    }
152    pack $itk_component(spinup) -side top -expand yes -fill both
153
154    itk_component add spindn {
155        button $itk_component(spinner).down -bitmap GaugeArrow-down \
156            -borderwidth 1 -relief raised -highlightthickness 0 \
157            -command [itcl::code $this bump -1]
158    } {
159        usual
160        ignore -borderwidth -highlightthickness
161    }
162    pack $itk_component(spindn) -side bottom -expand yes -fill both
163
164
165    itk_component add presets {
166        button $itk_component(vframe).psbtn -bitmap GaugeArrow \
167            -borderwidth 1 -highlightthickness 0 -relief flat
168    } {
169        usual
170        ignore -borderwidth -relief -highlightthickness
171        rename -background -textbackground textBackground Background
172    }
173
174    bind $itk_component(presets) <Enter> [itcl::code $this _hilite presets on]
175    bind $itk_component(presets) <Leave> [itcl::code $this _hilite presets off]
176
177    itk_component add presetlist {
178        Rappture::Dropdownlist $itk_component(presets).plist \
179            -postcommand [itcl::code $this _presets post] \
180            -unpostcommand [itcl::code $this _presets unpost] \
181    }
182
183    bind $itk_component(presetlist) <<DropdownlistSelect>> \
184        [itcl::code $this _presets select]
185
186    $itk_component(presets) configure -command \
187        [list $itk_component(presetlist) post $itk_component(vframe) left]
188
189    eval itk_initialize $args
190}
191
192# ----------------------------------------------------------------------
193# USAGE: value ?-check? ?<newval>?
194#
195# Clients use this to query/set the value for this widget.  With
196# no args, it returns the current value for the widget.  If the
197# <newval> is specified, it sets the value of the widget and
198# sends a <<Value>> event.  If the -check flag is included, the
199# new value is not actually applied, but just checked for correctness.
200# ----------------------------------------------------------------------
201itcl::body Rappture::Gauge::value {args} {
202    set onlycheck 0
203    set i [lsearch -exact $args -check]
204    if {$i >= 0} {
205        set onlycheck 1
206        set args [lreplace $args $i $i]
207    }
208
209    if {[llength $args] == 1} {
210        #
211        # If this gauge has -units, try to convert the incoming
212        # value to that system of units.  Also, make sure that
213        # the value is bound by any min/max value constraints.
214        #
215        # Keep track of the inputted units so we can give a
216        # response about min and max values in familiar units.
217        #
218        set newval [set nv [lindex $args 0]]
219        set units $itk_option(-units)
220        if {"" != $units} {
221            set newval [Rappture::Units::convert $newval -context $units]
222            set nvUnits [Rappture::Units::Search::for $newval]
223            if { "" == $nvUnits} {
224                set msg [Rappture::Units::description $units]
225                error "Unrecognized units: $newval\nEnter value with units of $msg"
226            }
227            set nv [Rappture::Units::convert $nv \
228                -context $units -to $units -units off]
229
230            # Normalize the units name
231            set newval [Rappture::Units::convert $newval -units off]$nvUnits
232        }
233
234        switch -- $itk_option(-type) {
235            integer {
236                if { [scan $nv "%g" value] != 1 || int($nv) != $value } {
237                    error "bad value \"$nv\": should be an integer value"
238                }
239            }
240            real {
241                # "scan" will reject the number if the string is "NaN" or
242                # "Inf" or the empty string.  It also is accepts large numbers
243                # (e.g. 111111111111111111111) that "string is double"
244                # rejects.  The problem with "scan" is that it doesn't care if
245                # there are extra characters trailing the number (eg. "123a").
246                # The extra %s substitution is used to detect this case.
247                if { [scan $nv "%g%s" dummy1 dummy2] != 1 } {
248                    error "bad value \"$nv\": should be a real number"
249                }
250            }
251        }
252
253        if {"" != $itk_option(-minvalue)} {
254            set convMinVal [set minv $itk_option(-minvalue)]
255            if {"" != $units} {
256                set minv [Rappture::Units::convert $minv \
257                    -context $units -to $units -units off]
258                set convMinVal [Rappture::Units::convert \
259                    $itk_option(-minvalue) -context $units -to $nvUnits]
260            } else {
261                set newval [format "%g" $newval]
262            }
263
264            # fix for the case when the user tries to
265            # compare values like minv=-500 nv=-0600
266            set nv [format "%g" $nv]
267            set minv [format "%g" $minv]
268
269            if {$nv < $minv} {
270                error "minimum value allowed here is $convMinVal"
271            }
272        }
273
274        if {"" != $itk_option(-maxvalue)} {
275            set convMaxVal [set maxv $itk_option(-maxvalue)]
276            if {"" != $units} {
277                set maxv [Rappture::Units::convert $maxv \
278                    -context $units -to $units -units off]
279                set convMaxVal [Rappture::Units::convert \
280                    $itk_option(-maxvalue) -context $units -to $nvUnits]
281            } else {
282                set newval [format "%g" $newval]
283            }
284
285            # fix for the case when the user tries to
286            # compare values like maxv=500 nv=0600
287            set nv [format "%g" $nv]
288            set maxv [format "%g" $maxv]
289
290            if {$nv > $maxv} {
291                error "maximum value allowed here is $convMaxVal"
292            }
293        }
294
295        if {$onlycheck} {
296            return
297        }
298
299        set _value $newval
300
301        _redraw
302        event generate $itk_component(hull) <<Value>>
303
304    } elseif {[llength $args] != 0} {
305        error "wrong # args: should be \"value ?-check? ?newval?\""
306    }
307    return $_value
308}
309
310# ----------------------------------------------------------------------
311# USAGE: edit cut
312# USAGE: edit copy
313# USAGE: edit paste
314#
315# Used internally to handle cut/copy/paste operations for the current
316# value.  Usually invoked by <<Cut>>, <<Copy>>, <<Paste>> events, but
317# can also be called directly through this method.
318# ----------------------------------------------------------------------
319itcl::body Rappture::Gauge::edit {option} {
320    if {$itk_option(-state) == "disabled"} {
321        return  ;# disabled? then bail out here!
322    }
323    switch -- $option {
324        cut {
325            edit copy
326            _editor popup
327            $itk_component(editor) value ""
328            $itk_component(editor) deactivate
329        }
330        copy {
331            clipboard clear
332            clipboard append $_value
333        }
334        paste {
335            _editor popup
336            $itk_component(editor) value [clipboard get]
337            $itk_component(editor) deactivate
338        }
339        default {
340            error "bad option \"$option\": should be cut, copy, paste"
341        }
342    }
343}
344
345# ----------------------------------------------------------------------
346# USAGE: bump <delta>
347#
348# Changes the current value up/down by the <delta> value.  Used
349# internally by the up/down spinner buttons when the value is
350# -type integer.
351# ----------------------------------------------------------------------
352itcl::body Rappture::Gauge::bump {delta} {
353    set val $_value
354    if {$val == ""} {
355        set val 0
356    }
357    if {[catch {value [expr {$val+$delta}]} result]} {
358        if {[regexp {allowed here is (.+)} $result match newval]} {
359            set _value $newval
360            $itk_component(value) configure -text $newval
361        }
362        if {[regexp {^bad.*: +(.)(.+)} $result match first tail]
363              || [regexp {(.)(.+)} $result match first tail]} {
364            set result "[string toupper $first]$tail"
365        }
366        bell
367        Rappture::Tooltip::cue $itk_component(value) $result
368        return 0
369    }
370}
371
372# ----------------------------------------------------------------------
373# USAGE: _redraw
374#
375# Used internally to redraw the gauge on the internal canvas based
376# on the current value and the size of the widget.  In this simple
377# base class, the gauge is drawn as a colored block, with an optional
378# image in the middle of it.
379# ----------------------------------------------------------------------
380itcl::body Rappture::Gauge::_redraw {} {
381    set c $itk_component(icon)
382    set w [winfo width $c]
383    set h [winfo height $c]
384
385    if {"" == [$c find all]} {
386        # first time around, create the items
387        $c create rectangle 0 0 1 1 -outline black -tags block
388        $c create image 0 0 -anchor center -image "" -tags bimage
389        $c create rectangle 0 0 1 1 -outline "" -fill "" -stipple gray50 -tags screen
390    }
391
392    if {"" != $itk_option(-spectrum)} {
393        set color [$itk_option(-spectrum) get $_value]
394    } else {
395        set color ""
396    }
397
398    # update the items based on current values
399    $c coords block 0 0 [expr {$w-1}] [expr {$h-1}]
400    $c coords screen 0 0 $w $h
401    $c itemconfigure block -fill $color
402
403    $c coords bimage [expr {0.5*$w}] [expr {0.5*$h}]
404
405    if {$itk_option(-state) == "disabled"} {
406        $c itemconfigure screen -fill white
407    } else {
408        $c itemconfigure screen -fill ""
409    }
410}
411
412# ----------------------------------------------------------------------
413# USAGE: _resize
414#
415# Used internally to resize the internal canvas based on the -image
416# option or the size of the text.
417# ----------------------------------------------------------------------
418itcl::body Rappture::Gauge::_resize {} {
419    set w 0
420    set h 0
421
422    if {"" != $itk_option(-image) || "" != $itk_option(-spectrum)} {
423        if {$itk_option(-samplewidth) > 0} {
424            set w $itk_option(-samplewidth)
425        } else {
426            if {$itk_option(-image) != ""} {
427                set w [expr {[image width $itk_option(-image)]+4}]
428            } else {
429                set w [winfo reqheight $itk_component(value)]
430            }
431        }
432
433        if {$itk_option(-sampleheight) > 0} {
434            set h $itk_option(-sampleheight)
435        } else {
436            if {$itk_option(-image) != ""} {
437                set h [expr {[image height $itk_option(-image)]+4}]
438            } else {
439                set h [winfo reqheight $itk_component(value)]
440            }
441        }
442    }
443
444    if {$w > 0 && $h > 0} {
445        $itk_component(icon) configure -width $w -height $h
446    }
447}
448
449# ----------------------------------------------------------------------
450# USAGE: _hilite <component> <state>
451#
452# Used internally to resize the internal canvas based on the -image
453# option or the size of the text.
454# ----------------------------------------------------------------------
455itcl::body Rappture::Gauge::_hilite {comp state} {
456    if {$itk_option(-state) == "disabled"} {
457        set state 0  ;# disabled? then don't hilite
458    }
459    if {$comp == "value" && !$itk_option(-editable)} {
460        $itk_component(value) configure -relief flat
461        return
462    }
463
464    if {$state} {
465        $itk_component($comp) configure -relief solid
466    } else {
467        $itk_component($comp) configure -relief flat
468    }
469}
470
471# ----------------------------------------------------------------------
472# USAGE: _editor popup
473# USAGE: _editor activate
474# USAGE: _editor validate <value>
475# USAGE: _editor apply <value>
476# USAGE: _editor menu <rootx> <rooty>
477#
478# Used internally to handle the various functions of the pop-up
479# editor for the value of this gauge.
480# ----------------------------------------------------------------------
481itcl::body Rappture::Gauge::_editor {option args} {
482    if {$itk_option(-state) == "disabled"} {
483        return  ;# disabled? then bail out here!
484    }
485    switch -- $option {
486        popup {
487            if {$itk_option(-editable)} {
488                $itk_component(editor) activate
489            }
490        }
491        activate {
492            return [list text $_value \
493                x [winfo rootx $itk_component(value)] \
494                y [winfo rooty $itk_component(value)] \
495                w [winfo width $itk_component(value)] \
496                h [winfo height $itk_component(value)]]
497        }
498        validate {
499            if {[llength $args] != 1} {
500                error "wrong # args: should be \"_editor validate val\""
501            }
502            set val [lindex $args 0]
503
504            if {[catch {value -check $val} result]} {
505                if {[regexp {allowed here is (.+)} $result match newval]} {
506                    $itk_component(editor) value $newval
507                }
508                if {[regexp {^bad.*: +(.)(.+)} $result match first tail]
509                      || [regexp {(.)(.+)} $result match first tail]} {
510                    set result "[string toupper $first]$tail"
511                }
512                bell
513                Rappture::Tooltip::cue $itk_component(editor) $result
514                return 0
515            }
516        }
517        apply {
518            if {[llength $args] != 1} {
519                error "wrong # args: should be \"_editor apply val\""
520            }
521            value [lindex $args 0]
522        }
523        menu {
524            eval tk_popup $itk_component(emenu) $args
525        }
526        default {
527            error "bad option \"$option\": should be popup, activate, validate, apply, and menu"
528        }
529    }
530}
531
532# ----------------------------------------------------------------------
533# USAGE: _presets post
534# USAGE: _presets unpost
535# USAGE: _presets select
536#
537# Used internally to handle the list of presets for this gauge.  The
538# post/unpost options are invoked when the list is posted or unposted
539# to manage the relief of the controlling button.  The select option
540# is invoked whenever there is a selection from the list, to assign
541# the value back to the gauge.
542# ----------------------------------------------------------------------
543itcl::body Rappture::Gauge::_presets {option} {
544    switch -- $option {
545        post {
546            set i [$itk_component(presetlist) index $_value]
547            if {$i >= 0} {
548                $itk_component(presetlist) select clear 0 end
549                $itk_component(presetlist) select set $i
550            }
551            after 10 [list $itk_component(presets) configure -relief sunken]
552        }
553        unpost {
554            $itk_component(presets) configure -relief flat
555        }
556        select {
557            set val [$itk_component(presetlist) current]
558            if {"" != $val} {
559                value $val
560            }
561        }
562        default {
563            error "bad option \"$option\": should be post, unpost, select"
564        }
565    }
566}
567
568# ----------------------------------------------------------------------
569# USAGE: _layout
570#
571# Used internally to fix the layout of widgets whenever there is a
572# change in the options that affect layout.  Puts the value in the
573# proper position according to the -valueposition option.  Also,
574# adds or removes the icon if it needs to be shown.
575# ----------------------------------------------------------------------
576itcl::body Rappture::Gauge::_layout {} {
577    foreach w [pack slaves $itk_component(hull)] {
578        pack forget $w
579    }
580
581    array set side2anchor {
582        left   e
583        right  w
584        top    s
585        bottom n
586    }
587    set pos $itk_option(-valueposition)
588    pack $itk_component(vframe) -side $pos \
589        -expand yes -fill both -ipadx 2
590    $itk_component(value) configure -anchor $side2anchor($pos)
591
592    if {"" != $itk_option(-image) || "" != $itk_option(-spectrum)} {
593        pack $itk_component(icon) -side $pos
594    }
595}
596
597# ----------------------------------------------------------------------
598# CONFIGURATION OPTION: -editable
599# ----------------------------------------------------------------------
600itcl::configbody Rappture::Gauge::editable {
601    if {![string is boolean -strict $itk_option(-editable)]} {
602        error "bad value \"$itk_option(-editable)\": should be boolean"
603    }
604    if {!$itk_option(-editable) && [winfo ismapped $itk_component(editor)]} {
605        $itk_component(editor) deactivate -abort
606    }
607}
608
609# ----------------------------------------------------------------------
610# CONFIGURATION OPTION: -state
611# ----------------------------------------------------------------------
612itcl::configbody Rappture::Gauge::state {
613    set valid {normal disabled}
614    if {[lsearch -exact $valid $itk_option(-state)] < 0} {
615        error "bad value \"$itk_option(-state)\": should be [join $valid {, }]"
616    }
617    $itk_component(value) configure -state $itk_option(-state)
618    $itk_component(spinup) configure -state $itk_option(-state)
619    $itk_component(spindn) configure -state $itk_option(-state)
620    $itk_component(presets) configure -state $itk_option(-state)
621    _redraw  ;# fix gauge
622}
623
624# ----------------------------------------------------------------------
625# CONFIGURATION OPTION: -spectrum
626# ----------------------------------------------------------------------
627itcl::configbody Rappture::Gauge::spectrum {
628    if {$itk_option(-spectrum) != ""
629          && ([catch {$itk_option(-spectrum) isa ::Rappture::Spectrum} valid]
630               || !$valid)} {
631        error "bad option \"$itk_option(-spectrum)\": should be Rappture::Spectrum object"
632    }
633    _resize
634    _layout
635    _redraw
636}
637
638# ----------------------------------------------------------------------
639# CONFIGURATION OPTION: -image
640# ----------------------------------------------------------------------
641itcl::configbody Rappture::Gauge::image {
642    if {$itk_option(-image) != ""
643          && [catch {image width $itk_option(-image)}]} {
644        error "bad value \"$itk_option(-image)\": should be Tk image"
645    }
646    _resize
647    _layout
648    $itk_component(icon) itemconfigure bimage -image $itk_option(-image)
649}
650
651# ----------------------------------------------------------------------
652# CONFIGURATION OPTION: -units
653# ----------------------------------------------------------------------
654itcl::configbody Rappture::Gauge::units {
655    if {$itk_option(-units) != ""
656          && [::Rappture::Units::System::for $itk_option(-units)] == ""} {
657        error "unrecognized system of units \"$itk_option(-units)\""
658    }
659}
660
661# ----------------------------------------------------------------------
662# CONFIGURATION OPTION: -valueposition
663# ----------------------------------------------------------------------
664itcl::configbody Rappture::Gauge::valueposition {
665    set pos $itk_option(-valueposition)
666    set opts {left right top bottom}
667    if {[lsearch -exact $opts $pos] < 0} {
668        error "bad value \"$pos\": should be [join $opts {, }]"
669    }
670    _layout
671}
672
673# ----------------------------------------------------------------------
674# CONFIGURATION OPTION: -presets
675# ----------------------------------------------------------------------
676itcl::configbody Rappture::Gauge::presets {
677    if {"" == $itk_option(-presets)} {
678        pack forget $itk_component(presets)
679    } else {
680        if {$itk_option(-valueposition) == "left"} {
681            set s "left"
682        } else {
683            set s "right"
684        }
685        set first [lindex [pack slaves $itk_component(vframe)] 0]
686        pack $itk_component(presets) -before $first -side $s -fill y
687
688        $itk_component(presetlist) delete 0 end
689        $itk_component(presetlist) insert end $itk_option(-presets)
690    }
691}
692
693# ----------------------------------------------------------------------
694# CONFIGURATION OPTION: -type
695# ----------------------------------------------------------------------
696itcl::configbody Rappture::Gauge::type {
697    switch -- $itk_option(-type) {
698        integer {
699            set first [lindex [pack slaves $itk_component(vframe)] 0]
700            if {$first == $itk_component(presets)} {
701                pack $itk_component(spinner) -after $first -side left -fill y
702            } else {
703                pack $itk_component(spinner) -before $first -side right -fill y
704            }
705        }
706        real {
707            pack forget $itk_component(spinner)
708        }
709        default {
710            error "bad number type \"$itk_option(-type)\": should be integer or real"
711        }
712    }
713}
Note: See TracBrowser for help on using the repository browser.