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