File: tree_editor.py

package info (click to toggle)
python-traitsui 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 13,292 kB
  • sloc: python: 39,867; makefile: 120; sh: 5
file content (2028 lines) | stat: -rw-r--r-- 82,006 bytes parent folder | download
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
#------------------------------------------------------------------------------
#
#  Copyright (c) 2005, Enthought, Inc.
#  All rights reserved.
#
#  This software is provided without warranty under the terms of the BSD
#  license included in enthought/LICENSE.txt and may be redistributed only
#  under the conditions described in the aforementioned license.  The license
#  is also available online at http://www.enthought.com/licenses/BSD.txt
#
#  Thanks for using Enthought open source!
#
#  Author: David C. Morrill
#  Date:   12/03/2004
#
#------------------------------------------------------------------------------

""" Defines the tree editor for the wxPython user interface toolkit.
"""

#-------------------------------------------------------------------------------
#  Imports:
#-------------------------------------------------------------------------------

import os
import wx
import copy

try:
    from pyface.wx.drag_and_drop import PythonDropSource, \
                                                PythonDropTarget
except:
    PythonDropSource = PythonDropTarget = None

from pyface.resource_manager \
    import resource_manager

from pyface.image_list \
    import ImageList

from traits.api \
    import HasStrictTraits, Any, Str, Event, TraitError

from traits.trait_base \
    import enumerate

from traitsui.api \
    import View, TreeNode, ObjectTreeNode, MultiTreeNode, Image

# FIXME: ToolkitEditorFactory is a proxy class defined here just for backward
# compatibility. The class has been moved to the
# traitsui.editors.tree_editor file.
from traitsui.editors.tree_editor \
    import ToolkitEditorFactory

from traitsui.undo \
    import ListUndoItem

from traitsui.tree_node \
    import ITreeNodeAdapterBridge

from traitsui.tree_node \
    import ITreeNodeAdapterBridge

from traitsui.menu \
    import Menu, Action, Separator

from pyface.api \
    import ImageResource

from pyface.dock.api \
    import DockWindow, DockSizer, DockSection, DockRegion, DockControl

from constants \
    import OKColor

from editor \
    import Editor

from helper \
    import open_fbi, TraitsUIPanel, TraitsUIScrolledPanel

#-------------------------------------------------------------------------------
#  Global data:
#-------------------------------------------------------------------------------

# Paste buffer for copy/cut/paste operations
paste_buffer = None

#-------------------------------------------------------------------------------
#  The core tree node menu actions:
#-------------------------------------------------------------------------------

NewAction    = 'NewAction'
CopyAction   = Action( name         = 'Copy',
                       action       = 'editor._menu_copy_node',
                       enabled_when = 'editor._is_copyable(object)' )
CutAction    = Action( name         = 'Cut',
                       action       = 'editor._menu_cut_node',
                       enabled_when = 'editor._is_cutable(object)' )
PasteAction  = Action( name         = 'Paste',
                       action       = 'editor._menu_paste_node',
                       enabled_when = 'editor._is_pasteable(object)' )
DeleteAction = Action( name         = 'Delete',
                       action       = 'editor._menu_delete_node',
                       enabled_when = 'editor._is_deletable(object)' )
RenameAction = Action( name         = 'Rename',
                       action       = 'editor._menu_rename_node',
                       enabled_when = 'editor._is_renameable(object)' )

#-------------------------------------------------------------------------------
#  'SimpleEditor' class:
#-------------------------------------------------------------------------------

