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