-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_designer_components.py
More file actions
2241 lines (2026 loc) · 80.9 KB
/
class_designer_components.py
File metadata and controls
2241 lines (2026 loc) · 80.9 KB
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
# -*- coding: utf-8 -*-
import os
from dabo import application
from dabo import color_tools
from dabo import events
from dabo import settings
from dabo import ui
from dabo.base_object import dObject
from dabo.lib import utils as libutils
from dabo.lib.DesignerUtils import addSizerDefaults
from dabo.lib.utils import ustr
from dabo.lib.xmltodict import xmltodict
from dabo.localization import _
from dabo.ui import dBorderSizer
from dabo.ui import dBox
from dabo.ui import dColumn
from dabo.ui import dDialog
from dabo.ui import dForm
from dabo.ui import dFormMain
from dabo.ui import dGrid
from dabo.ui import dGridSizer
from dabo.ui import dImage
from dabo.ui import dLabel
from dabo.ui import dMenu
from dabo.ui import dPage
from dabo.ui import dPageFrame
from dabo.ui import dPageFrameNoTabs
from dabo.ui import dPageList
from dabo.ui import dPageSelect
from dabo.ui import dPageStyled
from dabo.ui import dPanel
from dabo.ui import dRadioList
from dabo.ui import dSizer
from dabo.ui import dSizerMixin
from dabo.ui import dSpinner
from dabo.ui import dSplitter
from dabo.ui import dTreeView
from dabo.ui.dialogs import Wizard
from dabo.ui.dialogs import WizardPage
from class_designer_exceptions import PropertyUpdateException
from drag_handle import DragHandle
dabo_module = settings.get_dabo_package()
# Defaults for sizer items
szItemDefaults = {
1: {
"BorderSides": ["All"],
"Proportion": 0,
"HAlign": "Left",
"VAlign": "Top",
"Border": 0,
"Expand": False,
},
2: {
"RowSpan": 1,
"BorderSides": ["All"],
"ColSpan": 1,
"Proportion": 1,
"HAlign": "Left",
"VAlign": "Top",
"Border": 0,
},
}
# This odd attribute name is given to any object that is added
# to a design as a class. We handle them differently; only the
# changes are saved in the design they are added to.
classFlagProp = "_CLASS_PATH_"
class LayoutSaverMixin(dObject):
"""Contains the basic code for generating the dict required
to save the ClassDesigner item's contents.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def getDesignerDict(
self,
itemNum=0,
allProps=False,
classID=None,
classDict=None,
propsToExclude=None,
):
app = self.Controller
ret = {}
if not app:
return ret
if not allProps:
# Can be set globally by the save routine
allProps = app.saveAllProps
# if isinstance(self, dColumn):
# # We need all props for this class.
# allProps = True
ret["attributes"] = ra = {}
isClass = hasattr(self, classFlagProp)
isWiz = isinstance(self, Wizard)
insideClass = isClass or (len(app._classStack) > 0)
if isClass:
clsPath = self.__getattribute__(classFlagProp)
app._classStack.append(clsPath)
if os.path.exists(clsPath):
classDict = xmltodict(open(clsPath).read())
else:
# New file
classDict = {}
if classID is None:
# Use the attribute.
ra["classID"] = self.classID
else:
ra["classID"] = classID
self.classID = classID
else:
if insideClass:
try:
myID = self.classID.split("-")[1]
except (AttributeError, IndexError):
myID = abs(self.__hash__())
if classID is None:
# First-time save. Get the classID of the parent
try:
classID = self.Parent.classID.split("-")[0]
except (IndexError, AttributeError):
# Try the sizer
try:
classID = self.ControllingSizer.classID.split("-")[0]
except (IndexError, AttributeError):
classID = "?????"
ra["classID"] = f"{classID}-{myID}"
self.classID = ra["classID"]
else:
if hasattr(self, "classID"):
ra["classID"] = self.classID
ret["name"] = self.getClass()
ret["cdata"] = ""
if insideClass and classDict:
if hasattr(self, "Form") and self.Form._formMode:
ret["code"] = self.diffClassCode(classDict.get("code", {}))
else:
ret["code"] = self.getCode()
else:
ret["code"] = self.getCode()
defVals = self.Controller.getDefaultValues(self)
if insideClass:
if classDict:
defVals.update(classDict.get("attributes", {}))
if isClass:
clsRef = os.path.abspath(clsPath)
if isinstance(self, (dForm, dFormMain)):
relPath = self._classFile
else:
relPath = self.Form._classFile
if not relPath:
relPath = os.path.split(relPath)[0]
if clsRef == relPath:
rp = clsRef
else:
rp = libutils.relativePath(clsRef, relPath)
ra["designerClass"] = libutils.getPathAttributePrefix() + rp
ra["savedClass"] = True
else:
ra["designerClass"] = self.getClassName()
hasSizer = bool(hasattr(self, "ControllingSizerItem") and self.ControllingSizerItem)
# We want to include some props whether they are the
# default or not.
if insideClass:
propsToInclude = ("classID", "SlotCount")
else:
propsToInclude = (
"Caption",
"Choices",
"ColumnCount",
"Orientation",
"PageCount",
"SashPosition",
"ScaleMode",
"SlotCount",
"Split",
)
# We want to exclude some props, since they are derived from
# other props or are settable via other props (fonts).
if propsToExclude is None:
propsToExclude = tuple()
elif isinstance(propsToExclude, list):
propsToExclude = tuple(propsToExclude)
propsToExclude += ("Right", "Bottom", "Font", "HeaderFont")
isSplitPanel = isinstance(self, dPanel) and isinstance(self.Parent, dSplitter)
desProps = list(self.DesignerProps.keys())
if isinstance(self, (dForm, dFormMain)) and hasattr(self, "UseSizers"):
desProps += ["UseSizers"]
elif isinstance(self, self.Controller.pagedControls) and isinstance(self.PageClass, str):
desProps += ["PageClass"]
elif isinstance(self, Wizard):
desProps += ["PageCount"]
for prop in desProps:
if prop.startswith("Sizer_"):
continue
if prop in propsToExclude:
continue
if (hasSizer or isinstance(self, dPage) or isSplitPanel) and prop in (
"Left",
"Right",
"Top",
"Bottom",
): # , "Width", "Height"
##"Right", "Top", "Bottom", "Width", "Height"):
## Note: there may be additional cases where we might have to fine-tune
## which if these parameters are skipped/included.
continue
try:
csz = self.ControllingSizer
except AttributeError:
csz = None
if (
(hasSizer or isinstance(self, dPage) or isSplitPanel)
and prop in ("Width", "Height")
and ((csz is not None) and csz.getItemProp(self, "Expand"))
):
continue
if isinstance(self, dLabel) and prop in ("Width", "Height") and csz is not None:
# If the width/height is controlled by the sizer, don't save it.
szornt = csz.Orientation
exp = csz.getItemProp(self, "Expand")
prptn = csz.getItemProp(self, "Proportion")
if szornt == "Horizontal":
if (prop == "Width") and (prptn > 0):
continue
elif (prop == "Height") and exp:
continue
elif szornt == "Vertical":
if (prop == "Width") and exp:
continue
elif (prop == "Height") and (prptn > 0):
continue
# Don't copy the size if AutoSize=True and the width is close to the default size.
if self.AutoResize:
defWd, defHt = ui.fontMetric(wind=self)
isDefaultSize = False
if prop == "Width":
isDefaultSize = abs(self.Width - defWd) <= 1
elif prop == "Height":
isDefaultSize = abs(self.Height - defHt) <= 1
if isDefaultSize:
# ignore it
continue
if prop == "BackColor" and isinstance(self, (LayoutPanel, LayoutSpacerPanel)):
continue
if isinstance(self, dImage) and (prop == "Value") and self.Picture:
# Don't save the byte stream if there is an image path
continue
if hasattr(self, prop):
val = eval(f"self.{prop}")
else:
# Custom-defined property; that's saved elsewhere
continue
if prop == "RegID" and (not val or not str(val).isidentifier()):
continue
# Convert any paths, but ignore the string properties that may
# accidentally contain a legal path but which do not represent paths.
if not prop in (
"Alignment",
"Caption",
"CxnName",
"DataField",
"DataSource",
"FontFace",
"HAlign",
"Name",
"RegID",
"SelectionMode",
"ToolTipText",
"VAlign",
"Value",
) and (
not prop.startswith("Border")
and not prop.startswith("Header")
and not prop.startswith("Sizer_")
):
if isinstance(val, str) and os.path.exists(val):
# It's a path; convert it to a relative path
if isinstance(self, (dForm, dFormMain, dDialog)):
ref = self._classFile
else:
ref = self.Form._classFile
ref = os.path.abspath(ref)
if not os.path.isdir(ref):
# Can't test for 'isfile' since the file may not have been saved yet.
ref = os.path.split(ref)[0]
val = os.path.join(
libutils.getPathAttributePrefix(),
libutils.relativePath(val, ref),
)
# If it hasn't changed from the default, skip it
if not allProps:
try:
defVals[prop]
except KeyError:
continue
if prop not in propsToInclude:
dv = defVals[prop]
if not isinstance(val, str) and isinstance(dv, str):
# Try to convert
if isinstance(val, bool):
dv = dv.lower() == "true"
elif isinstance(val, int):
dv = int(dv)
elif isinstance(val, int):
dv = int(dv)
elif isinstance(val, float):
dv = float(dv)
elif dv in dColors.colors:
dv = dColors.colorDict[dv]
elif isinstance(val, (list, tuple, dict)):
dv = eval(dv)
elif dv == "None":
dv = None
if dv == val:
continue
if isinstance(val, str):
strval = val
else:
strval = str(val)
ra[prop] = strval
# Add the controlling sizer item properties, if applicable
try:
itmProps = self.ControllingSizer.getItemProps(self.ControllingSizerItem)
if insideClass:
itmDiffProps = self._diffSizerItemProps(itmProps, classDict, direct=True)
else:
itmDiffProps = self._diffSizerItemProps(itmProps, self.ControllingSizer)
ret["attributes"]["sizerInfo"] = itmDiffProps
except AttributeError:
# Not controlled by a sizer.
pass
propDefs = self.getPropDefs()
if propDefs:
ret["properties"] = propDefs
# Add the child objects. This will vary depending on the
# class of the item
ret["children"] = self.getChildrenPropDict(classDict)
if isClass:
# Remove this class from the processing stack
app._classStack.pop()
return ret
def _diffSizerItemProps(self, dct, szOrDict, direct=False):
"""Remove all of the default values from the sizer item props."""
if direct:
defaults = szOrDict
else:
# First, what type of sizer is it?
try:
cls = self.superControl
except AttributeError:
cls = self.__class__
if isinstance(szOrDict, dGridSizer):
typ = "G"
else:
typ = szOrDict.Orientation.upper()[0]
defaults = self.Controller.getDefaultSizerProps(cls, typ).copy()
if isinstance(self, LayoutPanel) and not isinstance(self, LayoutSpacerPanel):
defaults["Expand"] = True
defaults["Proportion"] = 1
for key, val in list(dct.items()):
if val == defaults.get(key, None):
dct.pop(key)
return dct
def diffClassCode(self, clsCode):
"""See what code, if any, has been changed between the code
in the defined class and the current object.
"""
ret = {}
currCode = self.getCode()
if currCode and (currCode != clsCode):
# Need to find all changed methods
for mthd, cd in list(currCode.items()):
clscd = clsCode.get(mthd, "")
if cd != clscd:
ret[mthd] = cd
# See if there are any cleared methods
if list(clsCode.keys()) != list(currCode.keys()):
currK = list(currCode.keys())
for clsK in list(clsCode.keys()):
if clsK not in currK:
ret[clsK] = ""
return ret
def getCode(self):
"""Return the code for the object in a method:code
dictionary.
"""
ret = {}
objCode = self.Controller.getCodeForObject(self)
if objCode is not None:
# Check for empty methods
emptyKeys = [kk for kk, vv in list(objCode.items()) if not vv]
for emp in emptyKeys:
del objCode[emp]
ret.update(objCode)
return ret
def getPropDefs(self):
"""Get a dict containing any defined properties for this object."""
ret = self.Controller.getPropDictForObject(self)
# if ret:
# # Need to escape any single quotes in the comments
# sqt = "'"
# sqtReplacement = r"\'"
# for prop, settings in ret.items():
# if sqt in settings["comment"]:
# settings["comment"] = settings["comment"].replace(sqt, sqtReplacement)
return ret
def serialName(self, nm, numItems=0):
"""Prepends a three-digit string to the beginning
of the passed string. This string starts at '000', and
is incremented for each object listed in the 'keys'
list. This enables us to maintain object order within
a dictionary, which is otherwise unordered.
"""
return f"d{strl(numItems).zfill(3)}{nm}"
def getChildrenPropDict(self, clsChildren=None):
"""Iterate through the children. For controls, this will
go through the containership hierarchy. Sizers will have
to override this method. If this is being called inside of a
class definition, 'clsChildren' will be a dict containing the
saved class definition for the child objects.
"""
ret = []
try:
kids = self.zChildren
except AttributeError:
# Use the normal Children prop
try:
if isinstance(self, dTreeView):
kids = self.BaseNodes
else:
kids = self.Children
if isinstance(kids, property):
print(f"fget patch hit: {self} at class_designer_components.py:456")
kids = kids.fget(self)
except AttributeError:
# Object does not have a Children prop
return ret
# Are we inside a class definition?
insideClass = clsChildren is not None
if insideClass:
childDict = clsChildren.get("children", [])
if isinstance(self, (dPageFrame, dPageList, dPageSelect, dPageStyled, dPageFrameNoTabs)):
nonSizerKids = kids
elif isinstance(self, dGrid):
# Grid children are Columns
nonSizerKids = self.Columns
elif isinstance(self, dSplitter):
nonSizerKids = [self.Panel1, self.Panel2]
elif isinstance(self, Wizard):
nonSizerKids = self._pages
elif isinstance(self, (dForm, dFormMain)) and not self.UseSizers:
nonSizerKids = kids
elif isinstance(self, (dRadioList, dSpinner)):
nonSizerKids = []
else:
nonSizerKids = [
kk
for kk in kids
if not hasattr(kk, "ControllingSizerItem") or kk.ControllingSizerItem is None
]
for kid in nonSizerKids:
numItems = len(ret)
if isinstance(kid, (dForm, dFormMain)):
# This is a child window; most likely part of the
# ClassDesigner interface, but certainly not part of
# the class defintion. Sklp it!
continue
if not hasattr(kid, "getDesignerDict"):
# This is some non-ClassDesigner control, such as a
# Status Bar, that we don't need to save
continue
# If we are inside of a class defintion, we need to
# get the dict specific to this child. If it has a classID,
# we can find the matching entry in our child dict.
# Otherwise, we have to assume that it is a new object
# added to the class.
kidDict = None
if insideClass:
try:
kidID = kid.classID
try:
kidDict = [cd for cd in childDict if cd["attributes"]["classID"] == kidID][
0
]
except Exception as e:
kidDict = {}
except AttributeError:
kidDict = {}
ret.append(kid.getDesignerDict(itemNum=numItems, classDict=kidDict))
if isinstance(self, Wizard):
# All the children have been processed
return ret
if hasattr(self, "_superBase"):
if isinstance(self, WizardPage):
sz = self.Sizer
else:
try:
sz = self.mainPanel.Sizer
except AttributeError:
sz = None
else:
if isinstance(self, dPageFrameNoTabs):
sz = None
else:
if isinstance(
self,
(
dRadioList,
dSpinner,
dPageSelect,
dPageStyled,
dColumn,
dTreeView.getBaseNodeClass(),
),
):
sz = None
else:
try:
sz = self.Sizer
except AttributeError:
dabo_module.error(_("No sizer information available for %s") % self)
sz = None
if sz:
szDict = None
if insideClass:
try:
szID = sz.classID
try:
szDict = [cd for cd in childDict if cd["attributes"]["classID"] == szID][0]
except Exception as e:
szDict = {}
except AttributeError:
szDict = {}
ret.append(sz.getDesignerDict(itemNum=len(ret), classDict=szDict))
return ret
def getClass(self):
"""Return a string representing the item's class. Can
be overridden by subclasses.
"""
return ustr(self.BaseClass).split("'")[1].split(".")[-1]
def getClassName(self):
"""Return a string representing the item's class name. Can
be overridden by subclasses.
"""
return ustr(self.__class__).split("'")[1].split(".")[-1]
class LayoutPanel(dPanel, LayoutSaverMixin):
"""Panel used to display empty sizer slots."""
def __init__(self, parent, properties=None, *args, **kwargs):
self._autoSizer = self._extractKey(kwargs, "AutoSizer", True)
kwargs["Size"] = (20, 20)
super().__init__(parent, properties, *args, **kwargs)
# Let the framework know that this is just a placeholder object
self._placeholder = True
# Store the defaults for the various props
self._propDefaults = {}
self._defaultSizerProps = {}
for prop in list(self.DesignerProps.keys()):
self._propDefaults[prop] = eval(f"self.{prop}")
def afterInit(self):
self.depth = self.crawlUp(self)
plat = self.Application.Platform
if plat == "Win":
self.normalColor = "cornsilk"
else:
self.normalColor = "azure"
self.normalBorder = self.BorderColor = "darkgrey"
self.hiliteColor = "white"
self.hiliteBorder = "gold"
self.BackColor = self.normalBorder
self._selected = False
self.Selected = False
self._innerPanel = dPanel(self, BackColor=self.normalColor, _EventTarget=self)
self.Sizer = dSizer("v")
self.Sizer.append1x(self._innerPanel, border=1)
# Make sure the panel allows full resizing
self.AlwaysResetSizer = True
# Windows has a problem with auto-clearing
### NOTE: seems to not flicker as much with this commented out (at least on Mac).
# self.autoClearDrawings = (plat != "Win")
if self._autoSizer:
if isinstance(self.Parent.Sizer, dSizer):
self.Parent.Sizer.append1x(self)
szi = self.ControllingSizerItem
ornt = "v"
prntSz = self.ControllingSizer
if prntSz is not None:
if prntSz.Orientation[:1].lower() == "v":
ornt = "h"
else:
ornt = "v"
# Store the initial defaults
ui.callAfter(self._setDefaultSizerProps)
def getChildrenPropDict(self, clsChildren=None):
"""LayoutPanels cannot have children."""
return []
def _setDefaultSizerProps(self):
if not self:
return
try:
self._defaultSizerProps = self.ControllingSizer.getItemProps(self)
except AttributeError:
self._defaultSizerProps = {}
def getDesignerDict(
self,
itemNum=0,
allProps=False,
classID=None,
classDict=None,
propsToExclude=None,
):
# Augment the default to add non-Property values
ret = super().getDesignerDict(
itemNum, allProps=allProps, classID=classID, classDict=classDict
)
if self.ControllingSizer:
itmProps = self.ControllingSizer.getItemProps(self.ControllingSizerItem)
itmDiffProps = self._diffSizerItemProps(itmProps, self.ControllingSizer)
else:
itmDiffProps = {}
ret["attributes"]["sizerInfo"] = itmDiffProps
return ret
def setMouseHandling(self, turnOn):
"""When turnOn is True, sets all the mouse event bindings. When
it is False, removes the bindings.
"""
if turnOn:
self.bindEvent(events.MouseMove, self.handleMouseMove)
else:
self.unbindEvent(events.MouseMove)
def handleMouseMove(self, evt):
if evt.dragging:
# Need to change the cursor
# Let the form know
self.Form.onMouseDrag(evt)
else:
self.Form.DragObject = None
def onMouseLeftUp(self, evt):
self.Form.processLeftUp(self, evt)
evt.stop()
def onMouseLeftClick(self, evt):
evt.stop()
def onMouseLeftDown(self, evt):
evt.stop()
def onSelect(self, evt):
print("PANEL ON SELECT")
def onContextMenu(self, evt):
if isinstance(self.Parent, dPage):
self.Parent.activePanel = self
pop = self.createContextMenu()
ui.callAfter(self.showContextMenu, pop)
evt.stop()
def createContextMenu(self):
pop = self.Controller.getControlMenu(self)
if isinstance(self.Parent, (dPage, dPanel)):
if not self.Parent is self.Form.mainPanel:
if len(self.Parent.Children) == 1:
sepAdded = False
if isinstance(self.Parent, dPage):
# Add option to delete the entire pageframe
pop.prependSeparator()
sepAdded = True
pop.prepend(
_("Delete the entire Paged Control"),
OnHit=self.onDeleteGrandParent,
)
prmpt = _("Delete this Page")
elif isinstance(self.Parent, dPanel):
prmpt = _("Delete this Panel")
# This is the only item
if not sepAdded:
pop.prependSeparator()
pop.prepend(prmpt, OnHit=self.onDeleteParent)
if self.Controller.Clipboard:
pop.prependSeparator()
pop.prepend(_("Paste"), OnHit=self.onPaste)
if not isinstance(self.ControllingSizer, LayoutGridSizer):
pop.append(_("Delete this Slot"), OnHit=self.onDelete)
self.Controller.addSlotOptions(self, pop, sepBefore=True)
# Add the Sizer editing option
pop.appendSeparator()
pop.append(_("Edit Sizer Settings"), OnHit=self.onEditSizer)
pop.appendSeparator()
pop.append(_("Add Controls from Data Environment"), OnHit=self.Form.onRunLayoutWiz)
return pop
def onEditSizer(self, evt):
"""Called when the user selects the context menu option
to edit this slot's sizer information.
"""
self.Controller.editSizerSettings(self)
def onCut(self, evt):
"""Place a copy of this control on the Controller clipboard,
and then delete the control
"""
self.Controller.copyObject(self)
self.onDelete(evt)
def onCopy(self, evt):
"""Place a copy of this control on the Controller clipboard"""
self.Controller.copyObject(self)
def onPaste(self, evt):
self.Controller.pasteObject(self)
def onDeleteParent(self, evt):
"""Called when this panel is the only object on its parent."""
self.Parent.onDelete(evt)
def onDeleteGrandParent(self, evt):
"""Called when the user wants to delete the control that contains
the page that this panel is on.
"""
self.Parent.Parent.onDelete(evt)
def onDelete(self, evt):
"""This is called when the user wants to remove the slot
represented by this panel. This is only allowed for
box-type sizers, not grid sizers.
"""
csz = self.ControllingSizer
if csz and isinstance(csz, LayoutSizerMixin):
csz.delete(self, refill=False)
def crawlUp(self, obj, lev=0):
pp = obj.Parent
if pp is None or (pp is self.Form):
return lev
else:
if isinstance(pp, LayoutPanel):
lev += 1
ret = self.crawlUp(pp, lev)
return ret
@property
def Controller(self):
"""Object to which this one reports events (object (varies))"""
try:
return self._controller
except AttributeError:
self._controller = self.Application
return self._controller
@Controller.setter
def Controller(self, val):
if self._constructed():
self._controller = val
else:
self._properties["Controller"] = val
@property
def DesignerEvents(self):
"""
Returns a list of the most common events for the control. This will determine which events
are displayed in the PropSheet for the developer to attach code to. (list)
"""
return []
@property
def DesignerProps(self):
"""
Returns a dict of editable properties for the sizer, with the prop names as the keys, and
the value for each another dict, containing the following keys: 'type', which controls how
to display and edit the property, and 'readonly', which will prevent editing when True.
(dict)
"""
return {
"BackColor": {"type": "color", "readonly": False},
"Visible": {"type": bool, "readonly": False},
}
@property
def Selected(self):
"""Denotes if this panel is selected for user interaction. (bool)"""
return self._selected
@Selected.setter
def Selected(self, val):
if self._selected != val:
if val:
self._innerPanel.BackColor = self.hiliteColor
self.BackColor = self.hiliteBorder
else:
self._innerPanel.BackColor = self.normalColor
self.BackColor = self.normalBorder
self._selected = val
@property
def Sizer_Border(self):
"""Border setting of controlling sizer item (int)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "Border")
@Sizer_Border.setter
def Sizer_Border(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "Border", val)
@property
def Sizer_BorderSides(self):
"""To which sides is the border applied? (default=All (str)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "BorderSides")
@Sizer_BorderSides.setter
def Sizer_BorderSides(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "BorderSides", val)
@property
def Sizer_Expand(self):
"""Expand setting of controlling sizer item (bool)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "Expand")
@Sizer_Expand.setter
def Sizer_Expand(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "Expand", val)
@property
def Sizer_ColExpand(self):
"""Column Expand setting of controlling grid sizer item (bool)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "ColExpand")
@Sizer_ColExpand.setter
def Sizer_ColExpand(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "ColExpand", val)
@property
def Sizer_ColSpan(self):
"""Column Span setting of controlling grid sizer item (int)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "ColSpan")
@Sizer_ColSpan.setter
def Sizer_ColSpan(self, val):
if val == libutils.get_super_property_value():
return
cs = self.ControllingSizer
try:
cs.setItemProp(self, "ColSpan", val)
except ui.GridSizerSpanException as e:
raise PropertyUpdateException(ustr(e))
@property
def Sizer_RowExpand(self):
"""Row Expand setting of controlling grid sizer item (bool)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "RowExpand")
@Sizer_RowExpand.setter
def Sizer_RowExpand(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "RowExpand", val)
@property
def Sizer_RowSpan(self):
"""Row Span setting of controlling grid sizer item (int)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "RowSpan")
@Sizer_RowSpan.setter
def Sizer_RowSpan(self, val):
if val == libutils.get_super_property_value():
return
cs = self.ControllingSizer
try:
cs.setItemProp(self, "RowSpan", val)
except ui.GridSizerSpanException as e:
raise PropertyUpdateException(ustr(e))
@property
def Sizer_Proportion(self):
"""Proportion setting of controlling sizer item (int)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "Proportion")
@Sizer_Proportion.setter
def Sizer_Proportion(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "Proportion", val)
@property
def Sizer_HAlign(self):
"""Horiz. Alignment setting of controlling sizer item (choice)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "Halign")
@Sizer_HAlign.setter
def Sizer_HAlign(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "Halign", val)
@property
def Sizer_VAlign(self):
"""Vert. Alignment setting of controlling sizer item (choice)"""
return self.ControllingSizer.getItemProp(self.ControllingSizerItem, "Valign")
@Sizer_VAlign.setter
def Sizer_VAlign(self, val):
self.ControllingSizer.setItemProp(self.ControllingSizerItem, "Valign", val)
class LayoutSpacerPanel(LayoutPanel):
def __init__(self, parent, properties=None, orient=None, inGrid=False, *args, **kwargs):
kwargs["AutoSizer"] = False
self._spacing = 10
self._orient = orient
self._inGrid = inGrid
super().__init__(parent, properties=properties, *args, **kwargs)
def afterInit(self):
super().afterInit()
self.AlwaysResetSizer = False
self.Size = self.SpacingSize
# Change these to make them different than LayoutPanels
self.normalColor = "antiquewhite"
self._innerPanel.BackColor = self.normalColor
self.normalBorder = "black"
self.hiliteColor = "white"
self.BackColor = self.normalBorder
# Set up sizer defaults
addSizerDefaults(
{
self.__class__: {
"G": {
"BorderSides": ["All"],
"Proportion": 0,
"HAlign": "Center",
"VAlign": "Middle",
"Border": 70,
"Expand": False,
"RowExpand": False,
"ColExpand": False,
},
"H": {
"BorderSides": ["All"],
"Proportion": 0,
"HAlign": "Left",
"VAlign": "Middle",
"Border": 80,
"Expand": False,
},
"V": {
"BorderSides": ["All"],
"Proportion": 0,
"HAlign": "Center",
"VAlign": "Top",
"Border": 90,
"Expand": False,
},
}
}
)
def onContextMenu(self, evt):
if isinstance(self.Parent, dPage):
self.Parent.activePanel = self
pop = dMenu()
pop.prepend(_("Delete"), OnHit=self.onDelete)
pop.prepend(_("Copy"), OnHit=self.onCopy)
pop.prepend(_("Cut"), OnHit=self.onCut)
self.Controller.addSlotOptions(self, pop, sepBefore=True)
# Add the Sizer editing option
pop.appendSeparator()
pop.append(_("Edit Sizer Settings"), OnHit=self.onEditSizer)
ui.callAfter(self.showContextMenu, pop)