File: UI.tcl

package info (click to toggle)
coccinella 0.96.20-9
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 13,184 kB
  • sloc: tcl: 124,744; xml: 206; makefile: 66; sh: 62
file content (2134 lines) | stat: -rw-r--r-- 54,523 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
#  UI.tcl ---
#  
#      This file is part of The Coccinella application. It implements user
#      interface elements.
#      
#  Copyright (c) 2002-2008  Mats Bengtsson
#  
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#   
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#   
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#  
# $Id: UI.tcl,v 1.200 2008-08-14 10:52:34 matben Exp $

package require ui::dialog
package require ui::entryex

package provide UI 1.0

namespace eval ::UI {
    global  this

    # Add all event hooks.
    ::hooks::register firstLaunchHook         ::UI::FirstLaunchHook
    ::hooks::register jabberBuildMain         ::UI::JabberBuildMainHook

    # Icons
#     option add *buttonOKImage            buttonok       widgetDefault
#     option add *buttonCancelImage        buttoncancel   widgetDefault
    option add *buttonOKImage            dialog-ok      widgetDefault
    option add *buttonCancelImage        dialog-cancel  widgetDefault
    
    option add *info64Image              info64         widgetDefault
    option add *error64Image             error64        widgetDefault
    option add *warning64Image           warning64      widgetDefault
    option add *question64Image          question64     widgetDefault
    option add *internet64Image          internet64     widgetDefault

    option add *info64Image              dialog-information  widgetDefault
    option add *error64Image             dialog-error        widgetDefault
    option add *warning64Image           dialog-warning      widgetDefault
    option add *question64Image          dialog-question     widgetDefault
    option add *worldmap64Image          world-map           widgetDefault
    
    option add *badge32Image        coccinella   widgetDefault
    option add *badge64Image        coccinella   widgetDefault
    
    # components stuff.
    variable menuSpecPublic
    set menuSpecPublic(wpaths) [list]
    
    variable regAccelerators [list]
    
    variable icons

    # The mac look-alike triangles.
    set icons(mactriangleopen) [image create photo -data {
	R0lGODlhCwALAPMAAP///97e3s7O/729vZyc/4yMjGNjzgAAAAAAAAAAAAAA
	AAAAAAAAAAAAAAAAAAAAACH5BAEAAAEALAAAAAALAAsAAAQgMMhJq7316M1P
	OEIoEkchHURKGOUwoWubsYVryZiNVREAOw==
    }]
    set icons(mactriangleclosed) [image create photo -data {
	R0lGODlhCwALAPMAAP///97e3s7O/729vZyc/4yMjGNjzgAAAAAAAAAAAAAA
	AAAAAAAAAAAAAAAAAAAAACH5BAEAAAEALAAAAAALAAsAAAQiMMgjqw2H3nqE
	3h3xWaEICgRhjBi6FgMpvDEpwuCBg3sVAQA7
    }]
    
    # Aqua gray arrows. PNG
    set icons(openAqua) [image create photo -data {
	iVBORw0KGgoAAAANSUhEUgAAAAsAAAALCAYAAACprHcmAAAAkklEQVR42pXP
	IQ4CQQyF4X+HE+HInAAJx0BXIZGI5xB7ATQrucEgkRxh5QrE4DAdQjbsZHmq
	Tb62KfyRxsxWQJphtw2AmV2ATQXeJS2DN3sgV/AOIABIegDtBOwk3T7YcwSG
	Ecx+FYBFKVJKzxjjC1h/4ZOkc2nCaFML9F4Pfo2fWFIuzwAHSf0k9oEOuFYe
	npc3YZcnhZloj+wAAAAASUVORK5CYII=
    }]
    set icons(closeAqua) [image create photo -data {
	iVBORw0KGgoAAAANSUhEUgAAAAsAAAALCAYAAACprHcmAAAAh0lEQVR42o2R
	IQ6DQBREXwkH4Ap1lUiuUEeP0oyqrKyYYLnFcovK2h4BicS1hjVkw+4zP5k8
	MZMPgKSeAqrtBkkfSV2JDNACb0lB0iUln7Yav12+AiPwsj3n5MgCPIHR9lpl
	NjXAAIR95xQzcLN9PZIX4A6cbU8xrEuGpeQJeNj+HhbLPSPyB7B0KtfTwC8y
	AAAAAElFTkSuQmCC
    }]

    # WinXP lool-alikes +- signs.
    set icons(openPM) [image create photo -data {
	R0lGODdhCQAJAKIAAP//////wsLCwsLCibS0tFOJwgAAAAAAACwAAAAACQAJ
	AAADHUi1XAowgiUjrYKavXOBQSh4YzkuAkEMrKI0C5EAADs=
    }]    
    set icons(closePM) [image create photo -data {
	R0lGODdhCQAJAKIAAP//////wsLCwsLCibS0tFOJwgAAAAAAACwAAAAACQAJ
	AAADIEi1XAowghVNpNACQY33XAEFRiCEp2Cki0AQQ6wozUIkADs=
    }]
    
    # Have a blank 1x1 image just for spacer.
    set icons(blank-1x1) [image create photo -data {
	iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAABmJLR0QA/wD/
	AP+gvaeTAAAADUlEQVQI12NgYGBgAAAABQABXvMqOgAAAABJRU5ErkJggg==
    }]    
    
    switch -- [tk windowingsystem] {
	aqua {
	    set imstate [list $icons(openAqua) open $icons(closeAqua) {}]
	    option add *TreeCtrl.buttonImage $imstate widgetDefault
	}
	x11 {
	    set imstate [list $icons(openPM) open $icons(closePM) {}]
	    option add *TreeCtrl.buttonImage $imstate widgetDefault
	}
    }
    
    # System colors.
    # @@@ This wont be right in a themed environment!
    set wtmp [listbox ._tmp_listbox]
    set this(sysHighlight)     [$wtmp cget -selectbackground]
    set this(sysHighlightText) [$wtmp cget -selectforeground]
    destroy $wtmp
    
    # Hardcoded configurations.
    set ::config(ui,pruneMenus) {}
}

proc ::UI::FirstLaunchHook {} {
    SetupAss
}

# UI::Init --
# 
#       Various initializations for the UI stuff.

proc ::UI::Init {} {
    global  this prefs
    
    ::Debug 2 "::UI::Init"    
    
    # Standard button icons. 
    # Special solution to be able to set image via the option database.
    ::Theme::Create16IconWithName . buttonOKImage
    ::Theme::Create16IconWithName . buttonCancelImage
    
    InitDialogs

    switch -- [tk windowingsystem] {
	aqua {
	    InitMac
	}
	x11 {
	    InitX11
	}
    }
}

proc ::UI::InitX11 {} {
    
    # button icons for ok and cancel buttons
    #
    option add *btok.image                         dialog-ok
    option add *btok.compound                      left
    option add *btcancel.image                     dialog-cancel
    option add *btcancel.compound                  left
    
    option add *Dialog*ok.image                    dialog-ok
    option add *Dialog*ok.compound                 left
    option add *Dialog*cancel.image                dialog-cancel
    option add *Dialog*cancel.compound             left
}

# @@@ This is only temporary until We've got the chasingarrowselem.

proc ::UI::ChaseArrows {w} {
    
    # Use ttk::progressbar win -style TChasingArrows if possible.
    
    if {([tk windowingsystem] eq "aqua") && \
      ![catch {package require chasingarrowselem 0.2}]} {
	ttk::progressbar $w -style TChasingArrows -length 16 -maximum 10000 -takefocus 0
    } else {
	::chasearrows::chasearrows $w -size 16
    }
    return $w
}

proc ::UI::FindFirstClassChild {win class} {
    foreach w [winfo children $win] {
	if {[winfo class $w] eq $class} {
	    return $w
	}
    }
    return
}

