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