summaryrefslogtreecommitdiff
path: root/itcl/iwidgets3.0.0/generic/hierarchy.itk
blob: f315fd07b8a38924145a92d659b9bf1c3a643986 (plain)
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
# Hierarchy
# ----------------------------------------------------------------------
# Hierarchical data viewer.  Manages a list of nodes that can be
# expanded or collapsed.  Individual nodes can be highlighted.
# Clicking with the right mouse button on any item brings up a
# special item menu.  Clicking on the background area brings up
# a different popup menu.
# ----------------------------------------------------------------------
#   AUTHOR:  Michael J. McLennan
#            Bell Labs Innovations for Lucent Technologies
#            mmclennan@lucent.com
#
#            Mark L. Ulferts
#            DSC Communications
#            mulferts@austin.dsccc.com
#
#      RCS:  $Id$
# ----------------------------------------------------------------------
#                Copyright (c) 1996  Lucent Technologies
# ======================================================================
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that the copyright notice and warranty disclaimer appear in
# supporting documentation, and that the names of Lucent Technologies
# any of their entities not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# Lucent Technologies disclaims all warranties with regard to this
# software, including all implied warranties of merchantability and
# fitness.  In no event shall Lucent Technologies be liable for any
# special, indirect or consequential damages or any damages whatsoever
# resulting from loss of use, data or profits, whether in an action of
# contract, negligence or other tortuous action, arising out of or in
# connection with the use or performance of this software.
#
# ----------------------------------------------------------------------
#            Copyright (c) 1996 DSC Technologies Corporation
# ======================================================================
# Permission to use, copy, modify, distribute and license this software 
# and its documentation for any purpose, and without fee or written 
# agreement with DSC, is hereby granted, provided that the above copyright 
# notice appears in all copies and that both the copyright notice and 
# warranty disclaimer below appear in supporting documentation, and that 
# the names of DSC Technologies Corporation or DSC Communications 
# Corporation not be used in advertising or publicity pertaining to the 
# software without specific, written prior permission.
# 
# DSC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING 
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, AND NON-
# INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE
# AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, 
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. IN NO EVENT SHALL 
# DSC BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR 
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, 
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS ACTION,
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS 
# SOFTWARE.
# ======================================================================

#
# Usual options.
#
itk::usual Hierarchy {
    keep -cursor -textfont -font
    keep -background -foreground -textbackground 
    keep -selectbackground -selectforeground 
}

# ------------------------------------------------------------------
#                            HIERARCHY
# ------------------------------------------------------------------
class iwidgets::Hierarchy {
    inherit iwidgets::Scrolledwidget

    constructor {args} {}

    destructor {}

    itk_option define -alwaysquery alwaysQuery AlwaysQuery 0
    itk_option define -closedicon closedIcon Icon {}
    itk_option define -dblclickcommand dblClickCommand Command {}
    itk_option define -expanded expanded Expanded 0 
    itk_option define -filter filter Filter 0 
    itk_option define -font font Font \
	-*-Courier-Medium-R-Normal--*-120-*-*-*-*-*-* 
    itk_option define -height height Height 0
    itk_option define -iconcommand iconCommand Command {}
    itk_option define -icondblcommand iconDblCommand Command {}
    itk_option define -imagecommand imageCommand Command {}
    itk_option define -imagedblcommand imageDblCommand Command {}
    itk_option define -imagemenuloadcommand imageMenuLoadCommand Command {}
    itk_option define -markbackground markBackground Foreground #a0a0a0 
    itk_option define -markforeground markForeground Background Black 
    itk_option define -nodeicon nodeIcon Icon {}
    itk_option define -openicon openIcon Icon {}
    itk_option define -querycommand queryCommand Command {}
    itk_option define -selectcommand selectCommand Command {}
    itk_option define -selectbackground selectBackground Foreground #c3c3c3 
    itk_option define -selectforeground selectForeground Background Black 
    itk_option define -textmenuloadcommand textMenuLoadCommand Command {}
    itk_option define -visibleitems visibleItems VisibleItems 80x24
    itk_option define -width width Width 0

    public {
	method clear {}
	method collapse {node}
	method current {}
	method draw {{when -now}}
	method expand {node}
	method expanded {node}
	method expState { }
	method mark {op args}
	method prune {node}
	method refresh {node}
	method selection {op args}
	method toggle {node}
	
	method bbox {index} 
	method compare {index1 op index2} 
	method debug {args} {eval $args}
	method delete {first {last {}}} 
	method dlineinfo {index} 
	method dump {args}
	method get {index1 {index2 {}}} 
	method index {index} 
	method insert {args} 
	method scan {option args} 
	method search {args} 
	method see {index} 
	method tag {op args} 
	method window {option args} 
	method xview {args}
	method yview {args}
    }

    protected {
	method _contents {uid}
	method _post {x y}
	method _drawLevel {node indent}
	method _select {x y}
	method _deselectSubNodes {uid}
	method _deleteNodeInfo {uid}
	method _getParent {uid}
	method _getHeritage {uid}
	method _isInternalTag {tag}
	method _iconSelect {node icon}
	method _iconDblSelect {node icon}
	method _imageSelect {node}
	method _imageDblClick {node}
	method _imagePost {node image type x y}
	method _double {x y}
    }
    
    private {
	variable _filterCode ""  ;# Compact view flag.
	variable _hcounter 0     ;# Counter for hierarchy icons
	variable _icons          ;# Array of user icons by uid
	variable _images         ;# Array of our icons by uid
	variable _indents        ;# Array of indentation by uid
	variable _marked         ;# Array of marked nodes by uid
	variable _markers ""     ;# List of markers for level being drawn
	variable _nodes          ;# List of subnodes by uid
	variable _pending ""     ;# Pending draw flag
	variable _posted ""      ;# List of tags at posted menu position
	variable _selected       ;# Array of selected nodes by uid
	variable _tags           ;# Array of user tags by uid
	variable _text           ;# Array of displayed text by uid
	variable _states         ;# Array of selection state by uid
	variable _ucounter 0     ;# Counter for user icons
    }
}

#
# Provide a lowercased access method for the Hierarchy class.
# 
proc ::iwidgets::hierarchy {pathName args} {
    uplevel ::iwidgets::Hierarchy $pathName $args
}

#
# Use option database to override default resources of base classes.
#
option add *Hierarchy.menuCursor arrow widgetDefault
option add *Hierarchy.labelPos n widgetDefault
option add *Hierarchy.tabs 30 widgetDefault

