]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/tools/XRCed/xrced.py
d9ffccd342c838cdaea7b78d6d66bfd29078aabf
[wxWidgets.git] / wxPython / wx / tools / XRCed / xrced.py
1 # Name: xrced.py
2 # Purpose: XRC editor, main module
3 # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be>
4 # Created: 20.08.2001
5 # RCS-ID: $Id$
6
7 """
8
9 xrced -- Simple resource editor for XRC format used by wxWindows/wxPython
10 GUI toolkit.
11
12 Usage:
13
14 xrced [ -h ] [ -v ] [ XRC-file ]
15
16 Options:
17
18 -h output short usage info and exit
19
20 -v output version info and exit
21 """
22
23
24 from globals import *
25 import os, sys, getopt, re, traceback
26
27 # Local modules
28 from tree import * # imports xxx which imports params
29 from panel import *
30 from tools import *
31 # Cleanup recursive import sideeffects, otherwise we can't create undoMan
32 import undo
33 undo.ParamPage = ParamPage
34 undoMan = g.undoMan = UndoManager()
35
36 # Set application path for loading resources
37 if __name__ == '__main__':
38 basePath = os.path.dirname(sys.argv[0])
39 else:
40 basePath = os.path.dirname(__file__)
41
42 # 1 adds CMD command to Help menu
43 debug = 0
44
45 g.helpText = """\
46 <HTML><H2>Welcome to XRC<font color="blue">ed</font></H2><H3><font color="green">DON'T PANIC :)</font></H3>
47 Read this note before clicking on anything!<P>
48 To start select tree root, then popup menu with your right mouse button,
49 select "Append Child", and then any command.<P>
50 Or just press one of the buttons on the tools palette.<P>
51 Enter XML ID, change properties, create children.<P>
52 To test your interface select Test command (View menu).<P>
53 Consult README file for the details.</HTML>
54 """
55
56 defaultIDs = {xxxPanel:'PANEL', xxxDialog:'DIALOG', xxxFrame:'FRAME',
57 xxxMenuBar:'MENUBAR', xxxMenu:'MENU', xxxToolBar:'TOOLBAR'}
58
59 ################################################################################
60
61 # ScrolledMessageDialog - modified from wxPython lib to set fixed-width font
62 class ScrolledMessageDialog(wxDialog):
63 def __init__(self, parent, msg, caption, pos = wxDefaultPosition, size = (500,300)):
64 from wxPython.lib.layoutf import Layoutf
65 wxDialog.__init__(self, parent, -1, caption, pos, size)
66 text = wxTextCtrl(self, -1, msg, wxDefaultPosition,
67 wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY)
68 text.SetFont(g.modernFont())
69 dc = wxWindowDC(text)
70 # !!! possible bug - GetTextExtent without font returns sysfont dims
71 w, h = dc.GetFullTextExtent(' ', g.modernFont())[:2]
72 ok = wxButton(self, wxID_OK, "OK")
73 text.SetConstraints(Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self,ok)))
74 text.SetSize((w * 80 + 30, h * 40))
75 text.ShowPosition(1)
76 ok.SetConstraints(Layoutf('b=b5#1;x%w50#1;w!80;h!25', (self,)))
77 self.SetAutoLayout(True)
78 self.Fit()
79 self.CenterOnScreen(wxBOTH)
80
81 ################################################################################
82
83 # Event handler for using during location
84 class Locator(wxEvtHandler):
85 def ProcessEvent(self, evt):
86 print evt
87
88 class Frame(wxFrame):
89 def __init__(self, pos, size):
90 wxFrame.__init__(self, None, -1, '', pos, size)
91 global frame
92 frame = g.frame = self
93 bar = self.CreateStatusBar(2)
94 bar.SetStatusWidths([-1, 40])
95 self.SetIcon(images.getIconIcon())
96
97 # Idle flag
98 self.inIdle = False
99
100 # Make menus
101 menuBar = wxMenuBar()
102
103 menu = wxMenu()
104 menu.Append(wxID_NEW, '&New\tCtrl-N', 'New file')
105 menu.AppendSeparator()
106 menu.Append(wxID_OPEN, '&Open...\tCtrl-O', 'Open XRC file')
107 self.recentMenu = wxMenu()
108 self.AppendRecent(self.recentMenu)
109 menu.AppendMenu(-1, 'Open Recent', self.recentMenu, 'Open a recent file')
110 menu.AppendSeparator()
111 menu.Append(wxID_SAVE, '&Save\tCtrl-S', 'Save XRC file')
112 menu.Append(wxID_SAVEAS, 'Save &As...', 'Save XRC file under different name')
113 menu.AppendSeparator()
114 menu.Append(wxID_EXIT, '&Quit\tCtrl-Q', 'Exit application')
115
116 menuBar.Append(menu, '&File')
117
118 menu = wxMenu()
119 menu.Append(wxID_UNDO, '&Undo\tCtrl-Z', 'Undo')
120 menu.Append(wxID_REDO, '&Redo\tCtrl-Y', 'Redo')
121 menu.AppendSeparator()
122 menu.Append(wxID_CUT, 'Cut\tCtrl-X', 'Cut to the clipboard')
123 menu.Append(wxID_COPY, '&Copy\tCtrl-C', 'Copy to the clipboard')
124 menu.Append(wxID_PASTE, '&Paste\tCtrl-V', 'Paste from the clipboard')
125 self.ID_DELETE = wxNewId()
126 menu.Append(self.ID_DELETE, '&Delete\tCtrl-D', 'Delete object')
127 # menu.AppendSeparator()
128 self.ID_LOCATE = wxNewId()
129 menu.Append(self.ID_LOCATE, '&Locate\tCtrl-L', 'Locate control in test window and select it')
130 menuBar.Append(menu, '&Edit')
131
132 menu = wxMenu()
133 self.ID_EMBED_PANEL = wxNewId()
134 menu.Append(self.ID_EMBED_PANEL, '&Embed Panel',
135 'Toggle embedding properties panel in the main window', True)
136 menu.Check(self.ID_EMBED_PANEL, conf.embedPanel)
137 self.ID_SHOW_TOOLS = wxNewId()
138 menu.Append(self.ID_SHOW_TOOLS, 'Show &Tools', 'Toggle tools', True)
139 menu.Check(self.ID_SHOW_TOOLS, conf.showTools)
140 menu.AppendSeparator()
141 self.ID_TEST = wxNewId()
142 menu.Append(self.ID_TEST, '&Test\tF5', 'Show test window')
143 self.ID_REFRESH = wxNewId()
144 menu.Append(self.ID_REFRESH, '&Refresh\tCtrl-R', 'Refresh test window')
145 self.ID_AUTO_REFRESH = wxNewId()
146 menu.Append(self.ID_AUTO_REFRESH, '&Auto-refresh\tCtrl-A',
147 'Toggle auto-refresh mode', True)
148 menu.Check(self.ID_AUTO_REFRESH, conf.autoRefresh)
149 menuBar.Append(menu, '&View')
150
151 menu = wxMenu()
152 menu.Append(wxID_ABOUT, '&About...', 'About XCRed')
153 self.ID_README = wxNewId()
154 menu.Append(self.ID_README, '&Readme...', 'View the README file')
155 if debug:
156 self.ID_DEBUG_CMD = wxNewId()
157 menu.Append(self.ID_DEBUG_CMD, 'CMD', 'Python command line')
158 EVT_MENU(self, self.ID_DEBUG_CMD, self.OnDebugCMD)
159 menuBar.Append(menu, '&Help')
160
161 self.menuBar = menuBar
162 self.SetMenuBar(menuBar)
163
164 # Create toolbar
165 tb = self.CreateToolBar(wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT)
166 tb.SetToolBitmapSize((24, 23))
167 tb.AddSimpleTool(wxID_NEW, images.getNewBitmap(), 'New', 'New file')
168 tb.AddSimpleTool(wxID_OPEN, images.getOpenBitmap(), 'Open', 'Open file')
169 tb.AddSimpleTool(wxID_SAVE, images.getSaveBitmap(), 'Save', 'Save file')
170 tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
171 tb.AddSimpleTool(wxID_UNDO, images.getUndoBitmap(), 'Undo', 'Undo')
172 tb.AddSimpleTool(wxID_REDO, images.getRedoBitmap(), 'Redo', 'Redo')
173 tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
174 tb.AddSimpleTool(wxID_CUT, images.getCutBitmap(), 'Cut', 'Cut')
175 tb.AddSimpleTool(wxID_COPY, images.getCopyBitmap(), 'Copy', 'Copy')
176 tb.AddSimpleTool(wxID_PASTE, images.getPasteBitmap(), 'Paste', 'Paste')
177 tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
178 tb.AddSimpleTool(self.ID_TEST, images.getTestBitmap(), 'Test', 'Test window')
179 tb.AddSimpleTool(self.ID_REFRESH, images.getRefreshBitmap(),
180 'Refresh', 'Refresh view')
181 tb.AddSimpleTool(self.ID_AUTO_REFRESH, images.getAutoRefreshBitmap(),
182 'Auto-refresh', 'Toggle auto-refresh mode', True)
183 if wxPlatform == '__WXGTK__':
184 tb.AddSeparator() # otherwise auto-refresh sticks in status line
185 tb.ToggleTool(self.ID_AUTO_REFRESH, conf.autoRefresh)
186 tb.Realize()
187 self.tb = tb
188 self.minWidth = tb.GetSize()[0] # minimal width is the size of toolbar
189
190 # File
191 EVT_MENU(self, wxID_NEW, self.OnNew)
192 EVT_MENU(self, wxID_OPEN, self.OnOpen)
193 EVT_MENU(self, wxID_SAVE, self.OnSaveOrSaveAs)
194 EVT_MENU(self, wxID_SAVEAS, self.OnSaveOrSaveAs)
195 EVT_MENU(self, wxID_EXIT, self.OnExit)
196 # Edit
197 EVT_MENU(self, wxID_UNDO, self.OnUndo)
198 EVT_MENU(self, wxID_REDO, self.OnRedo)
199 EVT_MENU(self, wxID_CUT, self.OnCutDelete)
200 EVT_MENU(self, wxID_COPY, self.OnCopy)
201 EVT_MENU(self, wxID_PASTE, self.OnPaste)
202 EVT_MENU(self, self.ID_DELETE, self.OnCutDelete)
203 EVT_MENU(self, self.ID_LOCATE, self.OnLocate)
204 # View
205 EVT_MENU(self, self.ID_EMBED_PANEL, self.OnEmbedPanel)
206 EVT_MENU(self, self.ID_SHOW_TOOLS, self.OnShowTools)
207 EVT_MENU(self, self.ID_TEST, self.OnTest)
208 EVT_MENU(self, self.ID_REFRESH, self.OnRefresh)
209 EVT_MENU(self, self.ID_AUTO_REFRESH, self.OnAutoRefresh)
210 # Help
211 EVT_MENU(self, wxID_ABOUT, self.OnAbout)
212 EVT_MENU(self, self.ID_README, self.OnReadme)
213
214 # Update events
215 EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateUI)
216 EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateUI)
217 EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateUI)
218 EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateUI)
219 EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateUI)
220 EVT_UPDATE_UI(self, self.ID_DELETE, self.OnUpdateUI)
221 EVT_UPDATE_UI(self, self.ID_TEST, self.OnUpdateUI)
222 EVT_UPDATE_UI(self, self.ID_REFRESH, self.OnUpdateUI)
223
224 # Build interface
225 sizer = wxBoxSizer(wxVERTICAL)
226 sizer.Add(wxStaticLine(self, -1), 0, wxEXPAND)
227 # Horizontal sizer for toolbar and splitter
228 self.toolsSizer = sizer1 = wxBoxSizer()
229 splitter = wxSplitterWindow(self, -1, style=wxSP_3DSASH)
230 self.splitter = splitter
231 splitter.SetMinimumPaneSize(100)
232 # Create tree
233 global tree
234 g.tree = tree = XML_Tree(splitter, -1)
235
236 # Init pull-down menu data
237 global pullDownMenu
238 g.pullDownMenu = pullDownMenu = PullDownMenu(self)
239
240 # Vertical toolbar for GUI buttons
241 g.tools = tools = Tools(self)
242 tools.Show(conf.showTools)
243 if conf.showTools: sizer1.Add(tools, 0, wxEXPAND)
244
245 tree.RegisterKeyEvents()
246
247 # !!! frame styles are broken
248 # Miniframe for not embedded mode
249 miniFrame = wxFrame(self, -1, 'Properties Panel',
250 (conf.panelX, conf.panelY),
251 (conf.panelWidth, conf.panelHeight))
252 self.miniFrame = miniFrame
253 sizer2 = wxBoxSizer()
254 miniFrame.SetAutoLayout(True)
255 miniFrame.SetSizer(sizer2)
256 EVT_CLOSE(self.miniFrame, self.OnCloseMiniFrame)
257 # Create panel for parameters
258 global panel
259 if conf.embedPanel:
260 panel = Panel(splitter)
261 # Set plitter windows
262 splitter.SplitVertically(tree, panel, conf.sashPos)
263 else:
264 panel = Panel(miniFrame)
265 sizer2.Add(panel, 1, wxEXPAND)
266 miniFrame.Show(True)
267 splitter.Initialize(tree)
268 sizer1.Add(splitter, 1, wxEXPAND)
269 sizer.Add(sizer1, 1, wxEXPAND)
270 self.SetAutoLayout(True)
271 self.SetSizer(sizer)
272
273 # Initialize
274 self.clipboard = None
275 self.Clear()
276
277 # Other events
278 EVT_IDLE(self, self.OnIdle)
279 EVT_CLOSE(self, self.OnCloseWindow)
280 EVT_KEY_DOWN(self, tools.OnKeyDown)
281 EVT_KEY_UP(self, tools.OnKeyUp)
282
283 def AppendRecent(self, menu):
284 # add recently used files to the menu
285 for id,name in conf.recentfiles.iteritems():
286 menu.Append(id,name)
287 EVT_MENU(self,id,self.OnRecentFile)
288 return
289
290 def OnRecentFile(self,evt):
291 # open recently used file
292 if not self.AskSave(): return
293 wxBeginBusyCursor()
294 try:
295 path=conf.recentfiles[evt.GetId()]
296 if self.Open(path):
297 self.SetStatusText('Data loaded')
298 else:
299 self.SetStatusText('Failed')
300 except KeyError:
301 self.SetStatusText('No such file')
302 wxEndBusyCursor()
303
304 def OnNew(self, evt):
305 if not self.AskSave(): return
306 self.Clear()
307
308 def OnOpen(self, evt):
309 if not self.AskSave(): return
310 dlg = wxFileDialog(self, 'Open', os.path.dirname(self.dataFile),
311 '', '*.xrc', wxOPEN | wxCHANGE_DIR)
312 if dlg.ShowModal() == wxID_OK:
313 path = dlg.GetPath()
314 self.SetStatusText('Loading...')
315 wxYield()
316 wxBeginBusyCursor()
317 if self.Open(path):
318 self.SetStatusText('Data loaded')
319 else:
320 self.SetStatusText('Failed')
321 self.SaveRecent(path)
322 wxEndBusyCursor()
323 dlg.Destroy()
324
325 def OnSaveOrSaveAs(self, evt):
326 if evt.GetId() == wxID_SAVEAS or not self.dataFile:
327 if self.dataFile: defaultName = ''
328 else: defaultName = 'UNTITLED.xrc'
329 dirname = os.path.dirname(self.dataFile)
330 dlg = wxFileDialog(self, 'Save As', dirname, defaultName, '*.xrc',
331 wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR)
332 if dlg.ShowModal() == wxID_OK:
333 path = dlg.GetPath()
334 dlg.Destroy()
335 else:
336 dlg.Destroy()
337 return
338 else:
339 path = self.dataFile
340 self.SetStatusText('Saving...')
341 wxYield()
342 wxBeginBusyCursor()
343 try:
344 self.Save(path)
345 self.dataFile = path
346 self.SetStatusText('Data saved')
347 self.SaveRecent(path)
348 except IOError:
349 self.SetStatusText('Failed')
350 wxEndBusyCursor()
351
352 def SaveRecent(self,path):
353 # append to recently used files
354 if path not in conf.recentfiles.values():
355 newid = wxNewId()
356 self.recentMenu.Append(newid, path)
357 EVT_MENU(self, newid, self.OnRecentFile)
358 conf.recentfiles[newid] = path
359
360 def OnExit(self, evt):
361 self.Close()
362
363 def OnUndo(self, evt):
364 # Extra check to not mess with idle updating
365 if undoMan.CanUndo():
366 undoMan.Undo()
367
368 def OnRedo(self, evt):
369 if undoMan.CanRedo():
370 undoMan.Redo()
371
372 def OnCopy(self, evt):
373 selected = tree.selection
374 if not selected: return # key pressed event
375 xxx = tree.GetPyData(selected)
376 self.clipboard = xxx.element.cloneNode(True)
377 self.SetStatusText('Copied')
378
379 def OnPaste(self, evt):
380 selected = tree.selection
381 if not selected: return # key pressed event
382 # For pasting with Ctrl pressed
383 if evt.GetId() == pullDownMenu.ID_PASTE_SIBLING: appendChild = False
384 else: appendChild = not tree.NeedInsert(selected)
385 xxx = tree.GetPyData(selected)
386 if not appendChild:
387 # If has next item, insert, else append to parent
388 nextItem = tree.GetNextSibling(selected)
389 parentLeaf = tree.GetItemParent(selected)
390 # Expanded container (must have children)
391 elif tree.IsExpanded(selected) and tree.GetChildrenCount(selected, False):
392 # Insert as first child
393 nextItem = tree.GetFirstChild(selected)[0]
394 parentLeaf = selected
395 else:
396 # No children or unexpanded item - appendChild stays True
397 nextItem = wxTreeItemId() # no next item
398 parentLeaf = selected
399 parent = tree.GetPyData(parentLeaf).treeObject()
400
401 # Create a copy of clipboard element
402 elem = self.clipboard.cloneNode(True)
403 # Tempopary xxx object to test things
404 xxx = MakeXXXFromDOM(parent, elem)
405
406 # Check compatibility
407 error = False
408 # Top-level
409 x = xxx.treeObject()
410 if x.__class__ in [xxxDialog, xxxFrame, xxxMenuBar]:
411 # Top-level classes
412 if parent.__class__ != xxxMainNode: error = True
413 elif x.__class__ == xxxToolBar:
414 # Toolbar can be top-level of child of panel or frame
415 if parent.__class__ not in [xxxMainNode, xxxPanel, xxxFrame]: error = True
416 elif x.__class__ == xxxPanel and parent.__class__ == xxxMainNode:
417 pass
418 elif x.__class__ == xxxSpacer:
419 if not parent.isSizer: error = True
420 elif x.__class__ == xxxSeparator:
421 if not parent.__class__ in [xxxMenu, xxxToolBar]: error = True
422 elif x.__class__ == xxxTool:
423 if parent.__class__ != xxxToolBar: error = True
424 elif x.__class__ == xxxMenu:
425 if not parent.__class__ in [xxxMainNode, xxxMenuBar, xxxMenu]: error = True
426 elif x.__class__ == xxxMenuItem:
427 if not parent.__class__ in [xxxMenuBar, xxxMenu]: error = True
428 elif x.isSizer and parent.__class__ == xxxNotebook: error = True
429 else: # normal controls can be almost anywhere
430 if parent.__class__ == xxxMainNode or \
431 parent.__class__ in [xxxMenuBar, xxxMenu]: error = True
432 if error:
433 if parent.__class__ == xxxMainNode: parentClass = 'root'
434 else: parentClass = parent.className
435 wxLogError('Incompatible parent/child: parent is %s, child is %s!' %
436 (parentClass, x.className))
437 return
438
439 # Check parent and child relationships.
440 # If parent is sizer or notebook, child is of wrong class or
441 # parent is normal window, child is child container then detach child.
442 isChildContainer = isinstance(xxx, xxxChildContainer)
443 if isChildContainer and \
444 ((parent.isSizer and not isinstance(xxx, xxxSizerItem)) or \
445 (isinstance(parent, xxxNotebook) and not isinstance(xxx, xxxNotebookPage)) or \
446 not (parent.isSizer or isinstance(parent, xxxNotebook))):
447 elem.removeChild(xxx.child.element) # detach child
448 elem.unlink() # delete child container
449 elem = xxx.child.element # replace
450 # This may help garbage collection
451 xxx.child.parent = None
452 isChildContainer = False
453 # Parent is sizer or notebook, child is not child container
454 if parent.isSizer and not isChildContainer and not isinstance(xxx, xxxSpacer):
455 # Create sizer item element
456 sizerItemElem = MakeEmptyDOM('sizeritem')
457 sizerItemElem.appendChild(elem)
458 elem = sizerItemElem
459 elif isinstance(parent, xxxNotebook) and not isChildContainer:
460 pageElem = MakeEmptyDOM('notebookpage')
461 pageElem.appendChild(elem)
462 elem = pageElem
463 # Insert new node, register undo
464 newItem = tree.InsertNode(parentLeaf, parent, elem, nextItem)
465 undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected))
466 # Scroll to show new item (!!! redundant?)
467 tree.EnsureVisible(newItem)
468 tree.SelectItem(newItem)
469 if not tree.IsVisible(newItem):
470 tree.ScrollTo(newItem)
471 tree.Refresh()
472 # Update view?
473 if g.testWin and tree.IsHighlatable(newItem):
474 if conf.autoRefresh:
475 tree.needUpdate = True
476 tree.pendingHighLight = newItem
477 else:
478 tree.pendingHighLight = None
479 self.modified = True
480 self.SetStatusText('Pasted')
481
482 def OnCutDelete(self, evt):
483 selected = tree.selection
484 if not selected: return # key pressed event
485 # Undo info
486 if evt.GetId() == wxID_CUT:
487 self.lastOp = 'CUT'
488 status = 'Removed to clipboard'
489 else:
490 self.lastOp = 'DELETE'
491 status = 'Deleted'
492 # Delete testWin?
493 if g.testWin:
494 # If deleting top-level item, delete testWin
495 if selected == g.testWin.item:
496 g.testWin.Destroy()
497 g.testWin = None
498 else:
499 # Remove highlight, update testWin
500 if g.testWin.highLight:
501 g.testWin.highLight.Remove()
502 tree.needUpdate = True
503 # Prepare undo data
504 panel.Apply()
505 index = tree.ItemFullIndex(selected)
506 parent = tree.GetPyData(tree.GetItemParent(selected)).treeObject()
507 elem = tree.RemoveLeaf(selected)
508 undoMan.RegisterUndo(UndoCutDelete(index, parent, elem))
509 if evt.GetId() == wxID_CUT:
510 if self.clipboard: self.clipboard.unlink()
511 self.clipboard = elem.cloneNode(True)
512 tree.pendingHighLight = None
513 tree.Unselect()
514 panel.Clear()
515 self.modified = True
516 self.SetStatusText(status)
517
518 def OnSubclass(self, evt):
519 selected = tree.selection
520 xxx = tree.GetPyData(selected).treeObject()
521 elem = xxx.element
522 subclass = xxx.subclass
523 dlg = wxTextEntryDialog(self, 'Subclass:', defaultValue=subclass)
524 if dlg.ShowModal() == wxID_OK:
525 subclass = dlg.GetValue()
526 if subclass:
527 elem.setAttribute('subclass', subclass)
528 self.modified = True
529 elif elem.hasAttribute('subclass'):
530 elem.removeAttribute('subclass')
531 self.modified = True
532 xxx.subclass = elem.getAttribute('subclass')
533 tree.SetItemText(selected, xxx.treeName())
534 panel.pages[0].box.SetLabel(xxx.panelName())
535 dlg.Destroy()
536
537 def OnEmbedPanel(self, evt):
538 conf.embedPanel = evt.IsChecked()
539 if conf.embedPanel:
540 # Remember last dimentions
541 conf.panelX, conf.panelY = self.miniFrame.GetPosition()
542 conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize()
543 size = self.GetSize()
544 pos = self.GetPosition()
545 sizePanel = panel.GetSize()
546 panel.Reparent(self.splitter)
547 self.miniFrame.GetSizer().Remove(panel)
548 wxYield()
549 # Widen
550 self.SetDimensions(pos.x, pos.y, size.width + sizePanel.width, size.height)
551 self.splitter.SplitVertically(tree, panel, conf.sashPos)
552 self.miniFrame.Show(False)
553 else:
554 conf.sashPos = self.splitter.GetSashPosition()
555 pos = self.GetPosition()
556 size = self.GetSize()
557 sizePanel = panel.GetSize()
558 self.splitter.Unsplit(panel)
559 sizer = self.miniFrame.GetSizer()
560 panel.Reparent(self.miniFrame)
561 panel.Show(True)
562 sizer.Add(panel, 1, wxEXPAND)
563 self.miniFrame.Show(True)
564 self.miniFrame.SetDimensions(conf.panelX, conf.panelY,
565 conf.panelWidth, conf.panelHeight)
566 wxYield()
567 # Reduce width
568 self.SetDimensions(pos.x, pos.y,
569 max(size.width - sizePanel.width, self.minWidth), size.height)
570
571 def OnShowTools(self, evt):
572 conf.showTools = evt.IsChecked()
573 g.tools.Show(conf.showTools)
574 if conf.showTools:
575 self.toolsSizer.Prepend(g.tools, 0, wxEXPAND)
576 else:
577 self.toolsSizer.Remove(g.tools)
578 self.toolsSizer.Layout()
579
580 def OnTest(self, evt):
581 if not tree.selection: return # key pressed event
582 tree.ShowTestWindow(tree.selection)
583
584 # Find object by relative position
585 def FindObject(self, item, obj):
586 # We simply perform depth-first traversal, sinse it's too much
587 # hassle to deal with all sizer/window combinations
588 w = tree.FindNodeObject(item)
589 if w == obj:
590 return item
591 if tree.ItemHasChildren(item):
592 child = tree.GetFirstChild(item)[0]
593 while child:
594 found = self.FindObject(child, obj)
595 if found: return found
596 child = tree.GetNextSibling(child)
597 return None
598
599 def OnTestWinLeftDown(self, evt):
600 pos = evt.GetPosition()
601 self.SetHandler(g.testWin)
602 g.testWin.Disconnect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN)
603 item = self.FindObject(g.testWin.item, evt.GetEventObject())
604 if item:
605 tree.SelectItem(item)
606
607 def SetHandler(self, w, h=None):
608 if h:
609 w.SetEventHandler(h)
610 w.SetCursor(wxCROSS_CURSOR)
611 else:
612 w.SetEventHandler(w)
613 w.SetCursor(wxNullCursor)
614 for ch in w.GetChildren():
615 self.SetHandler(ch, h)
616
617 def OnLocate(self, evt):
618 if g.testWin:
619 self.SetHandler(g.testWin, g.testWin)
620 g.testWin.Connect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN, self.OnTestWinLeftDown)
621
622 def OnRefresh(self, evt):
623 # If modified, apply first
624 selection = tree.selection
625 if selection:
626 xxx = tree.GetPyData(selection)
627 if xxx and panel.IsModified():
628 tree.Apply(xxx, selection)
629 if g.testWin:
630 # (re)create
631 tree.CreateTestWin(g.testWin.item)
632 panel.modified = False
633 tree.needUpdate = False
634
635 def OnAutoRefresh(self, evt):
636 conf.autoRefresh = evt.IsChecked()
637 self.menuBar.Check(self.ID_AUTO_REFRESH, conf.autoRefresh)
638 self.tb.ToggleTool(self.ID_AUTO_REFRESH, conf.autoRefresh)
639
640 def OnAbout(self, evt):
641 str = '''\
642 XRCed version %s
643
644 (c) Roman Rolinsky <rollrom@users.sourceforge.net>
645 Homepage: http://xrced.sourceforge.net\
646 ''' % version
647 dlg = wxMessageDialog(self, str, 'About XRCed', wxOK | wxCENTRE)
648 dlg.ShowModal()
649 dlg.Destroy()
650
651 def OnReadme(self, evt):
652 text = open(os.path.join(basePath, 'README.txt'), 'r').read()
653 dlg = ScrolledMessageDialog(self, text, "XRCed README")
654 dlg.ShowModal()
655 dlg.Destroy()
656
657 # Simple emulation of python command line
658 def OnDebugCMD(self, evt):
659 import traceback
660 while 1:
661 try:
662 exec raw_input('C:\> ')
663 except EOFError:
664 print '^D'
665 break
666 except:
667 (etype, value, tb) =sys.exc_info()
668 tblist =traceback.extract_tb(tb)[1:]
669 msg =' '.join(traceback.format_exception_only(etype, value)
670 +traceback.format_list(tblist))
671 print msg
672
673 def OnCreate(self, evt):
674 selected = tree.selection
675 if tree.ctrl: appendChild = False
676 else: appendChild = not tree.NeedInsert(selected)
677 xxx = tree.GetPyData(selected)
678 if not appendChild:
679 # If insert before
680 if tree.shift:
681 # If has previous item, insert after it, else append to parent
682 nextItem = selected
683 parentLeaf = tree.GetItemParent(selected)
684 else:
685 # If has next item, insert, else append to parent
686 nextItem = tree.GetNextSibling(selected)
687 parentLeaf = tree.GetItemParent(selected)
688 # Expanded container (must have children)
689 elif tree.shift and tree.IsExpanded(selected) \
690 and tree.GetChildrenCount(selected, False):
691 nextItem = tree.GetFirstChild(selected)[0]
692 parentLeaf = selected
693 else:
694 nextItem = wxTreeItemId()
695 parentLeaf = selected
696 parent = tree.GetPyData(parentLeaf)
697 if parent.hasChild: parent = parent.child
698
699 # Create element
700 className = pullDownMenu.createMap[evt.GetId()]
701 xxx = MakeEmptyXXX(parent, className)
702
703 # Set default name for top-level windows
704 if parent.__class__ == xxxMainNode:
705 cl = xxx.treeObject().__class__
706 frame.maxIDs[cl] += 1
707 xxx.treeObject().name = '%s%d' % (defaultIDs[cl], frame.maxIDs[cl])
708 xxx.treeObject().element.setAttribute('name', xxx.treeObject().name)
709
710 # Insert new node, register undo
711 elem = xxx.element
712 newItem = tree.InsertNode(parentLeaf, parent, elem, nextItem)
713 undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected))
714 tree.EnsureVisible(newItem)
715 tree.SelectItem(newItem)
716 if not tree.IsVisible(newItem):
717 tree.ScrollTo(newItem)
718 tree.Refresh()
719 # Update view?
720 if g.testWin and tree.IsHighlatable(newItem):
721 if conf.autoRefresh:
722 tree.needUpdate = True
723 tree.pendingHighLight = newItem
724 else:
725 tree.pendingHighLight = None
726 tree.SetFocus()
727 self.modified = True
728
729 # Replace one object with another
730 def OnReplace(self, evt):
731 selected = tree.selection
732 xxx = tree.GetPyData(selected).treeObject()
733 elem = xxx.element
734 parent = elem.parentNode
735 parentXXX = xxx.parent
736 # New class
737 className = pullDownMenu.createMap[evt.GetId() - 1000]
738 # Create temporary empty node (with default values)
739 dummy = MakeEmptyDOM(className)
740 xxxClass = xxxDict[className]
741 # Remove non-compatible children
742 if tree.ItemHasChildren(selected) and not xxxClass.hasChildren:
743 tree.DeleteChildren(selected)
744 nodes = elem.childNodes[:]
745 tags = []
746 for node in nodes:
747 remove = False
748 tag = node.tagName
749 if tag == 'object':
750 if not xxxClass.hasChildren:
751 remove = True
752 elif tag not in xxxClass.allParams and \
753 (not xxxClass.hasStyle or tag not in xxxClass.styles):
754 remove = True
755 else:
756 tags.append(tag)
757 if remove:
758 elem.removeChild(node)
759 node.unlink()
760
761 # Copy parameters present in dummy but not in elem
762 for node in dummy.childNodes:
763 tag = node.tagName
764 if tag not in tags:
765 elem.appendChild(node.cloneNode(True))
766 dummy.unlink()
767 # Change class name
768 elem.setAttribute('class', className)
769 # Re-create xxx element
770 xxx = MakeXXXFromDOM(parentXXX, elem)
771 # Update parent in child objects
772 if tree.ItemHasChildren(selected):
773 i, cookie = tree.GetFirstChild(selected)
774 while i.IsOk():
775 x = tree.GetPyData(i)
776 x.parent = xxx
777 if x.hasChild: x.child.parent = xxx
778 i, cookie = tree.GetNextChild(selected, cookie)
779
780 # Update tree
781 if tree.GetPyData(selected).hasChild: # child container
782 container = tree.GetPyData(selected)
783 container.child = xxx
784 container.hasChildren = xxx.hasChildren
785 container.isSizer = xxx.isSizer
786 else:
787 tree.SetPyData(selected, xxx)
788 tree.SetItemText(selected, xxx.treeName())
789 tree.SetItemImage(selected, xxx.treeImage())
790
791 # Set default name for top-level windows
792 if parent.__class__ == xxxMainNode:
793 cl = xxx.treeObject().__class__
794 frame.maxIDs[cl] += 1
795 xxx.treeObject().name = '%s%d' % (defaultIDs[cl], frame.maxIDs[cl])
796 xxx.treeObject().element.setAttribute('name', xxx.treeObject().name)
797
798 # Update panel
799 g.panel.SetData(xxx)
800 # Update tools
801 g.tools.UpdateUI()
802
803 #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected))
804 # Update view?
805 if g.testWin and tree.IsHighlatable(selected):
806 if conf.autoRefresh:
807 tree.needUpdate = True
808 tree.pendingHighLight = selected
809 else:
810 tree.pendingHighLight = None
811 tree.SetFocus()
812 self.modified = True
813
814 # Expand/collapse subtree
815 def OnExpand(self, evt):
816 if tree.selection: tree.ExpandAll(tree.selection)
817 else: tree.ExpandAll(tree.root)
818 def OnCollapse(self, evt):
819 if tree.selection: tree.CollapseAll(tree.selection)
820 else: tree.CollapseAll(tree.root)
821
822 def OnPullDownHighlight(self, evt):
823 menuId = evt.GetMenuId()
824 if menuId != -1:
825 menu = evt.GetEventObject()
826 help = menu.GetHelpString(menuId)
827 self.SetStatusText(help)
828 else:
829 self.SetStatusText('')
830
831 def OnUpdateUI(self, evt):
832 if evt.GetId() in [wxID_CUT, wxID_COPY, self.ID_DELETE]:
833 evt.Enable(tree.selection is not None and tree.selection != tree.root)
834 elif evt.GetId() == wxID_PASTE:
835 evt.Enable((self.clipboard and tree.selection) != None)
836 elif evt.GetId() == self.ID_TEST:
837 evt.Enable(tree.selection is not None and tree.selection != tree.root)
838 elif evt.GetId() == wxID_UNDO: evt.Enable(undoMan.CanUndo())
839 elif evt.GetId() == wxID_REDO: evt.Enable(undoMan.CanRedo())
840
841 def OnIdle(self, evt):
842 if self.inIdle: return # Recursive call protection
843 self.inIdle = True
844 if tree.needUpdate:
845 if conf.autoRefresh:
846 if g.testWin:
847 self.SetStatusText('Refreshing test window...')
848 # (re)create
849 tree.CreateTestWin(g.testWin.item)
850 wxYield()
851 self.SetStatusText('')
852 tree.needUpdate = False
853 elif tree.pendingHighLight:
854 tree.HighLight(tree.pendingHighLight)
855 else:
856 evt.Skip()
857 self.inIdle = False
858
859 # We don't let close panel window
860 def OnCloseMiniFrame(self, evt):
861 return
862
863 def OnCloseWindow(self, evt):
864 if not self.AskSave(): return
865 if g.testWin: g.testWin.Destroy()
866 if not panel.GetPageCount() == 2:
867 panel.page2.Destroy()
868 else:
869 # If we don't do this, page does not get destroyed (a bug?)
870 panel.RemovePage(1)
871 if not self.IsIconized():
872 conf.x, conf.y = self.GetPosition()
873 conf.width, conf.height = self.GetSize()
874 if conf.embedPanel:
875 conf.sashPos = self.splitter.GetSashPosition()
876 else:
877 conf.panelX, conf.panelY = self.miniFrame.GetPosition()
878 conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize()
879 evt.Skip()
880
881 def Clear(self):
882 self.dataFile = ''
883 if self.clipboard:
884 self.clipboard.unlink()
885 self.clipboard = None
886 undoMan.Clear()
887 self.modified = False
888 tree.Clear()
889 panel.Clear()
890 if g.testWin:
891 g.testWin.Destroy()
892 g.testWin = None
893 self.SetTitle(progname)
894 # Numbers for new controls
895 self.maxIDs = {}
896 self.maxIDs[xxxPanel] = self.maxIDs[xxxDialog] = self.maxIDs[xxxFrame] = \
897 self.maxIDs[xxxMenuBar] = self.maxIDs[xxxMenu] = self.maxIDs[xxxToolBar] = 0
898
899 def Open(self, path):
900 if not os.path.exists(path):
901 wxLogError('File does not exists: %s' % path)
902 return False
903 # Try to read the file
904 try:
905 f = open(path)
906 self.Clear()
907 dom = minidom.parse(f)
908 f.close()
909 # Set encoding global variable
910 if dom.encoding: g.currentEncoding = dom.encoding
911 # Change dir
912 self.dataFile = path = os.path.abspath(path)
913 dir = os.path.dirname(path)
914 if dir: os.chdir(dir)
915 tree.SetData(dom)
916 self.SetTitle(progname + ': ' + os.path.basename(path))
917 except:
918 # Nice exception printing
919 inf = sys.exc_info()
920 wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1])
921 wxLogError('Error reading file: %s' % path)
922 return False
923 return True
924
925 def Indent(self, node, indent = 0):
926 # Copy child list because it will change soon
927 children = node.childNodes[:]
928 # Main node doesn't need to be indented
929 if indent:
930 text = self.domCopy.createTextNode('\n' + ' ' * indent)
931 node.parentNode.insertBefore(text, node)
932 if children:
933 # Append newline after last child, except for text nodes
934 if children[-1].nodeType == minidom.Node.ELEMENT_NODE:
935 text = self.domCopy.createTextNode('\n' + ' ' * indent)
936 node.appendChild(text)
937 # Indent children which are elements
938 for n in children:
939 if n.nodeType == minidom.Node.ELEMENT_NODE:
940 self.Indent(n, indent + 2)
941
942 def Save(self, path):
943 try:
944 import codecs
945 # Apply changes
946 if tree.selection and panel.IsModified():
947 self.OnRefresh(wxCommandEvent())
948 f = codecs.open(path, 'w', g.currentEncoding)
949 # Make temporary copy for formatting it
950 # !!! We can't clone dom node, it works only once
951 #self.domCopy = tree.dom.cloneNode(True)
952 self.domCopy = MyDocument()
953 mainNode = self.domCopy.appendChild(tree.mainNode.cloneNode(True))
954 self.Indent(mainNode)
955 self.domCopy.writexml(f, encoding = g.currentEncoding)
956 f.close()
957 self.domCopy.unlink()
958 self.domCopy = None
959 self.modified = False
960 panel.SetModified(False)
961 except:
962 wxLogError('Error writing file: %s' % path)
963 raise
964
965 def AskSave(self):
966 if not (self.modified or panel.IsModified()): return True
967 flags = wxICON_EXCLAMATION | wxYES_NO | wxCANCEL | wxCENTRE
968 dlg = wxMessageDialog( self, 'File is modified. Save before exit?',
969 'Save before too late?', flags )
970 say = dlg.ShowModal()
971 dlg.Destroy()
972 if say == wxID_YES:
973 self.OnSaveOrSaveAs(wxCommandEvent(wxID_SAVE))
974 # If save was successful, modified flag is unset
975 if not self.modified: return True
976 elif say == wxID_NO:
977 self.modified = False
978 panel.SetModified(False)
979 return True
980 return False
981
982 def SaveUndo(self):
983 pass # !!!
984
985 ################################################################################
986
987 def usage():
988 print >> sys.stderr, 'usage: xrced [-dhiv] [file]'
989
990 class App(wxApp):
991 def OnInit(self):
992 global debug
993 # Process comand-line
994 opts = args = None
995 try:
996 opts, args = getopt.getopt(sys.argv[1:], 'dhiv')
997 for o,a in opts:
998 if o == '-h':
999 usage()
1000 sys.exit(0)
1001 elif o == '-d':
1002 debug = True
1003 elif o == '-v':
1004 print 'XRCed version', version
1005 sys.exit(0)
1006
1007 except getopt.GetoptError:
1008 if wxPlatform != '__WXMAC__': # macs have some extra parameters
1009 print >> sys.stderr, 'Unknown option'
1010 usage()
1011 sys.exit(1)
1012
1013 self.SetAppName('xrced')
1014 # Settings
1015 global conf
1016 conf = g.conf = wxConfig(style = wxCONFIG_USE_LOCAL_FILE)
1017 conf.autoRefresh = conf.ReadInt('autorefresh', True)
1018 pos = conf.ReadInt('x', -1), conf.ReadInt('y', -1)
1019 size = conf.ReadInt('width', 800), conf.ReadInt('height', 600)
1020 conf.embedPanel = conf.ReadInt('embedPanel', True)
1021 conf.showTools = conf.ReadInt('showTools', True)
1022 conf.sashPos = conf.ReadInt('sashPos', 200)
1023 # read recently used files
1024 recentfiles=conf.Read('recentFiles','')
1025 conf.recentfiles={}
1026 if recentfiles:
1027 for fil in recentfiles.split('|'):
1028 conf.recentfiles[wxNewId()]=fil
1029 if not conf.embedPanel:
1030 conf.panelX = conf.ReadInt('panelX', -1)
1031 conf.panelY = conf.ReadInt('panelY', -1)
1032 else:
1033 conf.panelX = conf.panelY = -1
1034 conf.panelWidth = conf.ReadInt('panelWidth', 200)
1035 conf.panelHeight = conf.ReadInt('panelHeight', 200)
1036 conf.panic = not conf.HasEntry('nopanic')
1037 # Add handlers
1038 wxFileSystem_AddHandler(wxMemoryFSHandler())
1039 wxInitAllImageHandlers()
1040 # Create main frame
1041 frame = Frame(pos, size)
1042 frame.Show(True)
1043 # Load resources from XRC file (!!! should be transformed to .py later?)
1044 frame.res = wxXmlResource('')
1045 # !!! Temporary blocking of assert failure occuring in unicode build
1046 try:
1047 frame.res.Load(os.path.join(basePath, 'xrced.xrc'))
1048 except wx._core.PyAssertionError:
1049 pass
1050
1051 # Load file after showing
1052 if args:
1053 conf.panic = False
1054 frame.open = frame.Open(args[0])
1055
1056 return True
1057
1058 def OnExit(self):
1059 # Write config
1060 global conf
1061 wc = wxConfigBase_Get()
1062 wc.WriteInt('autorefresh', conf.autoRefresh)
1063 wc.WriteInt('x', conf.x)
1064 wc.WriteInt('y', conf.y)
1065 wc.WriteInt('width', conf.width)
1066 wc.WriteInt('height', conf.height)
1067 wc.WriteInt('embedPanel', conf.embedPanel)
1068 wc.WriteInt('showTools', conf.showTools)
1069 if not conf.embedPanel:
1070 wc.WriteInt('panelX', conf.panelX)
1071 wc.WriteInt('panelY', conf.panelY)
1072 wc.WriteInt('sashPos', conf.sashPos)
1073 wc.WriteInt('panelWidth', conf.panelWidth)
1074 wc.WriteInt('panelHeight', conf.panelHeight)
1075 wc.WriteInt('nopanic', True)
1076 wc.Write('recentFiles', '|'.join(conf.recentfiles.values()[-5:]))
1077 wc.Flush()
1078
1079 def main():
1080 app = App(0, useBestVisual=False)
1081 #app.SetAssertMode(wxPYAPP_ASSERT_LOG)
1082 app.MainLoop()
1083 app.OnExit()
1084 global conf
1085 del conf
1086
1087 if __name__ == '__main__':
1088 main()