2 # Purpose: XRC editor, main module
3 # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be>
9 xrced -- Simple resource editor for XRC format used by wxWindows/wxPython
14 xrced [ -h ] [ -v ] [ XRC-file ]
18 -h output short usage info and exit
20 -v output version info and exit
25 import os
, sys
, getopt
, re
, traceback
, tempfile
, shutil
28 from tree
import * # imports xxx which imports params
31 # Cleanup recursive import sideeffects, otherwise we can't create undoMan
33 undo
.ParamPage
= ParamPage
34 undoMan
= g
.undoMan
= UndoManager()
36 # Set application path for loading resources
37 if __name__
== '__main__':
38 basePath
= os
.path
.dirname(sys
.argv
[0])
40 basePath
= os
.path
.dirname(__file__
)
42 # 1 adds CMD command to Help menu
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>
56 defaultIDs
= {xxxPanel
:'PANEL', xxxDialog
:'DIALOG', xxxFrame
:'FRAME',
57 xxxMenuBar
:'MENUBAR', xxxMenu
:'MENU', xxxToolBar
:'TOOLBAR',
60 ################################################################################
62 # ScrolledMessageDialog - modified from wxPython lib to set fixed-width font
63 class ScrolledMessageDialog(wxDialog
):
64 def __init__(self
, parent
, msg
, caption
, pos
= wxDefaultPosition
, size
= (500,300)):
65 from wxPython
.lib
.layoutf
import Layoutf
66 wxDialog
.__init
__(self
, parent
, -1, caption
, pos
, size
)
67 text
= wxTextCtrl(self
, -1, msg
, wxDefaultPosition
,
68 wxDefaultSize
, wxTE_MULTILINE | wxTE_READONLY
)
69 text
.SetFont(g
.modernFont())
71 # !!! possible bug - GetTextExtent without font returns sysfont dims
72 w
, h
= dc
.GetFullTextExtent(' ', g
.modernFont())[:2]
73 ok
= wxButton(self
, wxID_OK
, "OK")
74 text
.SetConstraints(Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self
,ok
)))
75 text
.SetSize((w
* 80 + 30, h
* 40))
77 ok
.SetConstraints(Layoutf('b=b5#1;x%w50#1;w!80;h!25', (self
,)))
78 self
.SetAutoLayout(True)
80 self
.CenterOnScreen(wxBOTH
)
82 ################################################################################
84 # Event handler for using during location
85 class Locator(wxEvtHandler
):
86 def ProcessEvent(self
, evt
):
90 def __init__(self
, pos
, size
):
91 wxFrame
.__init
__(self
, None, -1, '', pos
, size
)
93 frame
= g
.frame
= self
94 bar
= self
.CreateStatusBar(2)
95 bar
.SetStatusWidths([-1, 40])
96 self
.SetIcon(images
.getIconIcon())
101 # Load our own resources
102 self
.res
= wxXmlResource('')
103 # !!! Blocking of assert failure occuring in older unicode builds
105 self
.res
.Load(os
.path
.join(basePath
, 'xrced.xrc'))
106 except wx
._core
.PyAssertionError
:
107 print 'PyAssertionError was ignored'
110 menuBar
= wxMenuBar()
113 menu
.Append(wxID_NEW
, '&New\tCtrl-N', 'New file')
114 menu
.AppendSeparator()
115 menu
.Append(wxID_OPEN
, '&Open...\tCtrl-O', 'Open XRC file')
116 self
.recentMenu
= wxMenu()
117 self
.AppendRecent(self
.recentMenu
)
118 menu
.AppendMenu(-1, 'Open Recent', self
.recentMenu
, 'Open a recent file')
119 menu
.AppendSeparator()
120 menu
.Append(wxID_SAVE
, '&Save\tCtrl-S', 'Save XRC file')
121 menu
.Append(wxID_SAVEAS
, 'Save &As...', 'Save XRC file under different name')
122 menu
.AppendSeparator()
123 menu
.Append(wxID_EXIT
, '&Quit\tCtrl-Q', 'Exit application')
125 menuBar
.Append(menu
, '&File')
128 menu
.Append(wxID_UNDO
, '&Undo\tCtrl-Z', 'Undo')
129 menu
.Append(wxID_REDO
, '&Redo\tCtrl-Y', 'Redo')
130 menu
.AppendSeparator()
131 menu
.Append(wxID_CUT
, 'Cut\tCtrl-X', 'Cut to the clipboard')
132 menu
.Append(wxID_COPY
, '&Copy\tCtrl-C', 'Copy to the clipboard')
133 menu
.Append(wxID_PASTE
, '&Paste\tCtrl-V', 'Paste from the clipboard')
134 self
.ID_DELETE
= wxNewId()
135 menu
.Append(self
.ID_DELETE
, '&Delete\tCtrl-D', 'Delete object')
136 menu
.AppendSeparator()
137 self
.ID_LOCATE
= wxNewId()
138 self
.ID_TOOL_LOCATE
= wxNewId()
139 self
.ID_TOOL_PASTE
= wxNewId()
140 menu
.Append(self
.ID_LOCATE
, '&Locate\tCtrl-L', 'Locate control in test window and select it')
141 menuBar
.Append(menu
, '&Edit')
144 self
.ID_EMBED_PANEL
= wxNewId()
145 menu
.Append(self
.ID_EMBED_PANEL
, '&Embed Panel',
146 'Toggle embedding properties panel in the main window', True)
147 menu
.Check(self
.ID_EMBED_PANEL
, conf
.embedPanel
)
148 self
.ID_SHOW_TOOLS
= wxNewId()
149 menu
.Append(self
.ID_SHOW_TOOLS
, 'Show &Tools', 'Toggle tools', True)
150 menu
.Check(self
.ID_SHOW_TOOLS
, conf
.showTools
)
151 menu
.AppendSeparator()
152 self
.ID_TEST
= wxNewId()
153 menu
.Append(self
.ID_TEST
, '&Test\tF5', 'Show test window')
154 self
.ID_REFRESH
= wxNewId()
155 menu
.Append(self
.ID_REFRESH
, '&Refresh\tCtrl-R', 'Refresh test window')
156 self
.ID_AUTO_REFRESH
= wxNewId()
157 menu
.Append(self
.ID_AUTO_REFRESH
, '&Auto-refresh\tCtrl-A',
158 'Toggle auto-refresh mode', True)
159 menu
.Check(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
160 self
.ID_TEST_HIDE
= wxNewId()
161 menu
.Append(self
.ID_TEST_HIDE
, '&Hide\tCtrl-H', 'Close test window')
162 menuBar
.Append(menu
, '&View')
165 menu
.Append(wxID_ABOUT
, '&About...', 'About XCRed')
166 self
.ID_README
= wxNewId()
167 menu
.Append(self
.ID_README
, '&Readme...', 'View the README file')
169 self
.ID_DEBUG_CMD
= wxNewId()
170 menu
.Append(self
.ID_DEBUG_CMD
, 'CMD', 'Python command line')
171 EVT_MENU(self
, self
.ID_DEBUG_CMD
, self
.OnDebugCMD
)
172 menuBar
.Append(menu
, '&Help')
174 self
.menuBar
= menuBar
175 self
.SetMenuBar(menuBar
)
178 tb
= self
.CreateToolBar(wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT
)
179 tb
.SetToolBitmapSize((24, 23))
180 tb
.AddSimpleTool(wxID_NEW
, images
.getNewBitmap(), 'New', 'New file')
181 tb
.AddSimpleTool(wxID_OPEN
, images
.getOpenBitmap(), 'Open', 'Open file')
182 tb
.AddSimpleTool(wxID_SAVE
, images
.getSaveBitmap(), 'Save', 'Save file')
183 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
184 tb
.AddSimpleTool(wxID_UNDO
, images
.getUndoBitmap(), 'Undo', 'Undo')
185 tb
.AddSimpleTool(wxID_REDO
, images
.getRedoBitmap(), 'Redo', 'Redo')
186 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
187 tb
.AddSimpleTool(wxID_CUT
, images
.getCutBitmap(), 'Cut', 'Cut')
188 tb
.AddSimpleTool(wxID_COPY
, images
.getCopyBitmap(), 'Copy', 'Copy')
189 tb
.AddSimpleTool(self
.ID_TOOL_PASTE
, images
.getPasteBitmap(), 'Paste', 'Paste')
190 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
191 tb
.AddCheckTool(self
.ID_TOOL_LOCATE
,
192 images
.getLocateBitmap(), images
.getLocateArmedBitmap(),
193 'Locate', 'Locate control in test window and select it')
194 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
195 tb
.AddSimpleTool(self
.ID_TEST
, images
.getTestBitmap(), 'Test', 'Test window')
196 tb
.AddSimpleTool(self
.ID_REFRESH
, images
.getRefreshBitmap(),
197 'Refresh', 'Refresh view')
198 tb
.AddSimpleTool(self
.ID_AUTO_REFRESH
, images
.getAutoRefreshBitmap(),
199 'Auto-refresh', 'Toggle auto-refresh mode', True)
200 if wxPlatform
== '__WXGTK__':
201 tb
.AddSeparator() # otherwise auto-refresh sticks in status line
202 tb
.ToggleTool(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
206 self
.minWidth
= tb
.GetSize()[0] # minimal width is the size of toolbar
209 EVT_MENU(self
, wxID_NEW
, self
.OnNew
)
210 EVT_MENU(self
, wxID_OPEN
, self
.OnOpen
)
211 EVT_MENU(self
, wxID_SAVE
, self
.OnSaveOrSaveAs
)
212 EVT_MENU(self
, wxID_SAVEAS
, self
.OnSaveOrSaveAs
)
213 EVT_MENU(self
, wxID_EXIT
, self
.OnExit
)
215 EVT_MENU(self
, wxID_UNDO
, self
.OnUndo
)
216 EVT_MENU(self
, wxID_REDO
, self
.OnRedo
)
217 EVT_MENU(self
, wxID_CUT
, self
.OnCutDelete
)
218 EVT_MENU(self
, wxID_COPY
, self
.OnCopy
)
219 EVT_MENU(self
, wxID_PASTE
, self
.OnPaste
)
220 EVT_MENU(self
, self
.ID_TOOL_PASTE
, self
.OnPaste
)
221 EVT_MENU(self
, self
.ID_DELETE
, self
.OnCutDelete
)
222 EVT_MENU(self
, self
.ID_LOCATE
, self
.OnLocate
)
223 EVT_MENU(self
, self
.ID_TOOL_LOCATE
, self
.OnLocate
)
225 EVT_MENU(self
, self
.ID_EMBED_PANEL
, self
.OnEmbedPanel
)
226 EVT_MENU(self
, self
.ID_SHOW_TOOLS
, self
.OnShowTools
)
227 EVT_MENU(self
, self
.ID_TEST
, self
.OnTest
)
228 EVT_MENU(self
, self
.ID_REFRESH
, self
.OnRefresh
)
229 EVT_MENU(self
, self
.ID_AUTO_REFRESH
, self
.OnAutoRefresh
)
230 EVT_MENU(self
, self
.ID_TEST_HIDE
, self
.OnTestHide
)
232 EVT_MENU(self
, wxID_ABOUT
, self
.OnAbout
)
233 EVT_MENU(self
, self
.ID_README
, self
.OnReadme
)
236 EVT_UPDATE_UI(self
, wxID_CUT
, self
.OnUpdateUI
)
237 EVT_UPDATE_UI(self
, wxID_COPY
, self
.OnUpdateUI
)
238 EVT_UPDATE_UI(self
, wxID_PASTE
, self
.OnUpdateUI
)
239 EVT_UPDATE_UI(self
, self
.ID_LOCATE
, self
.OnUpdateUI
)
240 EVT_UPDATE_UI(self
, self
.ID_TOOL_LOCATE
, self
.OnUpdateUI
)
241 EVT_UPDATE_UI(self
, self
.ID_TOOL_PASTE
, self
.OnUpdateUI
)
242 EVT_UPDATE_UI(self
, wxID_UNDO
, self
.OnUpdateUI
)
243 EVT_UPDATE_UI(self
, wxID_REDO
, self
.OnUpdateUI
)
244 EVT_UPDATE_UI(self
, self
.ID_DELETE
, self
.OnUpdateUI
)
245 EVT_UPDATE_UI(self
, self
.ID_TEST
, self
.OnUpdateUI
)
246 EVT_UPDATE_UI(self
, self
.ID_REFRESH
, self
.OnUpdateUI
)
249 sizer
= wxBoxSizer(wxVERTICAL
)
250 sizer
.Add(wxStaticLine(self
, -1), 0, wxEXPAND
)
251 # Horizontal sizer for toolbar and splitter
252 self
.toolsSizer
= sizer1
= wxBoxSizer()
253 splitter
= wxSplitterWindow(self
, -1, style
=wxSP_3DSASH
)
254 self
.splitter
= splitter
255 splitter
.SetMinimumPaneSize(100)
258 g
.tree
= tree
= XML_Tree(splitter
, -1)
260 # Init pull-down menu data
262 g
.pullDownMenu
= pullDownMenu
= PullDownMenu(self
)
264 # Vertical toolbar for GUI buttons
265 g
.tools
= tools
= Tools(self
)
266 tools
.Show(conf
.showTools
)
267 if conf
.showTools
: sizer1
.Add(tools
, 0, wxEXPAND
)
269 tree
.RegisterKeyEvents()
271 # !!! frame styles are broken
272 # Miniframe for not embedded mode
273 miniFrame
= wxFrame(self
, -1, 'Properties Panel',
274 (conf
.panelX
, conf
.panelY
),
275 (conf
.panelWidth
, conf
.panelHeight
))
276 self
.miniFrame
= miniFrame
277 sizer2
= wxBoxSizer()
278 miniFrame
.SetAutoLayout(True)
279 miniFrame
.SetSizer(sizer2
)
280 EVT_CLOSE(self
.miniFrame
, self
.OnCloseMiniFrame
)
281 # Create panel for parameters
284 panel
= Panel(splitter
)
285 # Set plitter windows
286 splitter
.SplitVertically(tree
, panel
, conf
.sashPos
)
288 panel
= Panel(miniFrame
)
289 sizer2
.Add(panel
, 1, wxEXPAND
)
291 splitter
.Initialize(tree
)
292 sizer1
.Add(splitter
, 1, wxEXPAND
)
293 sizer
.Add(sizer1
, 1, wxEXPAND
)
294 self
.SetAutoLayout(True)
298 self
.clipboard
= None
302 EVT_IDLE(self
, self
.OnIdle
)
303 EVT_CLOSE(self
, self
.OnCloseWindow
)
304 EVT_KEY_DOWN(self
, tools
.OnKeyDown
)
305 EVT_KEY_UP(self
, tools
.OnKeyUp
)
307 def AppendRecent(self
, menu
):
308 # add recently used files to the menu
309 for id,name
in conf
.recentfiles
.iteritems():
311 EVT_MENU(self
,id,self
.OnRecentFile
)
314 def OnRecentFile(self
,evt
):
315 # open recently used file
316 if not self
.AskSave(): return
319 path
=conf
.recentfiles
[evt
.GetId()]
321 self
.SetStatusText('Data loaded')
323 self
.SetStatusText('Failed')
325 self
.SetStatusText('No such file')
328 def OnNew(self
, evt
):
329 if not self
.AskSave(): return
332 def OnOpen(self
, evt
):
333 if not self
.AskSave(): return
334 dlg
= wxFileDialog(self
, 'Open', os
.path
.dirname(self
.dataFile
),
335 '', '*.xrc', wxOPEN | wxCHANGE_DIR
)
336 if dlg
.ShowModal() == wxID_OK
:
338 self
.SetStatusText('Loading...')
343 self
.SetStatusText('Data loaded')
345 self
.SetStatusText('Failed')
346 self
.SaveRecent(path
)
351 def OnSaveOrSaveAs(self
, evt
):
352 if evt
.GetId() == wxID_SAVEAS
or not self
.dataFile
:
353 if self
.dataFile
: defaultName
= ''
354 else: defaultName
= 'UNTITLED.xrc'
355 dirname
= os
.path
.dirname(self
.dataFile
)
356 dlg
= wxFileDialog(self
, 'Save As', dirname
, defaultName
, '*.xrc',
357 wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR
)
358 if dlg
.ShowModal() == wxID_OK
:
366 self
.SetStatusText('Saving...')
371 tmpFile
,tmpName
= tempfile
.mkstemp(prefix
='xrced-')
373 self
.Save(tmpName
) # save temporary file first
374 shutil
.move(tmpName
, path
)
376 self
.SetStatusText('Data saved')
377 self
.SaveRecent(path
)
379 self
.SetStatusText('Failed')
383 def SaveRecent(self
,path
):
384 # append to recently used files
385 if path
not in conf
.recentfiles
.values():
387 self
.recentMenu
.Append(newid
, path
)
388 EVT_MENU(self
, newid
, self
.OnRecentFile
)
389 conf
.recentfiles
[newid
] = path
391 def OnExit(self
, evt
):
394 def OnUndo(self
, evt
):
395 # Extra check to not mess with idle updating
396 if undoMan
.CanUndo():
399 def OnRedo(self
, evt
):
400 if undoMan
.CanRedo():
403 def OnCopy(self
, evt
):
404 selected
= tree
.selection
405 if not selected
: return # key pressed event
406 xxx
= tree
.GetPyData(selected
)
407 self
.clipboard
= xxx
.element
.cloneNode(True)
408 self
.SetStatusText('Copied')
410 def OnPaste(self
, evt
):
411 selected
= tree
.selection
412 if not selected
: return # key pressed event
413 # For pasting with Ctrl pressed
415 if evt
.GetId() == pullDownMenu
.ID_PASTE_SIBLING
: appendChild
= False
416 elif evt
.GetId() == self
.ID_TOOL_PASTE
:
417 if g
.tree
.ctrl
: appendChild
= False
418 else: appendChild
= not tree
.NeedInsert(selected
)
419 else: appendChild
= not tree
.NeedInsert(selected
)
420 xxx
= tree
.GetPyData(selected
)
422 # If has next item, insert, else append to parent
423 nextItem
= tree
.GetNextSibling(selected
)
424 parentLeaf
= tree
.GetItemParent(selected
)
425 # Expanded container (must have children)
426 elif tree
.IsExpanded(selected
) and tree
.GetChildrenCount(selected
, False):
427 # Insert as first child
428 nextItem
= tree
.GetFirstChild(selected
)[0]
429 parentLeaf
= selected
431 # No children or unexpanded item - appendChild stays True
432 nextItem
= wxTreeItemId() # no next item
433 parentLeaf
= selected
434 parent
= tree
.GetPyData(parentLeaf
).treeObject()
436 # Create a copy of clipboard element
437 elem
= self
.clipboard
.cloneNode(True)
438 # Tempopary xxx object to test things
439 xxx
= MakeXXXFromDOM(parent
, elem
)
441 # Check compatibility
445 if x
.__class
__ in [xxxDialog
, xxxFrame
, xxxMenuBar
, xxxWizard
]:
447 if parent
.__class
__ != xxxMainNode
: error
= True
448 elif x
.__class
__ == xxxToolBar
:
449 # Toolbar can be top-level of child of panel or frame
450 if parent
.__class
__ not in [xxxMainNode
, xxxPanel
, xxxFrame
]: error
= True
451 elif x
.__class
__ == xxxPanel
and parent
.__class
__ == xxxMainNode
:
453 elif x
.__class
__ == xxxSpacer
:
454 if not parent
.isSizer
: error
= True
455 elif x
.__class
__ == xxxSeparator
:
456 if not parent
.__class
__ in [xxxMenu
, xxxToolBar
]: error
= True
457 elif x
.__class
__ == xxxTool
:
458 if parent
.__class
__ != xxxToolBar
: error
= True
459 elif x
.__class
__ == xxxMenu
:
460 if not parent
.__class
__ in [xxxMainNode
, xxxMenuBar
, xxxMenu
]: error
= True
461 elif x
.__class
__ == xxxMenuItem
:
462 if not parent
.__class
__ in [xxxMenuBar
, xxxMenu
]: error
= True
463 elif x
.isSizer
and parent
.__class
__ == xxxNotebook
: error
= True
464 else: # normal controls can be almost anywhere
465 if parent
.__class
__ == xxxMainNode
or \
466 parent
.__class
__ in [xxxMenuBar
, xxxMenu
]: error
= True
468 if parent
.__class
__ == xxxMainNode
: parentClass
= 'root'
469 else: parentClass
= parent
.className
470 wxLogError('Incompatible parent/child: parent is %s, child is %s!' %
471 (parentClass
, x
.className
))
474 # Check parent and child relationships.
475 # If parent is sizer or notebook, child is of wrong class or
476 # parent is normal window, child is child container then detach child.
477 isChildContainer
= isinstance(xxx
, xxxChildContainer
)
478 if isChildContainer
and \
479 ((parent
.isSizer
and not isinstance(xxx
, xxxSizerItem
)) or \
480 (isinstance(parent
, xxxNotebook
) and not isinstance(xxx
, xxxNotebookPage
)) or \
481 not (parent
.isSizer
or isinstance(parent
, xxxNotebook
))):
482 elem
.removeChild(xxx
.child
.element
) # detach child
483 elem
.unlink() # delete child container
484 elem
= xxx
.child
.element
# replace
485 # This may help garbage collection
486 xxx
.child
.parent
= None
487 isChildContainer
= False
488 # Parent is sizer or notebook, child is not child container
489 if parent
.isSizer
and not isChildContainer
and not isinstance(xxx
, xxxSpacer
):
490 # Create sizer item element
491 sizerItemElem
= MakeEmptyDOM('sizeritem')
492 sizerItemElem
.appendChild(elem
)
494 elif isinstance(parent
, xxxNotebook
) and not isChildContainer
:
495 pageElem
= MakeEmptyDOM('notebookpage')
496 pageElem
.appendChild(elem
)
498 # Insert new node, register undo
499 newItem
= tree
.InsertNode(parentLeaf
, parent
, elem
, nextItem
)
500 undoMan
.RegisterUndo(UndoPasteCreate(parentLeaf
, parent
, newItem
, selected
))
501 # Scroll to show new item (!!! redundant?)
502 tree
.EnsureVisible(newItem
)
503 tree
.SelectItem(newItem
)
504 if not tree
.IsVisible(newItem
):
505 tree
.ScrollTo(newItem
)
508 if g
.testWin
and tree
.IsHighlatable(newItem
):
510 tree
.needUpdate
= True
511 tree
.pendingHighLight
= newItem
513 tree
.pendingHighLight
= None
515 self
.SetStatusText('Pasted')
517 def OnCutDelete(self
, evt
):
518 selected
= tree
.selection
519 if not selected
: return # key pressed event
521 if evt
.GetId() == wxID_CUT
:
523 status
= 'Removed to clipboard'
525 self
.lastOp
= 'DELETE'
529 # If deleting top-level item, delete testWin
530 if selected
== g
.testWin
.item
:
534 # Remove highlight, update testWin
535 if g
.testWin
.highLight
:
536 g
.testWin
.highLight
.Remove()
537 tree
.needUpdate
= True
540 index
= tree
.ItemFullIndex(selected
)
541 parent
= tree
.GetPyData(tree
.GetItemParent(selected
)).treeObject()
542 elem
= tree
.RemoveLeaf(selected
)
543 undoMan
.RegisterUndo(UndoCutDelete(index
, parent
, elem
))
544 if evt
.GetId() == wxID_CUT
:
545 if self
.clipboard
: self
.clipboard
.unlink()
546 self
.clipboard
= elem
.cloneNode(True)
547 tree
.pendingHighLight
= None
551 self
.SetStatusText(status
)
553 def OnSubclass(self
, evt
):
554 selected
= tree
.selection
555 xxx
= tree
.GetPyData(selected
).treeObject()
557 subclass
= xxx
.subclass
558 dlg
= wxTextEntryDialog(self
, 'Subclass:', defaultValue
=subclass
)
559 if dlg
.ShowModal() == wxID_OK
:
560 subclass
= dlg
.GetValue()
562 elem
.setAttribute('subclass', subclass
)
564 elif elem
.hasAttribute('subclass'):
565 elem
.removeAttribute('subclass')
567 xxx
.subclass
= elem
.getAttribute('subclass')
568 tree
.SetItemText(selected
, xxx
.treeName())
569 panel
.pages
[0].box
.SetLabel(xxx
.panelName())
572 def OnEmbedPanel(self
, evt
):
573 conf
.embedPanel
= evt
.IsChecked()
575 # Remember last dimentions
576 conf
.panelX
, conf
.panelY
= self
.miniFrame
.GetPosition()
577 conf
.panelWidth
, conf
.panelHeight
= self
.miniFrame
.GetSize()
578 size
= self
.GetSize()
579 pos
= self
.GetPosition()
580 sizePanel
= panel
.GetSize()
581 panel
.Reparent(self
.splitter
)
582 self
.miniFrame
.GetSizer().Remove(panel
)
585 self
.SetDimensions(pos
.x
, pos
.y
, size
.width
+ sizePanel
.width
, size
.height
)
586 self
.splitter
.SplitVertically(tree
, panel
, conf
.sashPos
)
587 self
.miniFrame
.Show(False)
589 conf
.sashPos
= self
.splitter
.GetSashPosition()
590 pos
= self
.GetPosition()
591 size
= self
.GetSize()
592 sizePanel
= panel
.GetSize()
593 self
.splitter
.Unsplit(panel
)
594 sizer
= self
.miniFrame
.GetSizer()
595 panel
.Reparent(self
.miniFrame
)
597 sizer
.Add(panel
, 1, wxEXPAND
)
598 self
.miniFrame
.Show(True)
599 self
.miniFrame
.SetDimensions(conf
.panelX
, conf
.panelY
,
600 conf
.panelWidth
, conf
.panelHeight
)
603 self
.SetDimensions(pos
.x
, pos
.y
,
604 max(size
.width
- sizePanel
.width
, self
.minWidth
), size
.height
)
606 def OnShowTools(self
, evt
):
607 conf
.showTools
= evt
.IsChecked()
608 g
.tools
.Show(conf
.showTools
)
610 self
.toolsSizer
.Prepend(g
.tools
, 0, wxEXPAND
)
612 self
.toolsSizer
.Remove(g
.tools
)
613 self
.toolsSizer
.Layout()
615 def OnTest(self
, evt
):
616 if not tree
.selection
: return # key pressed event
617 tree
.ShowTestWindow(tree
.selection
)
619 def OnTestHide(self
, evt
):
620 tree
.CloseTestWindow()
622 # Find object by relative position
623 def FindObject(self
, item
, obj
):
624 # We simply perform depth-first traversal, sinse it's too much
625 # hassle to deal with all sizer/window combinations
626 w
= tree
.FindNodeObject(item
)
629 if tree
.ItemHasChildren(item
):
630 child
= tree
.GetFirstChild(item
)[0]
632 found
= self
.FindObject(child
, obj
)
633 if found
: return found
634 child
= tree
.GetNextSibling(child
)
637 def OnTestWinLeftDown(self
, evt
):
638 pos
= evt
.GetPosition()
639 self
.SetHandler(g
.testWin
)
640 g
.testWin
.Disconnect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
)
641 item
= self
.FindObject(g
.testWin
.item
, evt
.GetEventObject())
643 tree
.SelectItem(item
)
644 self
.tb
.ToggleTool(self
.ID_TOOL_LOCATE
, False)
646 self
.SetStatusText('Selected %s' % tree
.GetItemText(item
))
648 self
.SetStatusText('Locate failed!')
650 def SetHandler(self
, w
, h
=None):
653 w
.SetCursor(wxCROSS_CURSOR
)
656 w
.SetCursor(wxNullCursor
)
657 for ch
in w
.GetChildren():
658 self
.SetHandler(ch
, h
)
660 def OnLocate(self
, evt
):
662 if evt
.GetId() == self
.ID_LOCATE
or \
663 evt
.GetId() == self
.ID_TOOL_LOCATE
and evt
.IsChecked():
664 self
.SetHandler(g
.testWin
, g
.testWin
)
665 g
.testWin
.Connect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
, self
.OnTestWinLeftDown
)
666 if evt
.GetId() == self
.ID_LOCATE
:
667 self
.tb
.ToggleTool(self
.ID_TOOL_LOCATE
, True)
668 elif evt
.GetId() == self
.ID_TOOL_LOCATE
and not evt
.IsChecked():
669 self
.SetHandler(g
.testWin
, None)
670 g
.testWin
.Disconnect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
)
671 self
.SetStatusText('Click somewhere in your test window now')
673 def OnRefresh(self
, evt
):
674 # If modified, apply first
675 selection
= tree
.selection
677 xxx
= tree
.GetPyData(selection
)
678 if xxx
and panel
.IsModified():
679 tree
.Apply(xxx
, selection
)
682 tree
.CreateTestWin(g
.testWin
.item
)
683 panel
.modified
= False
684 tree
.needUpdate
= False
686 def OnAutoRefresh(self
, evt
):
687 conf
.autoRefresh
= evt
.IsChecked()
688 self
.menuBar
.Check(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
689 self
.tb
.ToggleTool(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
691 def OnAbout(self
, evt
):
695 (c) Roman Rolinsky <rollrom@users.sourceforge.net>
696 Homepage: http://xrced.sourceforge.net\
698 dlg
= wxMessageDialog(self
, str, 'About XRCed', wxOK | wxCENTRE
)
702 def OnReadme(self
, evt
):
703 text
= open(os
.path
.join(basePath
, 'README.txt'), 'r').read()
704 dlg
= ScrolledMessageDialog(self
, text
, "XRCed README")
708 # Simple emulation of python command line
709 def OnDebugCMD(self
, evt
):
713 exec raw_input('C:\> ')
718 (etype
, value
, tb
) =sys
.exc_info()
719 tblist
=traceback
.extract_tb(tb
)[1:]
720 msg
=' '.join(traceback
.format_exception_only(etype
, value
)
721 +traceback
.format_list(tblist
))
724 def OnCreate(self
, evt
):
725 selected
= tree
.selection
726 if tree
.ctrl
: appendChild
= False
727 else: appendChild
= not tree
.NeedInsert(selected
)
728 xxx
= tree
.GetPyData(selected
)
732 # If has previous item, insert after it, else append to parent
734 parentLeaf
= tree
.GetItemParent(selected
)
736 # If has next item, insert, else append to parent
737 nextItem
= tree
.GetNextSibling(selected
)
738 parentLeaf
= tree
.GetItemParent(selected
)
739 # Expanded container (must have children)
740 elif tree
.shift
and tree
.IsExpanded(selected
) \
741 and tree
.GetChildrenCount(selected
, False):
742 nextItem
= tree
.GetFirstChild(selected
)[0]
743 parentLeaf
= selected
745 nextItem
= wxTreeItemId()
746 parentLeaf
= selected
747 parent
= tree
.GetPyData(parentLeaf
)
748 if parent
.hasChild
: parent
= parent
.child
751 className
= pullDownMenu
.createMap
[evt
.GetId()]
752 xxx
= MakeEmptyXXX(parent
, className
)
754 # Set default name for top-level windows
755 if parent
.__class
__ == xxxMainNode
:
756 cl
= xxx
.treeObject().__class
__
757 frame
.maxIDs
[cl
] += 1
758 xxx
.treeObject().name
= '%s%d' % (defaultIDs
[cl
], frame
.maxIDs
[cl
])
759 xxx
.treeObject().element
.setAttribute('name', xxx
.treeObject().name
)
761 # Insert new node, register undo
763 newItem
= tree
.InsertNode(parentLeaf
, parent
, elem
, nextItem
)
764 undoMan
.RegisterUndo(UndoPasteCreate(parentLeaf
, parent
, newItem
, selected
))
765 tree
.EnsureVisible(newItem
)
766 tree
.SelectItem(newItem
)
767 if not tree
.IsVisible(newItem
):
768 tree
.ScrollTo(newItem
)
771 if g
.testWin
and tree
.IsHighlatable(newItem
):
773 tree
.needUpdate
= True
774 tree
.pendingHighLight
= newItem
776 tree
.pendingHighLight
= None
780 # Replace one object with another
781 def OnReplace(self
, evt
):
782 selected
= tree
.selection
783 xxx
= tree
.GetPyData(selected
).treeObject()
785 parent
= elem
.parentNode
786 parentXXX
= xxx
.parent
788 className
= pullDownMenu
.createMap
[evt
.GetId() - 1000]
789 # Create temporary empty node (with default values)
790 dummy
= MakeEmptyDOM(className
)
791 xxxClass
= xxxDict
[className
]
792 # Remove non-compatible children
793 if tree
.ItemHasChildren(selected
) and not xxxClass
.hasChildren
:
794 tree
.DeleteChildren(selected
)
795 nodes
= elem
.childNodes
[:]
798 if node
.nodeType
!= minidom
.Node
.ELEMENT_NODE
: continue
802 if not xxxClass
.hasChildren
:
804 elif tag
not in xxxClass
.allParams
and \
805 (not xxxClass
.hasStyle
or tag
not in xxxClass
.styles
):
810 elem
.removeChild(node
)
813 # Copy parameters present in dummy but not in elem
814 for node
in dummy
.childNodes
:
817 elem
.appendChild(node
.cloneNode(True))
820 elem
.setAttribute('class', className
)
821 if elem
.hasAttribute('subclass'):
822 elem
.removeAttribute('subclass') # clear subclassing
823 # Re-create xxx element
824 xxx
= MakeXXXFromDOM(parentXXX
, elem
)
825 # Update parent in child objects
826 if tree
.ItemHasChildren(selected
):
827 i
, cookie
= tree
.GetFirstChild(selected
)
829 x
= tree
.GetPyData(i
)
831 if x
.hasChild
: x
.child
.parent
= xxx
832 i
, cookie
= tree
.GetNextChild(selected
, cookie
)
835 if tree
.GetPyData(selected
).hasChild
: # child container
836 container
= tree
.GetPyData(selected
)
837 container
.child
= xxx
838 container
.hasChildren
= xxx
.hasChildren
839 container
.isSizer
= xxx
.isSizer
841 tree
.SetPyData(selected
, xxx
)
842 tree
.SetItemText(selected
, xxx
.treeName())
843 tree
.SetItemImage(selected
, xxx
.treeImage())
845 # Set default name for top-level windows
846 if parent
.__class
__ == xxxMainNode
:
847 cl
= xxx
.treeObject().__class
__
848 frame
.maxIDs
[cl
] += 1
849 xxx
.treeObject().name
= '%s%d' % (defaultIDs
[cl
], frame
.maxIDs
[cl
])
850 xxx
.treeObject().element
.setAttribute('name', xxx
.treeObject().name
)
857 #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected))
859 if g
.testWin
and tree
.IsHighlatable(selected
):
861 tree
.needUpdate
= True
862 tree
.pendingHighLight
= selected
864 tree
.pendingHighLight
= None
868 # Expand/collapse subtree
869 def OnExpand(self
, evt
):
870 if tree
.selection
: tree
.ExpandAll(tree
.selection
)
871 else: tree
.ExpandAll(tree
.root
)
872 def OnCollapse(self
, evt
):
873 if tree
.selection
: tree
.CollapseAll(tree
.selection
)
874 else: tree
.CollapseAll(tree
.root
)
876 def OnPullDownHighlight(self
, evt
):
877 menuId
= evt
.GetMenuId()
879 menu
= evt
.GetEventObject()
880 help = menu
.GetHelpString(menuId
)
881 self
.SetStatusText(help)
883 self
.SetStatusText('')
885 def OnUpdateUI(self
, evt
):
886 if evt
.GetId() in [wxID_CUT
, wxID_COPY
, self
.ID_DELETE
]:
887 evt
.Enable(tree
.selection
is not None and tree
.selection
!= tree
.root
)
888 elif evt
.GetId() in [wxID_PASTE
, self
.ID_TOOL_PASTE
]:
889 evt
.Enable((self
.clipboard
and tree
.selection
) != None)
890 elif evt
.GetId() == self
.ID_TEST
:
891 evt
.Enable(tree
.selection
is not None and tree
.selection
!= tree
.root
)
892 elif evt
.GetId() in [self
.ID_LOCATE
, self
.ID_TOOL_LOCATE
]:
893 evt
.Enable(g
.testWin
is not None)
894 elif evt
.GetId() == wxID_UNDO
: evt
.Enable(undoMan
.CanUndo())
895 elif evt
.GetId() == wxID_REDO
: evt
.Enable(undoMan
.CanRedo())
897 def OnIdle(self
, evt
):
898 if self
.inIdle
: return # Recursive call protection
903 self
.SetStatusText('Refreshing test window...')
905 tree
.CreateTestWin(g
.testWin
.item
)
907 self
.SetStatusText('')
908 tree
.needUpdate
= False
909 elif tree
.pendingHighLight
:
910 tree
.HighLight(tree
.pendingHighLight
)
915 # We don't let close panel window
916 def OnCloseMiniFrame(self
, evt
):
919 def OnCloseWindow(self
, evt
):
920 if not self
.AskSave(): return
921 if g
.testWin
: g
.testWin
.Destroy()
922 if not panel
.GetPageCount() == 2:
923 panel
.page2
.Destroy()
925 # If we don't do this, page does not get destroyed (a bug?)
927 if not self
.IsIconized():
928 conf
.x
, conf
.y
= self
.GetPosition()
929 conf
.width
, conf
.height
= self
.GetSize()
931 conf
.sashPos
= self
.splitter
.GetSashPosition()
933 conf
.panelX
, conf
.panelY
= self
.miniFrame
.GetPosition()
934 conf
.panelWidth
, conf
.panelHeight
= self
.miniFrame
.GetSize()
940 self
.clipboard
.unlink()
941 self
.clipboard
= None
943 self
.modified
= False
949 self
.SetTitle(progname
)
950 # Numbers for new controls
952 self
.maxIDs
[xxxPanel
] = self
.maxIDs
[xxxDialog
] = self
.maxIDs
[xxxFrame
] = \
953 self
.maxIDs
[xxxMenuBar
] = self
.maxIDs
[xxxMenu
] = self
.maxIDs
[xxxToolBar
] = \
954 self
.maxIDs
[xxxWizard
] = 0
956 def Open(self
, path
):
957 if not os
.path
.exists(path
):
958 wxLogError('File does not exists: %s' % path
)
960 # Try to read the file
964 dom
= minidom
.parse(f
)
966 # Set encoding global variable and default encoding
968 g
.currentEncoding
= dom
.encoding
969 wx
.SetDefaultPyEncoding(g
.currentEncoding
.encode())
971 self
.dataFile
= path
= os
.path
.abspath(path
)
972 dir = os
.path
.dirname(path
)
973 if dir: os
.chdir(dir)
975 self
.SetTitle(progname
+ ': ' + os
.path
.basename(path
))
977 # Nice exception printing
979 wxLogError(traceback
.format_exception(inf
[0], inf
[1], None)[-1])
980 wxLogError('Error reading file: %s' % path
)
985 def Indent(self
, node
, indent
= 0):
986 # Copy child list because it will change soon
987 children
= node
.childNodes
[:]
988 # Main node doesn't need to be indented
990 text
= self
.domCopy
.createTextNode('\n' + ' ' * indent
)
991 node
.parentNode
.insertBefore(text
, node
)
993 # Append newline after last child, except for text nodes
994 if children
[-1].nodeType
== minidom
.Node
.ELEMENT_NODE
:
995 text
= self
.domCopy
.createTextNode('\n' + ' ' * indent
)
996 node
.appendChild(text
)
997 # Indent children which are elements
999 if n
.nodeType
== minidom
.Node
.ELEMENT_NODE
:
1000 self
.Indent(n
, indent
+ 2)
1002 def Save(self
, path
):
1006 if tree
.selection
and panel
.IsModified():
1007 self
.OnRefresh(wxCommandEvent())
1008 if g
.currentEncoding
:
1009 f
= codecs
.open(path
, 'w', g
.currentEncoding
)
1011 f
= codecs
.open(path
, 'w')
1012 # Make temporary copy for formatting it
1013 # !!! We can't clone dom node, it works only once
1014 #self.domCopy = tree.dom.cloneNode(True)
1015 self
.domCopy
= MyDocument()
1016 mainNode
= self
.domCopy
.appendChild(tree
.mainNode
.cloneNode(True))
1017 self
.Indent(mainNode
)
1018 self
.domCopy
.writexml(f
, encoding
= g
.currentEncoding
)
1020 self
.domCopy
.unlink()
1022 self
.modified
= False
1023 panel
.SetModified(False)
1025 wxLogError('Error writing file: %s' % path
)
1029 if not (self
.modified
or panel
.IsModified()): return True
1030 flags
= wxICON_EXCLAMATION | wxYES_NO | wxCANCEL | wxCENTRE
1031 dlg
= wxMessageDialog( self
, 'File is modified. Save before exit?',
1032 'Save before too late?', flags
)
1033 say
= dlg
.ShowModal()
1036 self
.OnSaveOrSaveAs(wxCommandEvent(wxID_SAVE
))
1037 # If save was successful, modified flag is unset
1038 if not self
.modified
: return True
1039 elif say
== wxID_NO
:
1040 self
.modified
= False
1041 panel
.SetModified(False)
1048 ################################################################################
1051 print >> sys
.stderr
, 'usage: xrced [-dhiv] [file]'
1056 # Process comand-line
1059 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'dhiv')
1067 print 'XRCed version', version
1070 except getopt
.GetoptError
:
1071 if wxPlatform
!= '__WXMAC__': # macs have some extra parameters
1072 print >> sys
.stderr
, 'Unknown option'
1076 self
.SetAppName('xrced')
1079 conf
= g
.conf
= wxConfig(style
= wxCONFIG_USE_LOCAL_FILE
)
1080 conf
.autoRefresh
= conf
.ReadInt('autorefresh', True)
1081 pos
= conf
.ReadInt('x', -1), conf
.ReadInt('y', -1)
1082 size
= conf
.ReadInt('width', 800), conf
.ReadInt('height', 600)
1083 conf
.embedPanel
= conf
.ReadInt('embedPanel', True)
1084 conf
.showTools
= conf
.ReadInt('showTools', True)
1085 conf
.sashPos
= conf
.ReadInt('sashPos', 200)
1086 # read recently used files
1087 recentfiles
=conf
.Read('recentFiles','')
1090 for fil
in recentfiles
.split('|'):
1091 conf
.recentfiles
[wxNewId()]=fil
1092 if not conf
.embedPanel
:
1093 conf
.panelX
= conf
.ReadInt('panelX', -1)
1094 conf
.panelY
= conf
.ReadInt('panelY', -1)
1096 conf
.panelX
= conf
.panelY
= -1
1097 conf
.panelWidth
= conf
.ReadInt('panelWidth', 200)
1098 conf
.panelHeight
= conf
.ReadInt('panelHeight', 200)
1099 conf
.panic
= not conf
.HasEntry('nopanic')
1101 wxFileSystem_AddHandler(wxMemoryFSHandler())
1102 wxInitAllImageHandlers()
1104 frame
= Frame(pos
, size
)
1107 # Load file after showing
1110 frame
.open = frame
.Open(args
[0])
1117 wc
= wxConfigBase_Get()
1118 wc
.WriteInt('autorefresh', conf
.autoRefresh
)
1119 wc
.WriteInt('x', conf
.x
)
1120 wc
.WriteInt('y', conf
.y
)
1121 wc
.WriteInt('width', conf
.width
)
1122 wc
.WriteInt('height', conf
.height
)
1123 wc
.WriteInt('embedPanel', conf
.embedPanel
)
1124 wc
.WriteInt('showTools', conf
.showTools
)
1125 if not conf
.embedPanel
:
1126 wc
.WriteInt('panelX', conf
.panelX
)
1127 wc
.WriteInt('panelY', conf
.panelY
)
1128 wc
.WriteInt('sashPos', conf
.sashPos
)
1129 wc
.WriteInt('panelWidth', conf
.panelWidth
)
1130 wc
.WriteInt('panelHeight', conf
.panelHeight
)
1131 wc
.WriteInt('nopanic', True)
1132 wc
.Write('recentFiles', '|'.join(conf
.recentfiles
.values()[-5:]))
1136 app
= App(0, useBestVisual
=False)
1137 #app.SetAssertMode(wxPYAPP_ASSERT_LOG)
1143 if __name__
== '__main__':