# ------------------------------------------------------------------
#                        CONSTRUCTOR
# ------------------------------------------------------------------
body iwidgets::Hierarchy::constructor {args} {
    itk_option remove iwidgets::Labeledwidget::state

    #
    # Our -width and -height options are slightly different than
    # those implemented by our base class, so we're going to
    # remove them and redefine our own.
    #
    itk_option remove iwidgets::Scrolledwidget::width
    itk_option remove iwidgets::Scrolledwidget::height

    #
    # Create a clipping frame which will provide the border for
    # relief display.
    #
    itk_component add clipper {
	frame $itk_interior.clipper
    } {
	usual

	keep -borderwidth -relief -highlightthickness -highlightcolor
	rename -highlightbackground -background background Background
    }	
    grid $itk_component(clipper) -row 0 -column 0 -sticky nsew
    grid rowconfigure $_interior 0 -weight 1
    grid columnconfigure $_interior 0 -weight 1

    #
    # Create a text widget for displaying our hierarchy.
    #
    itk_component add list {
	text $itk_component(clipper).list -wrap none -cursor center_ptr \
                -state disabled -width 1 -height 1 \
	        -xscrollcommand \
		[code $this _scrollWidget $itk_interior.horizsb] \
		-yscrollcommand \
		[code $this _scrollWidget $itk_interior.vertsb] \
	        -borderwidth 0 -highlightthickness 0
    } {
	usual

	keep -spacing1 -spacing2 -spacing3 -tabs
	rename -font -textfont textFont Font
	rename -background -textbackground textBackground Background
	ignore -highlightthickness -highlightcolor
	ignore -insertbackground -insertborderwidth
	ignore -insertontime -insertofftime -insertwidth
	ignore -selectborderwidth
	ignore -borderwidth
    }
    grid $itk_component(list) -row 0 -column 0 -sticky nsew
    grid rowconfigure $itk_component(clipper) 0 -weight 1
    grid columnconfigure $itk_component(clipper) 0 -weight 1
    
    # 
    # Configure the command on the vertical scroll bar in the base class.
    #
    $itk_component(vertsb) configure \
	-command [code $itk_component(list) yview]

    #
    # Configure the command on the horizontal scroll bar in the base class.
    #
    $itk_component(horizsb) configure \
		-command [code $itk_component(list) xview]
    
    #
    # Configure our text component's tab settings for twenty levels.
    #
    set tabs ""
    for {set i 1} {$i < 20} {incr i} {
	lappend tabs [expr $i*12+4]
    }
    $itk_component(list) configure -tabs $tabs

    #
    # Add popup menus that can be configured by the user to add
    # new functionality.
    #
    itk_component add itemMenu {
	menu $itk_component(list).itemmenu -tearoff 0
    } {
	usual
	ignore -tearoff
	rename -cursor -menucursor menuCursor Cursor
    }

    itk_component add bgMenu {
	menu $itk_component(list).bgmenu -tearoff 0
    } {
	usual
	ignore -tearoff
	rename -cursor -menucursor menuCursor Cursor
    }

    #
    # Adjust the bind tags to remove the class bindings.  Also, add
    # bindings for mouse button 1 to do selection and button 3 to 
    # display a popup.
    #
    bindtags $itk_component(list) [list $itk_component(list) . all]
    
    bind $itk_component(list) <ButtonPress-1> \
            [code $this _select %x %y]

    bind $itk_component(list) <Double-1> \
            [code $this _double %x %y]

    bind $itk_component(list) <ButtonPress-3> \
            [code $this _post %x %y]
    
    #
    # Initialize the widget based on the command line options.
    #
    eval itk_initialize $args
}

# ------------------------------------------------------------------
#                           DESTRUCTOR
# ------------------------------------------------------------------
body iwidgets::Hierarchy::destructor {} {
    if {$_pending != ""} {
	after cancel $_pending
    }
}

# ------------------------------------------------------------------
#                             OPTIONS
# ------------------------------------------------------------------

# ------------------------------------------------------------------
# OPTION: -font
#
# Font used for text in the list.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::font {
    $itk_component(list) tag configure info \
            -font $itk_option(-font) -spacing1 6
}

# ------------------------------------------------------------------
# OPTION: -selectbackground
#
# Background color scheme for selected nodes.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::selectbackground {
    $itk_component(list) tag configure hilite \
            -background $itk_option(-selectbackground)
}

# ------------------------------------------------------------------
# OPTION: -selectforeground
#
# Foreground color scheme for selected nodes.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::selectforeground {
    $itk_component(list) tag configure hilite \
            -foreground $itk_option(-selectforeground)
}

# ------------------------------------------------------------------
# OPTION: -markbackground
#
# Background color scheme for marked nodes.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::markbackground {
    $itk_component(list) tag configure lowlite \
            -background $itk_option(-markbackground)
}

# ------------------------------------------------------------------
# OPTION: -markforeground
#
# Foreground color scheme for marked nodes.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::markforeground {
    $itk_component(list) tag configure lowlite \
            -foreground $itk_option(-markforeground)
}

# ------------------------------------------------------------------
# OPTION: -querycommand
#
# Command executed to query the contents of each node.  If this 
# command contains "%n", it is replaced with the name of the desired 
# node.  In its simpilest form it should return the children of the 
# given node as a list which will be depicted in the display.
#
# Since the names of the children are used as tags in the underlying 
# text widget, each child must be unique in the hierarchy.  Due to
# the unique requirement, the nodes shall be reffered to as uids 
# or uid in the singular sense.
# 
#   {uid [uid ...]}
#
#   where uid is a unique id and primary key for the hierarchy entry
#
# Should the unique requirement pose a problem, the list returned
# can take on another more extended form which enables the 
# association of text to be displayed with the uids.  The uid must
# still be unique, but the text does not have to obey the unique
# rule.  In addition, the format also allows the specification of
# additional tags to be used on the same entry in the hierarchy
# as the uid and additional icons to be displayed just before
# the node.  The tags and icons are considered to be the property of
# the user in that the hierarchy widget will not depend on any of 
# their values.
#
#   {{uid [text [tags [icons]]]} {uid [text [tags [icons]]]} ...}
#
#   where uid is a unique id and primary key for the hierarchy entry
#         text is the text to be displayed for this uid
#         tags is a list of user tags to be applied to the entry
#         icons is a list of icons to be displayed in front of the text
#
# The hierarchy widget does a look ahead from each node to determine
# if the node has a children.  This can be cost some performace with
# large hierarchies.  User's can avoid this by providing a hint in
# the user tags.  A tag of "leaf" or "branch" tells the hierarchy
# widget the information it needs to know thereby avoiding the look
# ahead operation.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::querycommand {
    clear
    draw -eventually
}