proc ::UI::InitDialogs {} {
        
    # Dialog images.
    foreach name {info error warning question worldmap} {
	set im [::Theme::Find64Icon . ${name}64Image]
	ui::dialog::setimage $name $im
    }
    ui::dialog::setbadge [::Theme::Find32Icon . badge32Image]
    ui::dialog::setimage coccinella [::Theme::Find64Icon . badge64Image]
    ui::dialog layoutpolicy stack

    # For ui::openimage
    option add *Dialog*image.style  Sunken.TLabel  widgetDefault    
}

proc ::UI::JabberBuildMainHook {} {
    ui::dialog defaultmenu [::JUI::GetMainMenu]
}

proc ::UI::InitMac {} {
    
    proc ::tk::mac::OpenDocument {args} {
	Debug 2 "::tk::mac::OpenDocument args=$args"
	# args will be a list of all the documents dropped on your app, 
	# or double-clicked 
	eval {::hooks::run macOpenDocument} $args
    }
}

proc ::UI::InitCommonBinds {} {
    global  this
    
    set mod $this(modkey)
    bind Text <$mod-a> {
	%W tag add sel 1.0 end
    }
    bind Entry <$mod-a> {
	%W selection range 0 end
    }
    bind TEntry <$mod-a> {
	%W selection range 0 end
    }
    if {[tk windowingsystem] eq "aqua"} {
	
	# Entry
	bind Entry <Command-Left> {
	    %W icursor 0
	    %W selection clear
	}
	bind Entry <Command-Right> {
	    %W icursor end
	    %W selection clear
	}
	bind Entry <Control-Left> {
	    %W icursor 0
	    %W selection clear
	}
	bind Entry <Control-Right> {
	    %W icursor end
	    %W selection clear
	}
	
	# TEntry
	bind TEntry <Command-Left> {
	    %W icursor 0
	    %W selection clear
	}
	bind TEntry <Command-Right> {
	    %W icursor end
	    %W selection clear
	}
	bind TEntry <Control-Left> {
	    %W icursor 0
	    %W selection clear
	}
	bind TEntry <Control-Right> {
	    %W icursor end
	    %W selection clear
	}	
    }
    
    # Read only text widget bindings.
    # Usage: bindtags $w [linsert [bindtags $w] 0 ReadOnlyText]
    bind ReadOnlyText <Button-1> { focus %W }
    bind ReadOnlyText <Tab> { 	
	focus [tk_focusNext %W]
	break
    }
    bind ReadOnlyText <Shift-Tab> { 	
	focus [tk_focusPrev %W]
	break
    }
    
    # Undo/redo text bindings. 
    # <<Undo>> and <<Redo>> already standard for text widget.
    foreach sep {space Tab Return BackSpace comma period} {
	bind UndoText <$sep> {
	    %W edit separator
	}
    }
    
    SetMoseWheelFor Canvas
    SetMoseWheelFor Html

    # Linux has a strange binding by default. Handled by <<Paste>>.
    if {[string equal $this(platform) "unix"]} {
	bind Text <Control-Key-v> {}
    }
}

proc ::UI::SetMoseWheelFor {bindTarget} {
    
    if {[string equal "x11" [tk windowingsystem]]} {
	# Support for mousewheels on Linux/Unix commonly comes through mapping
	# the wheel to the extended buttons.  If you have a mousewheel, find
	# Linux configuration info at:
	#	http://www.inria.fr/koala/colas/mouse-wheel-scroll/
	bind $bindTarget <4> {
	    if {!$::tk_strictMotif} {
		if {![string equal [%W yview] "0 1"]} {
		    %W yview scroll -5 units
		}
	    }
	}
	bind $bindTarget <5> {
	    if {!$::tk_strictMotif} {
		if {![string equal [%W yview] "0 1"]} {
		    %W yview scroll 5 units
		}
	    }
	}
    } elseif {[string equal [tk windowingsystem] "aqua"]} {
	bind $bindTarget <MouseWheel> {
	    if {![string equal [%W yview] "0 1"]} {
		%W yview scroll [expr {- (%D)}] units
	    }
	}
	bind $bindTarget <Shift-MouseWheel> {
	    if {![string equal [%W xview] "0 1"]} {
		%W xview scroll [expr {- (%D)}] units
	    }
	}
    } else {
	bind $bindTarget <MouseWheel> {
	    if {![string equal [%W yview] "0 1"]} {
		%W yview scroll [expr {- (%D / 120) * 4}] units
	    }
	}
	bind $bindTarget <Shift-MouseWheel> {
	    if {![string equal [%W xview] "0 1"]} {
		%W xview scroll [expr {- (%D / 120) * 4}] units
	    }
	}
    }
}

proc ::UI::InitVirtualEvents {} {
    global  this
      
    # Virtual events.
    event add <<CloseWindow>>    <$this(modkey)-Key-w>
    event add <<ReturnEnter>>    <Return> <KP_Enter>
    event add <<Find>>           <$this(modkey)-Key-f>
    event add <<FindAgain>>      <$this(modkey)-Key-g>
    event add <<FindPrevious>>   <$this(modkey)-Shift-Key-g>

    switch -- $this(platform) {
	macintosh {
	    event add <<ButtonPopup>> <Button-2> <Control-Button-1>
	}
	macosx {
	    event add <<ButtonPopup>> <Button-2> <Control-Button-1>
	}
	unix {
	    event add <<ButtonPopup>> <Button-3>
	}
	windows {
	    event add <<CloseWindow>> <Key-F4>
	    event add <<ButtonPopup>> <Button-3>
	}
    }
}

proc ::UI::InitDlgs {} {
    global  wDlgs
    
    # Define the toplevel windows here so they don't collide.
    # Toplevel dialogs.
    array set wDlgs {
	comp            .comp
	editFonts       .edfnt
	editShorts      .tshcts
	fileAssoc       .fass
	infoClient      .infocli
	infoServ        .infoserv
	iteminsp        .iteminsp
	netSetup        .netsetup
	openConn        .opc
	openMulti       .opqtmulti
	prefs           .prefs
	print           .prt
	prog            .prog
	plugs           .plugs
	setupass        .setupass
	wb              .wb
	mainwb          .wb0
    }
    
    # Toplevel dialogs for the jabber part.
    array set wDlgs {
	jmain           .jmain
	jreg            .jreg
	jlogin          .jlogin
	jrost           .jrost
	jrostnewedit    .jrostnewedit
	jrostadduser    .jrostadduser
	jrostedituser   .jrostedituser
	jsubsc          .jsubsc
	jsubsced        .jsubsced
	jsendmsg        .jsendmsg
	jgotmsg         .jgotmsg
	jstartchat      .jstartchat
	jchat           .jchat
	jbrowse         .jbrowse
	jenterroom      .jenterroom
	jcreateroom     .jcreateroom
	jinbox          .jinbox
	jpresmsg        .jpresmsg
	joutst          .joutst
	jpasswd         .jpasswd
	jsearch         .jsearch
	jvcard          .jvcard
	jgcenter        .jgcenter
	jgc             .jgc
	jmucenter       .jmucenter
	jmucinvite      .jmucinvite
	jmucinfo        .jmucinfo
	jmucedit        .jmucedit
	jmuccfg         .jmuccfg
	jmucdestroy     .jmucdestroy
	jchist          .jchist
	jhist           .jhist
	jprofiles       .jprofiles
	jftrans         .jftrans
	jerrdlg         .jerrdlg
	jwbinbox        .jwbinbox
	jprivacy        .jprivacy
	jdirpres        .jdirpres
	jdisaddserv     .jdisaddserv
	juserinfo       .juserinfo
	jgcbmark        .jgcbmark
	jpopupdisco     .jpopupdi
	jpopuproster    .jpopupro
	jpopupgroupchat .jpopupgc
	jadhoc          .jadhoc
    }
}

# @@@ TODO
proc ::UI::RegisterDlgName {nameDlgFlatA} {
    global  wDlgs
    
    foreach {name w} $nameDlgFlatA {
	if {[info exists $wDlgs($name)]} {
	    return -code error "name \"$name\" already exists in wDlgs"
	}
	
    }
}

# UI::InitMenuDefs --
# 
#       The menu organization. Only least common parts here,
#       that is, the Apple menu.

