-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport_designer.py
executable file
·2853 lines (2388 loc) · 98.8 KB
/
report_designer.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import os
import sys
from .. import events
from .. import icons
from .. import ui
from ..application import dApp
from ..dReportWriter import dReportWriter
from ..lib.reportWriter import *
from ..lib.utils import ustr
from ..localization import _
from ..ui import dEditor
from ..ui import dFont
from ..ui import dForm
from ..ui import dImage
from ..ui import dKeys
from ..ui import dLabel
from ..ui import dMenu
from ..ui import dPageFrame
from ..ui import dPanel
from ..ui import dScrollPanel
from ..ui import dTreeView
from . import class_designer_prop_sheet
NEW_FILE_CAPTION = "< New >"
SHORTEN_EXPRESSIONS_FOR_DISPLAY = False
rdc = None
iconPath = os.path.dirname(icons.__file__) # + r'/themes/tango/16x16'
def DesignerController():
# Wrapper function to enforce singleton class instance
class DesignerController(dApp):
def initProperties(self):
self.BasePrefKey = "dabo.ide.reportdesigner"
self.setAppInfo("appName", "Dabo Report Designer")
self.MainFormClass = None
def beforeInit(self):
self._inSelection = False
def afterInit(self):
if sys.platform == "darwin":
self.bindEvent(events.KeyDown, self._onKeyDown)
def startPropEdit(self):
## Class Designer uses this; don't think it's necessary here.
pass
def endPropEdit(self):
## Class Designer uses this; don't think it's necessary here.
pass
def _onKeyDown(self, evt):
# Mac-specific behavior
self.ActiveEditor.onKeyDown(evt)
def onFileExit(self, evt):
ret = self.ActiveEditor.closeFile()
if ret is not None:
self.finish()
def getShortExpr(self, expr):
"""Given an expression, return a shortened version for display in designer."""
if not SHORTEN_EXPRESSIONS_FOR_DISPLAY:
expr = expr.strip()
if len(expr) > 1 and expr[0] == expr[-1] and expr[0] in ("'", '"'):
expr = expr[1:-1]
return expr
if expr is None:
return "None"
if len(expr) < 3:
return expr
def isVariable(name):
for v in rdc.ReportForm["Variables"]:
if v.get("Name", None) == name:
return True
return False
def isRecord(name):
if (
name
and ("TestCursor" in rdc.ReportForm)
and rdc.ReportForm["TestCursor"]
and (name in rdc.ReportForm["TestCursor"][0])
):
return True
return False
import re
c = re.compile("self.(?P<type>Record|Variables)\[(?P<name>.*)\]")
m = c.match(expr)
if m:
name = m.group("name")
name = name[1:-1] ## (remove outer quotes)
else:
if "." in expr:
name = expr.split(".")[-1]
else:
# No record or variable found: leave alone
name = None
if not isVariable(name) and not isRecord(name):
# This isn't a record or variable: don't shortcut the name as a
# visual cue to the developer.
name = None
if name is None:
quotes = ('"', "'")
if expr[0] in quotes and expr[-1] in quotes:
# Remove outer quotes
name = expr[1:-1]
else:
for quote in quotes:
if expr.count(quote) >= 2:
name_candidate = expr[expr.find(quote) + 1 :]
name_candidate = name_candidate[: name_candidate.find(quote)]
if name_candidate.strip():
name = name_candidate
break
if name:
expr = name
return expr
def objectDoubleClicked(self, obj, evt=None):
"""A report object was double-clicked: edit its major property in the propsheet."""
editProp = obj.MajorProperty
if evt.EventData["shiftDown"]:
editProp = None
rdc.editProperty(editProp)
def editProperty(self, prop=None):
"""Display the property dialog, and bring it to top.
If a valid propname is passed, start the editor for that property.
After the property is edited, send focus back to the designer or
object tree.
"""
activeForm = self.ActiveForm
self.showPropSheet(bringToTop=True, prop=prop, enableEditor=True, focusBack=activeForm)
def newObject(self, typ, mousePosition):
"""Add a new object of the passed type to the selected band."""
rf = self.ReportForm
parents = []
objects = []
defaultProps = {}
if typ == Variable:
parents.append(rf["Variables"])
elif typ == Group:
parents.append(rf["Groups"])
else:
# Normal report object. Place it in all selected bands.
if isinstance(typ, str):
if typ[:7] == "Field: ":
# Testcursor field. Create string object with expr of this field.
defaultProps["expr"] = "self.%s" % typ[7:].strip()
typ = String
elif typ[:10] == "Variable: ":
# Report Variable: Create string object with expr of this variable.
defaultProps["expr"] = "self.%s" % typ[10:].strip()
typ = String
## Want to put the object where the mouse was, however there are things to
## consider such as zoom factor, and that the mouse position is absolute
## screen position. Also, we only want to do this if we were dealing with the
## context menu from the designer, as opposed to the one in the object tree.
# defaultProps["x"] = "%s" % mousePosition[0]
# defaultProps["y"] = "%s" % mousePosition[1]
for selObj in self.SelectedObjects:
if isinstance(selObj, Band):
parents.append(selObj)
for parent in parents:
obj = parent.addObject(typ)
obj.update(defaultProps.copy())
objects.append(obj)
if objects:
self.SelectedObjects = objects
dabo.ui.callAfter(self.ActiveEditor.Form.Raise)
def getGroupBandByExpr(self, expr):
for g in self.ReportForm["Groups"]:
if g["expr"] == expr:
return g
return None
def getContextMenu(self, mousePosition):
def onNewObject(evt):
"""Called from the context menu."""
tag = evt.EventObject.Tag
self.newObject(tag, mousePosition)
def onSelectAll(evt):
self.selectAllObjects()
def onCopy(evt):
self.copy()
def onPaste(evt):
self.paste()
def onCut(evt):
self.cut()
def onDelete(evt):
self.delete()
def onMoveToTop(evt):
self.ActiveEditor.sendToBack()
def onMoveUp(evt):
self.ActiveEditor.sendBackwards()
def onMoveDown(evt):
self.ActiveEditor.sendUpwards()
def onMoveToBottom(evt):
self.ActiveEditor.bringToFront()
menu = dMenu()
newObjectMenuCreated = False
newVariableMenuCreated = False
newGroupMenuCreated = False
variableSelected, groupSelected = False, False
for robj in self.SelectedObjects:
if isinstance(robj, Variable):
variableSelected = True
if isinstance(robj, Group):
groupSelected = True
if not newVariableMenuCreated and isinstance(robj, (Variables, Variable)):
menu.append("New variable", OnHit=onNewObject, Tag=Variable)
newVariableMenuCreated = True
if not newGroupMenuCreated and isinstance(robj, (Groups, Group)):
menu.append("New group", OnHit=onNewObject, Tag=Group)
newGroupMenuCreated = True
if not newObjectMenuCreated and isinstance(robj, Band):
newObjectMenuCreated = True
objectChoices = dMenu(Caption="New object")
for choice in (Image, Line, Rectangle, String, Memo):
objectChoices.append(choice.__name__, OnHit=onNewObject, Tag=choice)
objectChoices.appendSeparator()
for choice in (SpanningLine, SpanningRectangle):
objectChoices.append(choice.__name__, OnHit=onNewObject, Tag=choice)
tc = self.ReportForm.get("TestCursor", [])
var = self.ReportForm.get("Variables", [])
if tc or var:
objectChoices.appendSeparator()
for typ, cap in ((tc, "Field"), (var, "Variable")):
if typ:
submenu = dMenu(Caption=cap)
fields = []
if typ == tc:
if tc:
fields = list(tc[0].keys())
elif typ == var:
for v in var:
try:
fields.append(v["Name"])
except KeyError:
# variable not given a name
pass
fields.sort()
for field in fields:
submenu.append(
field,
OnHit=onNewObject,
Tag="%s: %s" % (cap, field),
)
objectChoices.appendMenu(submenu)
menu.appendMenu(objectChoices)
if len(menu.Children) > 0:
menu.appendSeparator()
menu.append(_("Select All"), HotKey="Ctrl+A", OnHit=onSelectAll)
menu.appendSeparator()
menu.append(_("Copy"), HotKey="Ctrl+C", OnHit=onCopy)
menu.append(_("Cut"), HotKey="Ctrl+X", OnHit=onCut)
menu.append(_("Paste"), HotKey="Ctrl+V", OnHit=onPaste)
menu.appendSeparator()
menu.append(_("Delete"), HotKey="Del", OnHit=onDelete)
if variableSelected or groupSelected:
menu.appendSeparator()
menu.append(_("Move to top"), HotKey="Ctrl+Shift+H", OnHit=onMoveToTop)
menu.append(_("Move up"), HotKey="Ctrl+H", OnHit=onMoveUp)
menu.append(_("Move down"), HotKey="Ctrl+J", OnHit=onMoveDown)
menu.append(_("Move to bottom"), HotKey="Ctrl+Shift+J", OnHit=onMoveToBottom)
return menu
def selectAllObjects(self):
"""Select all objects in the selected band(s)."""
selection = []
for band in self.getSelectedBands():
for obj in band["Objects"]:
selection.append(obj)
self.SelectedObjects = selection
def showObjectTree(self, bringToTop=False, refresh=False):
ot = self.ObjectTree
if ot is None:
refresh = True
ot = self.loadObjectTree()
self.refreshTree()
ot.Form.Visible = True
if refresh:
ot.refreshSelection()
if bringToTop:
ot.Raise()
def hideObjectTree(self):
ot = self.ObjectTree
if ot is not None and ot.Form.Visible:
ot.Form.Visible = False
def loadObjectTree(self):
otf = ObjectTreeForm()
ot = self.ObjectTree = otf.Editor
otf.bindEvent(events.Close, self._onObjectTreeFormClose)
# Allow the activate to fire so that position is set:
otf.Visible = True
otf.Raise()
self.ActiveEditor.Form.Raise()
return ot
def showPropSheet(
self,
bringToTop=False,
refresh=False,
prop=None,
enableEditor=False,
focusBack=None,
):
ps = self.PropSheet
if ps is None:
refresh = True
ps = self.loadPropSheet()
ps.Form.Visible = True
if refresh:
ps.refreshSelection()
pg = ps.propGrid
ds = pg.DataSet
if enableEditor:
# Select the value column and enable the editor for the prop. Note:
# This needs to be done before changing rows, for some reason, or the
# editor column isn't activated.
pg.CurrentColumn = 1
pg._focusBack = focusBack
if prop:
# Put the propsheet on the row for the passed prop.
for idx, record in enumerate(ds):
if record["prop"].lower() == prop.lower():
pg.CurrentRow = idx
break
else:
pg.CurrentRow = pg.CurrentRow
if bringToTop:
ps.Form.Raise()
def hidePropSheet(self):
ps = self.PropSheet
if ps is not None and ps.Form.Visible:
ps.Form.Visible = False
def loadPropSheet(self):
psf = PropSheetForm()
ps = self.PropSheet = psf.Editor
psf.bindEvent(events.Close, self._onPropSheetFormClose)
psf.Visible = True
psf.Raise()
self.ActiveEditor.Form.Raise()
return ps
def refreshTree(self):
if self.ObjectTree:
self.ObjectTree.refreshTree()
self.ObjectTree.refreshSelection()
def refreshProps(self, refreshEditor=True):
if refreshEditor and self.ActiveEditor:
self.ActiveEditor.refresh()
if self.PropSheet and self.PropSheet.Form.Visible:
self.PropSheet.refreshSelection()
def refreshSelection(self, refreshEditor=False):
self._inSelection = True
for obj in (self.PropSheet, self.ObjectTree):
if obj is not None:
obj.refreshSelection()
if refreshEditor:
self.ActiveEditor.refresh()
self._inSelection = False
def isSelected(self, obj):
"""Return True if the object is selected."""
for selObj in self.SelectedObjects:
if id(selObj) == id(obj):
return True
return False
def getNextDrawable(self, obj):
"""Return the next drawable after the passed obj."""
collection = self.getParentBand(obj)["Objects"]
idx = collection.index(obj) + 1
if len(collection) <= idx:
idx = 0
return collection[idx]
def getPriorDrawable(self, obj):
"""Return the prior drawable before the passed obj."""
collection = self.getParentBand(obj)["Objects"]
idx = collection.index(obj) - 1
if len(collection) <= idx:
idx = len(collection) - 1
return collection[idx]
def ReportObjectSelection(self):
import pickle
import wx
rw = self.ActiveEditor._rw
class ReportObjectSelection(wx.CustomDataObject):
def __init__(self):
# wx.CustomDataObject.__init__(self, wx.CustomDataFormat("ReportObjectSelection"))
# self.SetFormat(wx.DataFormat("my data format"))
wx.CustomDataObject.__init__(self, wx.DataFormat("ReportObjectSelection"))
self.setObject([])
def setObject(self, objs):
# We are receiving a sequence of selected objects. Convert to a list of
# new dicts representing the object properties.
copyObjs = []
for obj in objs:
copyObj = obj.getMemento()
if obj.__class__.__name__ == "Group":
parentBandInfo = ["Groups", None]
elif obj.__class__.__name__ == "Variable":
parentBandInfo = ["Variables", None]
else:
parentBand = rdc.getParentBand(obj)
parentBandInfo = [
ustr(type(parentBand)).split(".")[-1][:-2],
None,
]
if "Group" in parentBandInfo[0]:
group = parentBand.parent
parentBandInfo[1] = group.get("expr")
copyObj["_parentBandInfo_"] = parentBandInfo
copyObjs.append(copyObj)
self.SetData(pickle.dumps(copyObjs))
def getObject(self):
# We need to convert the representative object dicts back into report
# objects
copyObjs = pickle.loads(self.GetData())
objs = []
for copyObj in copyObjs:
obj = self.getReportObjectFromMemento(copyObj)
objs.append(obj)
return objs
def getReportObjectFromMemento(self, memento, parent=None):
try:
parentInfo = memento.pop("_parentBandInfo_")
except KeyError:
parentInfo = None
if parentInfo:
if parentInfo[0] == "Groups":
parent = rdc.ReportForm["Groups"]
elif parentInfo[0] == "Variables":
parent = rdc.ReportForm["Variables"]
elif "Group" in parentInfo[0]:
parent = rdc.getGroupBandByExpr(parentInfo[1])[parentInfo[0]]
else:
parent = rdc.ReportForm[parentInfo[0]]
obj = rw._getReportObject(memento["type"], parent)
del memento["type"]
for k, v in list(memento.items()):
if isinstance(v, dict):
obj[k] = self.getReportObjectFromMemento(v, obj)
elif isinstance(v, list):
obj[k] = rw._getReportObject(k, obj)
for c in v:
obj[k].append(self.getReportObjectFromMemento(c, obj))
else:
obj[k] = v
return obj
return ReportObjectSelection()
def getSelectedBands(self):
"""Return the list of bands that are currently selected."""
selBands = []
for selObj in self.SelectedObjects:
if (
not isinstance(selObj, Band)
and selObj.parent is not None
and isinstance(selObj.parent.parent, Band)
):
selObj = selObj.parent.parent
if isinstance(selObj, Band):
if selObj not in selBands:
selBands.append(selObj)
return selBands
def copy(self, cut=False):
import wx
do = self.ReportObjectSelection()
copyObjs = [
selObj
for selObj in self.SelectedObjects
if not isinstance(selObj, (Report, Band, list))
]
if not copyObjs:
# don't override the current clipboard with an empty clipboard
return
do.setObject(copyObjs)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(do)
wx.TheClipboard.Close()
if cut:
self.delete()
def delete(self):
objs = [
obj for obj in self.SelectedObjects if not isinstance(obj, (Report, Band, list))
]
if not objs:
return
parent = None
reInit = False
for obj in objs:
parent = obj.parent
removeNode = False
if isinstance(parent, dict):
for typ in ("Objects", "Variables", "Groups"):
if typ in parent:
if obj in parent[typ]:
parent[typ].remove(obj)
removeNode = True
elif isinstance(parent, list):
parent.remove(obj)
removeNode = True
if removeNode:
ot = self.ObjectTree
if ot:
nd = ot.removeNode(ot.nodeForObject(obj))
if isinstance(obj, Group):
reInit = True
self.ActiveEditor.propsChanged(reinit=reInit)
def cut(self):
self.copy(cut=True)
def paste(self):
import wx
success = False
do = self.ReportObjectSelection()
if wx.TheClipboard.Open():
success = wx.TheClipboard.GetData(do)
wx.TheClipboard.Close()
if success:
objs = do.getObject()
else:
# nothing valid in the clipboard
return
# Figure out the band to paste the obj(s) into. If the objects are from multiple
# bands, then paste the new objects into the same bands. If the objects are all
# from the same band, paste the new objects into the currently-selected band.
parents = []
selBand = None
for obj in objs:
if obj.parent not in parents:
parents.append(obj.parent)
if len(parents) > 1:
# keep pasted objects in the same parents
pass
else:
selBands = self.getSelectedBands()
if len(selBands) > 0:
# paste into the first selected band
selBand = selBands[-1]
else:
if len(self.SelectedObjects) > 0:
# paste into the parent band of the first selected object:
selBand = self.getParentBand(self.SelectedObjects[-1])
reInit = False
selectedObjects = []
max_y_needed = 0 # resize band if needed to show any objects
for obj in objs:
if isinstance(obj, Variable):
# paste into Variables whether or not Variables selected
pfObjects = self.ReportForm.setdefault("Variables", Variables(self.ReportForm))
obj.parent = pfObjects
elif isinstance(obj, Group):
# paste into Groups whether or not Groups selected
pfObjects = self.ReportForm.setdefault("Groups", Groups(self.ReportForm))
obj.parent = pfObjects
reInit = True
else:
if selBand is not None:
max_y_needed = max(max_y_needed, obj.getTopPt())
pfObjects = selBand.setdefault("Objects", [])
obj.parent = selBand
else:
pfObjects = obj.parent.setdefault("Objects", [])
pfObjects.append(obj)
selectedObjects.append(obj)
if selBand and selBand.getProp("Height") is not None:
# Resize the pasted-into band to accomodate the new object, if necessary:
selBand.setProp("Height", ustr(max(selBand.getProp("Height"), max_y_needed)))
self.ActiveEditor.propsChanged(reinit=reInit)
self.SelectedObjects = selectedObjects
def getParentBand(self, obj):
"""Return the band that the obj is a member of."""
parent = obj
while parent is not None:
if isinstance(parent, Band):
return parent
parent = parent.parent
return None
def _onObjectTreeFormClose(self, evt):
self.ObjectTree = None
def _onPropSheetFormClose(self, evt):
self.PropSheet = None
def _getActiveEditor(self):
return getattr(self, "_activeEditor", None)
def _setActiveEditor(self, val):
changed = val != self.ActiveEditor
if changed:
self._activeEditor = val
self.refreshTree()
self.refreshProps()
def _getObjectTree(self):
try:
val = self._objectTree
except AttributeError:
val = self._objectTree = None
return val
def _setObjectTree(self, val):
self._objectTree = val
def _getPropSheet(self):
try:
val = self._propSheet
except AttributeError:
val = self._propSheet = None
return val
def _setPropSheet(self, val):
self._propSheet = val
def _getReportForm(self):
return self.ActiveEditor.ReportForm
def _getSelectedObjects(self):
return getattr(self.ActiveEditor, "_selectedObjects", [])
def _setSelectedObjects(self, val):
self.ActiveEditor._selectedObjects = val
self.refreshSelection(refreshEditor=True)
ActiveEditor = property(_getActiveEditor, _setActiveEditor)
ObjectTree = property(_getObjectTree, _setObjectTree)
PropSheet = property(_getPropSheet, _setPropSheet)
ReportForm = property(_getReportForm)
SelectedObjects = property(_getSelectedObjects, _setSelectedObjects)
Selection = SelectedObjects ## compatability with ClassDesignerPropSheet
global rdc
if rdc is None:
rdc = DesignerController()
return rdc
# All the classes below will use the singleton DesignerController instance:
rdc = DesignerController()
class DesignerControllerForm(dForm):
def initProperties(self):
self.Caption = "DesignerController Form"
self.TinyTitleBar = True
self.ShowMaxButton = False
self.ShowStatusBar = False
self.ShowMinButton = False
self.ShowSystemMenu = False
self.ShowInTaskBar = False
self.ShowMenuBar = False
def afterInit(self):
sz = self.Sizer
sz.Orientation = "h"
self.Editor = self.addObject(self.EditorClass)
sz.append(self.Editor, 2, "x")
self.layout()
def _getEditor(self):
if hasattr(self, "_editor"):
val = self._editor
else:
val = self._editor = None
return val
def _setEditor(self, val):
self._editor = val
def _getEditorClass(self):
if hasattr(self, "_editorClass"):
val = self._editorClass
else:
val = self._editorClass = None
return val
def _setEditorClass(self, val):
self._editorClass = val
Editor = property(_getEditor, _setEditor)
EditorClass = property(_getEditorClass, _setEditorClass)
class ReportObjectTree(dTreeView):
def initProperties(self):
self.MultipleSelect = True
self.ShowButtons = True
def initEvents(self):
self.bindKey("ctrl+c", self.onCopy)
self.bindKey("ctrl+x", self.onCut)
self.bindKey("ctrl+v", self.onPaste)
def onCopy(self, evt):
rdc.copy()
def onCut(self, evt):
rdc.cut()
def onPaste(self, evt):
rdc.paste()
def syncSelected(self):
"""Sync the treeview's selection to the rdc."""
if not rdc._inSelection:
rdc.SelectedObjects = [obj.Object for obj in self.Selection]
def onHit(self, evt):
self.syncSelected()
def onMouseLeftDoubleClick(self, evt):
node = evt.EventData["selectedNode"][0]
rdc.objectDoubleClicked(node.Object, evt)
def onContextMenu(self, evt):
evt.stop()
self.syncSelected()
self.showContextMenu(rdc.getContextMenu(mousePosition=evt.EventData["mousePosition"]))
def refreshTree(self):
"""Constructs the tree of report objects."""
self.clear()
self.recurseLayout()
self.expandAll()
def recurseLayout(self, frm=None, parentNode=None):
rd = rdc.ActiveEditor
rw = rd._rw
rf = rdc.ReportForm
if rf is None:
# No form to recurse
return
fontSize = 8
if frm is None:
frm = rf
parentNode = self.setRootNode(frm.__class__.__name__)
parentNode.FontSize = fontSize
parentNode.Object = frm
elements = list(frm.keys())
# elements.sort(rw._elementSort)
elements.sort()
for name in elements:
self.recurseLayout(frm=frm[name], parentNode=parentNode)
return
if isinstance(frm, dict):
node = parentNode.appendChild(self.getNodeCaption(frm))
node.Object = frm
node.FontSize = fontSize
for child in frm.get("Objects", []):
self.recurseLayout(frm=child, parentNode=node)
for band in ("GroupHeader", "GroupFooter"):
if band in frm:
self.recurseLayout(frm=frm[band], parentNode=node)
elif frm.__class__.__name__ in ("Variables", "Groups", "TestCursor"):
node = parentNode.appendChild(self.getNodeCaption(frm))
node.Object = frm
node.FontSize = fontSize
for child in frm:
self.recurseLayout(frm=child, parentNode=node)
def getNodeCaption(self, frm):
caption = frm.__class__.__name__
if not frm.__class__.__name__ in ("Variables", "Groups", "TestCursor"):
expr = rdc.getShortExpr(frm.get("expr", ""))
if expr:
if caption.lower() in ("group",):
caption = expr
elif caption.lower() in ("variable",):
caption = frm.getProp("Name", evaluate=False)
else:
expr = ": %s" % expr
caption = "%s%s" % (frm.__class__.__name__, expr)
return caption
def refreshSelection(self):
"""Iterate through the nodes, and set their Selected status
to match if they are in the current selection of controls.
"""
objList = rdc.SelectedObjects
# First, make sure all selected objects are represented:
for obj in objList:
rep = False
for node in self.nodes:
if id(node.Object) == id(obj):
rep = True
break
if not rep:
# Nope, the object isn't in the tree yet.
self.refreshTree()
break
# Now select the proper nodes:
selNodes = []
for obj in objList:
for node in self.nodes:
if id(node.Object) == id(obj):
selNodes.append(node)
self.Selection = selNodes
def refreshCaption(self):
"""Iterate the Selection, and refresh the Caption."""
for node in self.Selection:
node.Caption = self.getNodeCaption(node.Object)
class ObjectTreeForm(DesignerControllerForm):
def initProperties(self):
super(ObjectTreeForm, self).initProperties()
self.Caption = "Report Object Tree"
self.EditorClass = ReportObjectTree
def selectAll(self):
rdc.selectAllObjects()
class ReportPropSheet(ClassDesignerPropSheet.PropSheet):
def beforeInit(self):
# The ClassDesignerPropSheet appears to need a self.app reference:
self.app = rdc
def afterInit(self):
super(ReportPropSheet, self).afterInit()
self.addObject(dLabel, Name="lblType", FontBold=True)
self.Sizer.insert(0, self.lblType, "expand", halign="left", border=10)
self.Sizer.insertSpacer(0, 10)
def getObjPropVal(self, obj, prop):
return obj.getPropVal(prop)
def getObjPropDoc(self, obj, prop):
doc = obj.getPropDoc(prop)
return self.formatDocString(doc)
def updateVal(self, prop, val, typ):
"""Called from the grid to notify that the current cell's
value has been changed. Update the corresponding
property value.
"""
reInit = False
if typ == "color":
# need to convert from rgb to reportlab rgb, and stringify.
val = rdc.ActiveEditor._rw.getReportLabColorTuple(val)
val = "(%.3f, %.3f, %.3f)" % (val[0], val[1], val[2])
for obj in self._selected:
obj.setProp(prop, val)
if isinstance(obj, Group) and prop.lower() == "expr":
reInit = True
rdc.ActiveEditor.propsChanged(reinit=reInit)
if rdc.ObjectTree:
rdc.ObjectTree.refreshCaption()
focusBack = getattr(self.propGrid, "_focusBack", None)
if focusBack:
focusBack.bringToFront()
self.propGrid._focusBack = None
def refreshSelection(self):
objs = rdc.SelectedObjects
self.select(objs)
if len(objs) > 1:
typ = "-multiple selection-"
elif len(objs) == 0:
typ = "None"
else:
typ = objs[0].__class__.__name__
self.lblType.Caption = typ
def editColor(self, objs, prop, val):
# Override base editColor: need to convert stringified rl tuple to
# rgb tuple.
try:
rgbTuple = eval(val)
except:
rgbTuple = None
if rgbTuple is None:
rgbTuple = (0, 0, 0)
rgbTuple = rdc.ActiveEditor._rw.getColorTupleFromReportLab(rgbTuple)
super(ReportPropSheet, self).editColor(objs, prop, val)
class PropSheetForm(DesignerControllerForm):
def initProperties(self):
super(PropSheetForm, self).initProperties()
self.Caption = "Report Properties"
self.EditorClass = ReportPropSheet
self.Controller = (
self.Application
) ## r7033 changed to allow for non-application controllers.
class DesignerPanel(dPanel):
def onGotFocus(self, evt):
# Microsoft Windows gives the keyboard focus to sub-panels, which
# really sucks. This takes care of it.
rdc.ActiveEditor.SetFocusIgnoringChildren()
# ------------------------------------------------------------------------------
# BandLabel Class
#
class BandLabel(DesignerPanel):
"""Base class for the movable label at the bottom of each band.
These are the bands like pageHeader, pageFooter, and detail that
the user can drag up and down to make the band smaller or larger,
respectively.
"""
def afterInit(self):
self._dragging = False
self._dragStart = (0, 0)
self._dragImage = None
def copy(self):