# ------------------------------------------------------------------
# OPTION: -selectcommand
#
# Command executed to select an item in the list.  If this command
# contains "%n", it is replaced with the name of the selected node.  
# If it contains a "%s", it is replaced with a boolean indicator of 
# the node's current selection status, where a value of 1 denotes
# that the node is currently selected and 0 that it is not.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::selectcommand {
}

# ------------------------------------------------------------------
# OPTION: -dblclickcommand
#
# Command executed to double click an item in the list.  If this command
# contains "%n", it is replaced with the name of the selected node.  
# If it contains a "%s", it is replaced with a boolean indicator of 
# the node's current selection status, where a value of 1 denotes
# that the node is currently selected and 0 that it is not.
#
# Douglas R. Howard, Jr.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::dblclickcommand {
}

# ------------------------------------------------------------------
# OPTION: -iconcommand
#
# Command executed upon selection of user icons.  If this command 
# contains "%n", it is replaced with the name of the node the icon
# belongs to.  Should it contain "%i" then the icon name is 
# substituted.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::iconcommand {
}

# ------------------------------------------------------------------
# OPTION: -icondblcommand
#
# Command executed upon double selection of user icons.  If this command 
# contains "%n", it is replaced with the name of the node the icon
# belongs to.  Should it contain "%i" then the icon name is 
# substituted.
#
# Douglas R. Howard, Jr.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::icondblcommand {
}

# ------------------------------------------------------------------
# OPTION: -imagecommand
#
# Command executed upon selection of image icons.  If this command 
# contains "%n", it is replaced with the name of the node the icon
# belongs to.  Should it contain "%i" then the icon name is 
# substituted.
#
# Douglas R. Howard, Jr.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::imagecommand {
}

# ------------------------------------------------------------------
# OPTION: -imagedblcommand
#
# Command executed upon double selection of user icons.  If this command 
# contains "%n", it is replaced with the name of the node the icon
# belongs to.
#
# Douglas R. Howard, Jr.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::imagedblcommand {
}

# ------------------------------------------------------------------
# OPTION: -alwaysquery
#
# Boolean flag which tells the hierarchy widget weather or not
# each refresh of the display should be via a new query using
# the -querycommand option or use the values previous found the
# last time the query was made.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::alwaysquery {
}

# ------------------------------------------------------------------
# OPTION: -filter
#
# When true only the branch nodes and selected items are displayed.
# This gives a compact view of important items.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::filter {
    switch -- $itk_option(-filter) {
	1 - true - yes - on {
	    set newCode {set display [info exists _selected($child)]}
	}
	0 - false - no - off {
	    set newCode {set display 1}
	}
	default {
	    error "bad filter option \"$itk_option(-filter)\":\
                   should be boolean"
	}
    }
    if {$newCode != $_filterCode} {
	set _filterCode $newCode
	draw -eventually
    }
}

# ------------------------------------------------------------------
# OPTION: -expanded
#
# When true, the hierarchy will be completely expanded when it
# is first displayed.  A fresh display can be triggered by
# resetting the -querycommand option.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::expanded {
    switch -- $itk_option(-expanded) {
	1 - true - yes - on {
	    ;# okay
	}
	0 - false - no - off {
	    ;# okay
	}
	default {
	    error "bad expanded option \"$itk_option(-expanded)\":\
                   should be boolean"
	}
    }
}
    
# ------------------------------------------------------------------
# OPTION: -openicon
#
# Specifies the open icon image to be used in the hierarchy.  Should
# one not be provided, then one will be generated, pixmap if 
# possible, bitmap otherwise.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::openicon {
    if {$itk_option(-openicon) == {}} {
	if {[lsearch [image names] openFolder] == -1} {
	    if {[lsearch [image types] pixmap] != -1} {
		image create pixmap openFolder -data {
		    /* XPM */
		    static char * dir_opened [] = {
			"16 16 4 1",
			/* colors */
			". c grey85 m white g4 grey90",
			"b c black  m black g4 black",
			"y c yellow m white g4 grey80",
			"g c grey70 m white g4 grey70",
			/* pixels */
			"................",
			"................",
			"................",
			"..bbbb..........",
			".bggggb.........",
			"bggggggbbbbbbb..",
			"bggggggggggggb..",
			"bgbbbbbbbbbbbbbb",
			"bgbyyyyyyyyyyybb",
			"bbyyyyyyyyyyyyb.",
			"bbyyyyyyyyyyybb.",
			"byyyyyyyyyyyyb..",
			"bbbbbbbbbbbbbb..",
			"................",
			"................",
			"................"};
		}
	    } else {
		image create bitmap openFolder -data {
		    #define open_width 16
		    #define open_height 16
		    static char open_bits[] = {
			0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x42, 0x00, 
			0x81, 0x3f, 0x01, 0x20, 0xf9, 0xff, 0x0d, 0xc0, 
			0x07, 0x40, 0x03, 0x60, 0x01, 0x20, 0x01, 0x30,
			0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
		}
	    }
	}
	set itk_option(-openicon) openFolder
    } else {
	if {[lsearch [image names] $itk_option(-openicon)] == -1} {
	    error "bad openicon option \"$itk_option(-openicon)\":\
                   should be an existing image"
	}
    }
}

# ------------------------------------------------------------------
# OPTION: -closedicon
#
# Specifies the closed icon image to be used in the hierarchy.  
# Should one not be provided, then one will be generated, pixmap if 
# possible, bitmap otherwise.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::closedicon {
    if {$itk_option(-closedicon) == {}} {
	if {[lsearch [image names] closedFolder] == -1} {
	    if {[lsearch [image types] pixmap] != -1} {
		image create pixmap closedFolder -data {
		    /* XPM */
		    static char *dir_closed[] = {
			"16 16 3 1",
			". c grey85 m white g4 grey90",
			"b c black  m black g4 black",
			"y c yellow m white g4 grey80",
			"................",
			"................",
			"................",
			"..bbbb..........",
			".byyyyb.........",
			"bbbbbbbbbbbbbb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"bbbbbbbbbbbbbb..",
			"................",
			"................",
			"................"};	
		}
	    } else {
		image create bitmap closedFolder -data {
		    #define closed_width 16
		    #define closed_height 16
		    static char closed_bits[] = {
			0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x84, 0x00, 
			0xfe, 0x7f, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 
			0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40,
			0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
		}
	    }
	}
	set itk_option(-closedicon) closedFolder
    } else {
	if {[lsearch [image names] $itk_option(-closedicon)] == -1} {
	    error "bad closedicon option \"$itk_option(-closedicon)\":\
                   should be an existing image"
	}
    }
}

