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