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