# ------------------------------------------------------------------
# OPTION: -nodeicon
#
# Specifies the node icon image to be used in the hierarchy.  Should 
# one not be provided, then one will be generated, pixmap if 
# possible, bitmap otherwise.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::nodeicon {
    if {$itk_option(-nodeicon) == {}} {
	if {[lsearch [image names] nodeFolder] == -1} {
	    if {[lsearch [image types] pixmap] != -1} {
		image create pixmap nodeFolder -data {
		    /* XPM */
		    static char *dir_node[] = {
			"16 16 3 1",
			". c grey85 m white g4 grey90",
			"b c black  m black g4 black",
			"y c yellow m white g4 grey80",
			"................",
			"................",
			"................",
			"...bbbbbbbbbbb..",
			"..bybyyyyyyyyb..",
			".byybyyyyyyyyb..",
			"byyybyyyyyyyyb..",
			"bbbbbyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"byyyyyyyyyyyyb..",
			"bbbbbbbbbbbbbb..",
			"................",
			"................",
			"................"};	
		}
	    } else {
		image create bitmap nodeFolder -data {
		    #define node_width 16
		    #define node_height 16
		    static char node_bits[] = {
			0x00, 0x00, 0x00, 0x00, 0xe0, 0x7f, 0x50, 0x40, 
			0x48, 0x40, 0x44, 0x40, 0x42, 0x40, 0x7e, 0x40, 
			0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40,
			0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
		}
	    }
	}
	set itk_option(-nodeicon) nodeFolder
    } else {
	if {[lsearch [image names] $itk_option(-nodeicon)] == -1} {
	    error "bad nodeicon option \"$itk_option(-nodeicon)\":\
                   should be an existing image"
	}
    }
}

# ------------------------------------------------------------------
# OPTION: -width
#
# Specifies the width of the hierarchy widget as an entire unit.
# The value may be specified in any of the forms acceptable to 
# Tk_GetPixels.  Any additional space needed to display the other
# components such as labels, margins, and scrollbars force the text
# to be compressed.  A value of zero along with the same value for 
# the height causes the value given for the visibleitems option 
# to be applied which administers geometry constraints in a different
# manner.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::width {
    if {$itk_option(-width) != 0} {
	set shell [lindex [grid info $itk_component(clipper)] 1]

	#
	# Due to a bug in the tk4.2 grid, we have to check the 
	# propagation before setting it.  Setting it to the same
	# value it already is will cause it to toggle.
	#
	if {[grid propagate $shell]} {
	    grid propagate $shell no
	}
	
	$itk_component(list) configure -width 1
	$shell configure \
		-width [winfo pixels $shell $itk_option(-width)] 
    } else {
	configure -visibleitems $itk_option(-visibleitems)
    }
}

# ------------------------------------------------------------------
# OPTION: -height
#
# Specifies the height of the hierarchy widget as an entire unit.
# The value may be specified in any of the forms acceptable to 
# Tk_GetPixels.  Any additional space needed to display the other
# components such as labels, margins, and scrollbars force the text
# to be compressed.  A value of zero along with the same value for 
# the width causes the value given for the visibleitems option 
# to be applied which administers geometry constraints in a different
# manner.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::height {
    if {$itk_option(-height) != 0} {
	set shell [lindex [grid info $itk_component(clipper)] 1]

	#
	# Due to a bug in the tk4.2 grid, we have to check the 
	# propagation before setting it.  Setting it to the same
	# value it already is will cause it to toggle.
	#
	if {[grid propagate $shell]} {
	    grid propagate $shell no
	}
	
	$itk_component(list) configure -height 1
	$shell configure \
		-height [winfo pixels $shell $itk_option(-height)] 
    } else {
	configure -visibleitems $itk_option(-visibleitems)
    }
}

# ------------------------------------------------------------------
# OPTION: -visibleitems
#
# Specified the widthxheight in characters and lines for the text.
# This option is only administered if the width and height options
# are both set to zero, otherwise they take precedence.  With the
# visibleitems option engaged, geometry constraints are maintained
# only on the text.  The size of the other components such as 
# labels, margins, and scroll bars, are additive and independent, 
# effecting the overall size of the scrolled text.  In contrast,
# should the width and height options have non zero values, they
# are applied to the scrolled text as a whole.  The text is 
# compressed or expanded to maintain the geometry constraints.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::visibleitems {
    if {[regexp {^[0-9]+x[0-9]+$} $itk_option(-visibleitems)]} {
	if {($itk_option(-width) == 0) && \
		($itk_option(-height) == 0)} {
	    set chars [lindex [split $itk_option(-visibleitems) x] 0]
	    set lines [lindex [split $itk_option(-visibleitems) x] 1]
	    
	    set shell [lindex [grid info $itk_component(clipper)] 1]

	    #
	    # Due to a bug in the tk4.2 grid, we have to check the 
	    # propagation before setting it.  Setting it to the same
	    # value it already is will cause it to toggle.
	    #
	    if {! [grid propagate $shell]} {
		grid propagate $shell yes
	    }
	    
	    $itk_component(list) configure -width $chars -height $lines
	}
	
    } else {
	error "bad visibleitems option\
		\"$itk_option(-visibleitems)\": should be\
		widthxheight"
    }
}

# ------------------------------------------------------------------
# OPTION: -textmenuloadcommand
#
# Dynamically loads the popup menu based on what was selected.
#
# Douglas R. Howard, Jr.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::textmenuloadcommand {}

# ------------------------------------------------------------------
# OPTION: -imagemenuloadcommand
#
# Dynamically loads the popup menu based on what was selected.
#
# Douglas R. Howard, Jr.
# ------------------------------------------------------------------
configbody iwidgets::Hierarchy::imagemenuloadcommand {}


# ------------------------------------------------------------------
#                         PUBLIC METHODS
# ------------------------------------------------------------------