proc ::UI::InitMenuDefs {} {
    global  prefs this
    variable menuDefs
	
    if {([tk windowingsystem] eq "aqua") && $prefs(haveMenus)} {
	set haveAppleMenu 1
    } else {
	set haveAppleMenu 0
    }
    
    # All menu definitions for the main (whiteboard) windows as:
    #      {{type name cmd accelerator opts} {{...} {...} ...}}

    set menuDefs(main,info,aboutwhiteboard)  \
      {command   mAboutCoccinella    {[mc "About %s" $prefs(appName)]} {::Splash::SplashScreen}   {}}
    set menuDefs(main,info,aboutquicktimetcl)  \
      {command   mAboutQuickTimeTcl  {[mc "About %s" QuickTimeTcl]} {::Dialogs::AboutQuickTimeTcl} {}}

    # Mac only.
    set menuDefs(main,apple) [list $menuDefs(main,info,aboutwhiteboard)]
    
    # Make platform specific things.
    set haveQuickTimeTcl [expr {![catch {package require QuickTimeTcl}]}]
    if {$haveAppleMenu && $haveQuickTimeTcl} {
	lappend menuDefs(main,apple) $menuDefs(main,info,aboutquicktimetcl)
    }
}

# UI::SetupAss --
# 
#       Setup assistant. Must be called after initing the jabber stuff.

proc ::UI::SetupAss {} {
    global wDlgs
    
    package require SetupAss

    catch {destroy $wDlgs(splash)}
    update
    ::SetupAss::SetupAss
    ::UI::CenterWindow $wDlgs(setupass)
    raise $wDlgs(setupass)
    tkwait window $wDlgs(setupass)
}

proc ::UI::GetMainMenu {} {
    return [::JUI::GetMainMenu]
}

proc ::UI::GetMenuFromWindow {w} {
    
    return $w.menu
}

proc ::UI::GetIcon {name} {
    variable icons
    
    if {[info exists icons($name)]} {
	return $icons($name)
    } else {
	return -code error "icon named \"$name\" does not exist"
    }
}

proc ::UI::GetScreenSize {} {
    
    return [list [winfo vrootwidth .] [winfo vrootheight .]]
}

# UI::IsAppInFront --
# 
#       Tells if application is frontmost (active).
#       [focus] is not reliable so it is better called after idle.

proc ::UI::IsAppInFront {} {
    global  this
    
    if {[tk windowingsystem] eq "aqua" \
      && [info exists this(package,carbon)]  \
      && $this(package,carbon)} {
	return [expr {[carbon::process current] == [carbon::process front]}]
    } else {
	
	# The 'wm stackorder' is not reliable in sorting windows!
	# How about message boxes in front? We never get called since they block.
	set isfront 0
	set wfocus [focus]
	foreach w [wm stackorder .] {
	    if {[string equal [wm state $w] "normal"]} {
		if {($wfocus ne "") && [string equal [winfo toplevel $wfocus] $w]} {
		    set isfront 1
		    break
		}
	    }
	}
    }
    return $isfront
}

proc ::UI::IsToplevelActive {w} {  
    set front 0
    set wfocus [focus]
    if {[string equal [wm state $w] "normal"]} {
	if {($wfocus ne "") && [string equal [winfo toplevel $wfocus] $w]} {
	    set front 1
	}
    }
    return $front
}

# UI::MessageBox --
# 
#       Wrapper for the tk_messageBox.

proc ::UI::MessageBox {args} {
    
    eval {::hooks::run newMessageBox} $args
    
    array set argsA $args
    if {[info exists argsA(-message)]} {
	set argsA(-message) [FormatTextForMessageBox $argsA(-message)]
    }
    set ans [eval {tk_messageBox} [array get argsA]]
    return $ans
}

# UI::FormatTextForMessageBox --
#
#       The tk_messageBox needs explicit newlines to format the message text.

proc ::UI::FormatTextForMessageBox {txt {width ""}} {
    global  prefs

    if {[tk windowingsystem] eq "windows"} {

	# Insert newlines to force line breaks.
	if {[string length $width] == 0} {
	    set width $prefs(msgWrapLength)
	}
	set len [string length $txt]
	set start $width
	set first 0
	set newtxt {}
	while {([set ind [tcl_wordBreakBefore $txt $start]] > 0) &&  \
	  ($start < $len)} {	    
	    append newtxt [string trim [string range $txt $first [expr {$ind-1}]]]
	    append newtxt "\n"
	    set start [expr {$ind + $width}]
	    set first $ind
	}
	append newtxt [string trim [string range $txt $first end]]
	return $newtxt
    } elseif {[tk windowingsystem] eq "x11"} {
	if {[string length $txt] < 32} {
	    append txt "             "
	}
	return $txt
    } else {
	return $txt
    }
}

# UI::Text --
# 
#       Faking Aqua text widget. Note that the container frame is returned.
#       From comp.lang.tcl Thank You!

proc ::UI::Text {w args} {
    
    if {[tk windowingsystem] eq "aqua"} {	
	set wcont [string range $w 0 [string last "." $w]]_cont
	ttk::frame $wcont -style TEntry
	eval {text $w -borderwidth 0 -highlightthickness 0} $args
	
	bind $w <FocusIn>  [list $wcont state focus]
	bind $w <FocusOut> [list $wcont state {!focus}]

	pack $w -in $wcont -padx 5 -pady 5 -fill both -expand 1
	return $wcont
    } else {
	eval $w $args
	return $w
    }
}

# Experiment!

namespace eval ::UI {
    variable slide
    #set slide(mode) linear
    set slide(mode) sinus
    set slide(step) 20
    
    # On slower OS/machines we should decrease this value.
    if {[tk windowingsystem] eq "aqua"} {
	set slide(ms) 20
    } else {
	set slide(ms) 30
    }
}

proc ::UI::SlideUp {win args} {
    variable slide
    
    set optsD [dict create]
    dict set optsD -y 0
    dict set optsD -mode $slide(mode)
    foreach {key value} $args {
	dict set optsD $key $value
    }
    set y [dict get $optsD -y]
    update idletasks
    set h [winfo reqheight $win]
    dict set optsD h $h
    
    place $win -x 0 -y $y -rely 1 -relwidth 1
    after $slide(ms) [list ::UI::SlideUpMove $win $y $optsD]
}

proc ::UI::SlideUpMove {win y optsD} {
    variable slide
    
    if {![winfo exists $win]} { return }
    set h [dict get $optsD h]
    set mode [dict get $optsD -mode]
    if {$mode eq "linear"} {
	incr y -$slide(step)
    } elseif {$mode eq "sinus"} {
	set yabs [expr {abs($y)}]
	set ystart [expr {abs([dict get $optsD -y])}]
	set delta [expr {$h - $ystart}]
	if {$delta > 1} {
	    set ypos [expr {$yabs - $ystart}]
	    set ysin [expr {sin( 3.14159*$ypos/$delta )}]
	    
	    # Extra factor of two here to compensate for sin < 1.
	    set dy [expr {2*max(int($slide(step)*$ysin), 1)}]
	} else {
	    set dy 1
	}
	incr y -$dy
    }    
    
    if {[expr {abs($y) < $h}]} {
	place $win -x 0 -y $y -rely 1 -relwidth 1
	after $slide(ms) [list ::UI::SlideUpMove $win $y $optsD]	
    } else {
	place $win -x 0 -y -$h -rely 1 -relwidth 1
	if {[dict exists $optsD -command]} {
	    uplevel #0 [dict get $optsD -command]
	}
    }
}

# -y is actually the y to stop sliding.

proc ::UI::SlideDown {win args} {
    variable slide
    
    set optsD [dict create]
    dict set optsD -y 0
    dict set optsD -mode $slide(mode)
    foreach {key value} $args {
	dict set optsD $key $value
    }
    update idletasks
    set h [winfo reqheight $win]
    dict set optsD h $h
    place $win -x 0 -y -$h -rely 1 -relwidth 1
    after $slide(ms) [list ::UI::SlideDownMove $win -$h $optsD]
}

