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