class SimpleEditor ( Editor ):
    """ Simple style of tree editor.
    """

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Is the tree editor is scrollable? This value overrides the default.
    scrollable = True

    # Allows an external agent to set the tree selection
    selection = Event

    # The currently selected object
    selected = Any

    # The event fired when a tree node is activated by double clicking or
    # pressing the enter key on a node.
    activated = Event

    # The event fired when a tree node is clicked on:
    click = Event

    # The event fired when a tree node is double-clicked on:
    dclick = Event

    # The event fired when the application wants to veto an operation:
    veto = Event

    #-- Private Traits ---------------------------------------------------------

    # An icon used by a TreeNode:
    _icon = Image

    #---------------------------------------------------------------------------
    #  Finishes initializing the editor by creating the underlying toolkit
    #  widget:
    #---------------------------------------------------------------------------

    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        factory = self.factory
        style = self._get_style()

        if factory.editable:

            # Check to see if the tree view is based on a shared trait editor:
            if factory.shared_editor:
                factory_editor = factory.editor

                # If this is the editor that defines the trait editor panel:
                if factory_editor is None:

                    # Remember which editor has the trait editor in the factory:
                    factory._editor = self

                    # Create the trait editor panel:
                    self.control = TraitsUIPanel( parent, -1 )
                    self.control._node_ui = self.control._editor_nid = None

                    # Check to see if there are any existing editors that are
                    # waiting to be bound to the trait editor panel:
                    editors = factory._shared_editors
                    if editors is not None:
                        for editor in factory._shared_editors:

                            # If the editor is part of this UI:
                            if editor.ui is self.ui:

                                # Then bind it to the trait editor panel:
                                editor._editor = self.control

                        # Indicate all pending editors have been processed:
                        factory._shared_editors = None

                    # We only needed to build the trait editor panel, so exit:
                    return

                # Check to see if the matching trait editor panel has been
                # created yet:
                editor = factory_editor._editor
                if (editor is None) or (editor.ui is not self.ui):
                    # If not, add ourselves to the list of pending editors:
                    shared_editors = factory_editor._shared_editors
                    if shared_editors is None:
                        factory_editor._shared_editors = shared_editors = []
                    shared_editors.append( self )
                else:
                    # Otherwise, bind our trait editor panel to the shared one:
                    self._editor = editor.control

                # Finally, create only the tree control:
                self.control = self._tree = tree = wx.TreeCtrl( parent, -1,
                                                                style = style )
            else:
                # If editable, create a tree control and an editor panel:
                self._is_dock_window = True
                theme = factory.dock_theme or self.item.container.dock_theme
                self.control = splitter = DockWindow( parent,
                                                      theme = theme ).control
                self._tree   = tree     = wx.TreeCtrl( splitter, -1,
                                                       style = style )
                self._editor = editor   = TraitsUIScrolledPanel( splitter )
                editor.SetSizer( wx.BoxSizer( wx.VERTICAL ) )
                editor.SetScrollRate( 16, 16 )
                editor.SetMinSize( wx.Size( 100, 100 ) )

                self._editor._node_ui = self._editor._editor_nid = None
                item = self.item
                hierarchy_name = editor_name = ''
                style = 'fixed'
                name  = item.label
                if name != '':
                    hierarchy_name = name + ' Hierarchy'
                    editor_name    = name + ' Editor'
                    style          = item.dock

                splitter.SetSizer( DockSizer( contents =
                    DockSection( contents = [
                        DockRegion( contents = [
                            DockControl( name    = hierarchy_name,
                                         id      = 'tree',
                                         control = tree,
                                         style   = style ) ] ),
                        DockRegion( contents = [
                            DockControl( name    = editor_name,
                                         id      = 'editor',
                                         control = self._editor,
                                         style   = style ) ] ) ],
                        is_row = (factory.orientation == 'horizontal') ) ) )
        else:
            # Otherwise, just create the tree control:
            self.control = self._tree = tree = wx.TreeCtrl( parent, -1,
                                                            style = style )

        # Set up to show tree node icon (if requested):
        if factory.show_icons:
            self._image_list = ImageList( *factory.icon_size )
            tree.AssignImageList( self._image_list )

        # Set up the mapping between objects and tree id's:
        self._map = {}

        # Initialize the 'undo state' stack:
        self._undoable = []

        # Get the tree control id:
        tid = tree.GetId()

        # Set up the mouse event handlers:
        wx.EVT_LEFT_DOWN(  tree, self._on_left_down )
        wx.EVT_RIGHT_DOWN( tree, self._on_right_down )
        wx.EVT_LEFT_DCLICK(tree, self._on_left_dclick )

        # Set up the tree event handlers:
        wx.EVT_TREE_ITEM_EXPANDING(   tree, tid, self._on_tree_item_expanding )
        wx.EVT_TREE_ITEM_EXPANDED(    tree, tid, self._on_tree_item_expanded )
        wx.EVT_TREE_ITEM_COLLAPSING(  tree, tid, self._on_tree_item_collapsing )
        wx.EVT_TREE_ITEM_COLLAPSED(   tree, tid, self._on_tree_item_collapsed )
        wx.EVT_TREE_ITEM_ACTIVATED(   tree, tid, self._on_tree_item_activated )
        wx.EVT_TREE_SEL_CHANGED(      tree, tid, self._on_tree_sel_changed )
        wx.EVT_TREE_BEGIN_DRAG(       tree, tid, self._on_tree_begin_drag )
        wx.EVT_TREE_BEGIN_LABEL_EDIT( tree, tid, self._on_tree_begin_label_edit)
        wx.EVT_TREE_END_LABEL_EDIT(   tree, tid, self._on_tree_end_label_edit )
        wx.EVT_TREE_ITEM_GETTOOLTIP(  tree, tid, self._on_tree_item_gettooltip )

        # Set up general mouse events
        wx.EVT_MOTION(tree, self._on_hover)

        # Synchronize external object traits with the editor:
        self.sync_value( factory.selected, 'selected' )
        self.sync_value( factory.activated,'activated', 'to' )
        self.sync_value( factory.click,    'click',  'to' )
        self.sync_value( factory.dclick,   'dclick', 'to' )
        self.sync_value( factory.veto,     'veto',   'from' )

        # Set up the drag and drop target:
        if PythonDropTarget is not None:
            tree.SetDropTarget( PythonDropTarget( self ) )

    #---------------------------------------------------------------------------
    #  Disposes of the contents of an editor:
    #---------------------------------------------------------------------------

    def dispose ( self ):
        """ Disposes of the contents of an editor.
        """
        tree = self._tree
        if tree is not None:
            id = tree.GetId()
            wx.EVT_LEFT_DOWN(             tree,     None )
            wx.EVT_RIGHT_DOWN(            tree,     None )
            wx.EVT_TREE_ITEM_EXPANDING(   tree, id, None )
            wx.EVT_TREE_ITEM_EXPANDED(    tree, id, None )
            wx.EVT_TREE_ITEM_COLLAPSING(  tree, id, None )
            wx.EVT_TREE_ITEM_COLLAPSED(   tree, id, None )
            wx.EVT_TREE_ITEM_ACTIVATED(   tree, id, None )
            wx.EVT_TREE_SEL_CHANGED(      tree, id, None )
            wx.EVT_TREE_BEGIN_DRAG(       tree, id, None )
            wx.EVT_TREE_BEGIN_LABEL_EDIT( tree, id, None )
            wx.EVT_TREE_END_LABEL_EDIT(   tree, id, None )
            wx.EVT_TREE_ITEM_GETTOOLTIP(  tree, id, None )

            nid = self._tree.GetRootItem()
            if nid.IsOk():
                self._delete_node( nid )

        super( SimpleEditor, self ).dispose()

    #---------------------------------------------------------------------------
    #  Handles the 'selection' trait being changed:
    #---------------------------------------------------------------------------

    def _selection_changed ( self, selection ):
        """ Handles the **selection** event.
        """
        try:
            self._tree.SelectItem( self._object_info( selection )[2] )
        except:
            pass

    #---------------------------------------------------------------------------
    #  Handles the 'selected' trait being changed:
    #---------------------------------------------------------------------------

    def _selected_changed ( self, selected ):
        """ Handles the **selected** trait being changed.
        """
        if not self._no_update_selected:
            self._selection_changed( selected )

    #---------------------------------------------------------------------------
    #  Handles the 'veto' event being fired:
    #---------------------------------------------------------------------------

    def _veto_changed ( self ):
        """ Handles the 'veto' event being fired.
        """
        self._veto = True

    #---------------------------------------------------------------------------
    #  Returns the style settings used for displaying the wx tree:
    #---------------------------------------------------------------------------

    def _get_style ( self ):
        """ Returns the style settings used for displaying the wx tree.
        """
        factory = self.factory
        style   = wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS | wx.CLIP_CHILDREN

        # Turn lines off if explicit or for appearance on *nix:
        if ((factory.lines_mode == 'off') or
            ((factory.lines_mode == 'appearance') and (os.name == 'posix'))):
            style |= wx.TR_NO_LINES

        if factory.hide_root:
            style |= (wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT)

        if factory.selection_mode != 'single':
            style |= wx.TR_MULTIPLE | wx.TR_EXTENDED


        return style

    #---------------------------------------------------------------------------
    #  Handles the user entering input data in the edit control:
    #---------------------------------------------------------------------------

    def update_object ( self, event ):
        """ Handles the user entering input data in the edit control.
        """
        try:
            self.value = self._get_value()
            self.control.SetBackgroundColour( OKColor )
            self.control.Refresh()
        except TraitError, excp:
            pass

    #---------------------------------------------------------------------------
    #  Saves the current 'expanded' state of all tree nodes:
    #---------------------------------------------------------------------------

    def _save_state ( self ):
        tree  = self._tree
        nid   = tree.GetRootItem()
        state = {}
        if nid.IsOk():
            nodes_to_do = [ nid ]
            while nodes_to_do:
                node = nodes_to_do.pop()
                data = self._get_node_data( node )
                try:
                    is_expanded = tree.IsExpanded( node )
                except:
                    is_expanded = True
                state[ hash( data[-1] ) ] = ( data[0], is_expanded )
                for cnid in self._nodes( node ):
                    nodes_to_do.append( cnid )
        return state

    #---------------------------------------------------------------------------
    #  Restores the 'expanded' state of all tree nodes:
    #---------------------------------------------------------------------------

    def _restore_state ( self, state ):
        if not state:
            return
        tree = self._tree
        nid  = tree.GetRootItem()
        if nid.IsOk():
            nodes_to_do = [ nid ]
            while nodes_to_do:
                node = nodes_to_do.pop()
                for cnid in self._nodes( node ):
                    data = self._get_node_data( cnid )
                    key  = hash( data[-1] )
                    if key in state:
                        was_expanded, current_state = state[ key ]
                        if was_expanded:
                            self._expand_node( cnid )
                            if current_state:
                                tree.Expand( cnid )
                            nodes_to_do.append( cnid )

    #---------------------------------------------------------------------------
    #  Expands all nodes starting from the current selection:
    #---------------------------------------------------------------------------

    def expand_all ( self ):
        """ Expands all nodes, starting from the selected node.
        """
        tree = self._tree

        def _do_expand ( nid ):
            expanded, node, object = self._get_node_data( nid )
            if self._has_children( node, object ):
                tree.SetItemHasChildren( nid, True )
                self._expand_node( nid )
                tree.Expand( nid )

        nid = tree.GetSelection()
        if nid.IsOk():
            nodes_to_do = [ nid ]
            while nodes_to_do:
                node = nodes_to_do.pop()
                _do_expand( node )
                for n in self._nodes( node ):
                    _do_expand( n )
                    nodes_to_do.append( n )

    #---------------------------------------------------------------------------
    #  Expands from the specified node the specified number of sub-levels:
    #---------------------------------------------------------------------------

    def expand_levels ( self, nid, levels, expand = True ):
        """ Expands from the specified node the specified number of sub-levels.
        """
        if levels > 0:
            expanded, node, object = self._get_node_data( nid )
            if self._has_children( node, object ):
                self._tree.SetItemHasChildren( nid, True )
                self._expand_node( nid )
                if expand:
                    self._tree.Expand( nid )
                for cnid in self._nodes( nid ):
                    self.expand_levels( cnid, levels - 1 )

    #---------------------------------------------------------------------------
    #  Updates the editor when the object trait changes external to the editor:
    #---------------------------------------------------------------------------

    def update_editor ( self ):
        """ Updates the editor when the object trait changes externally to the
            editor.
        """
        tree        = self._tree
        saved_state = {}
        if tree is not None:
            nid = tree.GetRootItem()
            if nid.IsOk():
                self._delete_node( nid )
            object, node = self._node_for( self.value )
            if node is not None:
                icon = self._get_icon( node, object )
                self._root_nid = nid = tree.AddRoot( node.get_label( object ),
                                                     icon, icon )
                self._map[ id( object ) ] = [ ( node.get_children_id( object ),
                                                nid ) ]
                self._add_listeners( node, object )
                self._set_node_data( nid, ( False, node, object) )
                if self.factory.hide_root or self._has_children( node, object ):
                    tree.SetItemHasChildren( nid, True )
                    self._expand_node( nid )
                    if not self.factory.hide_root:
                        tree.Expand( nid )
                        tree.SelectItem( nid )
                        self._on_tree_sel_changed()

                self.expand_levels( nid, self.factory.auto_open, False )

                # It seems like in some cases, an explicit Refresh is needed to
                # trigger a screen update:
                tree.Refresh()

            # fixme: Clear the current editor (if any)...

    #---------------------------------------------------------------------------
    #  Returns the editor's control for indicating error status:
    #---------------------------------------------------------------------------

    def get_error_control ( self ):
        """ Returns the editor's control for indicating error status.
        """
        return self._tree

    #---------------------------------------------------------------------------
    #  Appends a new node to the specified node:
    #---------------------------------------------------------------------------

    def _append_node ( self, nid, node, object ):
        """ Appends a new node to the specified node.
        """
        return self._insert_node( nid, None, node, object )

    #---------------------------------------------------------------------------
    #  Inserts a new node before a specified index into the children of the
    #  specified node:
    #---------------------------------------------------------------------------

    def _insert_node ( self, nid, index, node, object ):
        """ Inserts a new node before a specified index into the children of the
            specified node.
        """
        tree  = self._tree
        icon  = self._get_icon( node, object )
        label = node.get_label( object )
        if index is None:
            cnid = tree.AppendItem( nid, label, icon, icon )
        else:
            cnid = tree.InsertItemBefore( nid, index, label, icon, icon )
        has_children = self._has_children( node, object )
        tree.SetItemHasChildren( cnid, has_children )
        self._set_node_data( cnid, ( False, node, object ) )
        self._map.setdefault( id( object ), [] ).append(
            ( node.get_children_id( object ), cnid ) )
        self._add_listeners( node, object )

        # Automatically expand the new node (if requested):
        if has_children and node.can_auto_open( object ):
            tree.Expand( cnid )

        # Return the newly created node:
        return cnid

    #---------------------------------------------------------------------------
    #  Deletes a specified tree node and all its children:
    #---------------------------------------------------------------------------

    def _delete_node ( self, nid ):
        """ Deletes a specified tree node and all of its children.
        """
        for cnid in self._nodes_for( nid ):
            self._delete_node( cnid )

        expanded, node, object = self._get_node_data( nid )
        id_object   = id( object )
        object_info = self._map[ id_object ]
        for i, info in enumerate( object_info ):
            if nid == info[1]:
                del object_info[i]
                break

        if len( object_info ) == 0:
            self._remove_listeners( node, object )
            del self._map[ id_object ]

        # We set the '_locked' flag here because wx seems to generate a
        # 'node selected' event when the node is deleted. This can lead to
        # some bad side effects. So the 'node selected' event handler exits
        # immediately if the '_locked' flag is set:
        self._locked = True
        self._tree.Delete( nid )
        self._locked = False

        # If the deleted node had an active editor panel showing, remove it:
        if (self._editor is not None) and (nid == self._editor._editor_nid):
            self._clear_editor()

    #---------------------------------------------------------------------------
    #  Expands the contents of a specified node (if required):
    #---------------------------------------------------------------------------

    def _expand_node ( self, nid ):
        """ Expands the contents of a specified node (if required).
        """
        expanded, node, object = self._get_node_data( nid )

        # Lazily populate the item's children:
        if not expanded:
            for child in node.get_children( object ):
                child, child_node = self._node_for( child )
                if child_node is not None:
                    self._append_node( nid, child_node, child )

            # Indicate the item is now populated:
            self._set_node_data( nid, ( True, node, object) )

    #---------------------------------------------------------------------------
    #  Returns each of the child nodes of a specified node id:
    #---------------------------------------------------------------------------

    def _nodes ( self, nid ):
        """ Returns each of the child nodes of a specified node.
        """
        tree         = self._tree
        cnid, cookie = tree.GetFirstChild( nid )
        while cnid.IsOk():
            yield cnid
            cnid, cookie = tree.GetNextChild( nid, cookie )

    def _nodes_for ( self, nid ):
        """ Returns all child node ids of a specified node id.
        """
        return [ cnid for cnid in self._nodes( nid ) ]

    #---------------------------------------------------------------------------
    #  Return the index of a specified node id within its parent:
    #---------------------------------------------------------------------------

    def _node_index ( self, nid ):
        pnid = self._tree.GetItemParent( nid )
        if not pnid.IsOk():
            return ( None, None, None )

        for i, cnid in enumerate( self._nodes( pnid ) ):
            if cnid == nid:
                ignore, pnode, pobject = self._get_node_data( pnid )

                return ( pnode, pobject, i )

    #---------------------------------------------------------------------------
    #  Returns whether a specified object has any children:
    #---------------------------------------------------------------------------

    def _has_children ( self, node, object ):
        """ Returns whether a specified object has any children.
        """
        return (node.allows_children( object ) and node.has_children( object ))

    #---------------------------------------------------------------------------
    #  Returns whether a given object is droppable on the node:
    #---------------------------------------------------------------------------

    def _is_droppable ( self, node, object, add_object, for_insert ):
        """ Returns whether a given object is droppable on the node.
        """
        if for_insert and (not node.can_insert( object )):
            return False

        return node.can_add( object, add_object )

    #---------------------------------------------------------------------------
    #  Returns a droppable version of a specified object:
    #---------------------------------------------------------------------------

    def _drop_object ( self, node, object, dropped_object, make_copy = True ):
        """ Returns a droppable version of a specified object.
        """
        new_object = node.drop_object( object, dropped_object )
        if (new_object is not dropped_object) or (not make_copy):
            return new_object

        return copy.deepcopy( new_object )

    #---------------------------------------------------------------------------
    #  Returns the icon index for the specified object:
    #---------------------------------------------------------------------------

    def _get_icon ( self, node, object, is_expanded = False ):
        """ Returns the index of the specified object icon.
        """
        if self._image_list is None:
            return -1

        icon_name = node.get_icon( object, is_expanded )
        if isinstance( icon_name, basestring ):
            if icon_name[:1] == '@':
                self._icon = icon_name
                icon_name  = self._icon
            else:
                if icon_name[:1] == '<':
                    icon_name = icon_name[1:-1]
                    path      = self
                else:
                    path = node.get_icon_path( object )
                    if isinstance( path, basestring ):
                        path = [ path, node ]
                    else:
                        path.append( node )

                reference = resource_manager.locate_image( icon_name, path )
                if reference is None:
                    return -1

                file_name = reference.filename

        # If it is an ImageResource, get its file name directly:
        if isinstance( icon_name, ImageResource ):
            file_name = icon_name

        return self._image_list.GetIndex( file_name )

    #---------------------------------------------------------------------------
    #  Adds the event listeners for a specified object:
    #---------------------------------------------------------------------------

    def _add_listeners ( self, node, object ):
        """ Adds the event listeners for a specified object.
        """
        if node.allows_children( object ):
            node.when_children_replaced( object, self._children_replaced, False)
            node.when_children_changed(  object, self._children_updated,  False)

        node.when_label_changed( object, self._label_updated, False )

    #---------------------------------------------------------------------------
    #  Removes any event listeners from a specified object:
    #---------------------------------------------------------------------------

    def _remove_listeners ( self, node, object ):
        """ Removes any event listeners from a specified object.
        """
        if node.allows_children( object ):
            node.when_children_replaced( object, self._children_replaced, True )
            node.when_children_changed(  object, self._children_updated,  True )

        node.when_label_changed( object, self._label_updated, True )

    #---------------------------------------------------------------------------
    #  Returns the tree node data for a specified object in the form
    #  ( expanded, node, nid ):
    #---------------------------------------------------------------------------

    def _object_info ( self, object, name = '' ):
        """ Returns the tree node data for a specified object in the form
            ( expanded, node, nid ).
        """
        info = self._map[ id( object ) ]
        for name2, nid in info:
            if name == name2:
                break
        else:
            nid = info[0][1]

        expanded, node, ignore = self._get_node_data( nid )

        return ( expanded, node, nid )

    def _object_info_for ( self, object, name = '' ):
        """ Returns the tree node data for a specified object as a list of the
            form: [ ( expanded, node, nid ), ... ].
        """
        result = []
        for name2, nid in self._map[ id( object ) ]:
            if name == name2:
                expanded, node, ignore = self._get_node_data( nid )
                result.append( ( expanded, node, nid ) )

        return result

    #---------------------------------------------------------------------------
    #  Returns the TreeNode associated with a specified object:
    #---------------------------------------------------------------------------

    def _node_for ( self, object ):
        """ Returns the TreeNode associated with a specified object.
        """
        if ((type( object ) is tuple) and (len( object ) == 2) and
            isinstance( object[1], TreeNode )):
            return object

        # Select all nodes which understand this object:
        factory = self.factory
        nodes   = [ node for node in factory.nodes
                    if object is not None and node.is_node_for( object ) ]

        # If only one found, we're done, return it:
        if len( nodes ) == 1:
            return ( object, nodes[0] )

        # If none found, try to create an adapted node for the object:
        if len( nodes ) == 0:
           return ( object, ITreeNodeAdapterBridge( adapter = object ) )

        # Use all selected nodes that have the same 'node_for' list as the
        # first selected node:
        base  = nodes[0].node_for
        nodes = [ node for node in nodes if base == node.node_for ]

        # If only one left, then return that node:
        if len( nodes ) == 1:
            return ( object, nodes[0] )

        # Otherwise, return a MultiTreeNode based on all selected nodes...

        # Use the node with no specified children as the root node. If not
        # found, just use the first selected node as the 'root node':
        root_node = None
        for i, node in enumerate( nodes ):
            if node.get_children_id( object ) == '':
                root_node = node
                del nodes[i]
                break
        else:
            root_node = nodes[0]

        # If we have a matching MultiTreeNode already cached, return it:
        key = ( root_node, ) + tuple( nodes )
        if key in factory.multi_nodes:
            return ( object, factory.multi_nodes[ key ] )

        # Otherwise create one, cache it, and return it:
        factory.multi_nodes[ key ] = multi_node = MultiTreeNode(
                                                       root_node = root_node,
                                                       nodes     = nodes )

        return ( object, multi_node )

    #---------------------------------------------------------------------------
    #  Returns the TreeNode associated with a specified class:
    #---------------------------------------------------------------------------

    def _node_for_class ( self, klass ):
        """ Returns the TreeNode associated with a specified class.
        """
        for node in self.factory.nodes:
            if issubclass( klass, tuple( node.node_for ) ):
                return node
        return None

    #---------------------------------------------------------------------------
    #  Returns the node and class associated with a specified class name:
    #---------------------------------------------------------------------------

    def _node_for_class_name ( self, class_name ):
        """ Returns the node and class associated with a specified class name.
        """
        for node in self.factory.nodes:
            for klass in node.node_for:
                if class_name == klass.__name__:
                    return ( node, klass )
        return ( None, None )

    #---------------------------------------------------------------------------
    #  Updates the icon for a specified node:
    #---------------------------------------------------------------------------

    def _update_icon ( self, event, is_expanded ):
        """ Updates the icon for a specified node.
        """
        self._update_icon_for_nid( event.GetItem() )

    #---------------------------------------------------------------------------
    #  Updates the icon for a specified node id:
    #---------------------------------------------------------------------------

    def _update_icon_for_nid ( self, nid ):
        """ Updates the icon for a specified node ID.
        """
        if self._image_list is not None:
            expanded, node, object = self._get_node_data( nid )
            icon = self._get_icon( node, object, expanded )
            self._tree.SetItemImage( nid, icon, wx.TreeItemIcon_Normal )
            self._tree.SetItemImage( nid, icon, wx.TreeItemIcon_Selected )

    #---------------------------------------------------------------------------
    #  Unpacks an event to see whether a tree item was involved:
    #---------------------------------------------------------------------------

    def _unpack_event ( self, event ):
        """ Unpacks an event to see whether a tree item was involved.
        """
        try:
            point = event.GetPosition()
        except:
            point = event.GetPoint()

        nid = None
        if hasattr( event, 'GetItem' ):
            nid = event.GetItem()

        if (nid is None) or (not nid.IsOk()):
            nid, flags = self._tree.HitTest( point )

        if nid.IsOk():
            return self._get_node_data( nid ) + ( nid, point )

        return ( None, None, None, nid, point )

    #---------------------------------------------------------------------------
    #  Returns information about the node at a specified point:
    #---------------------------------------------------------------------------

    def _hit_test ( self, point ):
        """ Returns information about the node at a specified point.
        """
        nid, flags = self._tree.HitTest( point )
        if nid.IsOk():
            return self._get_node_data( nid ) + ( nid, point )
        return ( None, None, None, nid, point )

    #---------------------------------------------------------------------------
    #  Begins an 'undoable' transaction:
    #---------------------------------------------------------------------------

    def _begin_undo ( self ):
        """ Begins an "undoable" transaction.
        """
        ui = self.ui
        self._undoable.append( ui._undoable )
        if (ui._undoable == -1) and (ui.history is not None):
            ui._undoable = ui.history.now

    #---------------------------------------------------------------------------
    #  Ends an 'undoable' transaction:
    #---------------------------------------------------------------------------

    def _end_undo ( self ):
        if self._undoable.pop() == -1:
            self.ui._undoable = -1

    #---------------------------------------------------------------------------
    #  Gets an 'undo' item for a change made to a node's children:
    #---------------------------------------------------------------------------

    def _get_undo_item ( self, object, name, event ):
        return ListUndoItem( object  = object,
                             name    = name,
                             index   = event.index,
                             added   = event.added,
                             removed = event.removed )

    #---------------------------------------------------------------------------
    #  Performs an undoable 'append' operation:
    #---------------------------------------------------------------------------

    def _undoable_append ( self, node, object, data, make_copy = True ):
        """ Performs an undoable append operation.
        """
        try:
            self._begin_undo()
            if make_copy:
                data = copy.deepcopy( data )
            node.append_child( object, data )
        finally:
            self._end_undo()

    #---------------------------------------------------------------------------
    #  Performs an undoable 'insert' operation:
    #---------------------------------------------------------------------------

    def _undoable_insert ( self, node, object, index, data, make_copy = True ):
        """ Performs an undoable insert operation.
        """
        try:
            self._begin_undo()
            if make_copy:
                data = copy.deepcopy( data )
            node.insert_child( object, index, data )
        finally:
            self._end_undo()

    #---------------------------------------------------------------------------
    #  Performs an undoable 'delete' operation:
    #---------------------------------------------------------------------------

    def _undoable_delete ( self, node, object, index ):
        """ Performs an undoable delete operation.
        """
        try:
            self._begin_undo()
            node.delete_child( object, index )
        finally:
            self._end_undo()

    #---------------------------------------------------------------------------
    #  Gets the id associated with a specified object (if any):
    #---------------------------------------------------------------------------

    def _get_object_nid ( self, object, name = '' ):
        """ Gets the ID associated with a specified object (if any).
        """
        info = self._map.get( id( object ) )
        if info is None:
            return None

        for name2, nid in info:
            if name == name2:
                return nid
        else:
            return info[0][1]

    #---------------------------------------------------------------------------
    #  Clears the current editor pane (if any):
    #---------------------------------------------------------------------------

    def _clear_editor ( self ):
        """ Clears the current editor pane (if any).
        """
        editor = self._editor
        if editor._node_ui is not None:
            editor.SetSizer( None )
            editor._node_ui.dispose()
            editor._node_ui = editor._editor_nid = None

    #---------------------------------------------------------------------------
    #  Gets/Sets the node specific data:
    #---------------------------------------------------------------------------

    def _get_node_data ( self, nid ):
        """ Gets the node specific data.
        """
        if nid == self._root_nid:
            return self._root_nid_data

        return self._tree.GetPyData( nid )

    def _set_node_data ( self, nid, data ):
        """ Sets the node specific data.
        """
        if nid == self._root_nid:
            self._root_nid_data = data
        else:
            self._tree.SetPyData( nid, data )