# ----------------------------------------------------------------------
# PUBLIC METHOD: clear
#
# Removes all items from the display including all tags and icons.  
# The display will remain empty until the -filter or -querycommand 
# options are set.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::clear {} {
    $itk_component(list) configure -state normal -cursor watch
    $itk_component(list) delete 1.0 end
    $itk_component(list) configure -state disabled -cursor $itk_option(-cursor)
    
    catch {unset _nodes}
    catch {unset _text}
    catch {unset _tags}
    catch {unset _icons}
    catch {unset _states}
    catch {unset _images}
    catch {unset _indents}

    return
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: selection option ?uid uid...?
#
# Handles all operations controlling selections in the hierarchy.
# Selections may be cleared, added, removed, or queried.  The add and
# remove options accept a series of unique ids.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::selection {op args} {
    switch -- $op {
        clear {
            $itk_component(list) tag remove hilite 1.0 end
            catch {unset _selected}
	    return
        }
        add {
            foreach node $args {
                set _selected($node) 1
                catch {
                    $itk_component(list) tag add hilite \
			    "$node.first" "$node.last"
                }
            }
        }
        remove {
            foreach node $args {
                catch {
                    unset _selected($node)
                    $itk_component(list) tag remove hilite \
			    "$node.first" "$node.last"
                }
            }
        }
	get {
	    return [array names _selected]
	}
        default {
            error "bad selection operation \"$op\":\
                   should be add, remove, clear or get"
        }
    }
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: mark option ?arg arg...?
#
# Handles all operations controlling marks in the hierarchy.  Marks may 
# be cleared, added, removed, or queried.  The add and remove options 
# accept a series of unique ids.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::mark {op args} {
    switch -- $op {
        clear {
            $itk_component(list) tag remove lowlite 1.0 end
            catch {unset _marked}
	    return
        }
        add {
            foreach node $args {
                set _marked($node) 1
                catch {
                    $itk_component(list) tag add lowlite \
			    "$node.first" "$node.last"
                }
            }
        }
        remove {
            foreach node $args {
                catch {
                    unset _marked($node)
                    $itk_component(list) tag remove lowlite \
			    "$node.first" "$node.last"
                }
            }
        }
	get {
	    return [array names _marked]
	}
        default {
            error "bad mark operation \"$op\":\
                   should be add, remove, clear or get"
        }
    }
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: current
#
# Returns the node that was most recently selected by the right mouse
# button when the item menu was posted.  Usually used by the code
# in the item menu to figure out what item is being manipulated.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::current {} {
    return $_posted
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: expand node
#
# Expands the hierarchy beneath the specified node.  Since this can take
# a moment for large hierarchies, the cursor will be changed to a watch
# during the expansion.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::expand {node} {
    if {! [info exists _states($node)]} {
	error "bad expand node argument: \"$node\", the node doesn't exist"
    }

    if {!$_states($node) && \
	    (([lsearch $_tags($node) branch] != -1) || \
	     ([llength [_contents $node]] > 0))} {
        $itk_component(list) configure -state normal -cursor watch
        update

	#
	# Get the indentation level for the node.
	#
        set indent $_indents($node)

        set _markers ""
        $itk_component(list) mark set insert "$node:start"
        _drawLevel $node $indent

	#
	# Following the draw, all our markers need adjusting.
	#
        foreach {name index} $_markers {
            $itk_component(list) mark set $name $index
        }

	#
	# Set the image to be the open icon, denote the new state,
	# and set the cursor back to normal along with the state.
	#
	$_images($node) configure -image $itk_option(-openicon)

        set _states($node) 1

        $itk_component(list) configure -state disabled \
		-cursor $itk_option(-cursor)
    }
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: collapse node
#
# Collapses the hierarchy beneath the specified node.  Since this can 
# take a moment for large hierarchies, the cursor will be changed to a 
# watch during the expansion.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::collapse {node} {
    if {! [info exists _states($node)]} {
	error "bad collapse node argument: \"$node\", the node doesn't exist"
    }

    if {[info exists _states($node)] && $_states($node) && \
	    (([lsearch $_tags($node) branch] != -1) || \
	     ([llength [_contents $node]] > 0))} {
        $itk_component(list) configure -state normal -cursor watch
	update

	_deselectSubNodes $node

        $itk_component(list) delete "$node:start" "$node:end"

	catch {$_images($node) configure -image $itk_option(-closedicon)}

        set _states($node) 0

        $itk_component(list) configure -state disabled \
	    -cursor $itk_option(-cursor)
    }
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: toggle node
#
# Toggles the hierarchy beneath the specified node.  If the hierarchy
# is currently expanded, then it is collapsed, and vice-versa.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::toggle {node} {
    if {! [info exists _states($node)]} {
	error "bad toggle node argument: \"$node\", the node doesn't exist"
    }

    if {$_states($node)} {
        collapse $node
    } else {
        expand $node
    }
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: prune node
#
# Removes a particular node from the hierarchy.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::prune {node} {
    #
    # While we're working, change the state and cursor so we can
    # edit the text and give a busy visual clue.
    #
    $itk_component(list) configure -state normal -cursor watch

    #
    # Recursively delete all the subnode information from our internal
    # arrays and remove all the tags.  
    #
    _deleteNodeInfo $node

    #
    # If the mark $node:end exists then the node has decendents so
    # so we'll remove from the mark $node:start to $node:end in order 
    # to delete all the subnodes below it in the text.  
    # 
    if {[lsearch [$itk_component(list) mark names] $node:end] != -1} {
	$itk_component(list) delete $node:start $node:end
	$itk_component(list) mark unset $node:end
    } 

    #
    # Next we need to remove the node itself.  Using the ranges for
    # its tag we'll remove it from line start to the end plus one
    # character which takes us to the start of the next node.
    #
    foreach {start end} [$itk_component(list) tag ranges $node] {
	$itk_component(list) delete "$start linestart" "$end + 1 char"
    }

    #
    # Delete the tag for this node.
    #
    $itk_component(list) tag delete $node

    #
    # The node must be removed from the list of subnodes for its parent.
    # We don't really have a clean way to do upwards referencing, so
    # the dirty way will have to do.  We'll cycle through each node
    # and if this node is in its list of subnodes, we'll remove it.
    #
    foreach uid [array names _nodes] {
	if {[set index [lsearch $_nodes($uid) $node]] != -1} {
	    set _nodes($uid) [lreplace $_nodes($uid) $index $index]
	}
    }

    #
    # We're done, so change the state and cursor back to their 
    # original values.
    #
    $itk_component(list) configure -state disabled -cursor $itk_option(-cursor)
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: draw ?when?
#
# Performs a complete draw of the entire hierarchy.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::draw {{when -now}} {
    if {$when == "-eventually"} {
        if {$_pending == ""} {
            set _pending [after idle [code $this draw -now]]
        }
        return
    } elseif {$when != "-now"} {
        error "bad when option \"$when\": should be -eventually or -now"
    }
    $itk_component(list) configure -state normal -cursor watch
    update

    $itk_component(list) delete 1.0 end
    catch {unset _images}
    set _markers ""

    _drawLevel "" ""

    foreach {name index} $_markers {
        $itk_component(list) mark set $name $index
    }

    $itk_component(list) configure -state disabled -cursor $itk_option(-cursor)
    set _pending ""
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: refresh node
#
# Performs a redraw of a specific node.  If that node is currently 
# not visible, then no action is taken.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::refresh {node} {
    if {! [info exists _nodes($node)]} {
	error "bad refresh node argument: \"$node\", the node doesn't exist"
    }

    
    if {! $_states($node)} {return}

    foreach parent [_getHeritage $node] {
	if {! $_states($parent)} {return}
    }

    $itk_component(list) configure -state normal -cursor watch
    $itk_component(list) delete $node:start $node:end

    set _markers ""
    $itk_component(list) mark set insert "$node:start"
    set indent $_indents($node)

    _drawLevel $node $indent

    foreach {name index} $_markers {
        $itk_component(list) mark set $name $index
    }

    $itk_component(list) configure -state disabled -cursor $itk_option(-cursor)
}

