forked from wxGlade/wxGlade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_properties.py
3504 lines (3013 loc) · 142 KB
/
new_properties.py
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
"""Classes to handle the various properties of the widgets (name, size, colour, etc.)
File has been created in 2016; parts are from the old version of widget_properties.py:
@copyright: 2002-2007 Alberto Griggio, 2012-2016 Carsten Grohmann
Interface to owner modified; see below for class PropertyOwner
@copyright: 2016-2021 Dietmar Schwertberger
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import common, config, compat, logging, misc
from collections import OrderedDict
import re, os
import wx
if wx.Platform != '__WXMSW__':
import wx.lib.stattext
class _DefaultArgument(object):
def __bool__(self):
return False
def __nonzero__(self):
return False
_DefaultArgument = _DefaultArgument()
# some building blocks for regular expressions:
_leading = r"^\s*\(?\s*" # whitespace, optionally including an opening "("
_int = r"(0|(?:-?[1-9]\d*))" # a number group matching any integer
_ge_m1 = r"((?:-1)|(?:\d+))" # a number group matching integers >=-1
_g_0 = r"([1-9]\d*)" # a number group matching integers >0
_ge_0 = r"(\d+)" # a number group matching integers >=0
_comma = r"\s*,\s*" # a comma, optionally with surrounding whitespace
_trailing = r"\s*\)?\s*$" # whitespace, optionally including a closing ")"
_float = r"([+-]?\d*(?:\.\d*))" # a number group matching a float
# track current property and allow flushing it before saving
current_property = None
def set_current_property(prop):
'called e.g. when focus is set to a property'
global current_property
current_property = prop
def flush_current_property():
'called before a file is saved or code is generated'
if not current_property or not current_property.editing: return
current_property.flush()
misc.flush_functions.append(flush_current_property)
class Property(object):
"Base class for property editors"
deactivated = None # None: can not be deactivated; otherwise bool value
auto_activated = False # if True, it can be deactivated, but not by the user
readonly = False
TOOLTIP = None
LABEL = None # defaults to property name
CONTROLNAMES = ["enabler"] # for activation; also these attributes will be set to None when the editor is destroyed
GROW = False # if this is True, no spacer is added after the control, so it may grow down to the lower edge
HAS_DATA = True
min_version = None # can be overwritten in instances; currently only used by BitmapProperty
_error = _warning = None # used by TextProperty and derived classes
def __init__(self, value, default_value=_DefaultArgument, name=None):#, write_always=False):
self.value = value
self.previous_value = None # only set during call of self.owner.properties_changed
# when the property is assigned to an instance property, these will be set:
self.owner = None
self.name = name
self.attributename = None
# this can be set to True by the owner, depending on another property value; value will still be written to XML
self.blocked = False
self.default_value = default_value
self.controls = None
self.editing = False
def set_owner(self, owner, attributename=None):
self.owner = owner
self.attributename = attributename
if self.name is None: self.name = attributename
####################################################################################################################
# the interface from owner and application
def get(self):
"get the value, or the default value if deactivated; usually not used directly, as owner.property will call it"
if not self.deactivated:
return self.value
return self.default_value
get_value = get # XXX remove again?
def _set_converter(self, value):
return value
def set(self, value, activate=None, deactivate=None, notify=False):
"""set the value of the property (note that the property need not be active)
updates display if editor is visible; doesn't notify owner or application!
optionally, the property will be activated or deactivated"""
self.value = self._set_converter(value)
if activate is None and deactivate is None:
self.update_display()
if notify: self._notify()
return
if activate and self.deactivated:
self.set_active(True) # set active will call update_display
elif deactivate and not self.deactivated:
self.set_active(False)
else:
self.update_display()
if notify: self._notify()
def set_temp(self, value):
# set e.g. to a temporary class name during preview; restored in CodeWriter.clean_up()
if value==self.value: return
if not hasattr(self.owner, "_restore_data"): self.owner._restore_data ={}
if not self.name in self.owner._restore_data:
self.owner._restore_data[self.name] = self.value
self.value = value
def load(self, value, activate=None, deactivate=None, notify=False):
# called from xml_parse ... add_property(self, name, val)
# a derived class like TextProperty may implement a load method, e.g. to unescape strings
# (this should actually handled by xml_parse itself, but this might have side effects)
self.set(value, activate, deactivate, notify)
self.previous_value = None
def set_default(self, default_value):
default_value = self._set_converter(default_value)
if default_value==self.default_value: return
self.default_value = default_value
if self.is_active(): return
self.value = default_value
self.update_display()
def is_active(self):
"check whether property is not deactivated"
return not self.deactivated
def set_active(self, active=True):
"activates or deactivates the property; updates display if editor is visible; doesn't notify owner or application!"
#assert self.default_value is not _DefaultArgument
if active and not self.deactivated: return
if not active and self.deactivated: return
self.deactivated = not active
self.update_display()
self.activate_controls()
def set_blocked(self, block=True):
if block and self.blocked: return
if not block and not self.blocked: return
self.blocked = block
self.activate_controls()
####################################################################################################################
# internal interface from the editor controls
def on_value_edited(self, value, active=None):
"""called from self when the user has entered a new value or de-/activated the property
controls need not to be set, but the owner needs to be notified and the application"""
common.history.property_changing(self)
if active is not None and self.deactivated is not None:
self.deactivated = not active
self.previous_value = self.value # this does not work always, e.g. for GridProperty which may edit in place
self.set(value)
self._notify()
common.history.property_changed(self)
self.previous_value = None
def _check_for_user_modification(self, new_value, force=False, activate=False):
# force: set to True when e.g. called from self.toggle_activate
if new_value == self.value:
if activate and not self.deactivated: activate = False
if not force and not activate:
return False
if not self.owner.check_property_modification(self.name, self.value, new_value):
if self.editing:
self.update_display()
return False
self.on_value_edited(new_value, activate or force or None)
if (activate or force) and self.deactivated is not None:
self.activate_controls()
return True
def _notify(self):
common.root.saved = False
self.owner.properties_changed([self.name])
def toggle_active(self, active=None, refresh=True):
"Toggle the activation state"
# active is not given when refreshing target and enabler
if active != self.deactivated: return
for controlname in self.CONTROLNAMES:
if controlname=="enabler": continue
control = getattr(self, controlname, None)
if control is None: continue
control.Enable(active)
self.on_value_edited(self.value, active)
self.activate_controls()
####################################################################################################################
# XML file
def get_string_value(self):
if self.value is True: return '1'
if self.value is False: return '0'
return str(self.value)
def write(self, output, tabs=0):
"""Writes the xml code for this property onto the given file or file-like object.
Argument tabs (int) is the indentation level.
This is the default implementation."""
if not self.is_active():
return
if self.default_value is wx.NullColour: # workaround for wxPython Phoenix bug 404
if self.value is self.default_value:
return
elif self.default_value is not _DefaultArgument and self.value==self.default_value:
#if self.default_value is not _DefaultArgument and self.value==self.default_value:
# value is the default value -> not to be written
return
if self.value is None or isinstance(self.value, compat.basestring) and not self.value:
# value is empty string
return
# get the value as string
string_getter = getattr(self.owner, "get_%s_string"%self.attributename, None)
if string_getter:
value = string_getter()
if not value: return
else:
value = self.get_string_value()
# write the value
output.extend( common.format_xml_tag(self.name, value, tabs) )
####################################################################################################################
# editor (controls are added to common.property_panel)
def create_editor(self, panel, sizer):
# when done, call self.update_display(start_editing=True)
return None # default implementation: no editor (hidden property, not user editable)
def destroy_editor(self):
# delete e.g. references to controls
for att in self.CONTROLNAMES:
setattr(self, att, None)
self.editing = False
def update_display(self, start_editing=False):
# when the value has changed
# if start_editing: self.editing = True
# if not self.editing or not self...: return
pass
def activate_controls(self):
"enable/disable controls; if the property can be enabled/disabled, also set the checkbox"
if not self.editing: return
if self.blocked:
active = False
else:
active = not self.deactivated
for controlname in self.CONTROLNAMES:
if controlname=="enabler": continue
control = getattr(self, controlname, None)
if not control: continue
if isinstance(control, (tuple,list)):
for c in control:
if c: c.Enable(active)
else:
control.Enable(active)
if "enabler" in self.CONTROLNAMES and self.enabler is not None:
self.enabler.Enable(not self.blocked)
self.enabler.SetValue(not self.deactivated)
def has_control(self, control):
"check whether control belongs to this property (e.g. for dropping onto property"
for controlname in self.CONTROLNAMES:
c = getattr(self, controlname, None)
if c is None: continue
if c is control: return True
# if hasattr(self, "label") and c is self.label: return True# this doesn't work f. wx.lib.stattext.GenStaticText
return False
# editor helpers
def _get_label(self, label, panel, name=None):
width, height = panel.GetTextExtent(label)
width = max(width, config.label_width)
if wx.Platform == '__WXMSW__':
if name is not None:
return wx.StaticText( panel, -1, label, size=(width,height), name=name )
return wx.StaticText( panel, -1, label, size=(width,height) )
return wx.lib.stattext.GenStaticText( panel, -1, label, size=(width,height) )
def on_focus(self, event=None):
global current_property
current_property = self
if event is not None:
event.Skip()
def flush(self):
pass
def set_focus(self):
pass
####################################################################################################################
# helpers
def _mangle(self, label):
"Returns a mangled version of label, suitable for displaying the name of a property"
return misc.wxstr(misc.capitalize(label).replace('_', ' '))
def _find_label(self):
"check self.LABEL; then go through base classes and check the _PROPERTY_LABELS dictionaries"
if self.LABEL: return self.LABEL
import inspect
classes = inspect.getmro(self.owner.__class__)
for cls in classes:
if not hasattr(cls, "_PROPERTY_LABELS"): continue
if self.name in cls._PROPERTY_LABELS:
return cls._PROPERTY_LABELS[self.name]
return self._mangle(self.name)
def _find_tooltip(self):
"go through base classes and check the _PROPERTY_HELP dictionaries"
if self.TOOLTIP: return self.TOOLTIP
ret = []
if self._error: ret.extend( [self._error, ""] )
if self._warning: ret.extend( [self._warning, ""] )
import inspect
classes = inspect.getmro(self.owner.__class__)
for cls in classes:
if hasattr(cls, "_PROPERTY_HELP") and self.name in cls._PROPERTY_HELP:
ret.append( cls._PROPERTY_HELP[self.name] )
break
if self.min_version:
min_version_s = ".".join( (str(v) for v in self.min_version) )
min_version_s = "This property is only supported on wx %s or later."%min_version_s
ret.extend( ["", min_version_s] )
return "\n".join(ret) or None
def _set_tooltip(self, *controls):
tooltip = self._find_tooltip()
if not tooltip: return
for c in controls:
if not c: continue
if not c.GetToolTip():
compat.SetToolTip(c, tooltip)
if self.min_version and isinstance(c, wx.TextCtrl):
c.SetForegroundColour(wx.BLUE)
# these classes are not really used, as they don't have an editor:
class PropertyA(Property):
# can be activated/deactivated; active by default
deactivated = False
class PropertyD(Property):
# can be activated/deactivated; deactivated by default
deactivated = True
class PropertyRO(Property):
# can be activated/deactivated; deactivated by default
readonly = True
class SpinProperty(Property):
# int
CONTROLNAMES = ["enabler", "spin"]
def __init__(self, value, val_range=(0,1000), immediate=False, default_value=_DefaultArgument, name=None):
# val_range: (min_value,max_value)
if isinstance(val_range, (int,float)): # we allow val_range to be supplied as integer
if val_range<0 and value>=0: # typically val_range is len(choices)-1 for empty choices
value = val_range
val_range = (val_range,val_range)
elif val_range>=0:
val_range = (0,val_range)
else:
val_range = (val_range,0)
self.val_range = val_range
self.immediate = immediate
Property.__init__(self, value, default_value, name)
def _set_converter(self, value):
return int(value)
def create_spin_ctrl(self, panel):
style = wx.TE_PROCESS_ENTER | wx.SP_ARROW_KEYS
spin = wx.SpinCtrl( panel, -1, style=style, min=self.val_range[0], max=self.val_range[1] )
val = self.value
if not val: spin.SetValue(1) # needed for GTK to display a '0'
spin.SetValue(val)
spin.SetSelection(-1,-1)
return spin
def create_editor(self, panel, sizer):
if self.val_range is None:
self.val_range = (0, 1000)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
# label
label_text = self._find_label()
label = self.label_ctrl = self._get_label(label_text, panel)
hsizer.Add(label, 0, wx.ALL | wx.ALIGN_CENTER, 3)
# checkbox, if applicable
self.enabler = None
if self.deactivated is not None:
self.enabler = wx.CheckBox(panel, -1, '')
if config.preferences.use_checkboxes_workaround:
size = self.enabler.GetSize()
self.enabler.SetLabel("Enable %s"%label_text)
self.enabler.SetMaxSize(size)
self.enabler.SetValue(not self.deactivated)
self.enabler.Bind( wx.EVT_CHECKBOX, lambda event: self.toggle_active(event.IsChecked()) )
hsizer.Add(self.enabler, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT, 3)
self.spin = self.create_spin_ctrl(panel)
if self.deactivated is not None:
self.spin.Enable(not self.deactivated)
elif self.blocked or self.readonly:
self.spin.Enable(False)
# layout of the controls / sizers
hsizer.Add(self.spin, 5, wx.ALL | wx.ALIGN_CENTER, 3)
sizer.Add(hsizer, 0, wx.EXPAND)
self._set_tooltip(label, self.spin, self.enabler)
self.spin.Bind(wx.EVT_KILL_FOCUS, self.on_kill_focus) # by default, the value is only set when the focus is lost
self.spin.Bind(wx.EVT_SET_FOCUS, self.on_focus)
if wx.Platform == '__WXMAC__' or self.immediate:
self.spin.Bind(wx.EVT_SPINCTRL, self._on_spin)
self.spin.Bind(wx.EVT_TEXT_ENTER, self._on_enter) # we want the enter key (see style above)
self.editing = True
def on_kill_focus(self, event=None):
if event is not None: event.Skip()
self.flush()
def flush(self):
if self.spin is None: return
if self.spin.IsBeingDeleted(): return
if not compat.wxWindow_IsEnabled(self.spin): return # XXX delete this?
self._check_for_user_modification(self.spin.GetValue())
def update_display(self, start_editing=False):
if start_editing: self.editing = True
if not self.editing or not self.spin: return
self.spin.SetValue(self.value)
def _on_spin(self, event):
event.Skip()
set_current_property(self)
if self.spin:
self._check_for_user_modification(self.spin.GetValue())
def _on_enter(self, event):
# in an EVT_TEXT_ENTER handler self.spin.GetValue() will return the old value on macOS
try:
# on macOS, invalid strings may be entered
value = self._set_converter( event.GetString() )
except:
self.spin.SetValue(self.value)
wx.Bell()
return
self._check_for_user_modification( value )
def set_range(self, min_v, max_v):
new_range = (min_v, max_v)
if new_range==self.val_range: return
self.val_range = new_range
try:
self.spin.SetRange(min_v, max_v)
except AttributeError:
pass
#def write(self, outfile, tabs=0):
#if self.is_active():
#Property.write(self, outfile, tabs)
class SpinPropertyA(SpinProperty):
deactivated = False
class SpinPropertyD(SpinProperty):
deactivated = True
class SpinDoubleProperty(SpinProperty):
# float
deactivated = False
def _set_converter(self, value):
if isinstance(value, compat.unicode):
return float(value.replace(u",", u"."))
elif isinstance(value, bytes):
return float(value.replace(b",", b"."))
return value
def create_spin_ctrl(self, panel):
style = wx.TE_PROCESS_ENTER | wx.SP_ARROW_KEYS
spin = wx.SpinCtrlDouble( panel, -1, style=style, min=self.val_range[0], max=self.val_range[1] )
spin.SetDigits(3)
spin.SetValue(self.value)
range_ = abs(self.val_range[1]-self.val_range[0])
if range_<=1.0:
spin.SetIncrement(0.1)
else:
spin.SetIncrement(1.0)
return spin
def set_range(self, min_v, max_v):
new_range = (min_v, max_v)
if new_range==self.val_range: return
self.val_range = new_range
try:
self.spin.SetRange(min_v, max_v)
except AttributeError:
pass
def on_spin(self, event):
event.Skip()
set_current_property(self)
if self.spin:
self._check_for_user_modification(event.GetString())
class SpinDoublePropertyA(SpinDoubleProperty):
deactivated = False
class SpinDoublePropertyD(SpinDoubleProperty):
deactivated = True
def _is_gridbag(sizer):
return sizer and sizer._IS_GRIDBAG
class LayoutProportionProperty(SpinProperty):
def __init__(self, value):
SpinProperty.__init__(self, value, name="option", immediate=True)
def write(self, outfile, tabs=0):
if not _is_gridbag(self.owner.sizer):
Property.write(self, outfile, tabs)
def create_editor(self, panel, sizer):
if _is_gridbag(self.owner.sizer): return
SpinProperty.create_editor(self, panel, sizer)
#class LayoutPosProperty(SpinProperty):
#readonly = True
#TOOLTIP = "Position of item within sizer\nCan't be edited; use Cut & Paste or Drag & Drop to reposition an item."
#def __init__(self, value):
#SpinProperty.__init__(self, value, val_range=(0,1000), immediate=False, default_value=_DefaultArgument, name="pos")
#def write(self, *args, **kwds):
## maybe, for GridBagSizers row/col should be written
#pass
class LayoutSpanProperty(Property):
TOOLTIP = "cell spanning for GridBagSizer items: rows, columns\nOnly editable if the adjacent cells are empty."
# (int,int)
CONTROLNAMES = ["rowspin","colspin"]
def __init__(self, value):
self.immediate = True
Property.__init__(self, value, default_value=(1,1), name="span")
validation_re = re.compile(_leading + _ge_0 + _comma + _ge_0 + _trailing ) # match a pair of integers >=0
normalization = "%s, %s%s" # for normalization % valiation_re.match(...).groups()
def _convert_from_text(self, value):
match = self.validation_re.match(value)
#if not match: return self.value
if not match: return None
groups = match.groups()
return (int(groups[0]),int(groups[1]))
def _set_converter(self, value):
if isinstance(value, compat.basestring):
return self._convert_from_text(value)
return value
def get_string_value(self):
return "%d, %d"%self.value
def create_editor(self, panel, sizer):
if not _is_gridbag(self.owner.parent): return
max_rows, max_cols = self.owner.parent.check_span_range(self.owner.index, *self.value)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
# label
self.label_ctrl = label = self._get_label(self._find_label(), panel)
hsizer.Add(label, 0, wx.ALL | wx.ALIGN_CENTER, 3)
# checkbox, if applicable
self.enabler = None
style = wx.TE_PROCESS_ENTER | wx.SP_ARROW_KEYS
self.rowspin = wx.SpinCtrl( panel, -1, style=style, min=1, max=max_rows) # don't set size here as the
self.colspin = wx.SpinCtrl( panel, -1, style=style, min=1, max=max_cols) # combination withe SetSelection fails
val = self.value
self.rowspin.SetValue(val and val[0] or 1)
self.colspin.SetValue(val and val[1] or 1)
self.rowspin.Enable(max_rows!=1)
self.colspin.Enable(max_cols!=1)
self.rowspin.SetSelection(-1, -1)
self.colspin.SetSelection(-1, -1)
# layout of the controls / sizers; when adding the spins, set min size as well
hsizer.Add(wx.StaticText(panel, -1, _("Rows:")), 1, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 3)
si = hsizer.Add(self.rowspin, 5, wx.ALL | wx.ALIGN_CENTER, 3).SetMinSize( (30,-1) )
hsizer.Add(wx.StaticText(panel, -1, _("Cols:")), 1, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 3)
hsizer.Add(self.colspin, 5, wx.ALL | wx.ALIGN_CENTER, 3).SetMinSize( (30,-1) )
sizer.Add(hsizer, 0, wx.EXPAND)
self._set_tooltip(label, self.rowspin, self.colspin)
self.rowspin.Bind(wx.EVT_KILL_FOCUS, self.on_kill_focus) # by default, the value is only set when the focus is lost
self.colspin.Bind(wx.EVT_KILL_FOCUS, self.on_kill_focus)
self.rowspin.Bind(wx.EVT_SET_FOCUS, self.on_focus)
self.colspin.Bind(wx.EVT_SET_FOCUS, self.on_focus)
if self.immediate:
self.rowspin.Bind(wx.EVT_SPINCTRL, self.on_spin)
self.rowspin.Bind(wx.EVT_TEXT_ENTER, self.on_spin) # we want the enter key (see style above)
self.colspin.Bind(wx.EVT_SPINCTRL, self.on_spin)
self.colspin.Bind(wx.EVT_TEXT_ENTER, self.on_spin)
self.editing = True
def on_kill_focus(self, event=None):
if event is not None: event.Skip()
self.flush()
def flush(self):
if self.rowspin is None or self.colspin is None: return
if self.rowspin.IsBeingDeleted() or self.colspin.IsBeingDeleted(): return
self._check_for_user_modification( (self.rowspin.GetValue(),self.colspin.GetValue() ) )
def update_display(self, start_editing=False):
if start_editing: self.editing = True
if not self.editing or not self.rowspin or not self.colspin: return
self.rowspin.SetValue(self.value[0])
self.colspin.SetValue(self.value[1])
def on_spin(self, event):
event.Skip()
set_current_property(self)
if self.rowspin and self.colspin:
self._check_for_user_modification( (self.rowspin.GetValue(),self.colspin.GetValue() ) )
# update ranges
max_rows, max_cols = self.owner.parent.check_span_range(self.owner.index, *self.value)
self.rowspin.SetRange(1,max_rows)
self.colspin.SetRange(1,max_cols)
self.rowspin.Enable(max_rows!=1)
self.colspin.Enable(max_cols!=1)
def write(self, outfile, tabs=0):
if _is_gridbag(self.owner.parent):
Property.write(self, outfile, tabs)
class CheckBoxProperty(Property):
# bool
CONTROLNAMES = ["checkbox"]
def _set_converter(self, value):
if isinstance(value, compat.basestring):
return int(value) # keep 0/1 instead of False/True for writing to XML file
return value
def _display_value(self):
self.checkbox.SetValue( bool(self.value) )
def create_editor(self, panel, sizer):
label_text = self._find_label()
self.checkbox = wx.CheckBox(panel, -1, '', name=label_text)
self._display_value()
if self.blocked: self.checkbox.Disable()
self.label_ctrl = label = self._get_label(label_text, panel, name=label_text)
if config.preferences.use_checkboxes_workaround:
size = self.checkbox.GetSize()
self.checkbox.SetLabel(label_text)
self.checkbox.SetMaxSize(size)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
#hsizer.Add(label, 2, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)
hsizer.Add(label, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)
#hsizer.SetItemMinSize(0, config.label_initial_width, -1)
#hsizer.AddSpacer(20)
hsizer.Add(self.checkbox, 0, wx.ALIGN_LEFT | wx.ALL, 3)
hsizer.AddStretchSpacer(5)
sizer.Add(hsizer, 0, wx.EXPAND)
self._set_tooltip(label, self.checkbox)
self.checkbox.Bind(wx.EVT_CHECKBOX, self.on_change_val)
self.editing = True
def update_display(self, start_editing=False):
if start_editing: self.editing = True
if not self.editing or not self.checkbox: return
self._display_value()
def on_change_val(self, event):
new_value = event.IsChecked()
self.on_focus()
self._check_for_user_modification(new_value)
class InvCheckBoxProperty(CheckBoxProperty):
# display is inverted; used for application.overwrite
def _display_value(self):
self.checkbox.SetValue( not bool(self.value) )
def on_change_val(self, event):
new_value = not event.IsChecked()
self.on_focus()
self._check_for_user_modification(new_value)
class RadioProperty(Property):
# choice
CONTROLNAMES = ["options"]
def __init__(self, value, values, labels=None, columns=1, aliases=None, tooltips=None, default_value=_DefaultArgument,
name=None):
self.values = values # e.g. a list of ints
self.aliases = aliases # e.g. a list of strings, corresponding to values; these can be set and will be written
self.labels = labels or aliases or values
self.tooltips = tooltips
self.columns = columns
Property.__init__(self, value, default_value, name)
def _set_converter(self, value):
if not value in self.values:
value = self.values[self.aliases.index(value)]
return value
def get_string_value(self):
if self.aliases and not self.value in self.aliases:
return self.aliases[self.values.index(self.value)]
return Property.get_string_value(self)
def create_editor(self, panel, sizer):
label = self._find_label()
style = wx.RA_SPECIFY_COLS | wx.NO_BORDER | wx.CLIP_CHILDREN
self.options = wx.RadioBox(panel, -1, label, choices=self.labels, majorDimension=self.columns, style=style)
sizer.Add(self.options, 0, wx.EXPAND)
if self.tooltips:
for i,tooltip in enumerate(self.tooltips):
if tooltip:
self.options.SetItemToolTip(i, tooltip)
else:
self._set_tooltip(self.options)
self.update_display(True)
self.options.Bind(wx.EVT_RADIOBOX, self.on_radio)
def update_display(self, start_editing=False):
if start_editing: self.editing = True
if not self.editing or not self.options: return
self.options.SetSelection( self.values.index(self.value) )
if self.blocked: self.options.Disable()
def on_radio(self, event):
event.Skip()
self.on_focus()
new_value = self.values[event.GetInt()]
self._check_for_user_modification(new_value)
def enable_item(self, index, enable=True):
if not self.editing or not self.options: return
self.options.EnableItem(index, enable)
class IntRadioProperty(RadioProperty):
#def set(self, value, activate=False, deactivate=False):
# RadioProperty.set(self, int(value), activate, deactivate)
def _set_converter(self, value):
return int(value)
class _CheckListProperty(Property):
# common base class for Flags and WidgetStyleFlags; keeps self.value_set as a set of strings
CONTROLNAMES = ["enabler", "_choices"]
EXCLUDES = EXCLUDES2 = None # EXCLUDES2 will be set dynamically
def __init__(self, value, default_value=_DefaultArgument, name=None, names=None, values=None):
self._names = names
self._values = values # these will sometimes only be calculated on demand, especially for WidgetStyle
self.value_set = self._decode_value(value)
self.enabler = self._choices = None
Property.__init__(self, None, default_value, name) # with value=None, as this is to be calculated on demand only
self._ignore_names = set() # flag values to be ignored for DesignWindow
self._one_required = None
def set_owner(self, owner, attributename):
Property.set_owner(self, owner, attributename)
self._check_value()
def _ensure_values(self):
if self._names is None or self._values is None: raise ValueError("implementation error")
def _decode_value(self, value):
if not value:
return set()
if isinstance(value, compat.basestring):
new_value = set( [v.strip() for v in value.split("|")] )
elif isinstance(value, int):
new_value = set()
if value:
# decode into set
self._ensure_values()
for name, flag_value in zip(self._names, self._values):
if flag_value is not None and value & flag_value == flag_value:
new_value.add(name)
elif isinstance(value, (set,tuple,list)):
new_value = set(value) # avoid side effects
return new_value
def get(self):
"get the value, or the default value if deactivated; usually not used directly, as owner.property will call it"
if self.value is None and not self.deactivated and not self.blocked:
# calculate the numeric value on demand
if self.value_set: self._ensure_values()
self.value = 0
for i, name in enumerate(self._names):
if name in self.value_set and not name in self._ignore_names:
value = self._values[i]
if value is not None: self.value |= value
return Property.get(self)
def set(self, value, activate=False, deactivate=False, notify=False):
new_value_set = self._decode_value(value)
if new_value_set!=self.value_set:
self.value_set = new_value_set
Property.set(self, None, activate, deactivate, notify) # with None, as this is to be calculated on demand only
self._check_value()
def add(self, value, activate=False, deactivate=False, notify=True):
if value in self.value_set: return
self.value_set.add(value)
Property.set(self, None, activate, deactivate, notify) # with value=None, as this is to be calculated on demand only
def remove(self, value, activate=False, deactivate=False, notify=True):
if not value in self.value_set: return
self.value_set.remove(value)
Property.set(self, None, activate, deactivate, notify) # with value=None, as this is to be calculated on demand only
def get_list_value(self):
"""Convert the current style in a list of boolean values."""
combined_values = set()
for name in self.value_set:
combined_values.add(name)
combined_values.update( self.style_defs[name].get("combination",[]) )
ret = [(name in combined_values) for name in self._names]
return ret
def get_string_value(self):
"Return the selected styles joined with '|', for writing to XML file"
if not self.value_set: return ""
ret = []
for name in self._names:
if name in self.value_set:
ret.append(name)
return '|'.join(ret)
def write(self, output, tabs=0):
value = self.get_string_value()
if value:
output.extend( common.format_xml_tag(self.name, value, tabs) )
def create_editor(self, panel, sizer):
self._choices = []
tooltips = self._create_tooltip_text()
for box_label in self.styles.keys():
static_box = wx.StaticBox(panel, -1, box_label, style=wx.FULL_REPAINT_ON_RESIZE)
box_sizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)
for style in self.styles[box_label]:
checkbox = wx.CheckBox(panel, -1, style)
if style in tooltips: compat.SetToolTip(checkbox, tooltips[style])
self._choices.append(checkbox)
box_sizer.Add(checkbox)
sizer.Add(box_sizer, 0, wx.ALL | wx.EXPAND, 5)
self.update_display(True)
for checkbox in self._choices:
if checkbox is None: continue # derived classes may not use all options, e.g. obsolete ones
checkbox.Bind(wx.EVT_CHECKBOX, self.on_checkbox)
def on_checkbox(self, event):
index = self._choices.index( event.GetEventObject() )
value = self._names[index]
checked = event.IsChecked()
event.Skip()
self.on_focus()
self._change_value(value, checked)
def _check_value(self, added=None):
# e.g. used by ManagedFlags
pass
def _change_value(self, value, checked):
"user has clicked checkbox or History is setting"
self.previous_value = self.value_set.copy()
# make a copy of the current set value and replace combinations w. single flags, as these may need to be excluded
value_set = self.value_set.copy()
for name in self.value_set:
combination = self.style_defs[name].get("combination",[])
if combination:
value_set.update(combination)
value_set.remove(name)
values = self.style_defs[value].get("combination",[value])
if checked:
if self.value_set.issuperset(values): return
value_set.update(values)
for value in values:
if self.EXCLUDES:
excludes = self.EXCLUDES.get(value, [])
else:
excludes = self.style_defs[value].get("exclude",[])
value_set.difference_update(excludes)
excludes = self.style_defs[value].get("disable",[])
value_set.difference_update(excludes)
else:
value_set.difference_update(values)
if self._one_required and not value_set.intersection(self._one_required):
if value in self._one_required:
value_set.add(value)
else:
value_set.add(self._one_required[0])
# check for combinations: if all flags of a combination are in value_set, we need only the combination
for name in self._names:
combination = self.style_defs[name].get("combination",[])
if combination and value_set.issuperset(combination):
value_set.difference_update(combination)
value_set.add(name)
# actually make the changes
common.history.set_property_changing(self)
self.value_set.clear()
self.value_set.update(value_set)
self._check_value(checked and value or None) # e.g. used by ManagedFlags
self.value = None # to be calculated on demand
self._notify()
common.history.set_property_changed(self, value, checked)
self.update_display()
self.previous_value = None
def update_display(self, start_editing=False):
# when the value has changed
if start_editing: self.editing = True
if not self.editing: return
checked = self.get_list_value()
for i,checkbox in enumerate(self._choices):
if not checkbox: continue
name = self._names[i]
if checked[i] and not checkbox.GetValue():
checkbox.SetValue(True)
elif not checked[i] and checkbox.GetValue():
checkbox.SetValue(False)
# display included flags in grey and excluded flags red
if self.EXCLUDES:
# mutually exclusive, e.g. ALIGN_RIGHT if ALIGN_CENTER is set
# red / enabled / can be checked and will then deactivate the other one
excludes = self.EXCLUDES.get(name, [])
else:
excludes = self.style_defs[name].get("exclude",[])
if self.EXCLUDES2:
# dynamically excluded, e.g. horizontal alignment flag in horizontal sizer
# grey / disabled / can not be checked
excludes2 = self.EXCLUDES2
else:
# disable if any of the flags in 'disabled' is set
excludes2 = self.style_defs[name].get("disabled",None)
if excludes2 is not None and self.value_set.intersection( excludes2 ):
excludes2 = [name]
if not config.preferences.no_checkbox_label_colours:
default_color = wx.NullColour if not "rename_to" in self.style_defs[name] else wx.Colour(130,130,130)
if checked[i] and not name in self.value_set:
checkbox.SetForegroundColour(wx.Colour(120,120,100)) # grey
elif self.value_set.intersection( excludes ):
checkbox.SetForegroundColour(wx.RED)
else:
supported_by = self.style_defs.get(name, {}).get("supported_by", None)
if supported_by:
checkbox.SetForegroundColour(wx.BLUE)
else:
checkbox.SetForegroundColour(default_color)
if self._one_required and name in self._one_required and checked[i]:
wx.CallAfter( checkbox.Disable )