]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/tools/XRCed/tree.py
1e77eac3a4554da23f5ecea7c69332ee609c4a68
[wxWidgets.git] / wxPython / wx / tools / XRCed / tree.py
1 # Name: tree.py
2 # Purpose: XRC editor, XML_tree class
3 # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be>
4 # Created: 02.12.2002
5 # RCS-ID: $Id$
6
7 from xxx import * # xxx imports globals and params
8 import types
9 import traceback
10
11 # Constant to define standart window name
12 STD_NAME = '_XRCED_T_W'
13
14 # Icons
15 import images
16
17 class MemoryFile:
18 def __init__(self, name):
19 self.name = name
20 self.buffer = ''
21 def write(self, data):
22 if g.currentEncoding:
23 encoding = g.currentEncoding
24 else:
25 encoding = wx.GetDefaultPyEncoding()
26 try:
27 self.buffer += data.encode(encoding)
28 except UnicodeEncodeError:
29 self.buffer += data.encode(encoding, 'xmlcharrefreplace')
30
31 def close(self):
32 wx.MemoryFSHandler.AddFile(self.name, self.buffer)
33
34 ################################################################################
35
36 # Redefine writing to include encoding
37 class MyDocument(minidom.Document):
38 def __init__(self):
39 minidom.Document.__init__(self)
40 self.encoding = ''
41 def writexml(self, writer, indent="", addindent="", newl="", encoding=""):
42 if encoding: encdstr = 'encoding="%s"' % encoding
43 else: encdstr = ''
44 writer.write('<?xml version="1.0" %s?>\n' % encdstr)
45 for node in self.childNodes:
46 node.writexml(writer, indent, addindent, newl)
47
48 ################################################################################
49
50 # Ids for menu commands
51 class ID_NEW:
52 PANEL = wx.NewId()
53 DIALOG = wx.NewId()
54 FRAME = wx.NewId()
55 TOOL_BAR = wx.NewId()
56 TOOL = wx.NewId()
57 MENU_BAR = wx.NewId()
58 MENU = wx.NewId()
59 STATUS_BAR = wx.NewId()
60
61 STATIC_TEXT = wx.NewId()
62 TEXT_CTRL = wx.NewId()
63
64 BUTTON = wx.NewId()
65 BITMAP_BUTTON = wx.NewId()
66 RADIO_BUTTON = wx.NewId()
67 SPIN_BUTTON = wx.NewId()
68 TOGGLE_BUTTON = wx.NewId()
69
70 STATIC_BOX = wx.NewId()
71 CHECK_BOX = wx.NewId()
72 RADIO_BOX = wx.NewId()
73 COMBO_BOX = wx.NewId()
74 LIST_BOX = wx.NewId()
75
76 STATIC_LINE = wx.NewId()
77 STATIC_BITMAP = wx.NewId()
78 CHOICE = wx.NewId()
79 SLIDER = wx.NewId()
80 GAUGE = wx.NewId()
81 SCROLL_BAR = wx.NewId()
82 TREE_CTRL = wx.NewId()
83 LIST_CTRL = wx.NewId()
84 CHECK_LIST = wx.NewId()
85 NOTEBOOK = wx.NewId()
86 CHOICEBOOK = wx.NewId()
87 LISTBOOK = wx.NewId()
88 SPLITTER_WINDOW = wx.NewId()
89 GRID = wx.NewId()
90 SCROLLED_WINDOW = wx.NewId()
91 HTML_WINDOW = wx.NewId()
92 CALENDAR_CTRL = wx.NewId()
93 DATE_CTRL = wx.NewId()
94 FILE_PICKER_CTRL = wx.NewId()
95 GENERIC_DIR_CTRL = wx.NewId()
96 SPIN_CTRL = wx.NewId()
97 UNKNOWN = wx.NewId()
98 WIZARD = wx.NewId()
99 WIZARD_PAGE = wx.NewId()
100 WIZARD_PAGE_SIMPLE = wx.NewId()
101 BITMAP = wx.NewId()
102 ICON = wx.NewId()
103 STATUS_BAR = wx.NewId()
104
105 BOX_SIZER = wx.NewId()
106 STATIC_BOX_SIZER = wx.NewId()
107 GRID_SIZER = wx.NewId()
108 FLEX_GRID_SIZER = wx.NewId()
109 GRID_BAG_SIZER = wx.NewId()
110 STD_DIALOG_BUTTON_SIZER = wx.NewId()
111 SPACER = wx.NewId()
112
113 TOOL_BAR = wx.NewId()
114 TOOL = wx.NewId()
115 MENU = wx.NewId()
116 MENU_ITEM = wx.NewId()
117 SEPARATOR = wx.NewId()
118
119 OK_BUTTON = wx.NewId()
120 YES_BUTTON = wx.NewId()
121 SAVE_BUTTON = wx.NewId()
122 APPLY_BUTTON = wx.NewId()
123 NO_BUTTON = wx.NewId()
124 CANCEL_BUTTON = wx.NewId()
125 HELP_BUTTON = wx.NewId()
126 CONTEXT_HELP_BUTTON = wx.NewId()
127
128 REF = wx.NewId()
129 COMMENT = wx.NewId()
130
131 CUSTOM = wx.NewId()
132 for i in range(99): wx.NewId() # reserve IDs for custom controls
133
134 LAST = wx.NewId()
135
136
137
138 class PullDownMenu:
139 ID_EXPAND = wx.NewId()
140 ID_COLLAPSE = wx.NewId()
141 ID_PASTE_SIBLING = wx.NewId()
142 ID_TOOL_PASTE = wx.NewId()
143 ID_SUBCLASS = wx.NewId()
144
145 def __init__(self, parent):
146 self.ID_DELETE = parent.ID_DELETE
147 wx.EVT_MENU_RANGE(parent, ID_NEW.PANEL, ID_NEW.LAST, parent.OnCreate)
148 wx.EVT_MENU_RANGE(parent, 1000 + ID_NEW.PANEL, 1000 + ID_NEW.LAST, parent.OnReplace)
149 wx.EVT_MENU(parent, self.ID_COLLAPSE, parent.OnCollapse)
150 wx.EVT_MENU(parent, self.ID_EXPAND, parent.OnExpand)
151 wx.EVT_MENU(parent, self.ID_PASTE_SIBLING, parent.OnPaste)
152 wx.EVT_MENU(parent, self.ID_SUBCLASS, parent.OnSubclass)
153 # We connect to tree, but process in frame
154 wx.EVT_MENU_HIGHLIGHT_ALL(g.tree, parent.OnPullDownHighlight)
155
156 # Mapping from IDs to element names
157 self.createMap = {
158 ID_NEW.PANEL: 'wxPanel',
159 ID_NEW.DIALOG: 'wxDialog',
160 ID_NEW.FRAME: 'wxFrame',
161 ID_NEW.WIZARD: 'wxWizard',
162 ID_NEW.WIZARD_PAGE: 'wxWizardPage',
163 ID_NEW.WIZARD_PAGE_SIMPLE: 'wxWizardPageSimple',
164 ID_NEW.TOOL_BAR: 'wxToolBar',
165 ID_NEW.TOOL: 'tool',
166 ID_NEW.STATUS_BAR: 'wxStatusBar',
167 ID_NEW.MENU_BAR: 'wxMenuBar',
168 ID_NEW.MENU: 'wxMenu',
169 ID_NEW.MENU_ITEM: 'wxMenuItem',
170 ID_NEW.BITMAP: 'wxBitmap',
171 ID_NEW.ICON: 'wxIcon',
172 ID_NEW.SEPARATOR: 'separator',
173
174 ID_NEW.STATIC_TEXT: 'wxStaticText',
175 ID_NEW.TEXT_CTRL: 'wxTextCtrl',
176
177 ID_NEW.BUTTON: 'wxButton',
178 ID_NEW.BITMAP_BUTTON: 'wxBitmapButton',
179 ID_NEW.RADIO_BUTTON: 'wxRadioButton',
180 ID_NEW.SPIN_BUTTON: 'wxSpinButton',
181 ID_NEW.TOGGLE_BUTTON: 'wxToggleButton',
182
183 ID_NEW.STATIC_BOX: 'wxStaticBox',
184 ID_NEW.CHECK_BOX: 'wxCheckBox',
185 ID_NEW.RADIO_BOX: 'wxRadioBox',
186 ID_NEW.COMBO_BOX: 'wxComboBox',
187 ID_NEW.LIST_BOX: 'wxListBox',
188 ID_NEW.CHECK_LIST: 'wxCheckListBox',
189
190 ID_NEW.STATIC_LINE: 'wxStaticLine',
191 ID_NEW.STATIC_BITMAP: 'wxStaticBitmap',
192 ID_NEW.CHOICE: 'wxChoice',
193 ID_NEW.SLIDER: 'wxSlider',
194 ID_NEW.GAUGE: 'wxGauge',
195 ID_NEW.SCROLL_BAR: 'wxScrollBar',
196 ID_NEW.TREE_CTRL: 'wxTreeCtrl',
197 ID_NEW.LIST_CTRL: 'wxListCtrl',
198 ID_NEW.NOTEBOOK: 'wxNotebook',
199 ID_NEW.CHOICEBOOK: 'wxChoicebook',
200 ID_NEW.LISTBOOK: 'wxListbook',
201 ID_NEW.SPLITTER_WINDOW: 'wxSplitterWindow',
202 ID_NEW.GRID: 'wxGrid',
203 ID_NEW.SCROLLED_WINDOW: 'wxScrolledWindow',
204 ID_NEW.HTML_WINDOW: 'wxHtmlWindow',
205 ID_NEW.CALENDAR_CTRL: 'wxCalendarCtrl',
206 ID_NEW.DATE_CTRL: 'wxDatePickerCtrl',
207 ID_NEW.FILE_PICKER_CTRL: 'wxFilePickerCtrl',
208 ID_NEW.GENERIC_DIR_CTRL: 'wxGenericDirCtrl',
209 ID_NEW.SPIN_CTRL: 'wxSpinCtrl',
210
211 ID_NEW.BOX_SIZER: 'wxBoxSizer',
212 ID_NEW.STATIC_BOX_SIZER: 'wxStaticBoxSizer',
213 ID_NEW.GRID_SIZER: 'wxGridSizer',
214 ID_NEW.FLEX_GRID_SIZER: 'wxFlexGridSizer',
215 ID_NEW.GRID_BAG_SIZER: 'wxGridBagSizer',
216 ID_NEW.STD_DIALOG_BUTTON_SIZER: 'wxStdDialogButtonSizer',
217 ID_NEW.SPACER: 'spacer',
218 ID_NEW.UNKNOWN: 'unknown',
219
220 ID_NEW.OK_BUTTON: 'wxButton',
221 ID_NEW.YES_BUTTON: 'wxButton',
222 ID_NEW.SAVE_BUTTON: 'wxButton',
223 ID_NEW.APPLY_BUTTON: 'wxButton',
224 ID_NEW.NO_BUTTON: 'wxButton',
225 ID_NEW.CANCEL_BUTTON: 'wxButton',
226 ID_NEW.HELP_BUTTON: 'wxButton',
227 ID_NEW.CONTEXT_HELP_BUTTON: 'wxButton',
228 }
229 self.topLevel = [
230 (ID_NEW.PANEL, 'Panel', 'Create panel'),
231 (ID_NEW.DIALOG, 'Dialog', 'Create dialog'),
232 (ID_NEW.FRAME, 'Frame', 'Create frame'),
233 (ID_NEW.WIZARD, 'Wizard', 'Create wizard'),
234 None,
235 (ID_NEW.TOOL_BAR, 'ToolBar', 'Create toolbar'),
236 (ID_NEW.MENU_BAR, 'MenuBar', 'Create menubar'),
237 (ID_NEW.MENU, 'Menu', 'Create menu'),
238 None,
239 (ID_NEW.BITMAP, 'Bitmap', 'Create bitmap'),
240 (ID_NEW.ICON, 'Icon', 'Create icon'),
241 ]
242 self.containers = [
243 (ID_NEW.PANEL, 'Panel', 'Create panel'),
244 (ID_NEW.NOTEBOOK, 'Notebook', 'Create notebook control'),
245 (ID_NEW.CHOICEBOOK, 'Choicebook', 'Create choicebook control'),
246 (ID_NEW.LISTBOOK, 'Listbook', 'Create listbook control'),
247 (ID_NEW.SPLITTER_WINDOW, 'SplitterWindow', 'Create splitter window'),
248 (ID_NEW.TOOL_BAR, 'ToolBar', 'Create toolbar'),
249 (ID_NEW.STATUS_BAR, 'StatusBar', 'Create status bar'),
250 # (ID_NEW.WIZARD_PAGE, 'WizardPage', 'Create wizard page'),
251 (ID_NEW.WIZARD_PAGE_SIMPLE, 'WizardPageSimple', 'Create simple wizard page'),
252 ]
253 self.sizers = [
254 (ID_NEW.BOX_SIZER, 'BoxSizer', 'Create box sizer'),
255 (ID_NEW.STATIC_BOX_SIZER, 'StaticBoxSizer',
256 'Create static box sizer'),
257 (ID_NEW.GRID_SIZER, 'GridSizer', 'Create grid sizer'),
258 (ID_NEW.FLEX_GRID_SIZER, 'FlexGridSizer',
259 'Create flexgrid sizer'),
260 (ID_NEW.GRID_BAG_SIZER, 'GridBagSizer',
261 'Create gridbag sizer'),
262 # (ID_NEW.STD_DIALOG_BUTTON_SIZER, 'StdDialogButtonSizer',
263 # 'Create standard button sizer'),
264 (ID_NEW.SPACER, 'Spacer', 'Create spacer'),
265 ]
266 self.controls = [
267 ['control', 'Various controls',
268 (ID_NEW.STATIC_TEXT, 'Label', 'Create label'),
269 (ID_NEW.STATIC_BITMAP, 'Bitmap', 'Create bitmap'),
270 (ID_NEW.STATIC_LINE, 'Line', 'Create line'),
271 (ID_NEW.TEXT_CTRL, 'TextBox', 'Create text box'),
272 (ID_NEW.CHOICE, 'Choice', 'Create choice'),
273 (ID_NEW.SLIDER, 'Slider', 'Create slider'),
274 (ID_NEW.GAUGE, 'Gauge', 'Create gauge'),
275 (ID_NEW.SPIN_CTRL, 'SpinCtrl', 'Create spin'),
276 (ID_NEW.SCROLL_BAR, 'ScrollBar', 'Create scroll bar'),
277 (ID_NEW.TREE_CTRL, 'TreeCtrl', 'Create tree'),
278 (ID_NEW.LIST_CTRL, 'ListCtrl', 'Create list'),
279 # (ID_NEW.GRID, 'Grid', 'Create grid'),
280 (ID_NEW.SCROLLED_WINDOW, 'ScrolledWindow', 'Create scrolled window'),
281 (ID_NEW.HTML_WINDOW, 'HtmlWindow', 'Create HTML window'),
282 (ID_NEW.CALENDAR_CTRL, 'CalendarCtrl', 'Create calendar control'),
283 (ID_NEW.DATE_CTRL, 'DatePickerCtrl', 'Create date picker control'),
284 # (ID_NEW.FILE_PICKER_CTRL, 'FilePickerCtrl', 'Create file picker control'),
285 (ID_NEW.GENERIC_DIR_CTRL, 'GenericDirCtrl', 'Create generic dir control'),
286 (ID_NEW.UNKNOWN, 'Unknown', 'Create custom control placeholder'),
287 ],
288 ['button', 'Buttons',
289 (ID_NEW.BUTTON, 'Button', 'Create button'),
290 (ID_NEW.BITMAP_BUTTON, 'BitmapButton', 'Create bitmap button'),
291 (ID_NEW.RADIO_BUTTON, 'RadioButton', 'Create radio button'),
292 (ID_NEW.SPIN_BUTTON, 'SpinButton', 'Create spin button'),
293 (ID_NEW.TOGGLE_BUTTON, 'ToggleButton', 'Create toggle button'),
294 ],
295 ['box', 'Boxes',
296 (ID_NEW.STATIC_BOX, 'StaticBox', 'Create static box'),
297 (ID_NEW.CHECK_BOX, 'CheckBox', 'Create check box'),
298 (ID_NEW.RADIO_BOX, 'RadioBox', 'Create radio box'),
299 (ID_NEW.COMBO_BOX, 'ComboBox', 'Create combo box'),
300 (ID_NEW.LIST_BOX, 'ListBox', 'Create list box'),
301 (ID_NEW.CHECK_LIST, 'CheckListBox', 'Create checklist box'),
302 ],
303 ['container', 'Containers',
304 (ID_NEW.PANEL, 'Panel', 'Create panel'),
305 (ID_NEW.NOTEBOOK, 'Notebook', 'Create notebook control'),
306 (ID_NEW.CHOICEBOOK, 'Choicebook', 'Create choicebook control'),
307 (ID_NEW.LISTBOOK, 'Listbook', 'Create listbook control'),
308 (ID_NEW.SPLITTER_WINDOW, 'SplitterWindow', 'Create splitter window'),
309 (ID_NEW.TOOL_BAR, 'ToolBar', 'Create toolbar'),
310 (ID_NEW.STATUS_BAR, 'StatusBar', 'Create status bar'),
311 (ID_NEW.MENU_BAR, 'MenuBar', 'Create menubar'),
312 # (ID_NEW.WIZARD_PAGE, 'Wizard Page', 'Create wizard page'),
313 (ID_NEW.WIZARD_PAGE_SIMPLE, 'WizardPageSimple', 'Create simple wizard page'),
314 ],
315 ['sizer', 'Sizers',
316 (ID_NEW.BOX_SIZER, 'BoxSizer', 'Create box sizer'),
317 (ID_NEW.STATIC_BOX_SIZER, 'StaticBoxSizer',
318 'Create static box sizer'),
319 (ID_NEW.GRID_SIZER, 'GridSizer', 'Create grid sizer'),
320 (ID_NEW.FLEX_GRID_SIZER, 'FlexGridSizer',
321 'Create flexgrid sizer'),
322 (ID_NEW.GRID_BAG_SIZER, 'GridBagSizer',
323 'Create gridbag sizer'),
324 (ID_NEW.SPACER, 'Spacer', 'Create spacer'),
325 (ID_NEW.STD_DIALOG_BUTTON_SIZER, 'StdDialogButtonSizer',
326 'Create standard button sizer'),
327 ]
328 ]
329 self.menuControls = [
330 (ID_NEW.MENU, 'Menu', 'Create menu'),
331 (ID_NEW.MENU_ITEM, 'MenuItem', 'Create menu item'),
332 (ID_NEW.SEPARATOR, 'Separator', 'Create separator'),
333 ]
334 self.toolBarControls = [
335 (ID_NEW.TOOL, 'Tool', 'Create tool'),
336 (ID_NEW.SEPARATOR, 'Separator', 'Create separator'),
337 ['control', 'Various controls',
338 (ID_NEW.STATIC_TEXT, 'Label', 'Create label'),
339 (ID_NEW.STATIC_BITMAP, 'Bitmap', 'Create bitmap'),
340 (ID_NEW.STATIC_LINE, 'Line', 'Create line'),
341 (ID_NEW.TEXT_CTRL, 'TextBox', 'Create text box'),
342 (ID_NEW.CHOICE, 'Choice', 'Create choice'),
343 (ID_NEW.SLIDER, 'Slider', 'Create slider'),
344 (ID_NEW.GAUGE, 'Gauge', 'Create gauge'),
345 (ID_NEW.SCROLL_BAR, 'ScrollBar', 'Create scroll bar'),
346 (ID_NEW.LIST_CTRL, 'ListCtrl', 'Create list control'),
347 ],
348 ['button', 'Buttons',
349 (ID_NEW.BUTTON, 'Button', 'Create button'),
350 (ID_NEW.BITMAP_BUTTON, 'BitmapButton', 'Create bitmap button'),
351 (ID_NEW.RADIO_BUTTON, 'RadioButton', 'Create radio button'),
352 (ID_NEW.SPIN_BUTTON, 'SpinButton', 'Create spin button'),
353 ],
354 ['box', 'Boxes',
355 (ID_NEW.STATIC_BOX, 'StaticBox', 'Create static box'),
356 (ID_NEW.CHECK_BOX, 'CheckBox', 'Create check box'),
357 (ID_NEW.RADIO_BOX, 'RadioBox', 'Create radio box'),
358 (ID_NEW.COMBO_BOX, 'ComboBox', 'Create combo box'),
359 (ID_NEW.LIST_BOX, 'ListBox', 'Create list box'),
360 (ID_NEW.CHECK_LIST, 'CheckListBox', 'Create checklist box'),
361 ],
362 ]
363 self.stdButtons = [
364 (ID_NEW.OK_BUTTON, 'OK Button', 'Create standard button'),
365 (ID_NEW.YES_BUTTON, 'YES Button', 'Create standard button'),
366 (ID_NEW.SAVE_BUTTON, 'SAVE Button', 'Create standard button'),
367 (ID_NEW.APPLY_BUTTON, 'APPLY Button', 'Create standard button'),
368 (ID_NEW.NO_BUTTON, 'NO Button', 'Create standard button'),
369 (ID_NEW.CANCEL_BUTTON, 'CANCEL Button', 'Create standard button'),
370 (ID_NEW.HELP_BUTTON, 'HELP Button', 'Create standard button'),
371 (ID_NEW.CONTEXT_HELP_BUTTON, 'CONTEXT HELP Button', 'Create standard button'),
372 ]
373 self.stdButtonIDs = {
374 ID_NEW.OK_BUTTON: ('wxID_OK', '&Ok'),
375 ID_NEW.YES_BUTTON: ('wxID_YES', '&Yes'),
376 ID_NEW.SAVE_BUTTON: ('wxID_SAVE', '&Save'),
377 ID_NEW.APPLY_BUTTON: ('wxID_APPLY', '&Apply'),
378 ID_NEW.NO_BUTTON: ('wxID_NO', '&No'),
379 ID_NEW.CANCEL_BUTTON: ('wxID_CANCEL', '&Cancel'),
380 ID_NEW.HELP_BUTTON: ('wxID_HELP', '&Help'),
381 ID_NEW.CONTEXT_HELP_BUTTON: ('wxID_CONTEXT_HELP', '&Help'),
382 }
383 self.custom = ['custom', 'User-defined controls']
384 self.customMap = {}
385
386 def addCustom(self, klass):
387 n = len(self.custom)-2
388 self.custom.append((ID_NEW.CUSTOM + n, klass))
389 self.customMap[ID_NEW.CUSTOM + n] = klass
390
391
392 ################################################################################
393
394 # Set menu to list items.
395 # Each menu command is a tuple (id, label, help)
396 # submenus are lists [id, label, help, submenu]
397 # and separators are any other type. Shift is for making
398 # alternative sets of IDs. (+1000).
399 def SetMenu(m, list, shift=False):
400 for l in list:
401 if type(l) == types.TupleType:
402 # Shift ID
403 if shift: l = (1000 + l[0],) + l[1:]
404 apply(m.Append, l)
405 elif type(l) == types.ListType:
406 subMenu = wx.Menu()
407 SetMenu(subMenu, l[2:], shift)
408 m.AppendMenu(wx.NewId(), l[0], subMenu, l[1])
409 else: # separator
410 m.AppendSeparator()
411
412 ################################################################################
413
414 class HighLightBox:
415 colour = None
416 def __init__(self, pos, size):
417 colour = g.tree.COLOUR_HL
418 if size.width == -1: size.width = 0
419 if size.height == -1: size.height = 0
420 w = g.testWin.panel
421 l1 = wx.Window(w, -1, pos, wx.Size(size.width, 2))
422 l1.SetBackgroundColour(colour)
423 l2 = wx.Window(w, -1, pos, wx.Size(2, size.height))
424 l2.SetBackgroundColour(colour)
425 l3 = wx.Window(w, -1, wx.Point(pos.x + size.width - 2, pos.y), wx.Size(2, size.height))
426 l3.SetBackgroundColour(colour)
427 l4 = wx.Window(w, -1, wx.Point(pos.x, pos.y + size.height - 2), wx.Size(size.width, 2))
428 l4.SetBackgroundColour(colour)
429 self.lines = [l1, l2, l3, l4]
430 if wx.Platform == '__WXMSW__':
431 for l in self.lines:
432 l.Bind(wx.EVT_PAINT, self.OnPaint)
433 g.testWin.highLight = self
434 self.size = size
435 # Repainting is not always done for these windows on Windows
436 def OnPaint(self, evt):
437 w = evt.GetEventObject()
438 dc = wx.PaintDC(w)
439 w.ClearBackground()
440 dc.Destroy()
441 # Move highlight to a new position
442 def Replace(self, pos, size):
443 if size.width == -1: size.width = 0
444 if size.height == -1: size.height = 0
445 self.lines[0].SetDimensions(pos.x, pos.y, size.width, 2)
446 self.lines[1].SetDimensions(pos.x, pos.y, 2, size.height)
447 self.lines[2].SetDimensions(pos.x + size.width - 2, pos.y, 2, size.height)
448 self.lines[3].SetDimensions(pos.x, pos.y + size.height - 2, size.width, 2)
449 self.size = size
450 def Remove(self):
451 map(wx.Window.Destroy, self.lines)
452 g.testWin.highLight = None
453 def Refresh(self):
454 map(wx.Window.Refresh, self.lines)
455
456 # Same for drop target
457 class HighLightDTBox(HighLightBox):
458 colour = None
459 def __init__(self, pos, size):
460 colour = g.tree.COLOUR_DT
461 if size.width == -1: size.width = 0
462 if size.height == -1: size.height = 0
463 w = g.testWin.panel
464 l1 = wx.Window(w, -1, pos, wx.Size(size.width, 2))
465 l1.SetBackgroundColour(colour)
466 l2 = wx.Window(w, -1, pos, wx.Size(2, size.height))
467 l2.SetBackgroundColour(colour)
468 l3 = wx.Window(w, -1, wx.Point(pos.x + size.width - 2, pos.y), wx.Size(2, size.height))
469 l3.SetBackgroundColour(colour)
470 l4 = wx.Window(w, -1, wx.Point(pos.x, pos.y + size.height - 2), wx.Size(size.width, 2))
471 l4.SetBackgroundColour(colour)
472 self.lines = [l1, l2, l3, l4]
473 self.item = None
474 self.size = size
475 # Remove it
476 def Remove(self):
477 map(wx.Window.Destroy, self.lines)
478 g.testWin.highLightDT = None
479
480 def updateHL(hl, hlClass, pos, size):
481 # Need to recreate window if size did not change to force update
482 if hl and hl.size == size:
483 hl.Remove()
484 hl = None
485 if hl:
486 hl.Replace(pos, size)
487 else:
488 hl = hlClass(pos, size)
489 hl.Refresh()
490 return hl
491
492 ################################################################################
493
494 class XML_Tree(wx.TreeCtrl):
495 def __init__(self, parent, id):
496 # Item colour
497 self.COLOUR_COMMENT = wx.Colour(0, 0, 255)
498 self.COLOUR_REF = wx.Colour(0, 0, 128)
499 self.COLOUR_HIDDEN = wx.Colour(128, 128, 128)
500 self.COLOUR_HL = wx.Colour(255, 0, 0)
501 self.COLOUR_DT = wx.Colour(0, 64, 0)
502
503 wx.TreeCtrl.__init__(self, parent, id,
504 style = wx.TR_HAS_BUTTONS | wx.TR_MULTIPLE | wx.TR_EDIT_LABELS)
505 self.SetBackgroundColour(wx.Colour(224, 248, 224))
506 self.fontComment = wx.FFont(self.GetFont().GetPointSize(),
507 self.GetFont().GetFamily(),
508 wx.FONTFLAG_ITALIC)
509 # Register events
510 wx.EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged)
511 # One works on Linux, another on Windows
512 if wx.Platform == '__WXGTK__': # !!! MAC too?
513 wx.EVT_TREE_ITEM_ACTIVATED(self, self.GetId(), self.OnItemActivated)
514 else:
515 wx.EVT_LEFT_DCLICK(self, self.OnDClick)
516 wx.EVT_RIGHT_DOWN(self, self.OnRightDown)
517 wx.EVT_TREE_ITEM_EXPANDED(self, self.GetId(), self.OnItemExpandedCollapsed)
518 wx.EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemExpandedCollapsed)
519 self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginLabelEdit)
520 self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndLabelEdit)
521
522 self.selection = None
523 self.selectionChanging = False
524 self.needUpdate = False
525 self.pendingHighLight = None
526 self.ctrl = self.shift = False
527 self.dom = None
528 # Create image list
529 il = wx.ImageList(16, 16, True)
530 self.rootImage = il.Add(images.getTreeRootImage().Scale(16,16).ConvertToBitmap())
531 xxxComment.image = il.Add(images.getTreeCommentImage().Scale(16,16).ConvertToBitmap())
532 xxxObject.image = il.Add(images.getTreeDefaultImage().Scale(16,16).ConvertToBitmap())
533 xxxPanel.image = il.Add(images.getTreePanelImage().Scale(16,16).ConvertToBitmap())
534 xxxDialog.image = il.Add(images.getTreeDialogImage().Scale(16,16).ConvertToBitmap())
535 xxxFrame.image = il.Add(images.getTreeFrameImage().Scale(16,16).ConvertToBitmap())
536 xxxMenuBar.image = il.Add(images.getTreeMenuBarImage().Scale(16,16).ConvertToBitmap())
537 xxxMenu.image = il.Add(images.getTreeMenuImage().Scale(16,16).ConvertToBitmap())
538 xxxMenuItem.image = il.Add(images.getTreeMenuItemImage().Scale(16,16).ConvertToBitmap())
539 xxxToolBar.image = il.Add(images.getTreeToolBarImage().Scale(16,16).ConvertToBitmap())
540 xxxTool.image = il.Add(images.getTreeToolImage().Scale(16,16).ConvertToBitmap())
541 xxxSeparator.image = il.Add(images.getTreeSeparatorImage().Scale(16,16).ConvertToBitmap())
542 xxxSizer.imageH = il.Add(images.getTreeSizerHImage().Scale(16,16).ConvertToBitmap())
543 xxxSizer.imageV = il.Add(images.getTreeSizerVImage().Scale(16,16).ConvertToBitmap())
544 xxxStaticBoxSizer.imageH = il.Add(images.getTreeStaticBoxSizerHImage().Scale(16,16).ConvertToBitmap())
545 xxxStaticBoxSizer.imageV = il.Add(images.getTreeStaticBoxSizerVImage().Scale(16,16).ConvertToBitmap())
546 xxxGridSizer.image = il.Add(images.getTreeSizerGridImage().Scale(16,16).ConvertToBitmap())
547 xxxFlexGridSizer.image = il.Add(images.getTreeSizerFlexGridImage().Scale(16,16).ConvertToBitmap())
548 self.il = il
549 self.SetImageList(il)
550
551 def RegisterKeyEvents(self):
552 wx.EVT_KEY_DOWN(self, g.tools.OnKeyDown)
553 wx.EVT_KEY_UP(self, g.tools.OnKeyUp)
554 wx.EVT_ENTER_WINDOW(self, g.tools.OnMouse)
555 wx.EVT_LEAVE_WINDOW(self, g.tools.OnMouse)
556
557 def ExpandAll(self, item):
558 if self.ItemHasChildren(item):
559 self.Expand(item)
560 i, cookie = self.GetFirstChild(item)
561 children = []
562 while i.IsOk():
563 children.append(i)
564 i, cookie = self.GetNextChild(item, cookie)
565 for i in children:
566 self.ExpandAll(i)
567 def CollapseAll(self, item):
568 if self.ItemHasChildren(item):
569 i, cookie = self.GetFirstChild(item)
570 children = []
571 while i.IsOk():
572 children.append(i)
573 i, cookie = self.GetNextChild(item, cookie)
574 for i in children:
575 self.CollapseAll(i)
576 self.Collapse(item)
577
578 # Clear tree
579 def Clear(self):
580 self.UnselectAll()
581 self.DeleteAllItems()
582 # Add minimal structure
583 if self.dom: self.dom.unlink()
584 self.dom = MyDocument()
585 self.dummyNode = self.dom.createComment('dummy node')
586 # Create main node
587 self.mainNode = self.dom.createElement('resource')
588 self.dom.appendChild(self.mainNode)
589 self.rootObj = xxxMainNode(self.dom)
590 self.root = self.AddRoot('XML tree', self.rootImage,
591 data=wx.TreeItemData(self.rootObj))
592 self.itemColour = self.GetItemTextColour(self.root)
593 self.SetItemHasChildren(self.root)
594 self.testElem = self.dom.createElement('dummy')
595 self.mainNode.appendChild(self.testElem)
596 self.Expand(self.root)
597
598 # Clear old data and set new
599 def SetData(self, dom):
600 self.UnselectAll()
601 self.DeleteAllItems()
602 # Add minimal structure
603 if self.dom: self.dom.unlink()
604 self.dom = dom
605 self.dummyNode = self.dom.createComment('dummy node')
606 # Find 'resource' child, add it's children
607 self.mainNode = dom.documentElement
608 self.rootObj = xxxMainNode(self.dom)
609 self.root = self.AddRoot('XML tree', self.rootImage,
610 data=wx.TreeItemData(self.rootObj))
611 self.SetItemHasChildren(self.root)
612 nodes = self.mainNode.childNodes[:]
613 for node in nodes:
614 if IsObject(node):
615 self.AddNode(self.root, None, node)
616 else:
617 self.mainNode.removeChild(node)
618 node.unlink()
619 if self.mainNode.firstChild:
620 self.testElem = self.dom.createElement('dummy')
621 self.mainNode.insertBefore(self.testElem, self.mainNode.firstChild)
622 else:
623 self.testElem = self.dom.createElement('dummy')
624 self.mainNode.appendChild(self.testElem)
625 self.Expand(self.root)
626
627 # Add tree item for given parent item if node is DOM element node with
628 # object/object_ref tag. xxxParent is parent xxx object
629 def AddNode(self, itemParent, xxxParent, node):
630 # Set item data to current node
631 try:
632 xxx = MakeXXXFromDOM(xxxParent, node)
633 except:
634 print 'ERROR: MakeXXXFromDom(%s, %s)' % (xxxParent, node)
635 raise
636 treeObj = xxx.treeObject()
637 # Append tree item
638 item = self.AppendItem(itemParent, treeObj.treeName(),
639 image=treeObj.treeImage(),
640 data=wx.TreeItemData(xxx))
641 # Different color for comments and references
642 if xxx.className == 'comment':
643 self.SetItemTextColour(item, self.COLOUR_COMMENT)
644 self.SetItemFont(item, self.fontComment)
645 elif treeObj.ref:
646 self.SetItemTextColour(item, self.COLOUR_REF)
647 elif treeObj.hasStyle and treeObj.params.get('hidden', False):
648 self.SetItemTextColour(item, self.COLOUR_HIDDEN)
649 # Try to find children objects
650 if treeObj.hasChildren:
651 nodes = treeObj.node.childNodes[:]
652 for n in nodes:
653 if IsObject(n):
654 self.AddNode(item, treeObj, n)
655 elif n.nodeType != minidom.Node.ELEMENT_NODE:
656 treeObj.node.removeChild(n)
657 n.unlink()
658
659 # Insert new item at specific position
660 def InsertNode(self, itemParent, parent, elem, nextItem):
661 # Insert in XML tree and wxWin
662 xxx = MakeXXXFromDOM(parent, elem)
663 # If nextItem is None, we append to parent, otherwise insert before it
664 if nextItem.IsOk():
665 node = self.GetPyData(nextItem).node
666 parent.node.insertBefore(elem, node)
667 # Inserting before is difficult, se we insert after or first child
668 index = self.ItemIndex(nextItem)
669 newItem = self.InsertItemBefore(itemParent, index,
670 xxx.treeName(), image=xxx.treeImage())
671 self.SetPyData(newItem, xxx)
672 else:
673 parent.node.appendChild(elem)
674 newItem = self.AppendItem(itemParent, xxx.treeName(), image=xxx.treeImage(),
675 data=wx.TreeItemData(xxx))
676 treeObj = xxx.treeObject()
677 # Different color for references and comments
678 if xxx.className == 'comment':
679 self.SetItemTextColour(newItem, self.COLOUR_COMMENT)
680 self.SetItemFont(newItem, self.fontComment)
681 elif treeObj.ref:
682 self.SetItemTextColour(newItem, self.COLOUR_REF)
683 elif treeObj.hasStyle and treeObj.params.get('hidden', False):
684 self.SetItemTextColour(newItem, self.COLOUR_HIDDEN)
685 # Add children items
686 if xxx.hasChildren:
687 treeObj = xxx.treeObject()
688 for n in treeObj.node.childNodes:
689 if IsObject(n):
690 self.AddNode(newItem, treeObj, n)
691 return newItem
692
693 # Remove leaf of tree, return it's data object
694 def RemoveLeaf(self, leaf):
695 xxx = self.GetPyData(leaf)
696 node = xxx.node
697 parent = node.parentNode
698 parent.removeChild(node)
699 self.Delete(leaf)
700 return node
701
702 # Find position relative to the top-level window
703 def FindNodePos(self, item, obj=None):
704 # Root at (0,0)
705 if item == g.testWin.item: return wx.Point(0, 0)
706 itemParent = self.GetItemParent(item)
707 # Select book page
708 if not obj: obj = self.FindNodeObject(item)
709 if self.GetPyData(itemParent).treeObject().__class__ in \
710 [xxxNotebook, xxxChoicebook, xxxListbook]:
711 book = self.FindNodeObject(itemParent)
712 # Find position
713 for i in range(book.GetPageCount()):
714 if book.GetPage(i) == obj:
715 if book.GetSelection() != i:
716 book.SetSelection(i)
717 # Remove highlight - otherwise highlight window won't be visible
718 if g.testWin.highLight:
719 g.testWin.highLight.Remove()
720 break
721 # For sizers and notebooks we must select the first window-like parent
722 winParent = itemParent
723 while self.GetPyData(winParent).isSizer:
724 winParent = self.GetItemParent(winParent)
725 # Notebook children are layed out in a little strange way
726 # wxGTK places NB panels relative to the NB parent
727 if wx.Platform == '__WXGTK__':
728 if self.GetPyData(itemParent).treeObject().__class__ == xxxNotebook:
729 winParent = self.GetItemParent(winParent)
730 parentPos = self.FindNodePos(winParent)
731 pos = obj.GetPosition()
732 # Position (-1,-1) is really (0,0)
733 if pos == (-1,-1): pos = (0,0)
734 return parentPos + pos
735
736 # Find window (or sizer) corresponding to a tree item.
737 def FindNodeObject(self, item):
738 testWin = g.testWin
739 # If top-level, return testWin (or panel its panel)
740 if item == testWin.item: return testWin.panel
741 itemParent = self.GetItemParent(item)
742 xxx = self.GetPyData(item).treeObject()
743 parentWin = self.FindNodeObject(itemParent)
744 # Top-level sizer? return window's sizer
745 if xxx.isSizer and isinstance(parentWin, wx.Window):
746 return parentWin.GetSizer()
747 elif xxx.__class__ in [xxxMenu, xxxMenuItem, xxxSeparator]: return None
748 elif xxx.__class__ in [xxxToolBar, xxxMenuBar]:
749 # If it's the main toolbar or menubar, we can't really select it
750 if xxx.parent.__class__ == xxxFrame: return None
751 elif isinstance(xxx.parent, xxxToolBar):
752 # Select complete toolbar
753 return parentWin
754 elif isinstance(xxx.parent, xxxStdDialogButtonSizer):
755 # This sizer returns non-existing children
756 for ch in parentWin.GetChildren():
757 if ch.GetWindow() and ch.GetWindow().GetName() == xxx.name:
758 return ch.GetWindow()
759 return None
760 elif xxx.parent.__class__ in [xxxChoicebook, xxxListbook]:
761 # First window is controld
762 return parentWin.GetChildren()[self.ItemIndex(item)+1]
763 # Otherwise get parent's object and it's child
764 child = parentWin.GetChildren()[self.WindowIndex(item)]
765 # Return window or sizer for sizer items
766 if child.GetClassName() == 'wxSizerItem':
767 if child.IsWindow(): child = child.GetWindow()
768 elif child.IsSizer():
769 child = child.GetSizer()
770 return child
771
772 def OnSelChanged(self, evt):
773 if self.selectionChanging: return
774 self.selectionChanging = True
775 wx.TreeCtrl.UnselectAll(self)
776 self.ChangeSelection(evt.GetItem())
777 wx.TreeCtrl.SelectItem(self, evt.GetItem())
778 self.selectionChanging = False
779 g.frame.SetStatusText('')
780 evt.Skip()
781
782 # Override to use like single-selection tree
783 def GetSelection(self):
784 return self.selection
785
786 def SelectItem(self, item):
787 self.UnselectAll()
788 self.ChangeSelection(item)
789 wx.TreeCtrl.SelectItem(self, item)
790
791 def UnselectAll(self):
792 self.selection = None
793 g.tools.UpdateUI()
794 wx.TreeCtrl.UnselectAll(self)
795 wx.Yield()
796
797 def ChangeSelection(self, item):
798 # Apply changes
799 # !!! problem with wxGTK - GetOldItem is Ok if nothing selected
800 #oldItem = evt.GetOldItem()
801 status = ''
802 oldItem = self.selection
803 if oldItem:
804 xxx = self.GetPyData(oldItem)
805 # If some data was modified, apply changes
806 if g.panel.IsModified():
807 self.Apply(xxx, oldItem)
808 if g.testWin:
809 if g.testWin.highLight:
810 g.testWin.highLight.Remove()
811 self.needUpdate = True
812 status = 'Changes were applied'
813 if status: g.frame.SetStatusText(status)
814 # Generate view
815 if not item:
816 self.selection = None
817 return
818 else:
819 self.selection = item
820 xxx = self.GetPyData(item)
821 # Update panel
822 g.panel.SetData(xxx)
823 # Update tools
824 g.tools.UpdateUI()
825 # Highlighting is done in OnIdle
826 self.pendingHighLight = self.selection
827
828 # Check if item is in testWin subtree
829 def IsHighlatable(self, item):
830 if item == g.testWin.item: return False
831 while item != self.root:
832 item = self.GetItemParent(item)
833 if item == g.testWin.item:
834 return True
835 return False
836
837 # Highlight selected item
838 def HighLight(self, item):
839 self.pendingHighLight = None
840 # Can highlight only with some top-level windows
841 if not g.testWin or self.GetPyData(g.testWin.item).treeObject().__class__ \
842 not in [xxxDialog, xxxPanel, xxxFrame]:
843 return
844 # If a control from another window is selected, remove highlight
845 if not self.IsHighlatable(item):
846 if g.testWin.highLight: g.testWin.highLight.Remove()
847 return
848 # Get window/sizer object
849 obj = self.FindNodeObject(item)
850 xxx = self.GetPyData(item).treeObject()
851 # Remove existing HL if item not found or is hidden
852 if not obj or xxx.hasStyle and xxx.params.get('hidden', False):
853 if g.testWin.highLight: g.testWin.highLight.Remove()
854 return
855 pos = self.FindNodePos(item, obj)
856 size = obj.GetSize()
857 # Highlight
858 # Negative positions are not working quite well
859 # If highlight object has the same size SetDimension does not repaint it
860 # so we must remove the old HL window
861 g.testWin.highLight = updateHL(g.testWin.highLight, HighLightBox, pos, size)
862 g.testWin.highLight.item = item
863 g.testWin.highLight.obj = obj
864
865 def ShowTestWindow(self, item):
866 xxx = self.GetPyData(item)
867 if g.panel.IsModified():
868 self.Apply(xxx, item) # apply changes
869 availableViews = ['wxFrame', 'wxPanel', 'wxDialog',
870 'wxMenuBar', 'wxToolBar', 'wxWizard',
871 'wxWizardPageSimple']
872 originalItem = item
873 # Walk up the tree until we find an item that has a view
874 while item and self.GetPyData(item).treeObject().className not in availableViews:
875 item = self.GetItemParent(item)
876 if not item or not item.IsOk():
877 wx.LogMessage('No view for this element (yet)')
878 return
879 # Show item in bold
880 if g.testWin: # Reset old
881 self.UnselectAll()
882 self.SetItemBold(g.testWin.item, False)
883 try:
884 wx.BeginBusyCursor()
885 self.CreateTestWin(item)
886 finally:
887 wx.EndBusyCursor()
888 # Maybe an error occurred, so we need to test
889 if g.testWin:
890 self.SetItemBold(g.testWin.item)
891 # Select original item
892 self.ChangeSelection(originalItem)
893
894 # Double-click on Linux
895 def OnItemActivated(self, evt):
896 if evt.GetItem() != self.root:
897 self.ShowTestWindow(evt.GetItem())
898
899 # Double-click on Windows
900 def OnDClick(self, evt):
901 item, flags = self.HitTest(evt.GetPosition())
902 if flags in [wx.TREE_HITTEST_ONITEMBUTTON, wx.TREE_HITTEST_ONITEMLABEL]:
903 if item != self.root: self.ShowTestWindow(item)
904 else:
905 evt.Skip()
906
907 def OnItemExpandedCollapsed(self, evt):
908 # Update tool palette
909 g.tools.UpdateUI()
910 evt.Skip()
911
912 # (re)create test window
913 def CreateTestWin(self, item):
914 testWin = g.testWin
915 # Create a window with this resource
916 xxx = self.GetPyData(item).treeObject()
917 # Close old window, remember where it was
918 highLight = None
919 if testWin:
920 pos = testWin.GetPosition()
921 if item == testWin.item:
922 # Remember highlight if same top-level window
923 if testWin.highLight:
924 highLight = testWin.highLight.item
925 if xxx.className == 'wxPanel':
926 if testWin.highLight:
927 testWin.pendingHighLight = highLight
928 testWin.highLight.Remove()
929 testWin.panel.Destroy()
930 testWin.panel = None
931 else:
932 testWin.Destroy()
933 testWin = g.testWin = None
934 else:
935 testWin.Destroy()
936 testWin = g.testWin = None
937 else:
938 pos = g.testWinPos
939 # Save in memory FS
940 memFile = MemoryFile('xxx.xrc')
941 # Create memory XML file
942 elem = xxx.node.cloneNode(True)
943 if not xxx.name:
944 name = 'noname'
945 else:
946 name = xxx.name
947 elem.setAttribute('name', STD_NAME)
948 oldTestNode = self.testElem
949 self.testElem = elem
950 self.mainNode.replaceChild(elem, oldTestNode)
951 oldTestNode.unlink()
952 # Replace wizard page class temporarily
953 if xxx.__class__ in [xxxWizardPage, xxxWizardPageSimple]:
954 oldCl = elem.getAttribute('class')
955 elem.setAttribute('class', 'wxPanel')
956 parent = elem.parentNode
957 encd = self.rootObj.params['encoding'].value()
958 if not encd: encd = None
959 try:
960 self.dom.writexml(memFile, encoding=encd)
961 except:
962 inf = sys.exc_info()
963 wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1])
964 wx.LogError('Error writing temporary file')
965 memFile.close() # write to wxMemoryFS
966 xmlFlags = xrc.XRC_NO_SUBCLASSING
967 # Use translations if encoding is not specified
968 if not g.currentEncoding:
969 xmlFlags != xrc.XRC_USE_LOCALE
970 res = xrc.XmlResource('', xmlFlags)
971 res.InitAllHandlers()
972 xrc.XmlResource.Set(res) # set as global
973 # Register handlers
974 addHandlers()
975 # Same module list
976 res.Load('memory:xxx.xrc')
977 try:
978 if xxx.__class__ == xxxFrame:
979 # Frame can't have many children,
980 # but it's first child possibly can...
981 # child = self.GetFirstChild(item)[0]
982 # if child.IsOk() and self.GetPyData(child).__class__ == xxxPanel:
983 # # Clean-up before recursive call or error
984 # wx.MemoryFSHandler.RemoveFile('xxx.xrc')
985 # wx.EndBusyCursor()
986 # self.CreateTestWin(child)
987 # return
988 # This currently works under GTK, but not under MSW
989 testWin = g.testWin = wx.PreFrame()
990 res.LoadOnFrame(testWin, g.frame, STD_NAME)
991 # Create status bar
992 testWin.panel = testWin
993 #testWin.CreateStatusBar()
994 testWin.SetClientSize(testWin.GetBestSize())
995 testWin.SetPosition(pos)
996 testWin.Show(True)
997 elif xxx.__class__ == xxxPanel:
998 # Create new frame
999 if not testWin:
1000 testWin = g.testWin = wx.Frame(g.frame, -1, 'Panel: ' + name,
1001 pos=pos, name=STD_NAME)
1002 testWin.panel = res.LoadPanel(testWin, STD_NAME)
1003 testWin.panel.SetSize(testWin.GetClientSize())
1004 #testWin.SetClientSize(testWin.GetSize())
1005 testWin.Show(True)
1006 elif xxx.__class__ == xxxDialog:
1007 testWin = g.testWin = res.LoadDialog(g.frame, STD_NAME)
1008 testWin.panel = testWin
1009 testWin.Layout()
1010 testWin.SetPosition(pos)
1011 testWin.Show(True)
1012 # Dialog's default code does not produce wx.EVT_CLOSE
1013 wx.EVT_BUTTON(testWin, wx.ID_OK, self.OnCloseTestWin)
1014 wx.EVT_BUTTON(testWin, wx.ID_CANCEL, self.OnCloseTestWin)
1015 elif xxx.__class__ == xxxWizard:
1016 wiz = wx.wizard.PreWizard()
1017 res.LoadOnObject(wiz, g.frame, STD_NAME, 'wxWizard')
1018 # Find first page (don't know better way)
1019 firstPage = None
1020 for w in wiz.GetChildren():
1021 if isinstance(w, wx.wizard.WizardPage):
1022 firstPage = w
1023 break
1024 if not firstPage:
1025 wx.LogError('Wizard is empty')
1026 else:
1027 # Wizard should be modal
1028 self.SetItemBold(item)
1029 wiz.RunWizard(w)
1030 self.SetItemBold(item, False)
1031 wiz.Destroy()
1032 elif xxx.__class__ in [xxxWizardPage, xxxWizardPageSimple]:
1033 # Create new frame
1034 if not testWin:
1035 testWin = g.testWin = wx.Frame(g.frame, -1, 'Wizard page: ' + name,
1036 pos=pos, name=STD_NAME)
1037 testWin.panel = wx.PrePanel()
1038 res.LoadOnObject(testWin.panel, testWin, STD_NAME, 'wxPanel')
1039 testWin.SetClientSize(testWin.GetBestSize())
1040 testWin.Show(True)
1041 elif xxx.__class__ == xxxMenuBar:
1042 testWin = g.testWin = wx.Frame(g.frame, -1, 'MenuBar: ' + name,
1043 pos=pos, name=STD_NAME)
1044 testWin.panel = None
1045 # Set status bar to display help
1046 testWin.CreateStatusBar()
1047 testWin.menuBar = res.LoadMenuBar(STD_NAME)
1048 testWin.SetMenuBar(testWin.menuBar)
1049 testWin.Show(True)
1050 elif xxx.__class__ == xxxToolBar:
1051 testWin = g.testWin = wx.Frame(g.frame, -1, 'ToolBar: ' + name,
1052 pos=pos, name=STD_NAME)
1053 testWin.panel = None
1054 # Set status bar to display help
1055 testWin.CreateStatusBar()
1056 testWin.toolBar = res.LoadToolBar(testWin, STD_NAME)
1057 testWin.SetToolBar(testWin.toolBar)
1058 testWin.Show(True)
1059 # Catch some events, set highlight
1060 if testWin:
1061 testWin.item = item
1062 wx.EVT_CLOSE(testWin, self.OnCloseTestWin)
1063 wx.EVT_SIZE(testWin, self.OnSizeTestWin)
1064 # Add drop target
1065 if testWin.panel:
1066 testWin.panel.SetDropTarget(DropTarget())
1067 else:
1068 testWin.SetDropTarget(DropTarget())
1069 # Reset highlights
1070 testWin.highLight = testWin.highLightDT = None
1071 if highLight and not self.pendingHighLight:
1072 self.HighLight(highLight)
1073 except:
1074 if g.testWin:
1075 self.SetItemBold(item, False)
1076 g.testWinPos = g.testWin.GetPosition()
1077 g.testWin.Destroy()
1078 g.testWin = None
1079 inf = sys.exc_info()
1080 wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1])
1081 wx.LogError('Error loading resource')
1082 # Cleanup
1083 res.Unload('xxx.xrc')
1084 xrc.XmlResource.Set(None)
1085 wx.MemoryFSHandler.RemoveFile('xxx.xrc')
1086
1087 def CloseTestWindow(self):
1088 if not g.testWin: return
1089 self.SetItemBold(g.testWin.item, False)
1090 g.frame.tb.ToggleTool(g.frame.ID_TOOL_LOCATE, False)
1091 g.testWinPos = g.testWin.GetPosition()
1092 g.testWin.Destroy()
1093 g.testWin = None
1094
1095 def OnCloseTestWin(self, evt):
1096 self.CloseTestWindow()
1097
1098 def OnSizeTestWin(self, evt):
1099 # Update highlight after size change
1100 hl = g.testWin.highLight
1101 if hl:
1102 hl.Replace(self.FindNodePos(hl.item), hl.obj.GetSize())
1103 hl.Refresh()
1104 #self.HighLight(g.testWin.highLight.item)
1105 evt.Skip()
1106
1107 # Return index in parent, for real window children
1108 def WindowIndex(self, item):
1109 n = 0 # index of sibling
1110 prev = self.GetPrevSibling(item)
1111 while prev.IsOk():
1112 # MenuBar is not a child
1113 if not isinstance(self.GetPyData(prev), xxxMenuBar):
1114 n += 1
1115 prev = self.GetPrevSibling(prev)
1116 return n
1117
1118 # Return item index in parent
1119 def ItemIndex(self, item):
1120 n = 0 # index of sibling
1121 prev = self.GetPrevSibling(item)
1122 while prev.IsOk():
1123 prev = self.GetPrevSibling(prev)
1124 n += 1
1125 return n
1126
1127 # Full tree index of an item - list of positions
1128 def ItemFullIndex(self, item):
1129 if not item.IsOk(): return None
1130 l = []
1131 while item != self.root:
1132 l.insert(0, self.ItemIndex(item))
1133 item = self.GetItemParent(item)
1134 return l
1135 # Get item position from full index
1136 def ItemAtFullIndex(self, index):
1137 if index is None: return wx.TreeItemId()
1138 item = self.root
1139 for i in index:
1140 item = self.GetFirstChild(item)[0]
1141 for k in range(i): item = self.GetNextSibling(item)
1142 return item
1143
1144 # True if next item should be inserted after current (vs. appended to it)
1145 def NeedInsert(self, item):
1146 xxx = self.GetPyData(item)
1147 if item == self.root: return False # root item
1148 if xxx.hasChildren and not self.GetChildrenCount(item, False):
1149 return False
1150 return not (self.IsExpanded(item) and self.GetChildrenCount(item, False))
1151
1152 # Pull-down
1153 def OnRightDown(self, evt):
1154 pullDownMenu = g.pullDownMenu
1155 # select this item
1156 pt = evt.GetPosition();
1157 item, flags = self.HitTest(pt)
1158 if item.Ok() and flags & wx.TREE_HITTEST_ONITEM:
1159 self.SelectItem(item)
1160
1161 # Setup menu
1162 menu = wx.Menu()
1163
1164 item = self.selection
1165 if not item:
1166 menu.Append(g.pullDownMenu.ID_EXPAND, 'Expand', 'Expand tree')
1167 menu.Append(g.pullDownMenu.ID_COLLAPSE, 'Collapse', 'Collapse tree')
1168 else:
1169 # self.ctrl = evt.ControlDown() # save Ctrl state
1170 # self.shift = evt.ShiftDown() # and Shift too
1171 m = wx.Menu() # create menu
1172 if self.ctrl:
1173 needInsert = True
1174 else:
1175 needInsert = self.NeedInsert(item)
1176 if item == self.root or needInsert and self.GetItemParent(item) == self.root:
1177 SetMenu(m, pullDownMenu.topLevel)
1178 m.AppendSeparator()
1179 m.Append(ID_NEW.REF, 'reference...', 'Create object_ref node')
1180 m.Append(ID_NEW.COMMENT, 'comment', 'Create comment node')
1181 else:
1182 xxx = self.GetPyData(item).treeObject()
1183 # Check parent for possible child nodes if inserting sibling
1184 if needInsert: xxx = xxx.parent
1185 if xxx.__class__ == xxxMenuBar:
1186 m.Append(ID_NEW.MENU, 'Menu', 'Create menu')
1187 elif xxx.__class__ in [xxxToolBar, xxxTool] or \
1188 xxx.__class__ == xxxSeparator and xxx.parent.__class__ == xxxToolBar:
1189 SetMenu(m, pullDownMenu.toolBarControls)
1190 elif xxx.__class__ in [xxxMenu, xxxMenuItem]:
1191 SetMenu(m, pullDownMenu.menuControls)
1192 elif xxx.__class__ == xxxStdDialogButtonSizer:
1193 SetMenu(m, pullDownMenu.stdButtons)
1194 else:
1195 SetMenu(m, pullDownMenu.controls)
1196 if xxx.__class__ in [xxxNotebook, xxxChoicebook, xxxListbook]:
1197 m.Enable(m.FindItem('sizer'), False)
1198 elif not (xxx.isSizer or xxx.parent and xxx.parent.isSizer):
1199 m.Enable(ID_NEW.SPACER, False)
1200 if xxx.__class__ is not xxxFrame:
1201 m.Enable(ID_NEW.MENU_BAR, False)
1202 # Add custom controls menu
1203 if len(pullDownMenu.custom) > 2:
1204 SetMenu(m, [pullDownMenu.custom])
1205 m.AppendSeparator()
1206 m.Append(ID_NEW.REF, 'reference...', 'Create object_ref node')
1207 m.Append(ID_NEW.COMMENT, 'comment', 'Create comment node')
1208 # Select correct label for create menu
1209 if not needInsert:
1210 if self.shift:
1211 menu.AppendMenu(wx.NewId(), 'Insert Child', m,
1212 'Create child object as the first child')
1213 else:
1214 menu.AppendMenu(wx.NewId(), 'Append Child', m,
1215 'Create child object as the last child')
1216 else:
1217 if self.shift:
1218 menu.AppendMenu(wx.NewId(), 'Create Sibling', m,
1219 'Create sibling before selected object')
1220 else:
1221 menu.AppendMenu(wx.NewId(), 'Create Sibling', m,
1222 'Create sibling after selected object')
1223 # Build replace menu
1224 if item != self.root:
1225 xxx = self.GetPyData(item).treeObject()
1226 m = wx.Menu() # create replace menu
1227 if xxx.__class__ == xxxMenuBar:
1228 m.Append(1000 + ID_NEW.MENU, 'Menu', 'Create menu')
1229 elif xxx.__class__ in [xxxMenu, xxxMenuItem]:
1230 SetMenu(m, pullDownMenu.menuControls, shift=True)
1231 elif xxx.__class__ == xxxToolBar and \
1232 self.GetItemParent(item) == self.root:
1233 SetMenu(m, [], shift=True)
1234 elif xxx.__class__ in [xxxFrame, xxxDialog, xxxPanel]:
1235 SetMenu(m, [
1236 (ID_NEW.PANEL, 'Panel', 'Create panel'),
1237 (ID_NEW.DIALOG, 'Dialog', 'Create dialog'),
1238 (ID_NEW.FRAME, 'Frame', 'Create frame')], shift=True)
1239 elif xxx.isSizer and self.ItemHasChildren(item):
1240 SetMenu(m, pullDownMenu.sizers, shift=True)
1241 else:
1242 SetMenu(m, pullDownMenu.controls, shift=True)
1243 if xxx.isElement:
1244 id = wx.NewId()
1245 menu.AppendMenu(id, 'Replace With', m)
1246 if not m.GetMenuItemCount(): menu.Enable(id, False)
1247 menu.Append(pullDownMenu.ID_SUBCLASS, 'Subclass...',
1248 'Set "subclass" property')
1249 menu.AppendSeparator()
1250 # Not using standart IDs because we don't want to show shortcuts
1251 menu.Append(wx.ID_CUT, 'Cut', 'Cut to the clipboard')
1252 menu.Append(wx.ID_COPY, 'Copy', 'Copy to the clipboard')
1253 if self.ctrl and item != self.root:
1254 menu.Append(pullDownMenu.ID_PASTE_SIBLING, 'Paste Sibling',
1255 'Paste from the clipboard as a sibling')
1256 else:
1257 menu.Append(wx.ID_PASTE, 'Paste', 'Paste from the clipboard')
1258 menu.Append(pullDownMenu.ID_DELETE,
1259 'Delete', 'Delete object')
1260 if self.ItemHasChildren(item):
1261 menu.AppendSeparator()
1262 menu.Append(pullDownMenu.ID_EXPAND, 'Expand', 'Expand subtree')
1263 menu.Append(pullDownMenu.ID_COLLAPSE, 'Collapse', 'Collapse subtree')
1264 self.PopupMenu(menu, evt.GetPosition())
1265 menu.Destroy()
1266
1267 # Redefine to force the update of font dimentions on wxGTK
1268 if wx.Platform == '__WXGTK__':
1269 def SetItemBold(self, item, state=True):
1270 wx.TreeCtrl.SetItemBold(self, item, state)
1271 self.SetIndent(self.GetIndent())
1272
1273 # Apply changes
1274 def Apply(self, xxx, item):
1275 g.panel.Apply()
1276 # Update tree view
1277 xxx = xxx.treeObject()
1278 if xxx.hasName and self.GetItemText(item) != xxx.name:
1279 self.SetItemText(item, xxx.treeName())
1280 # Item width may have changed
1281 # !!! Tric to update tree width (wxGTK, ??)
1282 self.SetIndent(self.GetIndent())
1283 elif xxx.className == 'comment':
1284 self.SetItemText(item, xxx.treeName())
1285 # Change tree icon for sizers
1286 if isinstance(xxx, xxxBoxSizer):
1287 self.SetItemImage(item, xxx.treeImage())
1288 # Set global modified state
1289 g.frame.SetModified()
1290
1291 def OnBeginLabelEdit(self, evt):
1292 xxx = self.GetPyData(evt.GetItem())
1293 if xxx.isElement:
1294 evt.Veto()
1295 else:
1296 evt.Skip()
1297
1298 def OnEndLabelEdit(self, evt):
1299 xxx = self.GetPyData(evt.GetItem())
1300 node = xxx.node
1301 if not xxx.isElement:
1302 node.data = evt.GetLabel()
1303 g.panel.SetData(xxx)
1304 evt.Skip()
1305
1306 ################################################################################
1307
1308 # DragAndDrop
1309
1310 class DropTarget(wx.PyDropTarget):
1311 def __init__(self):
1312 self.do = MyDataObject()
1313 wx.DropTarget.__init__(self, self.do)
1314
1315 # Find best object for dropping
1316 def WhereToDrop(self, x, y, d):
1317 # Find object by position
1318 obj = wx.FindWindowAtPoint(g.testWin.ClientToScreen((x,y)))
1319 if not obj:
1320 return wx.DragNone, ()
1321 item = g.frame.FindObject(g.testWin.item, obj)
1322 if not item:
1323 return wx.DragNone, ()
1324 xxx = g.tree.GetPyData(item).treeObject()
1325 parentItem = None
1326 # Check if window has a XRC sizer, then use it as parent
1327 if obj.GetSizer():
1328 sizer = obj.GetSizer()
1329 sizerItem = g.frame.FindObject(g.testWin.item, sizer)
1330 if sizerItem:
1331 parentItem = sizerItem
1332 obj = sizer
1333 item = wx.TreeItemId()
1334 # if not sizer but can have children, it is parent with free placement
1335 elif xxx.hasChildren:
1336 parentItem = item
1337 item = wx.TreeItemId()
1338 # Otherwise, try to add to item's parent
1339 if not parentItem:
1340 parentItem = g.tree.GetItemParent(item)
1341 obj = g.tree.FindNodeObject(parentItem)
1342 parent = g.tree.GetPyData(parentItem).treeObject()
1343 return d,(obj,parent,parentItem,item)
1344
1345 # Drop
1346 def OnData(self, x, y, d):
1347 self.GetData()
1348 id = int(self.do.GetDataHere())
1349 d,other = self.WhereToDrop(x, y, d)
1350 if d != wx.DragNone:
1351 obj,parent,parentItem,item = other
1352 g.tree.selection = parentItem
1353 xxx = g.frame.CreateXXX(parent, parentItem, item, id)
1354 # Set coordinates if parent is not sizer
1355 if not parent.isSizer:
1356 xxx.set('pos', '%d,%d' % (x, y))
1357 g.panel.SetData(xxx)
1358 g.frame.SetStatusText('Object created')
1359 self.RemoveHL()
1360 return d
1361
1362 def OnDragOver(self, x, y, d):
1363 d,other = self.WhereToDrop(x, y, d)
1364 if d != wx.DragNone:
1365 obj,parent,parentItem,item = other
1366 pos, size = g.tree.FindNodePos(parentItem, obj), obj.GetSize()
1367 hl = g.testWin.highLightDT
1368 # Set color of highlighted item back to normal
1369 if hl and hl.item:
1370 if hl.item != parentItem:
1371 g.tree.SetItemTextColour(hl.item, g.tree.itemColour)
1372 # Highlight future parent
1373 g.tree.itemColour = g.tree.GetItemTextColour(parentItem) # save current
1374 if not hl or hl.item != parentItem:
1375 g.testWin.highLightDT = updateHL(hl, HighLightDTBox, pos, size)
1376 g.testWin.highLightDT.item = parentItem
1377 g.tree.SetItemTextColour(parentItem, g.tree.COLOUR_DT)
1378 g.tree.EnsureVisible(parentItem)
1379 g.frame.SetStatusText('Drop target: %s' % parent.treeName())
1380 else:
1381 g.frame.SetStatusText('Inappropriate drop target')
1382 self.RemoveHL()
1383 return d
1384
1385 def OnLeave(self):
1386 self.RemoveHL()
1387
1388 def RemoveHL(self):
1389 hl = g.testWin.highLightDT
1390 if hl:
1391 if hl.item:
1392 g.tree.SetItemTextColour(hl.item, g.tree.itemColour)
1393 hl.Remove()
1394