#----- User callable methods: --------------------------------------------------

    #---------------------------------------------------------------------------
    #  Gets the object associated with a specified node:
    #---------------------------------------------------------------------------

    def get_object ( self, nid ):
        """ Gets the object associated with a specified node.
        """
        return self._get_node_data( nid )[2]

    #---------------------------------------------------------------------------
    #  Returns the object which is the immmediate parent of a specified object
    #  in the tree:
    #---------------------------------------------------------------------------

    def get_parent ( self, object, name = '' ):
        """ Returns the object that is the immmediate parent of a specified
            object in the tree.
        """
        nid = self._get_object_nid( object, name )
        if nid is not None:
            pnid = self._tree.GetItemParent( nid )
            if pnid.IsOk():
                return self.get_object( pnid )

        return None

    #---------------------------------------------------------------------------
    #  Returns the node associated with a specified object:
    #---------------------------------------------------------------------------

    def get_node ( self, object, name = '' ):
        """ Returns the node associated with a specified object.
        """
        nid = self._get_object_nid( object, name )
        if nid is not None:
            return self._get_node_data( nid )[1]

        return None

    #-- Tree Event Handlers: ---------------------------------------------------

    #---------------------------------------------------------------------------
    #  Handles a tree node expanding:
    #---------------------------------------------------------------------------

    def _on_tree_item_expanding ( self, event ):
        """ Handles a tree node expanding.
        """
        if self._veto:
            self._veto = False
            event.Veto()
            return

        nid  = event.GetItem()
        tree = self._tree
        expanded, node, object = self._get_node_data( nid )

        # If 'auto_close' requested for this node type, close all of the node's
        # siblings:
        if node.can_auto_close( object ):
            snid = nid
            while True:
                snid = tree.GetPrevSibling( snid )
                if not snid.IsOk():
                    break
                tree.Collapse( snid )
            snid = nid
            while True:
                snid = tree.GetNextSibling( snid )
                if not snid.IsOk():
                    break
                tree.Collapse( snid )

        # Expand the node (i.e. populate its children if they are not there
        # yet):
        self._expand_node( nid )

    #---------------------------------------------------------------------------
    #  Handles a tree node being expanded:
    #---------------------------------------------------------------------------

    def _on_tree_item_expanded ( self, event ):
        """ Handles a tree node being expanded.
        """
        self._update_icon( event, True )

    #---------------------------------------------------------------------------
    #  Handles a tree node collapsing:
    #---------------------------------------------------------------------------

    def _on_tree_item_collapsing ( self, event ):
        """ Handles a tree node collapsing.
        """
        if self._veto:
            self._veto = False
            event.Veto()

    #---------------------------------------------------------------------------
    #  Handles a tree node being collapsed:
    #---------------------------------------------------------------------------

    def _on_tree_item_collapsed ( self, event ):
        """ Handles a tree node being collapsed.
        """
        self._update_icon( event, False )

    #---------------------------------------------------------------------------
    #  Handles a tree node being selected:
    #---------------------------------------------------------------------------

    def _on_tree_sel_changed ( self, event = None ):
        """ Handles a tree node being selected.
        """
        if self._locked:
            return

        # Get the new selection:
        object      = None
        not_handled = True
        nids        = self._tree.GetSelections()

        selected = []
        for nid in nids:
            if not nid.IsOk():
                continue

            # If there is a real selection, get the associated object:
            expanded, node, sel_object = self._get_node_data( nid )
            selected.append(sel_object)

            # Try to inform the node specific handler of the selection,
            # if there are multiple selections, we only care about the
            # first (or maybe the last makes more sense?)
            if nid == nids[0]:
                object = sel_object
                not_handled = node.select( object )

        # Set the value of the new selection:
        if self.factory.selection_mode == 'single':
            self._no_update_selected = True
            self.selected = object
            self._no_update_selected = False
        else:
            self._no_update_selected = True
            self.selected = selected
            self._no_update_selected = False

        # If no one has been notified of the selection yet, inform the editor's
        # select handler (if any) of the new selection:
        if not_handled is True:
            self.ui.evaluate( self.factory.on_select, object )

        # Check to see if there is an associated node editor pane:
        editor = self._editor
        if editor is not None:
            # If we already had a node editor, destroy it:
            editor.Freeze()
            self._clear_editor()

            # If there is a selected object, create a new editor for it:
            if object is not None:
                # Try to chain the undo history to the main undo history:
                view = node.get_view( object )

                if view is None or isinstance(view, str) :
                    view = object.trait_view(view)

                if (self.ui.history is not None) or (view.kind == 'subpanel'):
                    ui = object.edit_traits( parent = editor,
                                             view   = view,
                                             kind   = 'subpanel' )
                else:
                    # Otherwise, just set up our own new one:
                    ui = object.edit_traits( parent = editor,
                                             view   = view,
                                             kind   = 'panel' )

                # Make our UI the parent of the new UI:
                ui.parent = self.ui

                # Remember the new editor's UI and node info:
                editor._node_ui    = ui
                editor._editor_nid = nid

                # Finish setting up the editor:
                sizer = wx.BoxSizer( wx.VERTICAL )
                sizer.Add( ui.control, 1, wx.EXPAND )
                editor.SetSizer( sizer )
                editor.Layout()

            # fixme: The following is a hack needed to make the editor window
            # (which is a wx.ScrolledWindow) recognize that its contents have
            # been changed:
            dx, dy = editor.GetSize()
            editor.SetSize( wx.Size( dx, dy + 1 ) )
            editor.SetSize( wx.Size( dx, dy ) )

            # Allow the editor view to show any changes that have occurred:
            editor.Thaw()

    def _on_hover(self, event):
        """ Handles the mouse moving over a tree node
        """
        id, flags = self._tree.HitTest(event.GetPosition())
        if flags & wx.TREE_HITTEST_ONITEMLABEL:
            expanded, node, object = self._get_node_data( id )
            if self.factory.on_hover is not None:
                self.ui.evaluate( self.factory.on_hover, object )
                self._veto = True
        elif self.factory and self.factory.on_hover is not None:
            self.ui.evaluate( self.factory.on_hover, None )

        # allow other events to be processed
        event.Skip(True)


    #---------------------------------------------------------------------------
    #  Handles a tree item being activated:
    #---------------------------------------------------------------------------

    def _on_tree_item_activated ( self, event ):
        """ Handles a tree item being activated.
        """
        expanded, node, object = self._get_node_data( event.GetItem() )

        # Fire the 'activated' event with the clicked on object as value:
        self.activated = object

        # FIXME: Firing the dclick event also for backward compatibility on wx.
        # Change it occur on mouse double click only.
        self.dclick = object

    #---------------------------------------------------------------------------
    #  Handles the user starting to edit a tree node label:
    #---------------------------------------------------------------------------

    def _on_tree_begin_label_edit ( self, event ):
        """ Handles the user starting to edit a tree node label.
        """
        item       = event.GetItem()
        parent     = self._tree.GetItemParent( item )
        can_rename = True
        if parent.IsOk():
            expanded, node, object = self._get_node_data( parent )
            can_rename = node.can_rename( object )

        if can_rename:
            expanded, node, object = self._get_node_data( item )
            if node.can_rename_me( object ):
                return

        event.Veto()

    #---------------------------------------------------------------------------
    #  Handles the user completing tree node label editing:
    #---------------------------------------------------------------------------

    def _on_tree_end_label_edit ( self, event ):
        """ Handles the user completing tree node label editing.
        """
        label = event.GetLabel()
        if len( label ) > 0:
            expanded, node, object = self._get_node_data( event.GetItem() )
            # Tell the node to change the label. If it raises an exception,
            # that means it didn't like the label, so veto the tree node change:
            try:
                node.set_label( object, label )
                return
            except:
                pass
        event.Veto()

    #---------------------------------------------------------------------------
    #  Handles a drag operation starting on a tree node:
    #---------------------------------------------------------------------------

    def _on_tree_begin_drag ( self, event ):
        """ Handles a drag operation starting on a tree node.
        """
        if PythonDropSource is not None:
            expanded, node, object, nid, point = self._unpack_event( event )
            if node is not None:
                try:
                    self._dragging = nid
                    PythonDropSource( self._tree,
                                      node.get_drag_object( object ) )
                finally:
                    self._dragging = None

    #---------------------------------------------------------------------------
    #  Handles a tooltip request on a tree node:
    #---------------------------------------------------------------------------

    def _on_tree_item_gettooltip ( self, event ):
        """ Handles a tooltip request on a tree node.
        """
        nid = event.GetItem()
        if nid.IsOk():
            node_data = self._get_node_data( nid )
            if node_data is not None:
                expanded, node, object = node_data
                tooltip = node.get_tooltip( object )
                if tooltip != '':
                    event.SetToolTip( tooltip )

        event.Skip()

    #---------------------------------------------------------------------------
    #  Handles a tree item being double-clicked:
    #---------------------------------------------------------------------------

    def _on_left_dclick ( self, event ):
        """ Handle left mouse dclick to emit dclick event for associated node.
        """
        # Determine what node (if any) was clicked on:
        expanded, node, object, nid, point = self._unpack_event( event )

        # If the mouse is over a node, then process the click:
        if node is not None:
            if ((node.dclick( object ) is True) and
                (self.factory.on_dclick is not None)):
                self.ui.evaluate( self.factory.on_dclick, object )

            # Fire the 'dclick' event with the object as its value:
            # FIXME: This is instead done in _on_item_activated for backward
            # compatibility only on wx toolkit.
            #self.dclick = object

        # Allow normal mouse event processing to occur:
        event.Skip()

    #---------------------------------------------------------------------------
    #  Handles the user left clicking on a tree node:
    #---------------------------------------------------------------------------

    def _on_left_down ( self, event ):
        """ Handles the user right clicking on a tree node.
        """
        # Determine what node (if any) was clicked on:
        expanded, node, object, nid, point = self._unpack_event( event )

        # If the mouse is over a node, then process the click:
        if node is not None:
            if ((node.click( object ) is True) and
                (self.factory.on_click is not None)):
                self.ui.evaluate( self.factory.on_click, object )

            # Fire the 'click' event with the object as its value:
            self.click = object

        # Allow normal mouse event processing to occur:
        event.Skip()

    #---------------------------------------------------------------------------
    #  Handles the user right clicking on a tree node:
    #---------------------------------------------------------------------------

    def _on_right_down ( self, event ):
        """ Handles the user right clicking on a tree node.
        """
        expanded, node, object, nid, point = self._unpack_event( event )

        if node is not None:
            self._data    = ( node, object, nid )
            self._context = { 'object':  object,
                              'editor':  self,
                              'node':    node,
                              'info':    self.ui.info,
                              'handler': self.ui.handler }

            # Try to get the parent node of the node clicked on:
            pnid = self._tree.GetItemParent( nid )
            if pnid.IsOk():
                ignore, parent_node, parent_object = self._get_node_data( pnid )
            else:
                parent_node = parent_object = None

            self._menu_node          = node
            self._menu_parent_node   = parent_node
            self._menu_parent_object = parent_object

            menu = node.get_menu( object )

            if menu is None:
                # Use the standard, default menu:
                menu = self._standard_menu( node, object )

            elif isinstance( menu, Menu ):
                # Use the menu specified by the node:
                group = menu.find_group( NewAction )
                if group is not None:
                    # Only set it the first time:
                    group.id = ''
                    actions  = self._new_actions( node, object )
                    if len( actions ) > 0:
                        group.insert( 0, Menu( name = 'New', *actions ) )

            else:
                # All other values mean no menu should be displayed:
                menu = None

            # Only display the menu if a valid menu is defined:
            if menu is not None:
                wxmenu = menu.create_menu( self._tree, self )
                self._tree.PopupMenuXY( wxmenu,
                                        point[0] - 10, point[1] - 10 )
                wxmenu.Destroy()

            # Reset all menu related cached values:
            self._data = self._context = self._menu_node = \
            self._menu_parent_node = self._menu_parent_object = None

    #---------------------------------------------------------------------------
    #  Returns the standard contextual pop-up menu:
    #---------------------------------------------------------------------------

    def _standard_menu ( self, node, object ):
        """ Returns the standard contextual pop-up menu.
        """
        actions = [ CutAction, CopyAction, PasteAction, Separator(),
                    DeleteAction, Separator(), RenameAction ]

        # See if the 'New' menu section should be added:
        items = self._new_actions( node, object )
        if len( items ) > 0:
            actions[0:0] = [ Menu( name = 'New', *items ), Separator() ]

        return Menu( *actions )

    #---------------------------------------------------------------------------
    #  Returns a list of Actions that will create 'new' objects:
    #---------------------------------------------------------------------------

    def _new_actions ( self, node, object ):
        """ Returns a list of Actions that will create new objects.
        """
        object = self._data[1]
        items  = []
        add    = node.get_add( object )
        if len( add ) > 0:
            for klass in add:
                prompt = False
                if isinstance( klass, tuple ):
                    klass, prompt = klass
                add_node = self._node_for_class( klass )
                if add_node is not None:
                    class_name = klass.__name__
                    name       = add_node.get_name( object )
                    if name == '':
                        name = class_name
                    items.append(
                        Action( name   = name,
                                action = "editor._menu_new_node('%s',%s)" %
                                         ( class_name, prompt ) ) )
        return items

    #---------------------------------------------------------------------------
    #  Menu action helper methods:
    #---------------------------------------------------------------------------

    def _is_copyable ( self, object ):
        parent = self._menu_parent_node
        if isinstance( parent, ObjectTreeNode ):
            return parent.can_copy( self._menu_parent_object )
        return ((parent is not None) and parent.can_copy( object ))

    def _is_cutable ( self, object ):
        parent = self._menu_parent_node
        if isinstance( parent, ObjectTreeNode ):
            can_cut = (parent.can_copy( self._menu_parent_object ) and
                       parent.can_delete( self._menu_parent_object ))
        else:
            can_cut = ((parent is not None) and
                       parent.can_copy( object ) and
                       parent.can_delete( object ))
        return (can_cut and self._menu_node.can_delete_me( object ))

    def _is_pasteable ( self, object ):
        from pyface.wx.clipboard import clipboard

        return self._menu_node.can_add( object, clipboard.object_type )

    def _is_deletable ( self, object ):
        parent = self._menu_parent_node
        if isinstance( parent, ObjectTreeNode ):
            can_delete = parent.can_delete( self._menu_parent_object )
        else:
            can_delete = ((parent is not None) and parent.can_delete( object ))
        return (can_delete and self._menu_node.can_delete_me( object ))

    def _is_renameable ( self, object ):
        parent = self._menu_parent_node
        if isinstance( parent, ObjectTreeNode ):
            can_rename = parent.can_rename( self._menu_parent_object )
        elif parent is not None:
            can_rename = parent.can_rename( object )
        else:
            can_rename = True
        return (can_rename and self._menu_node.can_rename_me( object ))