proc ::UI::SlideDownMove {win y optsD} {
    variable slide
    
    if {![winfo exists $win]} { return }
    set h [dict get $optsD h]
    set hstop [dict get $optsD -y]
    set mode [dict get $optsD -mode]
    if {$mode eq "linear"} {
	incr y $slide(step)
    } elseif {$mode eq "sinus"} {
	set yabs [expr {abs($y)}]
	set ystop [expr {abs([dict get $optsD -y])}]
	set delta [expr {$h - $ystop}]
	if {$delta > 1} {
	    set ypos [expr {$yabs - $ystop}]
	    set ysin [expr {sin( 3.14159*$ypos/$delta )}]
	    
	    # Extra factor of two here to compensate for sin < 1.
	    set dy [expr {2*max(int($slide(step)*$ysin), 1)}]
	} else {
	    set dy 1
	}
	incr y $dy
    }    
	
    if {[expr {abs($y) > $hstop}]} {
	place $win -x 0 -y $y -rely 1 -relwidth 1
	after $slide(ms) [list ::UI::SlideDownMove $win $y $optsD]	
    } else {
	place $win -x 0 -y -$hstop -rely 1 -relwidth 1
	if {[dict exists $optsD -command]} {
	    uplevel #0 [dict get $optsD -command]
	}
    }
}

# Administrative code to handle toplevels:
#       create, close, hide, show

namespace eval ::UI {

    variable topcache
    set topcache(state)       show
#     set topcache(.,w)         .
#     set topcache(.,prevstate) "normal"
}

# UI::Toplevel --
# 
#       Wrapper for making a toplevel window.
#       
# Arguments:
#       w
#       args:
#       -allowclose 0|1
#       -class  
#       -closecommand
#       -macstyle:
#           macintosh (classic) and macosx
#           documentProc, dBoxProc, plainDBox, altDBoxProc, movableDBoxProc, 
#           zoomDocProc, rDocProc, floatProc, floatZoomProc, floatSideProc, 
#           or floatSideZoomProc
#       -macclass
#           macosx only; {class attributesList} 
#           class = alert moveableAlert modal moveableModal floating document
#                   help toolbar
#           attributes = closeBox noActivates horizontalZoom verticalZoom 
#                   collapseBox resizable sideTitlebar noUpdates noActivates
#       -usemacmainmenu

proc ::UI::Toplevel {w args} {
    global  this prefs
    variable topcache
    
    array set argsA {
	-allowclose       1
	-usemacmainmenu   0
    }
    array set argsA $args
    set opts [list]
    if {[info exists argsA(-class)]} {
	lappend opts -class $argsA(-class)
    }
    if {[info exists argsA(-closecommand)]} {
	set topcache($w,-closecommand) $argsA(-closecommand)
    }
    if {[tk windowingsystem] eq "aqua"} {
	if {$argsA(-usemacmainmenu)} {
	    lappend opts -menu [GetMainMenu]
	}
    }
    set topcache($w,prevstate) "normal"
    set topcache($w,w) $w
    eval {toplevel $w} $opts
        
    # We direct all close events through DoCloseWindow so things can
    # be handled from there.
    wm protocol $w WM_DELETE_WINDOW [list ::UI::DoCloseWindow $w "wm"]
    if {$argsA(-allowclose)} {
	bind $w <Escape> [list ::UI::DoCloseWindow $w "command"]
    }
    if {[tk windowingsystem] eq "aqua"} {
	if {[info exists argsA(-macclass)]} {
	    eval {::tk::unsupported::MacWindowStyle style $w} $argsA(-macclass)
	} elseif {[info exists argsA(-macstyle)]} {
	    ::tk::unsupported::MacWindowStyle style $w $argsA(-macstyle)
	}
	# Unreliable!!!
	# ::UI::SetAquaProxyIcon $w
    }
    if {$argsA(-allowclose)} {
	bind $w <<CloseWindow>> [list ::UI::DoCloseWindow $w "command"]
    }
    if {$argsA(-usemacmainmenu)} {
	SetMenubarAcceleratorBinds $w [GetMainMenu]
    }
    if {$prefs(opacity) != 100} {
	array set attr [wm attributes $w]
	if {[info exists attr(-alpha)]} {
	    after idle [list \
	      wm attributes $w -alpha [expr {$prefs(opacity)/100.0}]]
	}
    }
    
    # This is binding for the apple menu which is created automatically.
    if {[tk windowingsystem] eq "aqua"} {
	bind $w <$this(modkey)-Key-q> { ::UserActions::DoQuit -warning 1 }
    }
    
    # We only want to bind to the actual toplevel window. Check in handlers.
    # @@@ This is not the most reliable way to get application activate events.
    bind $w <FocusIn>  +[list ::UI::OnFocusIn %W $w]
    bind $w <FocusOut> +[list ::UI::OnFocusOut %W $w]
    bind $w <Destroy>  +[list ::UI::OnDestroy %W $w]

    # These get duplicated since Text widget binds them directly.
    bind $w <$this(modkey)-Key-z> {}
    bind $w <$this(modkey)-Key-Z> {}

    ::hooks::run newToplevelWindowHook $w
    
    return $w
}

namespace eval ::UI {
    
    variable appInFront 1
    variable closeType -
}

proc ::UI::OnFocusIn {win w} {
    variable appInFront
    
    if {$win eq $w} {
	if {!$appInFront} {
	    set appInFront 1
	    ::hooks::run appInFrontHook
	}
    }
}

proc ::UI::OnFocusOut {win w} {
    variable appInFront
    
    # We must check focus after idle.
    if {$win eq $w} {
	after idle {
	    if {[focus] eq ""} {
		set ::UI::appInFront 0
		::hooks::run appInBackgroundHook
	    }
	}
    }
}

proc ::UI::OnDestroy {win w} {
    variable topcache
    
    if {$win eq $w} {
	array unset topcache $w,*
    }
}

# @@@ Unreliable!!!
proc ::UI::SetAquaProxyIcon {w} {
    
    set f [info nameofexecutable]
    if {$f ne ""} {
	set path [eval file join [lrange [file split $f] 0 end-3]]
	wm attributes $w -titlepath $path -modified 0
    }
}

# UI::DoCloseWindow --
#
#       Take special actions before a window is closed.
#       
#       Notes: There are four ways to close a window:
#       1) from the menus Close Window command
#       2) using the menu keyboard shortcut command/control-w
#       3) using the <<CloseWindow>> virtual event
#       4) clicking the windows close button
#       
#       If any cleanup etc. is necessary all three must execute the same code.
#       In case where window must not be destroyed a hook must be registered
#       that returns stop.
#       
#       Default behaviour when no hook registered is to destroy window.
#       
# Arguments:
#       wevent
#       type:
#         command:    menu action or accelerator keys
#         wm:         window manager; user pressed windows close button.

