]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/tools/XRCed/tree.py
'[1219035] cleanup: miscellaneous' and minor source cleaning.
[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 self.buffer += data.encode(g.currentEncoding)
24 else:
25 self.buffer += data.encode()
26 def close(self):
27 wxMemoryFSHandler_AddFile(self.name, self.buffer)
28
29 ################################################################################
30
31 # Redefine writing to include encoding
32 class MyDocument(minidom.Document):
33 def __init__(self):
34 minidom.Document.__init__(self)
35 self.encoding = ''
36 def writexml(self, writer, indent="", addindent="", newl="", encoding=""):
37 if encoding: encdstr = 'encoding="%s"' % encoding
38 else: encdstr = ''
39 writer.write('<?xml version="1.0" %s?>\n' % encdstr)
40 for node in self.childNodes:
41 node.writexml(writer, indent, addindent, newl)
42
43 ################################################################################
44
45 # Ids for menu commands
46 class ID_NEW:
47 PANEL = wxNewId()
48 DIALOG = wxNewId()
49 FRAME = wxNewId()
50 TOOL_BAR = wxNewId()
51 TOOL = wxNewId()
52 MENU_BAR = wxNewId()
53 MENU = wxNewId()
54
55 STATIC_TEXT = wxNewId()
56 TEXT_CTRL = wxNewId()
57
58 BUTTON = wxNewId()
59 BITMAP_BUTTON = wxNewId()
60 RADIO_BUTTON = wxNewId()
61 SPIN_BUTTON = wxNewId()
62 TOGGLE_BUTTON = wxNewId()
63
64 STATIC_BOX = wxNewId()
65 CHECK_BOX = wxNewId()
66 RADIO_BOX = wxNewId()
67 COMBO_BOX = wxNewId()
68 LIST_BOX = wxNewId()
69
70 STATIC_LINE = wxNewId()
71 STATIC_BITMAP = wxNewId()
72 CHOICE = wxNewId()
73 SLIDER = wxNewId()
74 GAUGE = wxNewId()
75 SCROLL_BAR = wxNewId()
76 TREE_CTRL = wxNewId()
77 LIST_CTRL = wxNewId()
78 CHECK_LIST = wxNewId()
79 NOTEBOOK = wxNewId()
80 SPLITTER_WINDOW = wxNewId()
81 SCROLLED_WINDOW = wxNewId()
82 HTML_WINDOW = wxNewId()
83 CALENDAR_CTRL = wxNewId()
84 GENERIC_DIR_CTRL = wxNewId()
85 SPIN_CTRL = wxNewId()
86 UNKNOWN = wxNewId()
87 WIZARD = wxNewId()
88 WIZARD_PAGE = wxNewId()
89 WIZARD_PAGE_SIMPLE = wxNewId()
90 STATUS_BAR = wxNewId()
91
92 BOX_SIZER = wxNewId()
93 STATIC_BOX_SIZER = wxNewId()
94 GRID_SIZER = wxNewId()
95 FLEX_GRID_SIZER = wxNewId()
96 GRID_BAG_SIZER = wxNewId()
97 STD_DIALOG_BUTTON_SIZER = wxNewId()
98 SPACER = wxNewId()
99
100 TOOL_BAR = wxNewId()
101 TOOL = wxNewId()
102 MENU = wxNewId()
103 MENU_ITEM = wxNewId()
104 SEPARATOR = wxNewId()
105 LAST = wxNewId()
106
107 class PullDownMenu:
108 ID_EXPAND = wxNewId()
109 ID_COLLAPSE = wxNewId()
110 ID_PASTE_SIBLING = wxNewId()
111 ID_TOOL_PASTE = wxNewId()
112 ID_SUBCLASS = wxNewId()
113
114 def __init__(self, parent):
115 self.ID_DELETE = parent.ID_DELETE
116 EVT_MENU_RANGE(parent, ID_NEW.PANEL, ID_NEW.LAST, parent.OnCreate)
117 EVT_MENU_RANGE(parent, 1000 + ID_NEW.PANEL, 1000 + ID_NEW.LAST, parent.OnReplace)
118 EVT_MENU(parent, self.ID_COLLAPSE, parent.OnCollapse)
119 EVT_MENU(parent, self.ID_EXPAND, parent.OnExpand)
120 EVT_MENU(parent, self.ID_PASTE_SIBLING, parent.OnPaste)
121 EVT_MENU(parent, self.ID_SUBCLASS, parent.OnSubclass)
122 # We connect to tree, but process in frame
123 EVT_MENU_HIGHLIGHT_ALL(g.tree, parent.OnPullDownHighlight)
124
125 # Mapping from IDs to element names
126 self.createMap = {
127 ID_NEW.PANEL: 'wxPanel',
128 ID_NEW.DIALOG: 'wxDialog',
129 ID_NEW.FRAME: 'wxFrame',
130 ID_NEW.WIZARD: 'wxWizard',
131 ID_NEW.WIZARD_PAGE: 'wxWizardPage',
132 ID_NEW.WIZARD_PAGE_SIMPLE: 'wxWizardPageSimple',
133 ID_NEW.TOOL_BAR: 'wxToolBar',
134 ID_NEW.TOOL: 'tool',
135 ID_NEW.MENU_BAR: 'wxMenuBar',
136 ID_NEW.MENU: 'wxMenu',
137 ID_NEW.MENU_ITEM: 'wxMenuItem',
138 ID_NEW.SEPARATOR: 'separator',
139
140 ID_NEW.STATIC_TEXT: 'wxStaticText',
141 ID_NEW.TEXT_CTRL: 'wxTextCtrl',
142
143 ID_NEW.BUTTON: 'wxButton',
144 ID_NEW.BITMAP_BUTTON: 'wxBitmapButton',
145 ID_NEW.RADIO_BUTTON: 'wxRadioButton',
146 ID_NEW.SPIN_BUTTON: 'wxSpinButton',
147 ID_NEW.TOGGLE_BUTTON: 'wxToggleButton',
148
149 ID_NEW.STATIC_BOX: 'wxStaticBox',
150 ID_NEW.CHECK_BOX: 'wxCheckBox',
151 ID_NEW.RADIO_BOX: 'wxRadioBox',
152 ID_NEW.COMBO_BOX: 'wxComboBox',
153 ID_NEW.LIST_BOX: 'wxListBox',
154
155 ID_NEW.STATIC_LINE: 'wxStaticLine',
156 ID_NEW.STATIC_BITMAP: 'wxStaticBitmap',
157 ID_NEW.CHOICE: 'wxChoice',
158 ID_NEW.SLIDER: 'wxSlider',
159 ID_NEW.GAUGE: 'wxGauge',
160 ID_NEW.SCROLL_BAR: 'wxScrollBar',
161 ID_NEW.TREE_CTRL: 'wxTreeCtrl',
162 ID_NEW.LIST_CTRL: 'wxListCtrl',
163 ID_NEW.CHECK_LIST: 'wxCheckListBox',
164 ID_NEW.NOTEBOOK: 'wxNotebook',
165 ID_NEW.SPLITTER_WINDOW: 'wxSplitterWindow',
166 ID_NEW.SCROLLED_WINDOW: 'wxScrolledWindow',
167 ID_NEW.HTML_WINDOW: 'wxHtmlWindow',
168 ID_NEW.CALENDAR_CTRL: 'wxCalendarCtrl',
169 ID_NEW.GENERIC_DIR_CTRL: 'wxGenericDirCtrl',
170 ID_NEW.SPIN_CTRL: 'wxSpinCtrl',
171
172 ID_NEW.BOX_SIZER: 'wxBoxSizer',
173 ID_NEW.STATIC_BOX_SIZER: 'wxStaticBoxSizer',
174 ID_NEW.GRID_SIZER: 'wxGridSizer',
175 ID_NEW.FLEX_GRID_SIZER: 'wxFlexGridSizer',
176 ID_NEW.GRID_BAG_SIZER: 'wxGridBagSizer',
177 ID_NEW.STD_DIALOG_BUTTON_SIZER: 'wxStdDialogButtonSizer',
178 ID_NEW.SPACER: 'spacer',
179 ID_NEW.UNKNOWN: 'unknown',
180 }
181 self.topLevel = [
182 (ID_NEW.PANEL, 'Panel', 'Create panel'),
183 (ID_NEW.DIALOG, 'Dialog', 'Create dialog'),
184 (ID_NEW.FRAME, 'Frame', 'Create frame'),
185 (ID_NEW.WIZARD, 'Wizard', 'Create wizard'),
186 None,
187 (ID_NEW.TOOL_BAR, 'ToolBar', 'Create toolbar'),
188 (ID_NEW.MENU_BAR, 'MenuBar', 'Create menubar'),
189 (ID_NEW.MENU, 'Menu', 'Create menu')
190 ]
191 self.containers = [
192 (ID_NEW.PANEL, 'Panel', 'Create panel'),
193 (ID_NEW.NOTEBOOK, 'Notebook', 'Create notebook control'),
194 (ID_NEW.SPLITTER_WINDOW, 'SplitterWindow', 'Create splitter window'),
195 (ID_NEW.TOOL_BAR, 'ToolBar', 'Create toolbar'),
196 # (ID_NEW.WIZARD_PAGE, 'WizardPage', 'Create wizard page'),
197 (ID_NEW.WIZARD_PAGE_SIMPLE, 'WizardPageSimple', 'Create simple wizard page'),
198 ]
199 self.sizers = [
200 (ID_NEW.BOX_SIZER, 'BoxSizer', 'Create box sizer'),
201 (ID_NEW.STATIC_BOX_SIZER, 'StaticBoxSizer',
202 'Create static box sizer'),
203 (ID_NEW.GRID_SIZER, 'GridSizer', 'Create grid sizer'),
204 (ID_NEW.FLEX_GRID_SIZER, 'FlexGridSizer',
205 'Create flexgrid sizer'),
206 (ID_NEW.GRID_BAG_SIZER, 'GridBagSizer',
207 'Create gridbag sizer'),
208 # (ID_NEW.STD_DIALOG_BUTTON_SIZER, 'StdDialogButtonSizer',
209 # 'Create standard button sizer'),
210 (ID_NEW.SPACER, 'Spacer', 'Create spacer'),
211 ]
212 self.controls = [
213 ['control', 'Various controls',
214 (ID_NEW.STATIC_TEXT, 'Label', 'Create label'),
215 (ID_NEW.STATIC_BITMAP, 'Bitmap', 'Create bitmap'),
216 (ID_NEW.STATIC_LINE, 'Line', 'Create line'),
217 (ID_NEW.TEXT_CTRL, 'TextBox', 'Create text box'),
218 (ID_NEW.CHOICE, 'Choice', 'Create choice'),
219 (ID_NEW.SLIDER, 'Slider', 'Create slider'),
220 (ID_NEW.GAUGE, 'Gauge', 'Create gauge'),
221 (ID_NEW.SPIN_CTRL, 'SpinCtrl', 'Create spin'),
222 (ID_NEW.SCROLL_BAR, 'ScrollBar', 'Create scroll bar'),
223 (ID_NEW.TREE_CTRL, 'TreeCtrl', 'Create tree'),
224 (ID_NEW.LIST_CTRL, 'ListCtrl', 'Create list'),
225 (ID_NEW.CHECK_LIST, 'CheckList', 'Create check list'),
226 (ID_NEW.SCROLLED_WINDOW, 'ScrolledWindow', 'Create scrolled window'),
227 (ID_NEW.HTML_WINDOW, 'HtmlWindow', 'Create HTML window'),
228 (ID_NEW.CALENDAR_CTRL, 'CalendarCtrl', 'Create calendar control'),
229 (ID_NEW.GENERIC_DIR_CTRL, 'GenericDirCtrl', 'Create generic dir control'),
230 (ID_NEW.UNKNOWN, 'Unknown', 'Create custom control placeholder'),
231 ],
232 ['button', 'Buttons',
233 (ID_NEW.BUTTON, 'Button', 'Create button'),
234 (ID_NEW.BITMAP_BUTTON, 'BitmapButton', 'Create bitmap button'),
235 (ID_NEW.RADIO_BUTTON, 'RadioButton', 'Create radio button'),
236 (ID_NEW.SPIN_BUTTON, 'SpinButton', 'Create spin button'),
237 (ID_NEW.TOGGLE_BUTTON, 'ToggleButton', 'Create toggle button'),
238 ],
239 ['box', 'Boxes',
240 (ID_NEW.STATIC_BOX, 'StaticBox', 'Create static box'),
241 (ID_NEW.CHECK_BOX, 'CheckBox', 'Create check box'),
242 (ID_NEW.RADIO_BOX, 'RadioBox', 'Create radio box'),
243 (ID_NEW.COMBO_BOX, 'ComboBox', 'Create combo box'),
244 (ID_NEW.LIST_BOX, 'ListBox', 'Create list box'),
245 ],
246 ['container', 'Containers',
247 (ID_NEW.PANEL, 'Panel', 'Create panel'),
248 (ID_NEW.NOTEBOOK, 'Notebook', 'Create notebook control'),
249 (ID_NEW.SPLITTER_WINDOW, 'SplitterWindow', 'Create splitter window'),
250 (ID_NEW.TOOL_BAR, 'ToolBar', 'Create toolbar'),
251 # (ID_NEW.WIZARD_PAGE, 'Wizard Page', 'Create wizard page'),
252 (ID_NEW.WIZARD_PAGE_SIMPLE, 'WizardPageSimple', 'Create simple wizard page'),
253 ],
254 ['sizer', 'Sizers',
255 (ID_NEW.BOX_SIZER, 'BoxSizer', 'Create box sizer'),
256 (ID_NEW.STATIC_BOX_SIZER, 'StaticBoxSizer',
257 'Create static box sizer'),
258 (ID_NEW.GRID_SIZER, 'GridSizer', 'Create grid sizer'),
259 (ID_NEW.FLEX_GRID_SIZER, 'FlexGridSizer',
260 'Create flexgrid sizer'),
261 (ID_NEW.GRID_BAG_SIZER, 'GridBagSizer',
262 'Create gridbag sizer'),
263 (ID_NEW.SPACER, 'Spacer', 'Create spacer'),
264 (ID_NEW.STD_DIALOG_BUTTON_SIZER, 'StdDialogButtonSizer',
265 'Create standard button sizer'),
266 ]
267 ]
268 self.menuControls = [
269 (ID_NEW.MENU, 'Menu', 'Create menu'),
270 (ID_NEW.MENU_ITEM, 'MenuItem', 'Create menu item'),
271 (ID_NEW.SEPARATOR, 'Separator', 'Create separator'),
272 ]
273 self.toolBarControls = [
274 (ID_NEW.TOOL, 'Tool', 'Create tool'),
275 (ID_NEW.SEPARATOR, 'Separator', 'Create separator'),
276 ['control', 'Various controls',
277 (ID_NEW.STATIC_TEXT, 'Label', 'Create label'),
278 (ID_NEW.STATIC_BITMAP, 'Bitmap', 'Create bitmap'),
279 (ID_NEW.STATIC_LINE, 'Line', 'Create line'),
280 (ID_NEW.TEXT_CTRL, 'TextBox', 'Create text box'),
281 (ID_NEW.CHOICE, 'Choice', 'Create choice'),
282 (ID_NEW.SLIDER, 'Slider', 'Create slider'),
283 (ID_NEW.GAUGE, 'Gauge', 'Create gauge'),
284 (ID_NEW.SCROLL_BAR, 'ScrollBar', 'Create scroll bar'),
285 (ID_NEW.LIST_CTRL, 'ListCtrl', 'Create list control'),
286 (ID_NEW.CHECK_LIST, 'CheckList', 'Create check list'),
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 ],
294 ['box', 'Boxes',
295 (ID_NEW.STATIC_BOX, 'StaticBox', 'Create static box'),
296 (ID_NEW.CHECK_BOX, 'CheckBox', 'Create check box'),
297 (ID_NEW.RADIO_BOX, 'RadioBox', 'Create radio box'),
298 (ID_NEW.COMBO_BOX, 'ComboBox', 'Create combo box'),
299 (ID_NEW.LIST_BOX, 'ListBox', 'Create list box'),
300 ],
301 ]
302
303 ################################################################################
304
305 # Set menu to list items.
306 # Each menu command is a tuple (id, label, help)
307 # submenus are lists [id, label, help, submenu]
308 # and separators are any other type
309 def SetMenu(m, list):
310 for l in list:
311 if type(l) == types.TupleType:
312 apply(m.Append, l)
313 elif type(l) == types.ListType:
314 subMenu = wxMenu()
315 SetMenu(subMenu, l[2:])
316 m.AppendMenu(wxNewId(), l[0], subMenu, l[1])
317 else: # separator
318 m.AppendSeparator()
319 # Same, but adds 1000 to all IDs
320 def SetMenu2(m, list):
321 for l in list:
322 if type(l) == types.TupleType:
323 # Shift ID
324 l = (1000 + l[0],) + l[1:]
325 apply(m.Append, l)
326 elif type(l) == types.ListType:
327 subMenu = wxMenu()
328 SetMenu2(subMenu, l[2:])
329 m.AppendMenu(wxNewId(), l[0], subMenu, l[1])
330 else: # separator
331 m.AppendSeparator()
332
333 ################################################################################
334
335 class HighLightBox:
336 def __init__(self, pos, size):
337 if size.width == -1: size.width = 0
338 if size.height == -1: size.height = 0
339 w = g.testWin.panel
340 l1 = wxWindow(w, -1, pos, wxSize(size.width, 2))
341 l1.SetBackgroundColour(wxRED)
342 l2 = wxWindow(w, -1, pos, wxSize(2, size.height))
343 l2.SetBackgroundColour(wxRED)
344 l3 = wxWindow(w, -1, wxPoint(pos.x + size.width - 2, pos.y), wxSize(2, size.height))
345 l3.SetBackgroundColour(wxRED)
346 l4 = wxWindow(w, -1, wxPoint(pos.x, pos.y + size.height - 2), wxSize(size.width, 2))
347 l4.SetBackgroundColour(wxRED)
348 self.lines = [l1, l2, l3, l4]
349 # Move highlight to a new position
350 def Replace(self, pos, size):
351 if size.width == -1: size.width = 0
352 if size.height == -1: size.height = 0
353 self.lines[0].SetDimensions(pos.x, pos.y, size.width, 2)
354 self.lines[1].SetDimensions(pos.x, pos.y, 2, size.height)
355 self.lines[2].SetDimensions(pos.x + size.width - 2, pos.y, 2, size.height)
356 self.lines[3].SetDimensions(pos.x, pos.y + size.height - 2, size.width, 2)
357 # Remove it
358 def Remove(self):
359 map(wxWindow.Destroy, self.lines)
360 g.testWin.highLight = None
361 def Refresh(self):
362 map(wxWindow.Refresh, self.lines)
363
364 ################################################################################
365
366 class XML_Tree(wxTreeCtrl):
367 def __init__(self, parent, id):
368 wxTreeCtrl.__init__(self, parent, id, style = wxTR_HAS_BUTTONS)
369 self.SetBackgroundColour(wxColour(224, 248, 224))
370 # Register events
371 EVT_TREE_SEL_CHANGED(self, self.GetId(), self.OnSelChanged)
372 # One works on Linux, another on Windows
373 if wxPlatform == '__WXGTK__':
374 EVT_TREE_ITEM_ACTIVATED(self, self.GetId(), self.OnItemActivated)
375 else:
376 EVT_LEFT_DCLICK(self, self.OnDClick)
377 EVT_RIGHT_DOWN(self, self.OnRightDown)
378 EVT_TREE_ITEM_EXPANDED(self, self.GetId(), self.OnItemExpandedCollapsed)
379 EVT_TREE_ITEM_COLLAPSED(self, self.GetId(), self.OnItemExpandedCollapsed)
380
381 self.selection = None
382 self.needUpdate = False
383 self.pendingHighLight = None
384 self.ctrl = self.shift = False
385 self.dom = None
386 # Create image list
387 il = wxImageList(16, 16, True)
388 self.rootImage = il.Add(images.getTreeRootImage().Scale(16,16).ConvertToBitmap())
389 xxxObject.image = il.Add(images.getTreeDefaultImage().Scale(16,16).ConvertToBitmap())
390 xxxPanel.image = il.Add(images.getTreePanelImage().Scale(16,16).ConvertToBitmap())
391 xxxDialog.image = il.Add(images.getTreeDialogImage().Scale(16,16).ConvertToBitmap())
392 xxxFrame.image = il.Add(images.getTreeFrameImage().Scale(16,16).ConvertToBitmap())
393 xxxMenuBar.image = il.Add(images.getTreeMenuBarImage().Scale(16,16).ConvertToBitmap())
394 xxxMenu.image = il.Add(images.getTreeMenuImage().Scale(16,16).ConvertToBitmap())
395 xxxMenuItem.image = il.Add(images.getTreeMenuItemImage().Scale(16,16).ConvertToBitmap())
396 xxxToolBar.image = il.Add(images.getTreeToolBarImage().Scale(16,16).ConvertToBitmap())
397 xxxTool.image = il.Add(images.getTreeToolImage().Scale(16,16).ConvertToBitmap())
398 xxxSeparator.image = il.Add(images.getTreeSeparatorImage().Scale(16,16).ConvertToBitmap())
399 xxxSizer.imageH = il.Add(images.getTreeSizerHImage().Scale(16,16).ConvertToBitmap())
400 xxxSizer.imageV = il.Add(images.getTreeSizerVImage().Scale(16,16).ConvertToBitmap())
401 xxxStaticBoxSizer.imageH = il.Add(images.getTreeStaticBoxSizerHImage().Scale(16,16).ConvertToBitmap())
402 xxxStaticBoxSizer.imageV = il.Add(images.getTreeStaticBoxSizerVImage().Scale(16,16).ConvertToBitmap())
403 xxxGridSizer.image = il.Add(images.getTreeSizerGridImage().Scale(16,16).ConvertToBitmap())
404 xxxFlexGridSizer.image = il.Add(images.getTreeSizerFlexGridImage().Scale(16,16).ConvertToBitmap())
405 self.il = il
406 self.SetImageList(il)
407
408 def RegisterKeyEvents(self):
409 EVT_KEY_DOWN(self, g.tools.OnKeyDown)
410 EVT_KEY_UP(self, g.tools.OnKeyUp)
411 EVT_ENTER_WINDOW(self, g.tools.OnMouse)
412 EVT_LEAVE_WINDOW(self, g.tools.OnMouse)
413
414 def Unselect(self):
415 self.selection = None
416 wxTreeCtrl.Unselect(self)
417 g.tools.UpdateUI()
418
419 def ExpandAll(self, item):
420 if self.ItemHasChildren(item):
421 self.Expand(item)
422 i, cookie = self.GetFirstChild(item)
423 children = []
424 while i.IsOk():
425 children.append(i)
426 i, cookie = self.GetNextChild(item, cookie)
427 for i in children:
428 self.ExpandAll(i)
429 def CollapseAll(self, item):
430 if self.ItemHasChildren(item):
431 i, cookie = self.GetFirstChild(item)
432 children = []
433 while i.IsOk():
434 children.append(i)
435 i, cookie = self.GetNextChild(item, cookie)
436 for i in children:
437 self.CollapseAll(i)
438 self.Collapse(item)
439
440 # Clear tree
441 def Clear(self):
442 self.DeleteAllItems()
443 # Add minimal structure
444 if self.dom: self.dom.unlink()
445 self.dom = MyDocument()
446 self.dummyNode = self.dom.createComment('dummy node')
447 # Create main node
448 self.mainNode = self.dom.createElement('resource')
449 self.dom.appendChild(self.mainNode)
450 self.rootObj = xxxMainNode(self.dom)
451 self.root = self.AddRoot('XML tree', self.rootImage,
452 data=wxTreeItemData(self.rootObj))
453 self.SetItemHasChildren(self.root)
454 self.Unselect()
455 self.Expand(self.root)
456
457 # Clear old data and set new
458 def SetData(self, dom):
459 self.DeleteAllItems()
460 # Add minimal structure
461 if self.dom: self.dom.unlink()
462 self.dom = dom
463 self.dummyNode = self.dom.createComment('dummy node')
464 # Find 'resource' child, add it's children
465 self.mainNode = dom.documentElement
466 self.rootObj = xxxMainNode(self.dom)
467 self.root = self.AddRoot('XML tree', self.rootImage,
468 data=wxTreeItemData(self.rootObj))
469 self.SetItemHasChildren(self.root)
470 nodes = self.mainNode.childNodes[:]
471 for node in nodes:
472 if IsObject(node):
473 self.AddNode(self.root, None, node)
474 else:
475 self.mainNode.removeChild(node)
476 node.unlink()
477 self.Expand(self.root)
478 self.Unselect()
479
480 # Add tree item for given parent item if node is DOM element node with
481 # 'object' tag. xxxParent is parent xxx object
482 def AddNode(self, itemParent, xxxParent, node):
483 # Set item data to current node
484 try:
485 xxx = MakeXXXFromDOM(xxxParent, node)
486 except:
487 print 'ERROR: MakeXXXFromDom(%s, %s)' % (xxxParent, node)
488 raise
489 treeObj = xxx.treeObject()
490 # Append tree item
491 item = self.AppendItem(itemParent, treeObj.treeName(),
492 image=treeObj.treeImage(),
493 data=wxTreeItemData(xxx))
494 # Try to find children objects
495 if treeObj.hasChildren:
496 nodes = treeObj.element.childNodes[:]
497 for n in nodes:
498 if IsObject(n):
499 self.AddNode(item, treeObj, n)
500 elif n.nodeType != minidom.Node.ELEMENT_NODE:
501 treeObj.element.removeChild(n)
502 n.unlink()
503
504 # Insert new item at specific position
505 def InsertNode(self, itemParent, parent, elem, nextItem):
506 # Insert in XML tree and wxWin
507 xxx = MakeXXXFromDOM(parent, elem)
508 # If nextItem is None, we append to parent, otherwise insert before it
509 if nextItem.IsOk():
510 node = self.GetPyData(nextItem).element
511 parent.element.insertBefore(elem, node)
512 # Inserting before is difficult, se we insert after or first child
513 index = self.ItemIndex(nextItem)
514 newItem = self.InsertItemBefore(itemParent, index,
515 xxx.treeName(), image=xxx.treeImage())
516 self.SetPyData(newItem, xxx)
517 else:
518 parent.element.appendChild(elem)
519 newItem = self.AppendItem(itemParent, xxx.treeName(), image=xxx.treeImage(),
520 data=wxTreeItemData(xxx))
521 # Add children items
522 if xxx.hasChildren:
523 treeObj = xxx.treeObject()
524 for n in treeObj.element.childNodes:
525 if IsObject(n):
526 self.AddNode(newItem, treeObj, n)
527 return newItem
528
529 # Remove leaf of tree, return it's data object
530 def RemoveLeaf(self, leaf):
531 xxx = self.GetPyData(leaf)
532 node = xxx.element
533 parent = node.parentNode
534 parent.removeChild(node)
535 self.Delete(leaf)
536 # Reset selection object
537 self.selection = None
538 return node
539 # Find position relative to the top-level window
540 def FindNodePos(self, item):
541 # Root at (0,0)
542 if item == g.testWin.item: return wxPoint(0, 0)
543 itemParent = self.GetItemParent(item)
544 # Select NB page
545 obj = self.FindNodeObject(item)
546 if self.GetPyData(itemParent).treeObject().__class__ == xxxNotebook:
547 notebook = self.FindNodeObject(itemParent)
548 # Find position
549 for i in range(notebook.GetPageCount()):
550 if notebook.GetPage(i) == obj:
551 if notebook.GetSelection() != i:
552 notebook.SetSelection(i)
553 # Remove highlight - otherwise highlight window won't be visible
554 if g.testWin.highLight:
555 g.testWin.highLight.Remove()
556 break
557 # Find first ancestor which is a wxWindow (not a sizer)
558 winParent = itemParent
559 while self.GetPyData(winParent).isSizer:
560 winParent = self.GetItemParent(winParent)
561 # Notebook children are layed out in a little strange way
562 if self.GetPyData(itemParent).treeObject().__class__ == xxxNotebook:
563 parentPos = wxPoint(0,0)
564 else:
565 parentPos = self.FindNodePos(winParent)
566 # Position (-1,-1) is really (0,0)
567 pos = obj.GetPosition()
568 if pos == (-1,-1): pos = (0,0)
569 return parentPos + pos
570
571 # Find window (or sizer) corresponding to a tree item.
572 def FindNodeObject(self, item):
573 testWin = g.testWin
574 # If top-level, return testWin (or panel its panel)
575 if item == testWin.item: return testWin.panel
576 itemParent = self.GetItemParent(item)
577 xxx = self.GetPyData(item).treeObject()
578 parentWin = self.FindNodeObject(itemParent)
579 # Top-level sizer? return window's sizer
580 if xxx.isSizer and isinstance(parentWin, wxWindow):
581 return parentWin.GetSizer()
582 # Otherwise get parent's object and it's child
583 child = parentWin.GetChildren()[self.ItemIndex(item)]
584 # Return window or sizer for sizer items
585 if child.GetClassName() == 'wxSizerItem':
586 if child.IsWindow(): child = child.GetWindow()
587 elif child.IsSizer():
588 child = child.GetSizer()
589 # Test for notebook sizers
590 if isinstance(child, wxNotebookSizer):
591 child = child.GetNotebook()
592 return child
593
594 def OnSelChanged(self, evt):
595 self.ChangeSelection(evt.GetItem())
596
597 def ChangeSelection(self, item):
598 # Apply changes
599 # !!! problem with wxGTK - GetOldItem is Ok if nothing selected
600 #oldItem = evt.GetOldItem()
601 status = ''
602 oldItem = self.selection
603 if oldItem:
604 xxx = self.GetPyData(oldItem)
605 # If some data was modified, apply changes
606 if g.panel.IsModified():
607 self.Apply(xxx, oldItem)
608 #if conf.autoRefresh:
609 if g.testWin:
610 if g.testWin.highLight:
611 g.testWin.highLight.Remove()
612 self.needUpdate = True
613 status = 'Changes were applied'
614 g.frame.SetStatusText(status)
615 # Generate view
616 self.selection = item
617 if not self.selection.IsOk():
618 self.selection = None
619 return
620 xxx = self.GetPyData(self.selection)
621 # Update panel
622 g.panel.SetData(xxx)
623 # Update tools
624 g.tools.UpdateUI()
625 # Highlighting is done in OnIdle
626 self.pendingHighLight = self.selection
627
628 # Check if item is in testWin subtree
629 def IsHighlatable(self, item):
630 if item == g.testWin.item: return False
631 while item != self.root:
632 item = self.GetItemParent(item)
633 if item == g.testWin.item: return True
634 return False
635
636 # Highlight selected item
637 def HighLight(self, item):
638 self.pendingHighLight = None
639 # Can highlight only with some top-level windows
640 if not g.testWin or self.GetPyData(g.testWin.item).treeObject().__class__ \
641 not in [xxxDialog, xxxPanel, xxxFrame]:
642 return
643 # If a control from another window is selected, remove highlight
644 if not self.IsHighlatable(item):
645 if g.testWin.highLight: g.testWin.highLight.Remove()
646 return
647 # Get window/sizer object
648 obj, pos = self.FindNodeObject(item), self.FindNodePos(item)
649 size = obj.GetSize()
650 # Highlight
651 # Negative positions are not working quite well
652 if g.testWin.highLight:
653 g.testWin.highLight.Replace(pos, size)
654 else:
655 g.testWin.highLight = HighLightBox(pos, size)
656 g.testWin.highLight.Refresh()
657 g.testWin.highLight.item = item
658
659 def ShowTestWindow(self, item):
660 xxx = self.GetPyData(item)
661 if g.panel.IsModified():
662 self.Apply(xxx, item) # apply changes
663 treeObj = xxx.treeObject()
664 if treeObj.className not in ['wxFrame', 'wxPanel', 'wxDialog',
665 'wxMenuBar', 'wxToolBar', 'wxWizard',
666 'wxWizardPageSimple']:
667 wxLogMessage('No view for this element (yet)')
668 return
669 # Show item in bold
670 if g.testWin: # Reset old
671 self.SetItemBold(g.testWin.item, False)
672 self.CreateTestWin(item)
673 # Maybe an error occurred, so we need to test
674 if g.testWin: self.SetItemBold(g.testWin.item)
675
676 # Double-click on Linux
677 def OnItemActivated(self, evt):
678 if evt.GetItem() != self.root:
679 self.ShowTestWindow(evt.GetItem())
680
681 # Double-click on Windows
682 def OnDClick(self, evt):
683 item, flags = self.HitTest(evt.GetPosition())
684 if flags in [wxTREE_HITTEST_ONITEMBUTTON, wxTREE_HITTEST_ONITEMLABEL]:
685 if item != self.root: self.ShowTestWindow(item)
686 else:
687 evt.Skip()
688
689 def OnItemExpandedCollapsed(self, evt):
690 # Update tool palette
691 g.tools.UpdateUI()
692 evt.Skip()
693
694 # (re)create test window
695 def CreateTestWin(self, item):
696 testWin = g.testWin
697 # Create a window with this resource
698 xxx = self.GetPyData(item).treeObject()
699
700 # If frame
701 # if xxx.__class__ == xxxFrame:
702 # Frame can't have many children,
703 # but it's first child possibly can...
704 # child = self.GetFirstChild(item)[0]
705 # if child.IsOk() and self.GetPyData(child).__class__ == xxxPanel:
706 # # Clean-up before recursive call or error
707 # wxMemoryFSHandler_RemoveFile('xxx.xrc')
708 # wxEndBusyCursor()
709 # self.CreateTestWin(child)
710 # return
711
712 wxBeginBusyCursor()
713 wxYield()
714 # Close old window, remember where it was
715 highLight = None
716 if testWin:
717 pos = testWin.GetPosition()
718 if item == testWin.item:
719 # Remember highlight if same top-level window
720 if testWin.highLight:
721 highLight = testWin.highLight.item
722 if xxx.className == 'wxPanel':
723 if testWin.highLight:
724 testWin.pendingHighLight = highLight
725 testWin.highLight.Remove()
726 testWin.panel.Destroy()
727 testWin.panel = None
728 else:
729 testWin.Destroy()
730 testWin = g.testWin = None
731 else:
732 testWin.Destroy()
733 testWin = g.testWin = None
734 else:
735 pos = g.testWinPos
736 # Save in memory FS
737 memFile = MemoryFile('xxx.xrc')
738 # Create partial XML file - faster for big files
739
740 dom = MyDocument()
741 mainNode = dom.createElement('resource')
742 dom.appendChild(mainNode)
743
744 # Remove temporarily from old parent
745 elem = xxx.element
746 # Change window id to _XRCED_T_W. This gives some name for
747 # unnamed windows, and for named gives the possibility to
748 # write sawfish scripts.
749 if not xxx.name:
750 name = 'noname'
751 else:
752 name = xxx.name
753 elem.setAttribute('name', STD_NAME)
754 # Replace wizard page class temporarily
755 if xxx.__class__ in [xxxWizardPage, xxxWizardPageSimple]:
756 oldCl = elem.getAttribute('class')
757 elem.setAttribute('class', 'wxPanel')
758 parent = elem.parentNode
759 next = elem.nextSibling
760 parent.replaceChild(self.dummyNode, elem)
761 # Append to new DOM, write it
762 mainNode.appendChild(elem)
763 dom.writexml(memFile, encoding=self.rootObj.params['encoding'].value())
764 # Put back in place
765 mainNode.removeChild(elem)
766 dom.unlink()
767 parent.replaceChild(elem, self.dummyNode)
768 # Remove temporary name or restore changed
769 if not xxx.name:
770 elem.removeAttribute('name')
771 else:
772 elem.setAttribute('name', xxx.name)
773 if xxx.__class__ in [xxxWizardPage, xxxWizardPageSimple]:
774 elem.setAttribute('class', oldCl)
775 memFile.close() # write to wxMemoryFS
776 xmlFlags = wxXRC_NO_SUBCLASSING
777 # Use translations if encoding is not specified
778 if not g.currentEncoding:
779 xmlFlags != wxXRC_USE_LOCALE
780 res = wxXmlResource('', xmlFlags)
781 res.Load('memory:xxx.xrc')
782 try:
783 if xxx.__class__ == xxxFrame:
784 # Frame can't have many children,
785 # but it's first child possibly can...
786 # child = self.GetFirstChild(item)[0]
787 # if child.IsOk() and self.GetPyData(child).__class__ == xxxPanel:
788 # # Clean-up before recursive call or error
789 # wxMemoryFSHandler_RemoveFile('xxx.xrc')
790 # wxEndBusyCursor()
791 # self.CreateTestWin(child)
792 # return
793 # This currently works under GTK, but not under MSW
794 testWin = g.testWin = wxPreFrame()
795 res.LoadOnFrame(testWin, g.frame, STD_NAME)
796 # Create status bar
797 testWin.panel = testWin
798 testWin.CreateStatusBar()
799 testWin.SetClientSize(testWin.GetBestSize())
800 testWin.SetPosition(pos)
801 testWin.Show(True)
802 elif xxx.__class__ == xxxPanel:
803 # Create new frame
804 if not testWin:
805 testWin = g.testWin = wxFrame(g.frame, -1, 'Panel: ' + name,
806 pos=pos, name=STD_NAME)
807 testWin.panel = res.LoadPanel(testWin, STD_NAME)
808 testWin.SetClientSize(testWin.GetBestSize())
809 testWin.Show(True)
810 elif xxx.__class__ == xxxDialog:
811 testWin = g.testWin = res.LoadDialog(None, STD_NAME)
812 testWin.panel = testWin
813 testWin.Layout()
814 testWin.SetPosition(pos)
815 testWin.Show(True)
816 # Dialog's default code does not produce EVT_CLOSE
817 EVT_BUTTON(testWin, wxID_OK, self.OnCloseTestWin)
818 EVT_BUTTON(testWin, wxID_CANCEL, self.OnCloseTestWin)
819 elif xxx.__class__ == xxxWizard:
820 wiz = wxPreWizard()
821 res.LoadOnObject(wiz, None, STD_NAME, 'wxWizard')
822 # Find first page (don't know better way)
823 firstPage = None
824 for w in wiz.GetChildren():
825 if isinstance(w, wxWizardPage):
826 firstPage = w
827 break
828 if not firstPage:
829 wxLogError('Wizard is empty')
830 else:
831 # Wizard should be modal
832 self.SetItemBold(item)
833 wiz.RunWizard(w)
834 self.SetItemBold(item, False)
835 wiz.Destroy()
836 elif xxx.__class__ in [xxxWizardPage, xxxWizardPageSimple]:
837 # Create new frame
838 if not testWin:
839 testWin = g.testWin = wxFrame(g.frame, -1, 'Wizard page: ' + name,
840 pos=pos, name=STD_NAME)
841 testWin.panel = wxPrePanel()
842 res.LoadOnObject(testWin.panel, testWin, STD_NAME, 'wxPanel')
843 testWin.SetClientSize(testWin.GetBestSize())
844 testWin.Show(True)
845 elif xxx.__class__ == xxxMenuBar:
846 testWin = g.testWin = wxFrame(g.frame, -1, 'MenuBar: ' + name,
847 pos=pos, name=STD_NAME)
848 testWin.panel = None
849 # Set status bar to display help
850 testWin.CreateStatusBar()
851 testWin.menuBar = res.LoadMenuBar(STD_NAME)
852 testWin.SetMenuBar(testWin.menuBar)
853 testWin.Show(True)
854 elif xxx.__class__ == xxxToolBar:
855 testWin = g.testWin = wxFrame(g.frame, -1, 'ToolBar: ' + name,
856 pos=pos, name=STD_NAME)
857 testWin.panel = None
858 # Set status bar to display help
859 testWin.CreateStatusBar()
860 testWin.toolBar = res.LoadToolBar(testWin, STD_NAME)
861 testWin.SetToolBar(testWin.toolBar)
862 testWin.Show(True)
863 if testWin:
864 testWin.item = item
865 EVT_CLOSE(testWin, self.OnCloseTestWin)
866 testWin.highLight = None
867 if highLight and not self.pendingHighLight:
868 self.HighLight(highLight)
869 except:
870 if g.testWin:
871 self.SetItemBold(item, False)
872 g.testWinPos = g.testWin.GetPosition()
873 g.testWin.Destroy()
874 g.testWin = None
875 inf = sys.exc_info()
876 wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1])
877 wxLogError('Error loading resource')
878 wxMemoryFSHandler_RemoveFile('xxx.xrc')
879 wxEndBusyCursor()
880
881 def CloseTestWindow(self):
882 if not g.testWin: return
883 self.SetItemBold(g.testWin.item, False)
884 g.frame.tb.ToggleTool(g.frame.ID_TOOL_LOCATE, False)
885 g.testWinPos = g.testWin.GetPosition()
886 g.testWin.Destroy()
887 g.testWin = None
888
889 def OnCloseTestWin(self, evt):
890 self.CloseTestWindow()
891
892 # Return item index in parent
893 def ItemIndex(self, item):
894 n = 0 # index of sibling
895 prev = self.GetPrevSibling(item)
896 while prev.IsOk():
897 prev = self.GetPrevSibling(prev)
898 n += 1
899 return n
900
901 # Full tree index of an item - list of positions
902 def ItemFullIndex(self, item):
903 if not item.IsOk(): return None
904 l = []
905 while item != self.root:
906 l.insert(0, self.ItemIndex(item))
907 item = self.GetItemParent(item)
908 return l
909 # Get item position from full index
910 def ItemAtFullIndex(self, index):
911 if index is None: return wxTreeItemId()
912 item = self.root
913 for i in index:
914 item = self.GetFirstChild(item)[0]
915 for k in range(i): item = self.GetNextSibling(item)
916 return item
917
918 # True if next item should be inserted after current (vs. appended to it)
919 def NeedInsert(self, item):
920 xxx = self.GetPyData(item)
921 if item == self.root: return False # root item
922 if xxx.hasChildren and not self.GetChildrenCount(item, False):
923 return False
924 return not (self.IsExpanded(item) and self.GetChildrenCount(item, False))
925
926 # Pull-down
927 def OnRightDown(self, evt):
928 pullDownMenu = g.pullDownMenu
929 # select this item
930 pt = evt.GetPosition();
931 item, flags = self.HitTest(pt)
932 if item.Ok() and flags & wxTREE_HITTEST_ONITEM:
933 self.SelectItem(item)
934
935 # Setup menu
936 menu = wxMenu()
937
938 item = self.selection
939 if not item:
940 menu.Append(g.pullDownMenu.ID_EXPAND, 'Expand', 'Expand tree')
941 menu.Append(g.pullDownMenu.ID_COLLAPSE, 'Collapse', 'Collapse tree')
942 else:
943 # self.ctrl = evt.ControlDown() # save Ctrl state
944 # self.shift = evt.ShiftDown() # and Shift too
945 m = wxMenu() # create menu
946 if self.ctrl:
947 needInsert = True
948 else:
949 needInsert = self.NeedInsert(item)
950 if item == self.root or needInsert and self.GetItemParent(item) == self.root:
951 SetMenu(m, pullDownMenu.topLevel)
952 else:
953 xxx = self.GetPyData(item).treeObject()
954 # Check parent for possible child nodes if inserting sibling
955 if needInsert: xxx = xxx.parent
956 if xxx.__class__ == xxxMenuBar:
957 m.Append(ID_NEW.MENU, 'Menu', 'Create menu')
958 elif xxx.__class__ in [xxxToolBar, xxxTool] or \
959 xxx.__class__ == xxxSeparator and xxx.parent.__class__ == xxxToolBar:
960 SetMenu(m, pullDownMenu.toolBarControls)
961 elif xxx.__class__ in [xxxMenu, xxxMenuItem]:
962 SetMenu(m, pullDownMenu.menuControls)
963 else:
964 SetMenu(m, pullDownMenu.controls)
965 if xxx.__class__ == xxxNotebook:
966 m.Enable(m.FindItem('sizer'), False)
967 elif not (xxx.isSizer or xxx.parent and xxx.parent.isSizer):
968 m.Enable(ID_NEW.SPACER, False)
969 # Select correct label for create menu
970 if not needInsert:
971 if self.shift:
972 menu.AppendMenu(wxNewId(), 'Insert Child', m,
973 'Create child object as the first child')
974 else:
975 menu.AppendMenu(wxNewId(), 'Append Child', m,
976 'Create child object as the last child')
977 else:
978 if self.shift:
979 menu.AppendMenu(wxNewId(), 'Create Sibling', m,
980 'Create sibling before selected object')
981 else:
982 menu.AppendMenu(wxNewId(), 'Create Sibling', m,
983 'Create sibling after selected object')
984 # Build replace menu
985 if item != self.root:
986 xxx = self.GetPyData(item).treeObject()
987 m = wxMenu() # create replace menu
988 if xxx.__class__ == xxxMenuBar:
989 m.Append(1000 + ID_NEW.MENU, 'Menu', 'Create menu')
990 elif xxx.__class__ in [xxxMenu, xxxMenuItem]:
991 SetMenu2(m, pullDownMenu.menuControls)
992 elif xxx.__class__ == xxxToolBar and \
993 self.GetItemParent(item) == self.root:
994 SetMenu2(m, [])
995 elif xxx.__class__ in [xxxFrame, xxxDialog, xxxPanel]:
996 SetMenu2(m, [
997 (ID_NEW.PANEL, 'Panel', 'Create panel'),
998 (ID_NEW.DIALOG, 'Dialog', 'Create dialog'),
999 (ID_NEW.FRAME, 'Frame', 'Create frame')])
1000 elif xxx.isSizer:
1001 SetMenu2(m, pullDownMenu.sizers)
1002 else:
1003 SetMenu2(m, pullDownMenu.controls)
1004 id = wxNewId()
1005 menu.AppendMenu(id, 'Replace With', m)
1006 if not m.GetMenuItemCount(): menu.Enable(id, False)
1007 menu.Append(pullDownMenu.ID_SUBCLASS, 'Subclass...',
1008 'Set subclass property')
1009 menu.AppendSeparator()
1010 # Not using standart IDs because we don't want to show shortcuts
1011 menu.Append(wxID_CUT, 'Cut', 'Cut to the clipboard')
1012 menu.Append(wxID_COPY, 'Copy', 'Copy to the clipboard')
1013 if self.ctrl and item != self.root:
1014 menu.Append(pullDownMenu.ID_PASTE_SIBLING, 'Paste Sibling',
1015 'Paste from the clipboard as a sibling')
1016 else:
1017 menu.Append(wxID_PASTE, 'Paste', 'Paste from the clipboard')
1018 menu.Append(pullDownMenu.ID_DELETE,
1019 'Delete', 'Delete object')
1020 if self.ItemHasChildren(item):
1021 menu.AppendSeparator()
1022 menu.Append(pullDownMenu.ID_EXPAND, 'Expand', 'Expand subtree')
1023 menu.Append(pullDownMenu.ID_COLLAPSE, 'Collapse', 'Collapse subtree')
1024 self.PopupMenu(menu, evt.GetPosition())
1025 menu.Destroy()
1026
1027 # Apply changes
1028 def Apply(self, xxx, item):
1029 g.panel.Apply()
1030 # Update tree view
1031 xxx = xxx.treeObject()
1032 if xxx.hasName and self.GetItemText(item) != xxx.name:
1033 self.SetItemText(item, xxx.treeName())
1034 # Item width may have changed
1035 # !!! Tric to update tree width (wxGTK, ??)
1036 self.SetIndent(self.GetIndent())
1037 # Change tree icon for sizers
1038 if isinstance(xxx, xxxBoxSizer):
1039 self.SetItemImage(item, xxx.treeImage())
1040 # Set global modified state
1041 g.frame.modified = True
1042