#----- Drag and drop event handlers: -------------------------------------------

    #---------------------------------------------------------------------------
    #  Handles a Python object being dropped on the tree:
    #---------------------------------------------------------------------------

    def wx_dropped_on ( self, x, y, data, drag_result ):
        """ Handles a Python object being dropped on the tree.
        """
        if isinstance( data, list ):
            rc = wx.DragNone
            for item in data:
                rc = self.wx_dropped_on( x, y, item, drag_result )
            return rc

        expanded, node, object, nid, point = self._hit_test( wx.Point( x, y ) )
        if node is not None:
            if drag_result == wx.DragMove:
                if not self._is_droppable( node, object, data, False ):
                    return wx.DragNone

                if self._dragging is not None:
                    data = self._drop_object( node, object, data, False )
                    if data is not None:
                        try:
                            self._begin_undo()
                            self._undoable_delete(
                                     *self._node_index( self._dragging ) )
                            self._undoable_append( node, object, data, False )
                        finally:
                            self._end_undo()
                else:
                    data = self._drop_object( node, object, data )
                    if data is not None:
                        self._undoable_append( node, object, data, False )

                return drag_result

            to_node, to_object, to_index = self._node_index( nid )
            if to_node is not None:
                if self._dragging is not None:
                    data = self._drop_object( node, to_object, data, False )
                    if data is not None:
                        from_node, from_object, from_index = \
                            self._node_index( self._dragging )
                        if ((to_object is from_object) and
                            (to_index > from_index)):
                            to_index -= 1
                        try:
                            self._begin_undo()
                            self._undoable_delete( from_node, from_object,
                                                   from_index )
                            self._undoable_insert( to_node, to_object, to_index,
                                                   data, False )
                        finally:
                            self._end_undo()
                else:
                    data = self._drop_object( to_node, to_object, data )
                    if data is not None:
                        self._undoable_insert( to_node, to_object, to_index,
                                               data, False )

                return drag_result

        return wx.DragNone

    #---------------------------------------------------------------------------
    #  Handles a Python object being dragged over the tree:
    #---------------------------------------------------------------------------

    def wx_drag_over ( self, x, y, data, drag_result ):
        """ Handles a Python object being dragged over the tree.
        """
        expanded, node, object, nid, point = self._hit_test( wx.Point( x, y ) )
        insert = False

        if (node is not None) and (drag_result == wx.DragCopy):
            node, object, index = self._node_index( nid )
            insert = True

        if ((self._dragging is not None) and
            (not self._is_drag_ok( self._dragging, data, object ))):
            return wx.DragNone

        if ((node is not None) and
            self._is_droppable( node, object, data, insert )):
            return drag_result

        return wx.DragNone

    #---------------------------------------------------------------------------
    #  Makes sure that the target is not the same as or a child of the source
    #  object:
    #---------------------------------------------------------------------------

    def _is_drag_ok ( self, snid, source, target ):
        if (snid is None) or (target is source):
            return False

        for cnid in self._nodes( snid ):
            if not self._is_drag_ok( cnid, self._get_node_data( cnid )[2],
                                     target ):
                return False

        return True