proc ::UI::DoCloseWindow {{wevent ""} {type "command"}} {
    variable topcache
    variable closeType $type
    
    set w ""
    if {$wevent eq ""} {
	if {[winfo exists [focus]]} {
	    set w [winfo toplevel [focus]]
	}
    } else {
	set w $wevent
    }
    if {$w ne ""} {

	Debug 2 "::UI::DoCloseWindow winfo class $w=[winfo class $w], type=$type"

	# Give components a chance to intersect destruction. (Win taskbar)
	set result [::hooks::run preCloseWindowHook $w]    
	if {[string equal $result "stop"]} {
	    return
	}
	
	if {[info exists topcache($w,-closecommand)]} {
	    set result [uplevel #0 $topcache($w,-closecommand) $w]
	    if {[string equal $result "stop"]} {
		return
	    }
	    destroy $w
	}
    
	# Run hooks. Only the one corresponding to the $w needs to act!
	set result [::hooks::run closeWindowHook $w]    
	if {![string equal $result "stop"]} {
	    destroy $w
	}
    }
}

# UI::GetCloseWindowType --
# 
#       There are situations where we want to know why a window is getting closed:
#         command:    menu action or accelerator keys
#         wm:         window manager; user pressed windows close button.

proc ::UI::GetCloseWindowType {} {
    variable closeType
    return $closeType
}

# UI::GetAllToplevels --
# 
#       Returns a list of all existing toplevel windows created using Toplevel.

proc ::UI::GetAllToplevels {} {
    variable topcache

    set tmp [list]
    foreach {key w} [array get topcache *,w] {
	if {[winfo exists $w]} {
	    lappend tmp $w
	}
    }
    return $tmp
}

proc ::UI::WithdrawAllToplevels {} {
    variable topcache
    
    foreach w [GetAllToplevels] {
	set topcache($w,prevstate) [wm state $w]
	wm withdraw $w
    }
    set topcache(state) hide
}

proc ::UI::ShowAllToplevels {} {
    variable topcache
    
    foreach w [GetAllToplevels] {
	set topcache($w,prevstate) [wm state $w]
	wm deiconify $w
    }
    set topcache(state) show
}

proc ::UI::GetToplevelState {} {
    variable topcache
    
    return $topcache(state)
}

# UI::GetToplevelFromPath --
# 
#       As 'winfo toplevel' but window need not exist.

proc ::UI::GetToplevelFromPath {w} {

    if {[string equal $w "."]} {
	return $w
    } else {
	regexp {^(\.[^.]+)} $w match wpath
	return $wpath
    }
}

# UI::ScrollFrame --
# 
#       A few functions to make scrollable frames.

proc ::UI::ScrollFrame {w args} {
    
    array set opts {
	-bd         0
	-padding    {0}
	-propagate  1
	-relief     flat
	-width      0
    }
    array set opts $args
    
    if {0} {
	frame $w -class Scrollframe -bd $opts(-bd) -relief $opts(-relief)	
    } else {
	ttk::frame $w -class Scrollframe
    }
    ttk::scrollbar $w.ysc -command [list $w.can yview]
    if {$opts(-width)} {
	set cwidth [expr {$opts(-width) - $opts(-bd) - [winfo reqwidth $w.ysc]}]
	canvas $w.can -yscrollcommand [list $w.ysc set] -highlightthickness 0 \
	  -width $cwidth
    } else {
	canvas $w.can -yscrollcommand [list $w.ysc set] -highlightthickness 0
    }
    pack $w.ysc -side right -fill y
    pack $w.can -side left -fill both -expand 1
    
    if {1 || !$opts(-propagate)} {
	ttk::frame $w.can.bg
	$w.can create window 0 0 -anchor nw -window $w.can.bg -tags twin
    }
    ttk::frame $w.can.f -padding $opts(-padding)
    $w.can create window 0 0 -anchor nw -window $w.can.f -tags twin

    if {$opts(-propagate)} {
	bind $w.can.f <Configure> [list ::UI::ScrollFrameResize $w]
	bind $w.can   <Configure> [list ::UI::ScrollFrameResizeBg $w]
    } else {
	bind $w.can.f <Configure> [list ::UI::ScrollFrameResizeScroll $w]
	bind $w.can   <Configure> [list ::UI::ScrollFrameResizeBg $w]
    }
    return $w
}

proc ::UI::ScrollFrameResize {w} {
    update idletasks
    set bbox [$w.can bbox twin]
    set width [winfo width $w.can.f]
    $w.can configure -width $width -scrollregion $bbox
}

proc ::UI::ScrollFrameResizeScroll {w} {
    set bbox [$w.can bbox all]
    $w.can configure -scrollregion $bbox
}

proc ::UI::ScrollFrameResizeBg {w} {   
    update idletasks
    set bbox [$w.can bbox all]
    set width  [winfo width $w.can]
    set height [winfo height $w.can]
    $w.can.bg configure -width $width -height $height
}

proc ::UI::ScrollFrameInterior {w} { 
    return $w.can.f
}

# UI::QuirkSize --
# 
#       This is a trick to trigger an extra Expose event which sometimes (Aqua)
#       is missing.

proc ::UI::QuirkSize {w} {    
    set geo [wm geometry $w]
    regexp {([0-9]+)x([0-9]+)} $geo - width height
    incr width
    wm geometry $w ${width}x${height}
    incr width -1
    wm geometry $w ${width}x${height}
}

# UI::ScrollSet --
# 
#       Command for auto hide/show scrollbars.

proc ::UI::ScrollSet {wscrollbar geocmd offset size} {
   # get the geometry manager
   set manager [lindex $geocmd 0]
   # Create the name for the focus
   set wfocus $wscrollbar.focus
   # that name must survive
   global $wfocus
   if {($offset != 0.0) || ($size != 1.0)} {
      # If the scrollbar hasn't a geomanager,
      # it means that this time it will appear (and get a geomanager)
      # then i record the name of the current focused object
      if {[string equal $manager "grid"] && [string equal [$manager info $wscrollbar] ""]} {
         set $wfocus [focus]
      }
      eval $geocmd
      $wscrollbar set $offset $size
   } else {
      $manager forget $wscrollbar
   }

   # Whatever would happen, i always will set the focus
   # on the "current focused object" recorded in the lines above.
   if {[info exists $wfocus]} {
      focus [set $wfocus]
   }
}

# UI::ScrollSetStdGrid --
# 
#       As 'ScrollSet' but with workaround for the grid display bug.

proc ::UI::ScrollSetStdGrid {wscrollbar geocmd offset size} {
    
    if {($offset != 0.0) || ($size != 1.0)} {
	eval $geocmd
	$wscrollbar set $offset $size
    } else {
	set manager [lindex $geocmd 0]
	$manager forget $wscrollbar
	
	# This helps as a workaround for one of horiz/vert blank areas.
	set wmaster [winfo parent $wscrollbar]
	array set opts [lrange $geocmd 2 end]
	after idle [list grid rowconfigure $wmaster 1 -minsize 0]
    }
}

proc ::UI::GetPaddingWidth {padding} {
    
    switch -- [llength $padding] {
	1 {
	    return [expr {2*$padding}]
	}
	2 {
	    return [expr {2*[lindex $padding 0]}]
	}
	4 {
	    return [expr {[lindex $padding 0] + [lindex $padding 2]}]
	}
    }
}

proc ::UI::GetPaddingHeight {padding} {
    
    switch -- [llength $padding] {
	1 {
	    return [expr {2*$padding}]
	}
	2 {
	    return [expr {2*[lindex $padding 1]}]
	}
	4 {
	    return [expr {[lindex $padding 1] + [lindex $padding 3]}]
	}
    }
}

# UI::SaveWinGeom, SaveWinPrefixGeom --
#
#       Call this when closing window to store its geometry if exists.
#
# Arguments:
#       key         toplevel or entry in storage array.
#       w           (D="") if set then 'key' is only entry in array, while 'w'
#                   is the actual toplevel window.
# 

proc ::UI::SaveWinGeom {key {w ""}} {
    global  prefs
    
    if {$w eq ""} {
	set w $key
    }
    if {[winfo exists $w]} {
	
	# If a bug somewhere we may get  1x1+563+158  which shall never be saved!
	set geom [wm geometry $w]
	lassign [ParseWMGeometry $geom] width height x y
	if {$width > 1 && $height > 1} {
	    set prefs(winGeom,$key) $geom
	}
    }
}

proc ::UI::SaveWinPrefixGeom {wprefix {key ""}} {
    
    if {$key eq ""} {
	set key $wprefix
    }
    set win [GetFirstPrefixedToplevel $wprefix]
    if {$win ne ""} {
	SaveWinGeom $key $win
    }	
}

proc ::UI::SaveWinGeomUseSize {key geom} {
    global  prefs
    
    set prefs(winGeom,$key) $geom
}

proc ::UI::SetWindowPosition {w {key ""}} {
    global  prefs
    
    if {$key eq ""} {
	set key $w
    }
    if {[info exists prefs(winGeom,$key)]} {

	# We shall verify that the window is not put offscreen.
	lassign [ParseWMGeometry $prefs(winGeom,$key)] width height x y

	# Protect for corrupted prefs.
	if {$width < 20}  {set width 20}
	if {$height < 20} {set height 20}

	KeepOnScreen $w x y $width $height
	wm geometry $w +${x}+${y}
    }
}

proc ::UI::SetWindowGeometry {w {key ""}} {
    global  prefs
    
    if {$key eq ""} {
	set key $w
    }
    if {[info exists prefs(winGeom,$key)]} {

	# We shall verify that the window is not put offscreen.
	lassign [ParseWMGeometry $prefs(winGeom,$key)] width height x y

	# Protect for corrupted prefs.
	if {$width < 20}  {set width 20}
	if {$height < 20} {set height 20}

	KeepOnScreen $w x y $width $height
	wm geometry $w ${width}x${height}+${x}+${y}
    }
}

proc ::UI::SaveSashPos {key w} {
    global  prefs
    
    if {[winfo exists $w]} {
	update
	set prefs(sashPos,$key) [$w sashpos 0]
    }
}

proc ::UI::SetSashPos {key w} {
    global  prefs
    
    # @@@ Not working!
    if {0} {
	if {[info exists prefs(sashPos,$key)]} {
	    update idletasks
	    $w sashpos 0 $prefs(sashPos,$key)
	}
    }
}

proc ::UI::KeepOnScreen {w xVar yVar width height} {
    global  this
    upvar $xVar x
    upvar $yVar y
    
    set margin 10
    set topmargin 0
    set botmargin 40
    if {[string match mac* $this(platform)]} {
	set topmargin 20
    }
    set screenwidth  [winfo vrootwidth $w]
    set screenheight [winfo vrootheight $w]
    set x2 [expr {$x + $width}]
    set y2 [expr {$y + $height}]
    if {$x < 0} {
	set x $margin
    }
    if {$x > [expr {$screenwidth - $margin}]} {
	set x [expr {$screenwidth - $width - $margin}]
    }
    if {$y < $topmargin} {
	set y $topmargin
    }
    if {$y > [expr {$screenheight - $botmargin}]} {
	set y [expr {$screenheight - $height - $botmargin}]
    }
}

proc ::UI::GetFirstPrefixedToplevel {wprefix} {
    
    set win ""
    set wins [lsearch -all -inline -glob [winfo children .] ${wprefix}*]
    if {[llength $wins]} {
	
	# 1st priority, pick if on top.
	set wfocus [focus]
	if {$wfocus ne ""} {
	    set win [winfo toplevel $wfocus]
	}
	set win [lsearch -inline $wins $wfocus]
	if {$win eq ""} {
	    
	    # 2nd priority, just get first in list.
	    set win [lindex $wins 0]
	}
    }
    return $win
}

proc ::UI::GetPrefixedToplevels {wprefix} {
    
    return [lsort -dictionary \
      [lsearch -all -inline -glob [winfo children .] ${wprefix}*]]
}

# @@@ All this menu code is a total mess!!! Perhaps a snidget?

# UI::NewMenu --
# 
#       Creates a new menu from a previously defined menu definition list.
#       
# Arguments:
#       w           toplevel window
#       wmenu       the menus widget path name (".menu.file" etc.).
#       label       its label.
#       menuSpec    a hierarchical list that defines the menu content.
#                   {{type name cmd accelerator opts} {{...} {...} ...}}
#       args        form ?-varName value? list that defines local variables to set.
#       
# Results:
#       $wmenu

proc ::UI::NewMenu {w wmenu label lname menuSpec args} {    
    variable mapWmenuToWtop
    variable cachedMenuSpec
    
    # Need to cache the complete menuSpec's since needed in MenuMethod.
    set cachedMenuSpec($w,$wmenu) $menuSpec
    set mapWmenuToWtop($wmenu)    $w

    eval {BuildMenu $w $wmenu $label $lname $menuSpec} $args
}

# UI::BuildMenu --
#
#       Make menus recursively from a hierarchical menu definition list.
#       Only called from ::UI::NewMenu!
#
# Arguments:
#       w           toplevel window
#       wmenu       the menus widget path name (".menu.file" etc.).
#       mLabel      its mLabel.
#       menuDef     a hierarchical list that defines the menu content.
#                   {{type name cmd accelerator opts} {{...} {...} ...}}
#       args        form ?-varName value? list that defines local variables to set.
#       
# Results:
#       $wmenu

proc ::UI::BuildMenu {w wmenu mLabel lname menuDef args} {
    global  this wDlgs prefs

    variable menuKeyToIndex
    variable menuNameToWmenu
    variable mapWmenuToWtop
    variable cachedMenuSpec
            
    # This is also used to rebuild an existing menu.
    if {[winfo exists $wmenu]} {
	
	# The toplevel cascades must not be deleted since this changes
	# their relative order.
	# Also must be sure to delete any child cascades so they are added
	# back properly below.
	$wmenu delete 0 end
	foreach mchild [winfo children $wmenu] {
	    destroy $mchild
	}
	set m $wmenu
	array unset menuKeyToIndex  $wmenu,*
	set exists 1
    } else {
	set m [menu $wmenu -tearoff 0]
	set exists 0
    }
    set wparent [winfo parent $wmenu]
    
    foreach {optName value} $args {
	set varName [string trimleft $optName "-"]
	set $varName $value
    }

    # A trick to make this work for popup menus, which do not have a Menu parent.
    if {!$exists && [string equal [winfo class $wparent] "Menu"]} {
	set lname [eval concat $lname]
	set ampersand [string first & $lname]
	set mopts [list]
	if {$ampersand != -1} {
	    regsub -all & $lname "" lname
	    lappend mopts -underline $ampersand
	}
	eval {$wparent add cascade -label $lname -menu $m} $mopts
    }
    
    # If we don't have a menubar, for instance, if embedded toplevel.
    # Only for the toplevel menubar.
    if {[string equal $wparent ".menu"] &&  \
      [string equal [winfo class $wparent] "Frame"]} {
	# label ${wmenu}la -text $locname
	label ${wmenu}la -text $lname
	pack  ${wmenu}la -side left -padx 4
	bind  ${wmenu}la <Button-1> [list ::UI::DoTopMenuPopup %W $wmenu]
    }
    
    set mod [string map {Control Ctrl} $this(modkey)]
    set i 0
    foreach line $menuDef {
	foreach {type name lname cmd accel mopts subdef} $line {
	    
	    set lname [eval concat $lname]

	    set menuKeyToIndex($wmenu,$name) $i
	    set menuNameToWmenu($w,$mLabel,$name) $wmenu
	    set ampersand [string first & $lname]
	    if {$ampersand != -1} {
		regsub -all & $lname "" lname
		lappend mopts -underline $ampersand
	    }
	    if {[string match "sep*" $type]} {
		$m add separator
	    } elseif {[string equal $type "cascade"]} {
		
		# Make cascade menu recursively.
		regsub -all -- " " [string tolower $name] "" mt
		regsub -all -- {\.} $mt "" mt
		
		set wsubmenu $wmenu.$mt
		set cachedMenuSpec($w,$wsubmenu) $subdef
		set mapWmenuToWtop($wsubmenu) $w
		eval {BuildMenu $w $wsubmenu $name $lname $subdef} $args
		
		# Explicitly set any disabled state of cascade.
		MenuMethod $m entryconfigure $name
	    } else {
		
		# All variables (and commands) in menuDef's cmd shall be 
		# substituted! Be sure they are all in here.

		# BUG: [ 1340712 ] Ex90 Error when trying to start New whiteboard 
		# FIX: protect menuDefs [string map {$ \\$} $f]
		# @@@ No spaces allowed in variables!
		set cmd [subst -nocommands $cmd]
		if {[string length $accel]} {
		    lappend mopts -accelerator $mod+$accel
		}
		eval {$m add $type -label $lname -command $cmd} $mopts 
	    }
	}
	incr i
    }
    return $wmenu
}

proc ::UI::GetMenu {w label1 {label2 ""}} {
    variable menuNameToWmenu

    return $menuNameToWmenu($w,$label1,$label2)
}

proc ::UI::GetMenuKeyToIndex {wmenu key} {
    variable menuKeyToIndex

    return $menuKeyToIndex($wmenu,$key)
}

proc ::UI::HaveMenuEntry {wmenu mLabel} {
    variable menuKeyToIndex

    return [info exists menuKeyToIndex($wmenu,$mLabel)]
}

proc ::UI::FreeMenu {w} {
    variable mapWmenuToWtop
    variable cachedMenuSpec
    variable menuKeyToIndex
    variable menuNameToWmenu
    
    foreach key [array names cachedMenuSpec $w,*] {
	set wmenu [string map [list "$w," ""] $key]
	unset mapWmenuToWtop($wmenu)
	array unset menuKeyToIndex $wmenu,*
    }
    array unset cachedMenuSpec  $w,*
    array unset menuNameToWmenu $w,*
}

# UI::MenuMethod --
#  
#       Utility to use instead of 'menuPath cmd index args' since it
#       handles menu accelerators as well.
#
# Arguments:
#       wmenu       menu's widget path
#       cmd         valid menu command
#       key         key to menus index (mOpen etc.)
#       args
#       
# Results:
#       binds to toplevel changed

proc ::UI::MenuMethod {wmenu cmd key args} {
    variable menuKeyToIndex
    
    # Be silent about nonexistent entries?
    if {[info exists menuKeyToIndex($wmenu,$key)]} {
	set mind  $menuKeyToIndex($wmenu,$key)
	if {[string match "entrycon*" $cmd]} {
	    if {[expr {[llength $args] % 2 == 0}]} {
		array set argsA $args
		if {[info exists argsA(-label)]} {
		    set name $argsA(-label)
		    set lname [mc $name]
		    set ampersand [string first & $lname]
		    if {$ampersand != -1} {
			regsub -all & $lname "" lname
			set argsA(-underline) $ampersand
		    }
		    set argsA(-label) $lname
		    set args [array get argsA]
		}
	    }
	}
	eval {$wmenu $cmd $mind} $args
    }
}

# UI::SetMenubarAcceleratorBinds --
# 
#       Binds all main menu accelerator keys to window.
#       
# Arguments:
#       w
#       wmenu
#       
# Results:
#       none

proc ::UI::SetMenubarAcceleratorBinds {w wmenubar} {
    global  this
    
    variable menuKeyToIndex
    variable mapWmenuToWtop
    variable cachedMenuSpec
    variable regAccelerators
        
    foreach {wmenu wtop} [array get mapWmenuToWtop $wmenubar.*] {
	foreach line $cachedMenuSpec($wtop,$wmenu) {
	    
	    # {type name cmd accel mopts subdef} $line
	    # Cut, Copy & Paste handled by widgets internally!
	    set accel [lindex $line 4]
	    if {[string length $accel] && ![regexp {(X|C|V)} $accel]} {
		set name [lindex $line 1]
		set mind $menuKeyToIndex($wmenu,$name)
		set key [string tolower [string range $accel end end]]
		set key [string map {< less > greater} $key]
		set prefix [string range $accel 0 end-1]
		if {$prefix eq "Shift-"} {
		    set key [string toupper $key]
		}
		bind $w <$this(modkey)-$prefix$key> [lindex $line 3]
	    }
	}
    }
    
    foreach spec $regAccelerators {
	lassign $spec key cmd
	bind $w <$this(modkey)-$key> $cmd
    }
}

# UI::SetMenuAcceleratorBinds --
# 
#       Sets the accelerator key binds to toplevel for specific menu.

proc ::UI::SetMenuAcceleratorBinds {w wmenu} {
    global  this

    variable cachedMenuSpec
    variable menuKeyToIndex
    
    foreach line $cachedMenuSpec($w,$wmenu) {
	set accel [lindex $line 4]
	if {[string length $accel]} {
	    set name [lindex $line 1]
	    set mind $menuKeyToIndex($wmenu,$name)
	    set key [string tolower [string range $accel end end]]
	    set key [string map {< less > greater} $key]
	    set prefix [string range $accel 0 end-1]
	    if {$prefix eq "Shift-"} {
		set key [string toupper $key]
	    }
	    bind $w <$this(modkey)-$prefix$key> [lindex $line 3]
	}
    }
}

# UI::RegisterAccelerator --
# 
#       This is a way to register an accelerator key which is not handled
#       with the other Menu code.

proc ::UI::RegisterAccelerator {key cmd} {
    global  this
    variable regAccelerators
    
    set key [string tolower $key]
    lappend regAccelerators [list $key $cmd]
}

proc ::UI::BuildAppleMenu {w wmenuapple state} {
    variable menuDefs
    
    NewMenu $w $wmenuapple  {}  $state  $menuDefs(main,apple)
    
    if {[tk windowingsystem] eq "aqua"} {
	proc ::tk::mac::ShowPreferences {} {
	    ::Preferences::Build
	}
    }
}

proc ::UI::MenubarDisableBut {mbar name} {

    # Accelerators must be handled from OnMenu* commands.
    set iend [$mbar index end]
    for {set ind 0} {$ind <= $iend} {incr ind} {
	set m [$mbar entrycget $ind -menu]
	if {$name ne [winfo name $m]} {
	    $mbar entryconfigure $ind -state disabled
	}
    }
}

proc ::UI::MenubarEnableAll {mbar} {
    
    # Accelerators must be handled from OnMenu* commands.
    set iend [$mbar index end]
    for {set ind 0} {$ind <= $iend} {incr ind} {
	$mbar entryconfigure $ind -state normal
    }    
}

proc ::UI::MenuEnableAll {mw} {
    
    set iend [$mw index end]
    for {set i 0} {$i <= $iend} {incr i} {
	if {[$mw type $i] ne "separator"} {
	    $mw entryconfigure $i -state normal
	}
    }
}

proc ::UI::MenuDisableAll {mw} {
    MenuDisableAllBut $mw {}
}

proc ::UI::MenuDisableAllBut {mw normalL} {

    set iend [$mw index end]
    for {set i 0} {$i <= $iend} {incr i} {
	if {[$mw type $i] ne "separator"} {
	    $mw entryconfigure $i -state disabled
	}
    }
    foreach name $normalL {
	::UI::MenuMethod $mw entryconfigure $name -state normal
    }
}

proc ::UI::DoTopMenuPopup {w wmenu} {
    
    if {[winfo exists $wmenu]} {
	set x [winfo rootx $w]
	set y [expr {[winfo rooty $w] + [winfo height $w]}]
	tk_popup $wmenu $x $y
    }
}

# These Grab/GrabRelease handle menus as well.

proc ::UI::Grab {w} {
	
    # Disable menubar except Edit menu.
    set mb [$w cget -menu]
    if {$mb ne ""} {
	MenubarDisableBut $mb edit
    }
    ui::grabWindow $w
}

proc ::UI::GrabRelease {w} {    
    ui::releaseGrab $w
    
    # Enable menubar.
    set mb [$w cget -menu]
    if {$mb ne ""} {
	MenubarEnableAll $mb
    }
}

# UI::PruneMenusFromConfig --
#
#       A method to remove specific menu entries from 'menuDefs' and
#       'menuDefsInsertInd' using an entry in the 'config' array:
#       config(ui,pruneMenus):   mInfo {mDebug mCoccinellaHome...}
#
# Arguments:
#       name            the menus key label, mJabber, mEdit etc.
#       menuDefVar      *name* if the menuDef variable.
#       
# Results:
#       None

proc ::UI::PruneMenusFromConfig {name menuDefVar} {
    global  config
    upvar $menuDefVar menuDef
    
    array set pruneArr $config(ui,pruneMenus)    
    if {[info exists pruneArr($name)]} {
    
	# Take each in turn and find any matching index.
	foreach mLabel $pruneArr($name) {
	    set idx [lsearch -glob $menuDef *${mLabel}*]
	    if {$idx >= 0} {
		set menuDef [lreplace $menuDef $idx $idx]
	    }
	}
    }
}

# UI::LabelButton --
# 
#       A html link type button from a label widget.

proc ::UI::LabelButton {w args} {

    array set eopts {
	-command          {}
    }
    array set lopts {
	-foreground       blue
	-activeforeground red
    }    
    foreach {key value} $args {	
	switch -- $key {
	    -command {
		set eopts($key) $value
	    }
	    default {
		set lopts($key) $value
	    }
	}
    }    
    eval {label $w} [array get lopts]
    set cursor [$w cget -cursor]
    array set fontArr [font actual [$w cget -font]]
    set fontArr(-underline) 1
    $w configure -font [array get fontArr]
    bind $w <Button-1> $eopts(-command)
    bind $w <Enter> [list $w configure -fg $lopts(-activeforeground) -cursor hand2]
    bind $w <Leave> [list $w configure -fg $lopts(-foreground) -cursor $cursor]
    return $w
}

# UI::OkCancelButtons --
# 
# 

proc ::UI::OkCancelButtons {args} {
    
    set padx [option get . buttonPadX {}]
    if {[option get . okcancelButtonOrder {}] eq "cancelok"} {
	set i 0
	foreach spec $args {
	    set wbt [eval {ttk::button} $spec]
	    pack $wbt -side right
	    if {[expr {$i & 2}] == 1} {
		pack $wbt -padx $padx
	    }
	    incr i
	}
    } else {
	for {set i [expr {[llength $args] - 1}]} {$i >= 0} {incr i -1} {
	    set wbt [eval {ttk::button} [lindex $args $i]]
	    pack $wbt -side right
	    if {[expr {$i & 2}] == 1} {
		pack $wbt -padx $padx
	    }
	}
    }
}

# UI::CutEvent, CopyEvent, PasteEvent --
# 
#       Used in menu commands to generate <<Cut>>, <<Copy>>, and <<Paste>>
#       virtual events for _any_ widget.

proc ::UI::CutEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<Cut>>
    }	
}

