File: ui_panel.py

package info (click to toggle)
python-traitsui 8.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,232 kB
  • sloc: python: 58,982; makefile: 113
file content (1231 lines) | stat: -rw-r--r-- 42,230 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
# (C) Copyright 2004-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in 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!

""" Creates a panel-based wxPython user interface for a specified UI object.
"""


import wx
import wx.html as wh
import re

from html import escape

from traits.api import Instance, Undefined

from traitsui.api import Group

from traitsui.undo import UndoHistory

from traitsui.dockable_view_element import DockableViewElement

from traitsui.help_template import help_template

from traitsui.menu import UndoButton, RevertButton, HelpButton

from pyface.api import SystemMetrics

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

from pyface.sizers.flow import FlowSizer

from .helper import (
    position_window,
    TraitsUIPanel,
    TraitsUIScrolledPanel,
    GroupEditor,
)

from .constants import WindowColor

from .ui_base import BaseDialog


# Pattern of all digits
all_digits = re.compile(r"\d+")

# Global font used for emphasis
emphasis_font = None

# Global color used for emphasis
emphasis_color = wx.Colour(0, 0, 127)


def ui_panel(ui, parent):
    """Creates a panel-based wxPython user interface for a specified UI object."""
    ui_panel_for(ui, parent, True)


def ui_subpanel(ui, parent):
    """Creates a subpanel-based wxPython user interface for a specified UI
    object. A subpanel does not allow control buttons (other than those
    specified in the UI object).
    """
    ui_panel_for(ui, parent, False)


def ui_panel_for(ui, parent, buttons):
    """Creates a panel-based wxPython user interface for a specified UI object."""
    # Disable screen updates on the parent control while we build the view:
    parent.Freeze()

    # Build the view:
    ui.control = control = Panel(ui, parent, buttons).control

    # Allow screen updates to occur again:
    parent.Thaw()

    control._parent = parent
    control._object = ui.context.get("object")
    control._ui = ui
    try:
        ui.prepare_ui()
    except:
        control.Destroy()
        ui.control = None
        ui.result = False
        raise
    ui.restore_prefs()
    ui.result = True