# ------------------------------------------------------------------
# THIN WRAPPED TEXT METHODS:
#
# The following methods are thin wraps of standard text methods.
# Consult the Tk text man pages for functionallity and argument
# documentation.
# ------------------------------------------------------------------

# ------------------------------------------------------------------
# PUBLIC METHOD: bbox index
#
# Returns four element list describing the bounding box for the list
# item at index
# ------------------------------------------------------------------
body iwidgets::Hierarchy::bbox {index} {
    return [$itk_component(list) bbox $index]
}

# ------------------------------------------------------------------
# PUBLIC METHOD compare index1 op index2
#
# Compare indices according to relational operator.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::compare {index1 op index2} {
    return [$itk_component(list) compare $index1 $op $index2]
}

# ------------------------------------------------------------------
# PUBLIC METHOD delete first ?last?
#
# Delete a range of characters from the text.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::delete {first {last {}}} {
    $itk_component(list) configure -state normal -cursor watch
    $itk_component(list) delete $first $last
    $itk_component(list) configure -state disabled -cursor $itk_option(-cursor)
}

# ------------------------------------------------------------------
# PUBLIC METHOD dump ?switches? index1 ?index2?
#
# Returns information about the contents of the text widget from 
# index1 to index2.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::dump {args} {
    return [eval $itk_component(list) dump $args]
}

# ------------------------------------------------------------------
# PUBLIC METHOD dlineinfo index
#
# Returns a five element list describing the area occupied by the
# display line containing index.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::dlineinfo {index} {
    return [$itk_component(list) dlineinfo $index]
}

# ------------------------------------------------------------------
# PUBLIC METHOD get index1 ?index2?
#
# Return text from start index to end index.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::get {index1 {index2 {}}} {
    return [$itk_component(list) get $index1 $index2]
}

# ------------------------------------------------------------------
# PUBLIC METHOD index index
#
# Return position corresponding to index.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::index {index} {
    return [$itk_component(list) index $index]
}

# ------------------------------------------------------------------
# PUBLIC METHOD insert index chars ?tagList?
#
# Insert text at index.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::insert {args} {
    $itk_component(list) configure -state normal -cursor watch
    eval $itk_component(list) insert $args
    $itk_component(list) configure -state disabled -cursor $itk_option(-cursor)
}

# ------------------------------------------------------------------
# PUBLIC METHOD scan option args
#
# Implements scanning on texts.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::scan {option args} {
    eval $itk_component(list) scan $option $args
}

# ------------------------------------------------------------------
# PUBLIC METHOD search ?switches? pattern index ?varName?
#
# Searches the text for characters matching a pattern.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::search {args} {
    return [eval $itk_component(list) search $args]
}

# ------------------------------------------------------------------
# PUBLIC METHOD see index
#
# Adjusts the view in the window so the character at index is 
# visible.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::see {index} {
    $itk_component(list) see $index
}

# ------------------------------------------------------------------
# PUBLIC METHOD tag option ?arg arg ...?
#
# Manipulate tags dependent on options.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::tag {op args} {
    return [eval $itk_component(list) tag $op $args]
}