proc ::UI::CopyEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<Copy>>
    }	
}

proc ::UI::PasteEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<Paste>>
    }	
}

proc ::UI::CloseWindowEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<CloseWindow>>
    }
}

proc ::UI::FindEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<Find>>
    }	
}

proc ::UI::FindAgainEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<FindAgain>>
    }	
}

proc ::UI::FindPreviousEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<FindPrevious>>
    }	
}

proc ::UI::UndoEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<Undo>>
    }	    
}

proc ::UI::RedoEvent {} {
    if {[winfo exists [focus]]} {
	event generate [focus] <<Redo>>
    }	    
}

# For menu commands.
# Note that we must allow CloseWindowEvent on grabbed window.

proc ::UI::OnMenuAll {} {
    if {[winfo exists [focus]]} {
	set w [focus]
	switch -- [winfo class [focus]] {
	    Text {
		$w tag add sel 1.0 end
	    }
	    Entry - TEntry {
		$w selection range 0 end
	    }
	}
    }
}

proc ::UI::OnMenuFind {} {
    if {[llength [grab current]]} { return }
    FindEvent
}

proc ::UI::OnMenuFindAgain {} {
    if {[llength [grab current]]} { return }
    FindAgainEvent
}

proc ::UI::OnMenuFindPrevious {} {
    if {[llength [grab current]]} { return }
    FindPreviousEvent
}

