#! ../mofe --f
### A simple script to show Magic Global Variables: Simply by altering
### the contents of global variables, magically the contents of linked
### Motif Label Widgets will change accordingly.
###
### This script is designed to work with global scalars and global
### associative array components.
###
### An example usage of linkLabel is included below.
### Gustaf Neumann

# establish a link between widget $w and a global tcl 
# variable (scalar variable or array component)
proc linkLabel {w varName} {
  regexp {^([^\(]+)} $varName _ stem
  global $stem _lnk
  set _lnk($varName) $w
  setLabel $varName [set $varName]
  trace variable $varName w changeLabel
}

# change a label, when the varaible was changed (prevent flickering
# when label is changed to the same value)
proc changeLabel {stem comp access} {
  global $stem _val
  set val [set [set varName [varName $stem $comp]]]
  if [string compare $_val($varName) $val] {
    setLabel $varName $val
  }
}

# set a widget label to a new value
proc setLabel {varName val} {
  global _lnk _val 
  sV $_lnk($varName) labelString $val
  set _val($varName) $val
}

# construct a variable name out of stem and component
proc varName {stem comp} {
  if [string compare "" $comp] { return [append n $stem ($comp)]
  } else { return $stem }
}

# set global variables used later together with linkLabel
set a 1
set b 2
set c 3
set t(1) 100

# build the widget tree and link labels with global variables
XmRowColumn B topLevel entryAlignment alignment_center
foreach l {a b c t(1)} {
  XmLabel $l: B
  XmRowColumn rc$l [XmFrame f$l B] \
      orientation horizontal entryAlignment alignment_end
  XmLabel $l rc$l recomputeSize 0 width 27
  XmPushButton $l++ rc$l activateCallback "incr $l"
  linkLabel B*$l $l
}
realize

# this procedure is an example of 'another' procedure which
# manipulates the global variable (causing updates in the label)
proc tic {} {  addTimeOut 1000 {incr t(1); tic}}
tic