# ------------------------------------------------------------------
# PUBLIC METHOD window option ?arg arg ...?
#
# Manipulate embedded windows.
# ------------------------------------------------------------------
body iwidgets::Hierarchy::window {option args} {
    return [eval $itk_component(list) window $option $args]
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: xview args
#
# Thin wrap of the text widget's xview command.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::xview {args} {
    return [eval itk_component(list) xview $args]
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: yview args
#
# Thin wrap of the text widget's yview command.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::yview {args} {
    return [eval $itk_component(list) yview $args]
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: expanded node
#
# Tells if a node is expanded or collapsed
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::expanded {node} {
    if {! [info exists _states($node)]} {
	error "bad collapse node argument: \"$node\", the node doesn't exist"
    }
    
    return $_states($node)
}

# ----------------------------------------------------------------------
# PUBLIC METHOD: expState
#
# Returns a list of all expanded nodes
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::expState {} {
    set nodes [_contents ""]
    set open ""
    set i 0
    while {1} {
	if {[info exists _states([lindex $nodes $i])] &&
	$_states([lindex $nodes $i])} {
	    lappend open [lindex $nodes $i]
	    foreach child [_contents [lindex $nodes $i]] {
		lappend nodes $child
	    }
	}
	incr i
	if {$i >= [llength $nodes]} {break}
    }
    
    return $open
}

# ------------------------------------------------------------------
#                       PROTECTED METHODS
# ------------------------------------------------------------------

# ----------------------------------------------------------------------
# PROTECTED METHOD: _drawLevel node indent
#
# Used internally by draw to draw one level of the hierarchy.
# Draws all of the nodes under node, using the indent string to
# indent nodes.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_drawLevel {node indent} {
    lappend _markers "$node:start" [$itk_component(list) index insert]
    set bg [$itk_component(list) cget -background]

    #
    # Obtain the list of subnodes for this node and cycle through
    # each one displaying it in the hierarchy.
    #
    foreach child [_contents $node] {
	set _images($child) "$itk_component(list).hicon[incr _hcounter]"

        if {![info exists _states($child)]} {
            set _states($child) $itk_option(-expanded)
        }

	#
	# Check the user tags to see if they have been kind enough
	# to tell us ahead of time what type of node we are dealing
	# with branch or leaf.  If they neglected to do so, then
	# get the contents of the child node to see if it has children
	# itself.
	#
	set display 0

	if {[lsearch $_tags($child) leaf] != -1} {
	    set type leaf
	} elseif {[lsearch $_tags($child) branch] != -1} {
	    set type branch
	} else {
	    if {[llength [_contents $child]] == 0} {
		set type leaf
	    } else {
		set type branch
	    }
	}

	#
	# Now that we know the type of node, branch or leaf, we know
	# the type of icon to use.
	#
	if {$type == "leaf"} {
            set icon $itk_option(-nodeicon)
            eval $_filterCode
	} else {
            if {$_states($child)} {
                set icon $itk_option(-openicon)
            } else {
                set icon $itk_option(-closedicon)
            }
            set display 1
	}

	#
	# If display is set then we're going to be drawing this node.
	# Save off the indentation level for this node and do the indent.
	#
	if {$display} {
	    set _indents($child) "$indent\t"
	    $itk_component(list) insert insert $indent

	    #
	    # Add the branch or leaf icon and setup a binding to toggle
	    # its expanded/collapsed state.
	    #
	    label $_images($child) -image $icon -background $bg 
	    # DRH - enhanced and added features that handle image clicking,
	    # double clicking, and right clicking behavior
	    bind $_images($child) <ButtonPress-1> \
	      "[code $this toggle $child]; [code $this _imageSelect $child]"
	    bind $_images($child) <Double-1> [code $this _imageDblClick $child]
	    bind $_images($child) <ButtonPress-3> \
	      [code $this _imagePost $child $_images($child) $type %x %y]
	    $itk_component(list) window create insert -window $_images($child)

	    #
	    # If any user icons exist then draw them as well.  The little
	    # regexp is just to check and see if they've passed in a
	    # command which needs to be evaluated as opposed to just
	    # a variable.  Also, attach a binding to call them if their
	    # icon is selected.
	    #
	    if {[info exists _icons($child)]} {
		foreach image $_icons($child) {
		    set wid "$itk_component(list).uicon[incr _ucounter]"

		    if {[regexp {\[.*\]} $image]} {
			eval label $wid -image $image -background $bg 
		    } else {
			label $wid -image $image -background $bg 
		    }

		    # DRH - this will bind events to the icons to allow
		    # clicking, double clicking, and right clicking actions.
		    bind $wid <ButtonPress-1> \
			    [code $this _iconSelect $child $image]
		    bind $wid <Double-1> \
			    [code $this _iconDblSelect $child $image]
		    bind $wid <ButtonPress-3> \
			    [code $this _imagePost $child $wid $type %x %y]
		    $itk_component(list) window create insert -window $wid
		}
	    }

	    #
	    # Create the list of tags to be applied to the text.  Start
	    # out with a tag of "info" and append "hilite" if the node
	    # is currently selected, finally add the tags given by the
	    # user.
	    #
	    set texttags [list "info" $child]

	    if {[info exists _selected($child)]} {
		lappend texttags hilite
	    } 

	    foreach tag $_tags($child) {
		lappend texttags $tag
	    }

	    #
	    # Insert the text for the node along with the tags and 
	    # append to the markers the start of this node.  The text
	    # has been broken at newlines into a list.  We'll make sure
	    # that each line is at the same indentation position.
	    #
	    set firstline 1
	    foreach line $_text($child) {
		if {$firstline} {
		    $itk_component(list) insert insert " "
		} else {
		    $itk_component(list) insert insert "$indent\t"
		}

		$itk_component(list) insert insert $line $texttags "\n"
		set firstline 0
	    }

	    lappend _markers "$child:start" [$itk_component(list) index insert]

	    #
	    # If the state of the node is open, proceed to draw the next 
	    # node below it in the hierarchy.
	    #
	    if {$_states($child)} {
		_drawLevel $child "$indent\t"
	    }
	}
    }

    lappend _markers "$node:end" [$itk_component(list) index insert]
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _contents uid
#
# Used internally to get the contents of a particular node.  If this
# is the first time the node has been seen or the -alwaysquery
# option is set, the -querycommand code is executed to query the node 
# list, and the list is stored until the next time it is needed.
#
# The querycommand may return not only the list of subnodes for the 
# node but additional information on the tags and icons to be used.  
# The return value must be parsed based on the number of elements in 
# the list where the format is a list of lists:
#
# {{uid [text [tags [icons]]]} {uid [text [tags [icons]]]} ...}
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_contents {uid} {
    if {! $itk_option(-alwaysquery) && [info exists _nodes($uid)]} {
        return $_nodes($uid)
    }

    # 
    # Substitute any %n's for the node name whose children we're
    # interested in obtaining.
    #
    set cmd $itk_option(-querycommand)
    regsub -all {%n} $cmd [list $uid] cmd

    set nodeinfolist [uplevel \#0 $cmd]

    #
    # Cycle through the node information returned by the query
    # command determining if additional information such as text,
    # user tags, or user icons have been provided.  For text,
    # break it into a list at any newline characters.
    #
    set _nodes($uid) {}

    foreach nodeinfo $nodeinfolist {
	set subnodeuid [lindex $nodeinfo 0]
	lappend _nodes($uid) $subnodeuid

	set llen [llength $nodeinfo] 

	if {$llen == 0 || $llen > 4} {
	    error "invalid number of elements returned by query\
                       command for node: \"$uid\",\
                       should be uid \[text \[tags \[icons\]\]\]"
	}

	if {$llen == 1} {
	    set _text($subnodeuid) [split $subnodeuid \n]
	} 
	if {$llen > 1} {
	    set _text($subnodeuid) [split [lindex $nodeinfo 1] \n]
	}
	if {$llen > 2} {
	    set _tags($subnodeuid) [lindex $nodeinfo 2]
	} else {
	    set _tags($subnodeuid) unknown
	}
	if {$llen > 3} {
	    set _icons($subnodeuid) [lindex $nodeinfo 3]
	}
    }
		  
    #
    # Return the list of nodes.
    #
    return $_nodes($uid)
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _post x y
#
# Used internally to post the popup menu at the coordinate (x,y)
# relative to the widget.  If (x,y) is on an item, then the itemMenu
# component is posted.  Otherwise, the bgMenu is posted.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_post {x y} {
    set rx [expr [winfo rootx $itk_component(list)]+$x]
    set ry [expr [winfo rooty $itk_component(list)]+$y]

    set index [$itk_component(list) index @$x,$y]

    #
    # The posted variable will hold the list of tags which exist at
    # this x,y position that will be passed back to the user.  They
    # don't need to know about our internal tags, info, hilite, and
    # lowlite, so remove them from the list.
    # 
    set _posted {}

    foreach tag [$itk_component(list) tag names $index] {
        if {![_isInternalTag $tag]} {
            lappend _posted $tag
        }
    }

    #
    # If we have tags then do the popup at this position.
    #
    if {$_posted != {}} {
	# DRH - here is where the user's function for dynamic popup
	# menu loading is done, if the user has specified to do so with the
	# "-textmenuloadcommand"
	if {$itk_option(-textmenuloadcommand) != {}} {
	    eval $itk_option(-textmenuloadcommand)
	}
	tk_popup $itk_component(itemMenu) $rx $ry
    } else {
	tk_popup $itk_component(bgMenu) $rx $ry
    }
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _imagePost node image type x y
#
# Used internally to post the popup menu at the coordinate (x,y)
# relative to the widget.  If (x,y) is on an image, then the itemMenu
# component is posted.
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_imagePost {node image type x y} {
    set rx [expr [winfo rootx $image]+$x]
    set ry [expr [winfo rooty $image]+$y]

    #
    # The posted variable will hold the list of tags which exist at
    # this x,y position that will be passed back to the user.  They
    # don't need to know about our internal tags, info, hilite, and
    # lowlite, so remove them from the list.
    # 
    set _posted {}

    lappend _posted $node $type

    #
    # If we have tags then do the popup at this position.
    #
    if {$itk_option(-imagemenuloadcommand) != {}} {
	eval $itk_option(-imagemenuloadcommand)
    }
    tk_popup $itk_component(itemMenu) $rx $ry
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _select x y
#
# Used internally to select an item at the coordinate (x,y) relative 
# to the widget.  The command associated with the -selectcommand
# option is execute following % character substitutions.  If %n
# appears in the command, the selected node is substituted.  If %s
# appears, a boolean value representing the current selection state
# will be substituted.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_select {x y} {
    if {$itk_option(-selectcommand) != {}} {
	if {[set seltags [$itk_component(list) tag names @$x,$y]] != {}} {
	    foreach tag $seltags {
		if {![_isInternalTag $tag]} {
		    lappend node $tag
		}
	    }

	    if {[lsearch $seltags "hilite"] == -1} {
		set selectstatus 0
	    } else {
		set selectstatus 1
	    }

	    set cmd $itk_option(-selectcommand)
	    regsub -all {%n} $cmd [list $node] cmd
	    regsub -all {%s} $cmd [list $selectstatus] cmd

	    uplevel #0 $cmd
	}
    }

    return
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _double x y
#
# Used internally to double click an item at the coordinate (x,y) relative 
# to the widget.  The command associated with the -dblclickcommand
# option is execute following % character substitutions.  If %n
# appears in the command, the selected node is substituted.  If %s
# appears, a boolean value representing the current selection state
# will be substituted.
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_double {x y} {
    if {$itk_option(-dblclickcommand) != {}} {
	if {[set seltags [$itk_component(list) tag names @$x,$y]] != {}} {
	    foreach tag $seltags {
		if {![_isInternalTag $tag]} {
		    lappend node $tag
		}
	    }

	    if {[lsearch $seltags "hilite"] == -1} {
		set selectstatus 0
	    } else {
		set selectstatus 1
	    }

	    set cmd $itk_option(-dblclickcommand)
	    regsub -all {%n} $cmd [list $node] cmd
	    regsub -all {%s} $cmd [list $selectstatus] cmd

	    uplevel #0 $cmd
	}
    }

    return
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _iconSelect node icon
#
# Used internally to upon selection of user icons.  The -iconcommand
# is executed after substitution of the node for %n and icon for %i.
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_iconSelect {node icon} {
    set cmd $itk_option(-iconcommand)
    regsub -all {%n} $cmd [list $node] cmd
    regsub -all {%i} $cmd [list $icon] cmd

    uplevel \#0 $cmd

    return {}
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _iconDblSelect node icon
#
# Used internally to upon double selection of user icons.  The 
# -icondblcommand is executed after substitution of the node for %n and 
# icon for %i.
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_iconDblSelect {node icon} {
    if {$itk_option(-icondblcommand) != {}} {
	set cmd $itk_option(-icondblcommand)
	regsub -all {%n} $cmd [list $node] cmd
	regsub -all {%i} $cmd [list $icon] cmd
	
	uplevel \#0 $cmd
    }
    return {}
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _imageSelect node icon
#
# Used internally to upon selection of user icons.  The -imagecommand
# is executed after substitution of the node for %n.
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_imageSelect {node} {
    if {$itk_option(-imagecommand) != {}} {
	set cmd $itk_option(-imagecommand)
	regsub -all {%n} $cmd [list $node] cmd
	
	uplevel \#0 $cmd
    }
    return {}
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _imageDblClick node
#
# Used internally to upon double selection of images.  The 
# -imagedblcommand is executed.
#
# Douglas R. Howard, Jr.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_imageDblClick {node} {
    if {$itk_option(-imagedblcommand) != {}} {
	set cmd $itk_option(-imagedblcommand)
	regsub -all {%n} $cmd [list $node] cmd
	
	uplevel \#0 $cmd
    }
    return {}
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _deselectSubNodes uid
#
# Used internally to recursively deselect all the nodes beneath a 
# particular node.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_deselectSubNodes {uid} {
    foreach node $_nodes($uid) {
	if {[array names _selected $node] != {}} {
	    unset _selected($node)
	}
	
	if {[array names _nodes $node] != {}} {
	    _deselectSubNodes $node
	}
    }
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _deleteNodeInfo uid
#
# Used internally to recursively delete all the information about a
# node and its decendents.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_deleteNodeInfo {uid} {
    #
    # Recursively call ourseleves as we go down the hierarchy beneath
    # this node.
    #
    if {[info exists _nodes($uid)]} {
	foreach node $_nodes($uid) {
	    if {[array names _nodes $node] != {}} {
		_deleteNodeInfo $node
	    }
	}
    }

    #
    # Unset any entries in our arrays for the node.
    #
    catch {unset _nodes($uid)}
    catch {unset _text($uid)}
    catch {unset _tags($uid)}
    catch {unset _icons($uid)}
    catch {unset _states($uid)}
    catch {unset _images($uid)}
    catch {unset _indents($uid)}
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _getParent uid
#
# Used internally to determine the parent for a node.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_getParent {uid} {
    foreach node [array names _nodes] {
	if {[set index [lsearch $_nodes($node) $uid]] != -1} {
	    return $node
	}
    }
}

# ----------------------------------------------------------------------
# PROTECTED METHOD: _getHeritage uid
#
# Used internally to determine the list of parents for a node.
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_getHeritage {uid} {
    set parents {}

    if {[set parent [_getParent $uid]] != {}} {
	lappend parents $parent
    }

    return $parents
}

# ----------------------------------------------------------------------
# PROTECTED METHOD (could be proc?): _isInternalTag tag
#
# Used internally to tags not to used for user callback commands
# ----------------------------------------------------------------------
body iwidgets::Hierarchy::_isInternalTag {tag} {
   set ii [expr [lsearch -exact {info hilite lowlite unknown} $tag] != -1];
   return $ii;
}