# UI::GenericCCPMenuStates --
# 
#       Retuns a flat array with cut, copy, and paste menu entry states when
#       any of the standard widgets TEntry, Entry, and Text have focus.
#
#       Edits are typically different from other commands in that they operate
#       on a specific widget.

proc ::UI::GenericCCPMenuStates {} {
    
    # @@@ The situation with a ttk::entry in readonly state is not understood.
    # @@@ Not sure focus is needed for selections.
    set w [focus]
    set haveFocus 1
    set haveSelection 0
    set editable 1
    
    array set ccpStateA {
	mCut    disabled
	mCopy   disabled
	mPaste  disabled
    }
    
    if {[winfo exists $w]} {

	switch -- [winfo class $w] {
	    TEntry - TCombobox {
		set haveSelection [$w selection present]
		set state [$w state]
		if {[lsearch $state disabled] >= 0} {
		    set editable 0
		} elseif {[lsearch $state readonly] >= 0} {
		    set editable 0
		}
	    }
	    Entry {
		set haveSelection [$w selection present]
		if {[$w cget -state] eq "disabled"} {
		    set editable 0
		}
	    }
	    Text {
		if {![catch {$w get sel.first sel.last} data]} {
		    if {$data ne ""} {
			set haveSelection 1
		    }
		}
		if {[$w cget -state] eq "disabled"} {
		    set editable 0
		}
	    }
	    default {
		set haveFocus 0
	    }
	}
    }    

    # Cut, copy and paste menu entries.
    if {$haveSelection} {
	if {$editable} {
	    set ccpStateA(mCut) normal
	}
	set ccpStateA(mCopy) normal
    }
    if {![catch {selection get -sel CLIPBOARD} str]} {
	if {$editable && $haveFocus && ($str ne "")} {
	    set ccpStateA(mPaste) normal
	}
    }
    return [array get ccpStateA]
}