#----- pyface.action 'controller' interface implementation: --------------------

    #---------------------------------------------------------------------------
    #  Adds a menu item to the menu being constructed:
    #---------------------------------------------------------------------------

    def add_to_menu ( self, menu_item ):
        """ Adds a menu item to the menu bar being constructed.
        """
        action = menu_item.item.action
        self.eval_when( action.enabled_when, menu_item, 'enabled' )
        self.eval_when( action.checked_when, menu_item, 'checked' )

    #---------------------------------------------------------------------------
    #  Adds a tool bar item to the tool bar being constructed:
    #---------------------------------------------------------------------------

    def add_to_toolbar ( self, toolbar_item ):
        """ Adds a toolbar item to the toolbar being constructed.
        """
        self.add_to_menu( toolbar_item )

    #---------------------------------------------------------------------------
    #  Returns whether the menu action should be defined in the user interface:
    #---------------------------------------------------------------------------

    def can_add_to_menu ( self, action ):
        """ Returns whether the action should be defined in the user interface.
        """
        if action.defined_when != '':
            try:
                if not eval( action.defined_when, globals(), self._context ):
                    return False
            except:
                open_fbi()

        if action.visible_when != '':
            try:
                if not eval( action.visible_when, globals(), self._context ):
                    return False
            except:
                open_fbi()

        return True

    #---------------------------------------------------------------------------
    #  Returns whether the toolbar action should be defined in the user
    #  interface:
    #---------------------------------------------------------------------------

    def can_add_to_toolbar ( self, action ):
        """ Returns whether the toolbar action should be defined in the user
            interface.
        """
        return self.can_add_to_menu( action )

    #---------------------------------------------------------------------------
    #  Performs the action described by a specified Action object:
    #---------------------------------------------------------------------------

    def perform ( self, action, action_event = None ):
        """ Performs the action described by a specified Action object.
        """
        self.ui.do_undoable( self._perform, action )

    def _perform ( self, action ):
        node, object, nid = self._data
        method_name       = action.action
        info              = self.ui.info
        handler           = self.ui.handler

        if method_name.find( '.' ) >= 0:
            if method_name.find( '(' ) < 0:
                method_name += '()'
            try:
                eval( method_name, globals(),
                      { 'object':  object,
                        'editor':  self,
                        'node':    node,
                        'info':    info,
                        'handler': handler } )
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()

            return

        method = getattr( handler, method_name, None )
        if method is not None:
            method( info, object )
            return

        if action.on_perform is not None:
            action.on_perform( object )