class Panel(BaseDialog):
    """wxPython user interface panel for Traits-based user interfaces."""

    def __init__(self, ui, parent, allow_buttons):
        """Initializes the object."""
        self.ui = ui
        history = None
        view = ui.view
        title = view.title

        # Reset any existing history listeners:
        history = ui.history
        if history is not None:
            history.observe(
                self._on_undoable, "undoable", remove=True, dispatch="ui"
            )
            history.observe(
                self._on_redoable, "redoable", remove=True, dispatch="ui"
            )
            history.observe(
                self._on_revertable, "undoable", remove=True, dispatch="ui"
            )

        # Determine if we need any buttons or an 'undo' history:
        buttons = [self.coerce_button(button) for button in view.buttons]
        nbuttons = len(buttons)
        if nbuttons == 0:
            if view.undo:
                self.check_button(buttons, UndoButton)
            if view.revert:
                self.check_button(buttons, RevertButton)
            if view.help:
                self.check_button(buttons, HelpButton)

        if allow_buttons and (history is None):
            for button in buttons:
                if self.is_button(button, "Undo") or self.is_button(
                    button, "Revert"
                ):
                    history = UndoHistory()
                    break
        ui.history = history

        # Create a container panel to put everything in:
        cpanel = getattr(self, "control", None)
        if cpanel is not None:
            cpanel.SetSizer(None)
            cpanel.DestroyChildren()
        else:
            self.control = cpanel = TraitsUIPanel(parent, -1)

        # Create the actual trait sheet panel and embed it in a scrollable
        # window (if requested):
        sw_sizer = wx.BoxSizer(wx.VERTICAL)
        if ui.scrollable:
            sizer = wx.BoxSizer(wx.VERTICAL)
            sw = TraitsUIScrolledPanel(cpanel)
            sizer.Add(panel(ui, sw), 1, wx.EXPAND)

            sw.SetSizerAndFit(sizer)
            sw.SetScrollRate(16, 16)
        else:
            sw = panel(ui, cpanel)

        if (title != "") and (
            not isinstance(getattr(parent, "owner", None), DockWindow)
        ):
            sw_sizer.Add(
                heading_text(cpanel, text=title).control, 0, wx.EXPAND
            )

        self.add_toolbar(sw_sizer)

        sw_sizer.Add(sw, 1, wx.EXPAND)

        if allow_buttons and (
            (nbuttons != 1) or (not self.is_button(buttons[0], ""))
        ):
            # Add the special function buttons:
            sw_sizer.Add(wx.StaticLine(cpanel, -1), 0, wx.EXPAND)
            b_sizer = wx.BoxSizer(wx.HORIZONTAL)
            for button in buttons:
                if self.is_button(button, "Undo"):
                    self.undo = self.add_button(
                        button, b_sizer, self._on_undo, False
                    )
                    self.redo = self.add_button(
                        button, b_sizer, self._on_redo, False, "Redo"
                    )
                    history.observe(
                        self._on_undoable, "undoable", dispatch="ui"
                    )
                    history.observe(
                        self._on_redoable, "redoable", dispatch="ui"
                    )
                elif self.is_button(button, "Revert"):
                    self.revert = self.add_button(
                        button, b_sizer, self._on_revert, False
                    )
                    history.observe(
                        self._on_revertable, "undoable", dispatch="ui"
                    )
                elif self.is_button(button, "Help"):
                    self.add_button(button, b_sizer, self._on_help)
                elif not self.is_button(button, ""):
                    self.add_button(button, b_sizer)

            sw_sizer.Add(b_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)

        cpanel.SetSizerAndFit(sw_sizer)

    def _on_undoable(self, event):
        """Handles a change to the "undoable" state of the undo history."""
        state = event.new
        self.undo.Enable(state)

    def _on_redoable(self, event):
        """Handles a change to the "redoable" state of the undo history."""
        state = event.new
        self.redo.Enable(state)

    def _on_revertable(self, event):
        """Handles a change to the "revert" state."""
        state = event.new
        self.revert.Enable(state)

    def add_toolbar(self, sizer):
        """Adds an optional toolbar to the dialog."""
        toolbar = self.ui.view.toolbar
        if toolbar is not None:
            self._last_group = self._last_parent = None
            sizer.Add(
                toolbar.create_tool_bar(self.control, self), 0, wx.EXPAND
            )
            self._last_group = self._last_parent = None


# -------------------------------------------------------------------------
#  Creates a panel-based wxPython user interface for a specified UI object:
#
#  Note: This version does not modify the UI object passed to it.
# -------------------------------------------------------------------------


def panel(ui, parent):
    """Creates a panel-based wxPython user interface for a specified UI object.

    This function does not modify the UI object passed to it
    """
    # Bind the context values to the 'info' object:
    ui.info.bind_context()

    # Get the content that will be displayed in the user interface:
    content = ui._groups

    # If there is 0 or 1 Groups in the content, create a single panel for it:
    if len(content) <= 1:
        panel = TraitsUIPanel(parent, -1)
        if len(content) == 1:
            # Fill the panel with the Group's content:
            sg_sizer, resizable, contents = fill_panel_for_group(
                panel, content[0], ui
            )
            sizer = panel.GetSizer()
            if sizer is not sg_sizer:
                sizer.Add(sg_sizer, 1, wx.EXPAND)

            # Make sure the panel and its contents have been laid out properly:
            sizer.Fit(panel)

        # Return the panel that was created:
        return panel

    # Create a notebook which will contain a page for each group in the
    # content:
    nb = create_notebook_for_items(content, ui, parent, None)
    nb.ui = ui

    # Notice when the notebook page changes (to display correct help)
    ###parent.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, _page_changed, id=nb.GetId())

    # Return the notebook as the result:
    return nb


# -------------------------------------------------------------------------
#  Creates a notebook and adds a list of groups or items to it as separate
#  pages:
# -------------------------------------------------------------------------