# ::UI::ParseWMGeometry --
# 
#       Parses 'wm geometry' result into a list.
#       
# Arguments:
#       wmgeom      output from 'wm geometry'
#       
# Results:
#       list {width height x y}

proc ::UI::ParseWMGeometry {wmgeom} {
    regexp {([0-9]+)x([0-9]+)\+(\-?[0-9]+)\+(\-?[0-9]+)} $wmgeom - w h x y
    return [list $w $h $x $y]
}

proc ::UI::CenterWindow {win} {
    
    if {[winfo toplevel $win] != $win} {
	error "::UI::CenterWindow: $win is not a toplevel window"
    }
    after idle [format {
	
	# @@@ This is potentially dangerous!
	update idletasks
	set win %s
	set sw [winfo screenwidth $win]
	set sh [winfo screenheight $win]
	set x [expr {($sw - [winfo reqwidth $win])/2}]
	set y [expr {($sh - [winfo reqheight $win])/2}]
	wm geometry $win "+$x+$y"
    } $win]
}

# ::UI::StartStopAnimatedWave, AnimateWave --
#
#       Utility routines for animating the wave in the status message frame.
#       
# Arguments:
#       w           canvas widget path (not the whiteboard)
#       
# Results:
#       none

proc ::UI::StartStopAnimatedWave {w theimage start} {
    variable icons
    variable animateWave
    
    # Define speed and update frequency. Pix per sec and times per sec.
    set speed 150
    set freq 16
    set animateWave(pix) [expr {int($speed/$freq)}]
    set animateWave(wait) [expr {int(1000.0/$freq)}]

    if {$start} {
	
	# Check if not already started.
	if {[info exists animateWave($w,id)]} {
	    return
	}
	set id [$w create image 0 0 -anchor nw -image $theimage]
	set animateWave($w,id) $id
	$w lower $id
	set animateWave($w,x) 0
	set animateWave($w,dir) 1
	set animateWave($w,killId)   \
	  [after $animateWave(wait) [list ::UI::AnimateWave $w]]
    } elseif {[info exists animateWave($w,killId)]} {
	after cancel $animateWave($w,killId)
	$w delete $animateWave($w,id)
	array unset animateWave $w,*
    }
}

proc ::UI::AnimateWave {w} {
    variable animateWave
    
    set deltax [expr {$animateWave($w,dir) * $animateWave(pix)}]
    incr animateWave($w,x) $deltax
    if {$animateWave($w,x) > [expr {[winfo width $w] - 80}]} {
	set animateWave($w,dir) -1
    } elseif {$animateWave($w,x) <= -60} {
	set animateWave($w,dir) 1
    }
    $w move $animateWave($w,id) $deltax 0
    set animateWave($w,killId)   \
      [after $animateWave(wait) [list ::UI::AnimateWave $w]]
}

#-------------------------------------------------------------------------------