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