#----- Menu support methods: ---------------------------------------------------

    #---------------------------------------------------------------------------
    #  Evaluates a condition within a defined context and sets a specified
    #  object trait based on the (assumed) boolean result:
    #---------------------------------------------------------------------------

    def eval_when ( self, condition, object, trait ):
        """ Evaluates a condition within a defined context, and sets a
        specified object trait based on the result, which is assumed to be a
        Boolean.
        """
        if condition != '':
            value = True
            try:
                if not eval( condition, globals(), self._context ):
                    value = False
            except:
                open_fbi()
            setattr( object, trait, value )

#----- Menu event handlers: ----------------------------------------------------

    #---------------------------------------------------------------------------
    #  Copies the current tree node object to the paste buffer:
    #---------------------------------------------------------------------------

    def _menu_copy_node ( self ):
        """ Copies the current tree node object to the paste buffer.
        """
        from pyface.wx.clipboard import clipboard

        clipboard.data = self._data[1]
        self._data     = None

    #---------------------------------------------------------------------------
    #   Cuts the current tree node object into the paste buffer:
    #---------------------------------------------------------------------------

    def _menu_cut_node ( self ):
        """  Cuts the current tree node object into the paste buffer.
        """
        from pyface.wx.clipboard import clipboard

        node, object, nid = self._data
        clipboard.data    = object
        self._data        = None
        self._undoable_delete( *self._node_index( nid ) )

    #---------------------------------------------------------------------------
    #  Pastes the current contents of the paste buffer into the current node:
    #---------------------------------------------------------------------------

    def _menu_paste_node ( self ):
        """ Pastes the current contents of the paste buffer into the current
            node.
        """
        from pyface.wx.clipboard import clipboard

        node, object, nid = self._data
        self._data        = None
        self._undoable_append( node, object, clipboard.object_data, False )

    #---------------------------------------------------------------------------
    #  Deletes the current node from the tree:
    #---------------------------------------------------------------------------

    def _menu_delete_node ( self ):
        """ Deletes the current node from the tree.
        """
        node, object, nid = self._data
        self._data        = None
        rc = node.confirm_delete( object )
        if rc is not False:
            if rc is not True:
                if self.ui.history is None:
                    # If no undo history, ask user to confirm the delete:
                    dlg = wx.MessageDialog(
                              self._tree,
                              'Are you sure you want to delete %s?' %
                                  node.get_label( object ),
                              'Confirm Deletion',
                              style = wx.OK | wx.CANCEL | wx.ICON_EXCLAMATION )
                    if dlg.ShowModal() != wx.ID_OK:
                        return

            self._undoable_delete( *self._node_index( nid ) )

    #---------------------------------------------------------------------------
    #  Renames the current tree node:
    #---------------------------------------------------------------------------

    def _menu_rename_node ( self ):
        """ Renames the current tree node.
        """
        node, object, nid = self._data
        self._data        = None
        object_label      = ObjectLabel( label = node.get_label( object ) )
        if object_label.edit_traits().result:
            label = object_label.label.strip()
            if label != '':
                node.set_label( object, label )

    #---------------------------------------------------------------------------
    #  Adds a new object to the current node:
    #---------------------------------------------------------------------------

    def _menu_new_node ( self, class_name, prompt = False ):
        """ Adds a new object to the current node.
        """
        node, object, nid   = self._data
        self._data          = None
        new_node, new_class = self._node_for_class_name( class_name )
        new_object          = new_class()
        if (not prompt) or new_object.edit_traits(
                            parent = self.control, kind = 'livemodal' ).result:
            self._undoable_append( node, object, new_object, False )

            # Automatically select the new object if editing is being performed:
            if self.factory.editable:
                self._tree.SelectItem( self._tree.GetLastChild( nid ) )

    #-- Model event handlers ---------------------------------------------------

    #---------------------------------------------------------------------------
    #  Handles the children of a node being completely replaced:
    #---------------------------------------------------------------------------

    def _children_replaced ( self, object, name = '', new = None ):
        """ Handles the children of a node being completely replaced.
        """
        tree = self._tree
        for expanded, node, nid in self._object_info_for( object, name ):
            children = node.get_children( object )

            # Only add/remove the changes if the node has already been expanded:
            if expanded:
                # Delete all current child nodes:
                for cnid in self._nodes_for( nid ):
                    self._delete_node( cnid )

                # Add all of the children back in as new nodes:
                for child in children:
                    child, child_node = self._node_for( child )
                    if child_node is not None:
                        self._append_node( nid, child_node, child )

            # Indicate whether the node has any children now:
            tree.SetItemHasChildren( nid, len( children ) > 0 )

            # Try to expand the node (if requested):
            if node.can_auto_open( object ):
                tree.Expand( nid )

    #---------------------------------------------------------------------------
    #  Handles the children of a node being changed:
    #---------------------------------------------------------------------------

    def _children_updated ( self, object, name, event ):
        """ Handles the children of a node being changed.
        """
        # Log the change that was made (removing '_items' from the end of the
        # name):
        name = name[:-6]
        self.log_change( self._get_undo_item, object, name, event )

        start = event.index
        end   = start + len( event.removed )
        tree  = self._tree

        for expanded, node, nid in self._object_info_for( object, name ):
            n = len( node.get_children( object ) )

            # Only add/remove the changes if the node has already been expanded:
            if expanded:
                # Remove all of the children that were deleted:
                for cnid in self._nodes_for( nid )[ start: end ]:
                    self._delete_node( cnid )

                # Add all of the children that were added:
                remaining = n - len( event.removed )
                child_index = 0
                for child in event.added:
                    child, child_node = self._node_for( child )
                    if child_node is not None:
                        insert_index = (start + child_index) if \
                                        (start < remaining) else None
                        self._insert_node( nid, insert_index, child_node,
                                           child )
                        child_index += 1


            # Indicate whether the node has any children now:
            tree.SetItemHasChildren( nid, n > 0 )

            # Try to expand the node (if requested):
            root = tree.GetRootItem()
            if node.can_auto_open( object ):
                if ( nid != root ) or not self.factory.hide_root:
                    tree.Expand( nid )

    #---------------------------------------------------------------------------
    #   Handles the label of an object being changed:
    #---------------------------------------------------------------------------

    def _label_updated ( self, object, name, label ):
        """  Handles the label of an object being changed.
        """
        nids = {}
        for name2, nid in self._map[ id( object ) ]:
            if nid not in nids:
                nids[ nid ] = None
                node = self._get_node_data( nid )[1]
                self._tree.SetItemText( nid, node.get_label( object ) )
                self._update_icon_for_nid ( nid )

