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