def create_notebook_for_items(
    content, ui, parent, group, item_handler=None, is_dock_window=False
):
    """Creates a notebook and adds a list of groups or items to it as separate
    pages.
    """
    if is_dock_window:
        nb = parent
    else:
        dw = DockWindow(
            parent, handler=ui.handler, handler_args=(ui.info,), id=ui.id
        )
        if group is not None:
            dw.theme = group.dock_theme
        nb = dw.control
    pages = []
    count = 0

    # Create a notebook page for each group or item in the content:
    active = 0
    for index, item in enumerate(content):
        if isinstance(item, Group):
            # Create the group as a nested DockWindow item:
            if item.selected:
                active = index
            sg_sizer, resizable, contents = fill_panel_for_group(
                nb, item, ui, suppress_label=True, is_dock_window=True
            )

            # If the result is a region (i.e. notebook) with only one page,
            # collapse it down into just the contents of the region:
            if isinstance(contents, DockRegion) and (
                len(contents.contents) == 1
            ):
                contents = contents.contents[0]

            # Add the content to the notebook as a new page:
            pages.append(contents)
        else:
            # Create the new page as a simple DockControl containing the
            # specified set of controls:
            page_name = item.get_label(ui)
            count += 1
            if page_name == "":
                page_name = "Page %d" % count

            sizer = wx.BoxSizer(wx.VERTICAL)

            panel = TraitsUIPanel(nb, -1)
            panel.SetSizer(sizer)

            pages.append(
                DockControl(
                    name=page_name,
                    image=item.image,
                    id=item.get_id(),
                    style=item.dock,
                    dockable=DockableViewElement(ui=ui, element=item),
                    export=item.export,
                    control=panel,
                )
            )
            item_handler(item, panel, sizer)
            panel.GetSizer().Fit(panel)

    region = DockRegion(contents=pages, active=active)

    # If the caller is a DockWindow, return the region as the result:
    if is_dock_window:
        return region

    nb.SetSizer(DockSizer(contents=DockSection(contents=[region])))

    # Return the notebook as the result:
    return nb


def _page_changed(event):
    nb = event.GetEventObject()
    nb.ui._active_group = event.GetSelection()


def show_help(ui, button):
    """Displays a help window for the specified UI's active Group."""
    group = ui._groups[ui._active_group]
    template = help_template()
    if group.help != "":
        header = template.group_help % escape(group.help)
    else:
        header = template.no_group_help
    fields = []
    for item in group.get_content(False):
        if not item.is_spacer():
            fields.append(
                template.item_help
                % (escape(item.get_label(ui)), escape(item.get_help(ui)))
            )
    html_content = template.group_html % (header, "\n".join(fields))
    HTMLHelpWindow(button, html_content, 0.25, 0.33)


def show_help_popup(event):
    """Displays a pop-up help window for a single trait."""
    control = event.GetEventObject()
    template = help_template()

    # Note: The following check is necessary because under Linux, we get back
    # a control which does not have the 'help' trait defined (it is the parent
    # of the object with the 'help' trait):
    help = getattr(control, "help", None)
    if help is not None:
        html_content = template.item_html % (control.GetLabel(), help)
        HTMLHelpWindow(control, html_content, 0.25, 0.13)


def fill_panel_for_group(
    panel,
    group,
    ui,
    suppress_label=False,
    is_dock_window=False,
    create_panel=False,
):
    """Builds the user interface for a specified Group within a specified
    Panel.
    """
    fp = FillPanel(
        panel, group, ui, suppress_label, is_dock_window, create_panel
    )
    return (fp.control or fp.sizer, fp.resizable, fp.dock_contents)