#-- UI preference save/restore interface ---------------------------------------

    #---------------------------------------------------------------------------
    #  Restores any saved user preference information associated with the
    #  editor:
    #---------------------------------------------------------------------------

    def restore_prefs ( self, prefs ):
        """ Restores any saved user preference information associated with the
            editor.
        """
        if self._is_dock_window:
            if isinstance( prefs, dict ):
                structure = prefs.get( 'structure' )
            else:
                structure = prefs
            self.control.GetSizer().SetStructure( self.control, structure )

    #---------------------------------------------------------------------------
    #  Returns any user preference information associated with the editor:
    #---------------------------------------------------------------------------

    def save_prefs ( self ):
        """ Returns any user preference information associated with the editor.
        """
        if self._is_dock_window:
            return { 'structure': self.control.GetSizer().GetStructure() }

        return None

#-- End UI preference save/restore interface -----------------------------------

#-------------------------------------------------------------------------------
#  'ObjectLabel' class:
#-------------------------------------------------------------------------------

class ObjectLabel ( HasStrictTraits ):
    """ An editable label for an object.
    """

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Label to be edited
    label = Str

    #---------------------------------------------------------------------------
    #  Traits view definition:
    #---------------------------------------------------------------------------

    traits_view = View( 'label',
                        title   = 'Edit Label',
                        kind    = 'modal',
                        buttons = [ 'OK', 'Cancel' ] )

### EOF #######################################################################