class FillPanel(object):
    """A subpanel for a single group of items."""

    def __init__(
        self, panel, group, ui, suppress_label, is_dock_window, create_panel
    ):
        """Initializes the object."""
        # Get the contents of the group:
        content = group.get_content()

        # Create a group editor object if one is needed:
        self.control = self.sizer = editor = None
        self.ui = ui
        self.group = group
        self.is_horizontal = group.orientation == "horizontal"
        layout = group.layout
        is_scrolled_panel = group.scrollable
        is_splitter = layout == "split"
        is_tabbed = layout == "tabbed"
        id = group.id

        # Assume our contents are not resizable:
        self.resizable = False

        if is_dock_window and (is_splitter or is_tabbed):
            if is_splitter:
                self.dock_contents = self.add_dock_window_splitter_items(
                    panel, content, group
                )
            else:
                self.resizable = group.springy
                self.dock_contents = create_notebook_for_items(
                    content, ui, panel, group, self.add_notebook_item, True
                )
            return

        if (
            is_dock_window
            or create_panel
            or is_scrolled_panel
            or (id != "")
            or (group.visible_when != "")
            or (group.enabled_when != "")
        ):
            if is_scrolled_panel:
                new_panel = TraitsUIScrolledPanel(panel)
                new_panel.SetMinSize(panel.GetMinSize())
                self.resizable = True
            else:
                new_panel = TraitsUIPanel(panel, -1)

            sizer = panel.GetSizer()
            if sizer is None:
                sizer = wx.BoxSizer(wx.VERTICAL)
                panel.SetSizer(sizer)
            self.control = panel = new_panel
            if is_splitter or is_tabbed:
                editor = DockWindowGroupEditor(control=panel, ui=ui)
            else:
                editor = GroupEditor(control=panel)
            if id != "":
                ui.info.bind(group.id, editor)
            if group.visible_when != "":
                ui.add_visible(group.visible_when, editor)
            if group.enabled_when != "":
                ui.add_enabled(group.enabled_when, editor)

        self.panel = panel
        self.dock_contents = None

        # Determine the horizontal/vertical orientation of the group:
        if self.is_horizontal:
            orientation = wx.HORIZONTAL
        else:
            orientation = wx.VERTICAL

        # Set up a group with or without a border around its contents:
        label = ""
        if not suppress_label:
            label = group.label

        if group.show_border:
            box = wx.StaticBox(panel, -1, label)
            self._set_owner(box, group)
            self.sizer = wx.StaticBoxSizer(box, orientation)
        else:
            if layout == "flow":
                self.sizer = FlowSizer(orientation)
            else:
                self.sizer = wx.BoxSizer(orientation)
            if label != "":
                self.sizer.Add(
                    heading_text(panel, text=label).control,
                    0,
                    wx.EXPAND | wx.LEFT | wx.TOP | wx.RIGHT,
                    4,
                )

        # If no sizer has been specified for the panel yet, make the new sizer
        # the layout sizer for the panel:
        if panel.GetSizer() is None:
            panel.SetSizer(self.sizer)

        # Set up scrolling now that the sizer has been set:
        if is_scrolled_panel:
            if self.is_horizontal:
                panel.SetupScrolling(scroll_y=False)
            else:
                panel.SetupScrolling(scroll_x=False)

        if is_splitter:
            dw = DockWindow(
                panel,
                handler=ui.handler,
                handler_args=(ui.info,),
                id=ui.id,
                theme=group.dock_theme,
            ).control
            if editor is not None:
                editor.dock_window = dw

            dw.SetSizer(
                DockSizer(
                    contents=self.add_dock_window_splitter_items(
                        dw, content, group
                    )
                )
            )
            self.sizer.Add(dw, 1, wx.EXPAND)
        elif len(content) > 0:
            if is_tabbed:
                self.resizable = group.springy
                dw = create_notebook_for_items(
                    content, ui, panel, group, self.add_notebook_item
                )
                if editor is not None:
                    editor.dock_window = dw

                self.sizer.Add(dw, self.resizable, wx.EXPAND)
            # Check if content is all Group objects:
            elif layout == "fold":
                self.resizable = True
                self.sizer.Add(
                    self.create_fold_for_items(panel, content), 1, wx.EXPAND
                )
            elif isinstance(content[0], Group):
                # If so, add them to the panel and exit:
                self.add_groups(content, panel)
            else:
                self.add_items(content, panel, self.sizer)

        # If the caller is a DockWindow, we need to define the content we are
        # adding to it:
        if is_dock_window:
            self.dock_contents = DockRegion(
                contents=[
                    DockControl(
                        name=group.get_label(self.ui),
                        image=group.image,
                        id=group.get_id(),
                        style=group.dock,
                        dockable=DockableViewElement(ui=ui, element=group),
                        export=group.export,
                        control=panel,
                    )
                ]
            )

    def add_dock_window_splitter_items(self, window, content, group):
        """Adds a set of groups or items separated by splitter bars to a
        DockWindow.
        """
        contents = [
            self.add_dock_window_splitter_item(window, item, group)
            for item in content
        ]

        # Create a splitter group to hold the contents:
        result = DockSection(contents=contents, is_row=self.is_horizontal)

        # If nothing is resizable, then mark each DockControl as such:
        if not self.resizable:
            for item in result.get_controls():
                item.resizable = False

        # Return the DockSection we created:
        return result

    def add_dock_window_splitter_item(self, window, item, group):
        """Adds a single group or item to a DockWindow."""
        if isinstance(item, Group):
            sizer, resizable, contents = fill_panel_for_group(
                window, item, self.ui, suppress_label=True, is_dock_window=True
            )
            self.resizable |= resizable

            return contents

        orientation = wx.VERTICAL
        if self.is_horizontal:
            orientation = wx.HORIZONTAL
        sizer = wx.BoxSizer(orientation)

        panel = TraitsUIPanel(window, -1)
        panel.SetSizer(sizer)

        self.add_items([item], panel, sizer)

        return DockRegion(
            contents=[
                DockControl(
                    name=item.get_label(self.ui),
                    image=item.image,
                    id=item.get_id(),
                    style=item.dock,
                    dockable=DockableViewElement(ui=self.ui, element=item),
                    export=item.export,
                    control=panel,
                )
            ]
        )

    def create_fold_for_items(self, window, content):
        """Adds a set of groups or items as vertical notebook pages to a
        vertical notebook.
        """
        raise NotImplementedError("VFold is not implemented for Wx backend")

    def create_fold_for_item(self, notebook, item):
        """Adds a single group or item to a vertical notebook."""
        # Create a new notebook page:
        page = notebook.create_page()

        # Create the page contents:
        if isinstance(item, Group):
            panel, resizable, contents = fill_panel_for_group(
                page.parent,
                item,
                self.ui,
                suppress_label=True,
                create_panel=True,
            )
        else:
            panel = TraitsUIPanel(page.parent, -1)
            sizer = wx.BoxSizer(wx.VERTICAL)
            panel.SetSizer(sizer)
            self.add_items([item], panel, sizer)

        # Set the page name and control:
        page.name = item.get_label(self.ui)
        page.control = panel

        # Return the new notebook page:
        return page

    def add_notebook_item(self, item, parent, sizer):
        """Adds a single Item to a notebook."""
        self.add_items([item], parent, sizer)

    def add_groups(self, content, panel):
        """Adds a list of Group objects to the panel."""
        sizer = self.sizer

        # Process each group:
        for subgroup in content:
            # Add the sub-group to the panel:
            sg_sizer, sg_resizable, contents = fill_panel_for_group(
                panel, subgroup, self.ui
            )

            # If the sub-group is resizable:
            if sg_resizable:

                # Then so are we:
                self.resizable = True

                # Add the sub-group so that it can be resized by the layout:
                sizer.Add(sg_sizer, 1, wx.EXPAND | wx.ALL, 2)

            else:
                style = wx.EXPAND | wx.ALL
                growable = 0
                if self.is_horizontal:
                    if subgroup.springy:
                        growable = 1
                sizer.Add(sg_sizer, growable, style, 2)

    def _label_when(self):
        """Set the visible and enabled states of all labels as controlled by
        a 'visible_when' or 'enabled_when' expression.
        """
        self._evaluate_label_condition(self._label_enabled_whens, "enabled")
        self._evaluate_label_condition(self._label_visible_whens, "visible")

    def _evaluate_label_condition(self, conditions, kind):
        """Evaluates a list of (eval, widget) pairs and calls the appropriate
        method on the label widget to toggle whether it is visible/enabled
        as needed.
        """
        context = self.ui._get_context(self.ui.context)

        method_dict = {"visible": "Show", "enabled": "Enable"}

        for when, label in conditions:
            method_to_call = getattr(label, method_dict[kind])
            try:
                cond_value = eval(when, globals(), context)
                method_to_call(bool(cond_value))
            except Exception:
                # catch errors in the validate_when expression
                from traitsui.api import raise_to_debug

                raise_to_debug()

    def add_items(self, content, panel, sizer):
        """Adds a list of Item objects to the panel."""
        # Get local references to various objects we need:
        ui = self.ui
        info = ui.info
        handler = ui.handler

        group = self.group
        show_left = group.show_left
        padding = group.padding
        col = -1
        col_incr = 1
        self.label_flags = 0

        self._label_enabled_whens = []
        self._label_visible_whens = []

        show_labels = False
        for item in content:
            show_labels |= item.show_label
        if (not self.is_horizontal) and (show_labels or (group.columns > 1)):
            # For a vertical list of Items with labels or multiple columns, use
            # a 'FlexGridSizer':
            self.label_pad = 0
            cols = group.columns
            if show_labels:
                cols *= 2
                col_incr = 2
            flags = wx.TOP | wx.BOTTOM
            border_size = 1
            item_sizer = wx.FlexGridSizer(0, cols, 0, 5)
            if show_left:
                self.label_flags = wx.ALIGN_RIGHT
                if show_labels:
                    for i in range(1, cols, 2):
                        item_sizer.AddGrowableCol(i)
        else:
            # Otherwise, the current sizer will work as is:
            self.label_pad = 4
            cols = 1
            flags = wx.ALL
            border_size = 1
            item_sizer = sizer

        # Process each Item in the list:
        for item in content:

            # Get the name in order to determine its type:
            name = item.name

            # Check if is a label:
            if name == "":
                label = item.label
                if label != "":
                    # Update the column counter:
                    col += col_incr

                    # If we are building a multi-column layout with labels,
                    # just add space in the next column:
                    if (cols > 1) and show_labels:
                        item_sizer.Add((1, 1))

                    if item.style == "simple":
                        # Add a simple text label:
                        label = wx.StaticText(
                            panel, -1, label, style=wx.ALIGN_LEFT
                        )
                        item_sizer.Add(label, 0, wx.EXPAND)
                    else:
                        # Add the label to the sizer:
                        label = heading_text(panel, text=label).control
                        item_sizer.Add(
                            label, 0, wx.TOP | wx.BOTTOM | wx.EXPAND, 3
                        )

                    if item.emphasized:
                        self._add_emphasis(label)

                    if item.visible_when:
                        self._label_visible_whens.append(
                            (item.visible_when, label)
                        )
                    if item.enabled_when:
                        self._label_enabled_whens.append(
                            (item.enabled_when, label)
                        )

                # Continue on to the next Item in the list:
                continue

            # Update the column counter:
            col += col_incr

            # Check if it is a separator:
            if name == "_":
                for i in range(cols):
                    if self.is_horizontal:
                        # Add a vertical separator:
                        line = wx.StaticLine(panel, -1, style=wx.LI_VERTICAL)
                        item_sizer.Add(
                            line, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 2
                        )
                    else:
                        # Add a horizontal separator:
                        line = wx.StaticLine(panel, -1, style=wx.LI_HORIZONTAL)
                        item_sizer.Add(
                            line, 0, wx.TOP | wx.BOTTOM | wx.EXPAND, 2
                        )
                    self._set_owner(line, item)
                # Continue on to the next Item in the list:
                continue

            # Convert a blank to a 5 pixel spacer:
            if name == " ":
                name = "5"

            # Check if it is a spacer:
            if all_digits.match(name):

                # If so, add the appropriate amount of space to the sizer:
                n = int(name)
                if self.is_horizontal:
                    item_sizer.Add((n, 1))
                else:
                    spacer = (1, n)
                    item_sizer.Add(spacer)
                    if show_labels:
                        item_sizer.Add(spacer)

                # Continue on to the next Item in the list:
                continue

            # Otherwise, it must be a trait Item:
            object = eval(item.object_, globals(), ui.context)
            trait = object.base_trait(name)
            desc = trait.tooltip
            if desc is None:
                desc = "Specifies " + trait.desc if trait.desc else ""

            label = None

            # If we are displaying labels on the left, add the label to the
            # user interface:
            if show_left:
                if item.show_label:
                    label = self.create_label(
                        item,
                        ui,
                        desc,
                        panel,
                        item_sizer,
                        border=group.show_border,
                    )
                elif (cols > 1) and show_labels:
                    label = self.dummy_label(panel, item_sizer)

            # Get the editor factory associated with the Item:
            editor_factory = item.editor
            if editor_factory is None:
                editor_factory = trait.get_editor()

                # If still no editor factory found, use a default text editor:
                if editor_factory is None:
                    from .text_editor import ToolkitEditorFactory

                    editor_factory = ToolkitEditorFactory()

                # If the item has formatting traits set them in the editor
                # factory:
                if item.format_func is not None:
                    editor_factory.format_func = item.format_func

                if item.format_str != "":
                    editor_factory.format_str = item.format_str

                # If the item has an invalid state extended trait name, set it
                # in the editor factory:
                if item.invalid != "":
                    editor_factory.invalid = item.invalid

            # Set up the background image (if used):
            item_panel = panel

            # Create the requested type of editor from the editor factory:
            factory_method = getattr(editor_factory, item.style + "_editor")
            editor = factory_method(
                ui, object, name, item.tooltip, item_panel
            ).trait_set(item=item, object_name=item.object)

            # Tell editor to actually build the editing widget:
            editor.prepare(item_panel)

            # Set the initial 'enabled' state of the editor from the factory:
            editor.enabled = editor_factory.enabled

            # Add emphasis to the editor control if requested:
            if item.emphasized:
                self._add_emphasis(editor.control)

            # Give the editor focus if it requested it:
            if item.has_focus:
                editor.control.SetFocus()

            # Adjust the maximum border size based on the editor's settings:
            border_size = min(border_size, editor.border_size)

            # Set up the reference to the correct 'control' to use in the
            # following section, depending upon whether we have wrapped an
            # ImagePanel around the editor control or not:
            control = editor.control
            width, height = control.GetSize()

            # Set the correct size on the control, as specified by the user:
            scrollable = editor.scrollable
            item_width = item.width
            item_height = item.height
            growable = 0
            if (item_width != -1.0) or (item_height != -1.0):
                if (0.0 < item_width <= 1.0) and self.is_horizontal:
                    growable = int(1000.0 * item_width)
                    item_width = -1

                item_width = int(item_width)
                if item_width < -1:
                    item_width = -item_width
                elif item_width != -1:
                    item_width = max(item_width, width)

                if (0.0 < item_height <= 1.0) and (not self.is_horizontal):
                    growable = int(1000.0 * item_height)
                    item_height = -1

                item_height = int(item_height)
                if item_height < -1:
                    item_height = -item_height
                elif item_height != -1:
                    item_height = max(item_height, height)

                control.SetMinSize(wx.Size(item_width, item_height))

            # Bind the item to the control and all of its children:
            self._set_owner(control, item)

            # Bind the editor into the UIInfo object name space so it can be
            # referred to by a Handler while the user interface is active:
            id = item.id or name
            info.bind(id, editor, item.id)

            # Also, add the editors to the list of editors used to construct
            # the user interface:
            ui._editors.append(editor)

            # If the handler wants to be notified when the editor is created,
            # add it to the list of methods to be called when the UI is
            # complete:
            defined = getattr(handler, id + "_defined", None)
            if defined is not None:
                ui.add_defined(defined)

            # If the editor is conditionally visible, add the visibility
            # 'expression' and the editor to the UI object's list of monitored
            # objects:
            if item.visible_when != "":
                ui.add_visible(item.visible_when, editor)

            # If the editor is conditionally enabled, add the enabling
            # 'expression' and the editor to the UI object's list of monitored
            # objects:
            if item.enabled_when != "":
                ui.add_enabled(item.enabled_when, editor)

            # Add the created editor control to the sizer with the appropriate
            # layout flags and values:
            ui._scrollable |= scrollable
            item_resizable = (item.resizable is True) or (
                (item.resizable is Undefined) and scrollable
            )
            if item_resizable:
                growable = growable or 500
                self.resizable = True
            elif item.springy:
                growable = growable or 500

            # The following is a hack to allow 'readonly' text fields to
            # work correctly (wx has a bug that setting wx.EXPAND on a
            # StaticText control seems to cause the text to be aligned higher
            # than it would be otherwise, causing it to misalign with its
            # label).
            layout_style = editor.layout_style
            if not show_labels:
                layout_style |= wx.EXPAND

            item_sizer.Add(
                control,
                growable,
                flags | layout_style,
                max(0, border_size + padding + item.padding),
            )

            # If we are displaying labels on the right, add the label to the
            # user interface:
            if not show_left:
                if item.show_label:
                    label = self.create_label(
                        item, ui, desc, panel, item_sizer, "", wx.RIGHT
                    )
                elif (cols > 1) and show_labels:
                    label = self.dummy_label(panel, item_sizer)

            # If the Item is resizable, and we are using a multi-column grid:
            if item_resizable and (cols > 1):
                # Mark the entire row as growable:
                item_sizer.AddGrowableRow(col // cols)

            # Save the reference to the label control (if any) in the editor:
            editor.label_control = label

        if (
            len(self._label_enabled_whens) + len(self._label_visible_whens)
        ) > 0:
            for object in self.ui.context.values():
                object.on_trait_change(
                    lambda: self._label_when(), dispatch="ui"
                )

        # If we created a grid sizer, add it to the original sizer:
        if item_sizer is not sizer:
            growable = 0
            if self.resizable:
                growable = 1

            sizer.Add(item_sizer, growable, wx.EXPAND | wx.ALL, 2)

    def create_label(
        self,
        item,
        ui,
        desc,
        parent,
        sizer,
        suffix=":",
        pad_side=wx.LEFT,
        border=False,
    ):
        """Creates an item label."""
        label = item.get_label(ui)
        if (label == "") or (label[-1:] in "?=:;,.<>/\\\"'-+#|"):
            suffix = ""

        control = wx.StaticText(
            parent,
            -1,
            label + suffix,
            style=wx.ALIGN_LEFT | wx.SIMPLE_BORDER if border else wx.NO_BORDER,
        )

        self._set_owner(control, item)

        if item.emphasized:
            self._add_emphasis(control)

        # XXX: Turning off help popups for now
        # control.Bind(wx.EVT_LEFT_UP, show_help_popup)

        control.help = item.get_help(ui)
        control.SetToolTip(wx.ToolTip(item.get_help(ui)))
        sizer.Add(
            control,
            0,
            self.label_flags | wx.ALIGN_TOP | pad_side,
            self.label_pad,
        )

        if desc != "":
            control.SetToolTip(desc)

        return control

    def dummy_label(self, parent, sizer):
        """Creates an item label."""
        control = wx.StaticText(parent, -1, "", style=wx.ALIGN_RIGHT)
        sizer.Add(control, 0)
        return control

    def _add_emphasis(self, control):
        """Adds emphasis to a specified control's font."""
        global emphasis_font

        control.SetForegroundColour(emphasis_color)
        if emphasis_font is None:
            font = control.GetFont()
            emphasis_font = wx.Font(
                font.GetPointSize() + 1,
                font.GetFamily(),
                font.GetStyle(),
                wx.BOLD,
            )
        control.SetFont(emphasis_font)

    def _set_owner(self, control, owner):
        control._owner = owner
        for child in control.GetChildren():
            self._set_owner(child, owner)


class DockWindowGroupEditor(GroupEditor):
    """Editor for a group which displays a DockWindow."""

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

    #: DockWindow for the group
    dock_window = Instance(wx.Window)

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

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

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

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


class HTMLHelpWindow(wx.Frame):
    """Window for displaying Traits-based help text with HTML formatting."""

    def __init__(self, parent, html_content, scale_dx, scale_dy):
        """Initializes the object."""
        wx.Frame.__init__(self, parent, -1, "Help", style=wx.SIMPLE_BORDER)
        self.SetBackgroundColour(WindowColor)

        # Wrap the dialog around the image button panel:
        sizer = wx.BoxSizer(wx.VERTICAL)
        html_control = wh.HtmlWindow(self)
        html_control.SetBorders(2)
        html_control.SetPage(html_content)
        sizer.Add(html_control, 1, wx.EXPAND)
        sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)
        b_sizer = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, -1, "OK")
        self.Bind(wx.EVT_BUTTON, self._on_ok, id=button.GetId())
        b_sizer.Add(button, 0)
        sizer.Add(b_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        self.SetSizer(sizer)
        self.SetSize(
            wx.Size(
                int(scale_dx * SystemMetrics().screen_width),
                int(scale_dy * SystemMetrics().screen_height),
            )
        )

        # Position and show the dialog:
        position_window(self, parent=parent)
        self.Show()

    def _on_ok(self, event):
        """Handles the window being closed."""
        self.Unbind(wx.EVT_BUTTON)
        self.Destroy()


# -------------------------------------------------------------------------
#  Creates a Pyface HeadingText control:
# -------------------------------------------------------------------------

HeadingText = None


def heading_text(*args, create=False, **kw):
    """Create a Pyface HeadingText control."""
    global HeadingText

    if HeadingText is None:
        from pyface.api import HeadingText

    widget = HeadingText(*args, create=create, **kw)
    widget.create()
    return widget