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
)
180 new_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_NORMAL_FILE
, wx
.ART_TOOLBAR
, tsize
)
181 open_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_FILE_OPEN
, wx
.ART_TOOLBAR
, tsize
)
182 save_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_FILE_SAVE
, wx
.ART_TOOLBAR
, tsize
)
183 undo_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_UNDO
, wx
.ART_TOOLBAR
, tsize
)
184 redo_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_REDO
, wx
.ART_TOOLBAR
, tsize
)
185 cut_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_CUT
, wx
.ART_TOOLBAR
, tsize
)
186 copy_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_COPY
, wx
.ART_TOOLBAR
, tsize
)
187 paste_bmp
= wx
.ArtProvider
.GetBitmap(wx
.ART_PASTE
, wx
.ART_TOOLBAR
, tsize
)
189 tb
.SetToolBitmapSize(tsize
)
190 tb
.AddSimpleTool(wxID_NEW
, new_bmp
, 'New', 'New file')
191 tb
.AddSimpleTool(wxID_OPEN
, open_bmp
, 'Open', 'Open file')
192 tb
.AddSimpleTool(wxID_SAVE
, save_bmp
, 'Save', 'Save file')
193 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
194 tb
.AddSimpleTool(wxID_UNDO
, undo_bmp
, 'Undo', 'Undo')
195 tb
.AddSimpleTool(wxID_REDO
, redo_bmp
, 'Redo', 'Redo')
196 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
197 tb
.AddSimpleTool(wxID_CUT
, cut_bmp
, 'Cut', 'Cut')
198 tb
.AddSimpleTool(wxID_COPY
, copy_bmp
, 'Copy', 'Copy')
199 tb
.AddSimpleTool(self
.ID_TOOL_PASTE
, paste_bmp
, 'Paste', 'Paste')
200 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
201 tb
.AddSimpleTool(self
.ID_TOOL_LOCATE
,
202 images
.getLocateBitmap(), #images.getLocateArmedBitmap(),
203 'Locate', 'Locate control in test window and select it', True)
204 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
205 tb
.AddSimpleTool(self
.ID_TEST
, images
.getTestBitmap(), 'Test', 'Test window')
206 tb
.AddSimpleTool(self
.ID_REFRESH
, images
.getRefreshBitmap(),
207 'Refresh', 'Refresh view')
208 tb
.AddSimpleTool(self
.ID_AUTO_REFRESH
, images
.getAutoRefreshBitmap(),
209 'Auto-refresh', 'Toggle auto-refresh mode', True)
210 if wxPlatform
== '__WXGTK__':
211 tb
.AddSeparator() # otherwise auto-refresh sticks in status line
212 tb
.ToggleTool(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
216 self
.minWidth
= tb
.GetSize()[0] # minimal width is the size of toolbar
219 EVT_MENU(self
, wxID_NEW
, self
.OnNew
)
220 EVT_MENU(self
, wxID_OPEN
, self
.OnOpen
)
221 EVT_MENU(self
, wxID_SAVE
, self
.OnSaveOrSaveAs
)
222 EVT_MENU(self
, wxID_SAVEAS
, self
.OnSaveOrSaveAs
)
223 EVT_MENU(self
, wxID_EXIT
, self
.OnExit
)
225 EVT_MENU(self
, wxID_UNDO
, self
.OnUndo
)
226 EVT_MENU(self
, wxID_REDO
, self
.OnRedo
)
227 EVT_MENU(self
, wxID_CUT
, self
.OnCutDelete
)
228 EVT_MENU(self
, wxID_COPY
, self
.OnCopy
)
229 EVT_MENU(self
, wxID_PASTE
, self
.OnPaste
)
230 EVT_MENU(self
, self
.ID_TOOL_PASTE
, self
.OnPaste
)
231 EVT_MENU(self
, self
.ID_DELETE
, self
.OnCutDelete
)
232 EVT_MENU(self
, self
.ID_LOCATE
, self
.OnLocate
)
233 EVT_MENU(self
, self
.ID_TOOL_LOCATE
, self
.OnLocate
)
235 EVT_MENU(self
, self
.ID_EMBED_PANEL
, self
.OnEmbedPanel
)
236 EVT_MENU(self
, self
.ID_SHOW_TOOLS
, self
.OnShowTools
)
237 EVT_MENU(self
, self
.ID_TEST
, self
.OnTest
)
238 EVT_MENU(self
, self
.ID_REFRESH
, self
.OnRefresh
)
239 EVT_MENU(self
, self
.ID_AUTO_REFRESH
, self
.OnAutoRefresh
)
240 EVT_MENU(self
, self
.ID_TEST_HIDE
, self
.OnTestHide
)
242 EVT_MENU(self
, wxID_ABOUT
, self
.OnAbout
)
243 EVT_MENU(self
, self
.ID_README
, self
.OnReadme
)
246 EVT_UPDATE_UI(self
, wxID_CUT
, self
.OnUpdateUI
)
247 EVT_UPDATE_UI(self
, wxID_COPY
, self
.OnUpdateUI
)
248 EVT_UPDATE_UI(self
, wxID_PASTE
, self
.OnUpdateUI
)
249 EVT_UPDATE_UI(self
, self
.ID_LOCATE
, self
.OnUpdateUI
)
250 EVT_UPDATE_UI(self
, self
.ID_TOOL_LOCATE
, self
.OnUpdateUI
)
251 EVT_UPDATE_UI(self
, self
.ID_TOOL_PASTE
, self
.OnUpdateUI
)
252 EVT_UPDATE_UI(self
, wxID_UNDO
, self
.OnUpdateUI
)
253 EVT_UPDATE_UI(self
, wxID_REDO
, self
.OnUpdateUI
)
254 EVT_UPDATE_UI(self
, self
.ID_DELETE
, self
.OnUpdateUI
)
255 EVT_UPDATE_UI(self
, self
.ID_TEST
, self
.OnUpdateUI
)
256 EVT_UPDATE_UI(self
, self
.ID_REFRESH
, self
.OnUpdateUI
)
259 sizer
= wxBoxSizer(wxVERTICAL
)
260 sizer
.Add(wxStaticLine(self
, -1), 0, wxEXPAND
)
261 # Horizontal sizer for toolbar and splitter
262 self
.toolsSizer
= sizer1
= wxBoxSizer()
263 splitter
= wxSplitterWindow(self
, -1, style
=wxSP_3DSASH
)
264 self
.splitter
= splitter
265 splitter
.SetMinimumPaneSize(100)
268 g
.tree
= tree
= XML_Tree(splitter
, -1)
270 # Init pull-down menu data
272 g
.pullDownMenu
= pullDownMenu
= PullDownMenu(self
)
274 # Vertical toolbar for GUI buttons
275 g
.tools
= tools
= Tools(self
)
276 tools
.Show(conf
.showTools
)
277 if conf
.showTools
: sizer1
.Add(tools
, 0, wxEXPAND
)
279 tree
.RegisterKeyEvents()
281 # !!! frame styles are broken
282 # Miniframe for not embedded mode
283 miniFrame
= wxFrame(self
, -1, 'Properties Panel',
284 (conf
.panelX
, conf
.panelY
),
285 (conf
.panelWidth
, conf
.panelHeight
))
286 self
.miniFrame
= miniFrame
287 sizer2
= wxBoxSizer()
288 miniFrame
.SetAutoLayout(True)
289 miniFrame
.SetSizer(sizer2
)
290 EVT_CLOSE(self
.miniFrame
, self
.OnCloseMiniFrame
)
291 # Create panel for parameters
294 panel
= Panel(splitter
)
295 # Set plitter windows
296 splitter
.SplitVertically(tree
, panel
, conf
.sashPos
)
298 panel
= Panel(miniFrame
)
299 sizer2
.Add(panel
, 1, wxEXPAND
)
301 splitter
.Initialize(tree
)
302 sizer1
.Add(splitter
, 1, wxEXPAND
)
303 sizer
.Add(sizer1
, 1, wxEXPAND
)
304 self
.SetAutoLayout(True)
308 self
.clipboard
= None
312 EVT_IDLE(self
, self
.OnIdle
)
313 EVT_CLOSE(self
, self
.OnCloseWindow
)
314 EVT_KEY_DOWN(self
, tools
.OnKeyDown
)
315 EVT_KEY_UP(self
, tools
.OnKeyUp
)
317 def AppendRecent(self
, menu
):
318 # add recently used files to the menu
319 for id,name
in conf
.recentfiles
.iteritems():
321 EVT_MENU(self
,id,self
.OnRecentFile
)
324 def OnRecentFile(self
,evt
):
325 # open recently used file
326 if not self
.AskSave(): return
329 path
=conf
.recentfiles
[evt
.GetId()]
331 self
.SetStatusText('Data loaded')
333 self
.SetStatusText('Failed')
335 self
.SetStatusText('No such file')
338 def OnNew(self
, evt
):
339 if not self
.AskSave(): return
342 def OnOpen(self
, evt
):
343 if not self
.AskSave(): return
344 dlg
= wxFileDialog(self
, 'Open', os
.path
.dirname(self
.dataFile
),
345 '', '*.xrc', wxOPEN | wxCHANGE_DIR
)
346 if dlg
.ShowModal() == wxID_OK
:
348 self
.SetStatusText('Loading...')
353 self
.SetStatusText('Data loaded')
355 self
.SetStatusText('Failed')
356 self
.SaveRecent(path
)
361 def OnSaveOrSaveAs(self
, evt
):
362 if evt
.GetId() == wxID_SAVEAS
or not self
.dataFile
:
363 if self
.dataFile
: defaultName
= ''
364 else: defaultName
= 'UNTITLED.xrc'
365 dirname
= os
.path
.dirname(self
.dataFile
)
366 dlg
= wxFileDialog(self
, 'Save As', dirname
, defaultName
, '*.xrc',
367 wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR
)
368 if dlg
.ShowModal() == wxID_OK
:
376 self
.SetStatusText('Saving...')
381 tmpFile
,tmpName
= tempfile
.mkstemp(prefix
='xrced-')
383 self
.Save(tmpName
) # save temporary file first
384 shutil
.move(tmpName
, path
)
386 self
.SetStatusText('Data saved')
387 self
.SaveRecent(path
)
389 self
.SetStatusText('Failed')
393 def SaveRecent(self
,path
):
394 # append to recently used files
395 if path
not in conf
.recentfiles
.values():
397 self
.recentMenu
.Append(newid
, path
)
398 EVT_MENU(self
, newid
, self
.OnRecentFile
)
399 conf
.recentfiles
[newid
] = path
401 def OnExit(self
, evt
):
404 def OnUndo(self
, evt
):
405 # Extra check to not mess with idle updating
406 if undoMan
.CanUndo():
409 def OnRedo(self
, evt
):
410 if undoMan
.CanRedo():
413 def OnCopy(self
, evt
):
414 selected
= tree
.selection
415 if not selected
: return # key pressed event
416 xxx
= tree
.GetPyData(selected
)
417 self
.clipboard
= xxx
.element
.cloneNode(True)
418 self
.SetStatusText('Copied')
420 def OnPaste(self
, evt
):
421 selected
= tree
.selection
422 if not selected
: return # key pressed event
423 # For pasting with Ctrl pressed
425 if evt
.GetId() == pullDownMenu
.ID_PASTE_SIBLING
: appendChild
= False
426 elif evt
.GetId() == self
.ID_TOOL_PASTE
:
427 if g
.tree
.ctrl
: appendChild
= False
428 else: appendChild
= not tree
.NeedInsert(selected
)
429 else: appendChild
= not tree
.NeedInsert(selected
)
430 xxx
= tree
.GetPyData(selected
)
432 # If has next item, insert, else append to parent
433 nextItem
= tree
.GetNextSibling(selected
)
434 parentLeaf
= tree
.GetItemParent(selected
)
435 # Expanded container (must have children)
436 elif tree
.IsExpanded(selected
) and tree
.GetChildrenCount(selected
, False):
437 # Insert as first child
438 nextItem
= tree
.GetFirstChild(selected
)[0]
439 parentLeaf
= selected
441 # No children or unexpanded item - appendChild stays True
442 nextItem
= wxTreeItemId() # no next item
443 parentLeaf
= selected
444 parent
= tree
.GetPyData(parentLeaf
).treeObject()
446 # Create a copy of clipboard element
447 elem
= self
.clipboard
.cloneNode(True)
448 # Tempopary xxx object to test things
449 xxx
= MakeXXXFromDOM(parent
, elem
)
451 # Check compatibility
455 if x
.__class
__ in [xxxDialog
, xxxFrame
, xxxMenuBar
, xxxWizard
]:
457 if parent
.__class
__ != xxxMainNode
: error
= True
458 elif x
.__class
__ == xxxToolBar
:
459 # Toolbar can be top-level of child of panel or frame
460 if parent
.__class
__ not in [xxxMainNode
, xxxPanel
, xxxFrame
]: error
= True
461 elif x
.__class
__ == xxxPanel
and parent
.__class
__ == xxxMainNode
:
463 elif x
.__class
__ == xxxSpacer
:
464 if not parent
.isSizer
: error
= True
465 elif x
.__class
__ == xxxSeparator
:
466 if not parent
.__class
__ in [xxxMenu
, xxxToolBar
]: error
= True
467 elif x
.__class
__ == xxxTool
:
468 if parent
.__class
__ != xxxToolBar
: error
= True
469 elif x
.__class
__ == xxxMenu
:
470 if not parent
.__class
__ in [xxxMainNode
, xxxMenuBar
, xxxMenu
]: error
= True
471 elif x
.__class
__ == xxxMenuItem
:
472 if not parent
.__class
__ in [xxxMenuBar
, xxxMenu
]: error
= True
473 elif x
.isSizer
and parent
.__class
__ == xxxNotebook
: error
= True
474 else: # normal controls can be almost anywhere
475 if parent
.__class
__ == xxxMainNode
or \
476 parent
.__class
__ in [xxxMenuBar
, xxxMenu
]: error
= True
478 if parent
.__class
__ == xxxMainNode
: parentClass
= 'root'
479 else: parentClass
= parent
.className
480 wxLogError('Incompatible parent/child: parent is %s, child is %s!' %
481 (parentClass
, x
.className
))
484 # Check parent and child relationships.
485 # If parent is sizer or notebook, child is of wrong class or
486 # parent is normal window, child is child container then detach child.
487 isChildContainer
= isinstance(xxx
, xxxChildContainer
)
488 if isChildContainer
and \
489 ((parent
.isSizer
and not isinstance(xxx
, xxxSizerItem
)) or \
490 (isinstance(parent
, xxxNotebook
) and not isinstance(xxx
, xxxNotebookPage
)) or \
491 not (parent
.isSizer
or isinstance(parent
, xxxNotebook
))):
492 elem
.removeChild(xxx
.child
.element
) # detach child
493 elem
.unlink() # delete child container
494 elem
= xxx
.child
.element
# replace
495 # This may help garbage collection
496 xxx
.child
.parent
= None
497 isChildContainer
= False
498 # Parent is sizer or notebook, child is not child container
499 if parent
.isSizer
and not isChildContainer
and not isinstance(xxx
, xxxSpacer
):
500 # Create sizer item element
501 sizerItemElem
= MakeEmptyDOM('sizeritem')
502 sizerItemElem
.appendChild(elem
)
504 elif isinstance(parent
, xxxNotebook
) and not isChildContainer
:
505 pageElem
= MakeEmptyDOM('notebookpage')
506 pageElem
.appendChild(elem
)
508 # Insert new node, register undo
509 newItem
= tree
.InsertNode(parentLeaf
, parent
, elem
, nextItem
)
510 undoMan
.RegisterUndo(UndoPasteCreate(parentLeaf
, parent
, newItem
, selected
))
511 # Scroll to show new item (!!! redundant?)
512 tree
.EnsureVisible(newItem
)
513 tree
.SelectItem(newItem
)
514 if not tree
.IsVisible(newItem
):
515 tree
.ScrollTo(newItem
)
518 if g
.testWin
and tree
.IsHighlatable(newItem
):
520 tree
.needUpdate
= True
521 tree
.pendingHighLight
= newItem
523 tree
.pendingHighLight
= None
525 self
.SetStatusText('Pasted')
527 def OnCutDelete(self
, evt
):
528 selected
= tree
.selection
529 if not selected
: return # key pressed event
531 if evt
.GetId() == wxID_CUT
:
533 status
= 'Removed to clipboard'
535 self
.lastOp
= 'DELETE'
539 # If deleting top-level item, delete testWin
540 if selected
== g
.testWin
.item
:
544 # Remove highlight, update testWin
545 if g
.testWin
.highLight
:
546 g
.testWin
.highLight
.Remove()
547 tree
.needUpdate
= True
550 index
= tree
.ItemFullIndex(selected
)
551 parent
= tree
.GetPyData(tree
.GetItemParent(selected
)).treeObject()
552 elem
= tree
.RemoveLeaf(selected
)
553 undoMan
.RegisterUndo(UndoCutDelete(index
, parent
, elem
))
554 if evt
.GetId() == wxID_CUT
:
555 if self
.clipboard
: self
.clipboard
.unlink()
556 self
.clipboard
= elem
.cloneNode(True)
557 tree
.pendingHighLight
= None
561 self
.SetStatusText(status
)
563 def OnSubclass(self
, evt
):
564 selected
= tree
.selection
565 xxx
= tree
.GetPyData(selected
).treeObject()
567 subclass
= xxx
.subclass
568 dlg
= wxTextEntryDialog(self
, 'Subclass:', defaultValue
=subclass
)
569 if dlg
.ShowModal() == wxID_OK
:
570 subclass
= dlg
.GetValue()
572 elem
.setAttribute('subclass', subclass
)
574 elif elem
.hasAttribute('subclass'):
575 elem
.removeAttribute('subclass')
577 xxx
.subclass
= elem
.getAttribute('subclass')
578 tree
.SetItemText(selected
, xxx
.treeName())
579 panel
.pages
[0].box
.SetLabel(xxx
.panelName())
582 def OnEmbedPanel(self
, evt
):
583 conf
.embedPanel
= evt
.IsChecked()
585 # Remember last dimentions
586 conf
.panelX
, conf
.panelY
= self
.miniFrame
.GetPosition()
587 conf
.panelWidth
, conf
.panelHeight
= self
.miniFrame
.GetSize()
588 size
= self
.GetSize()
589 pos
= self
.GetPosition()
590 sizePanel
= panel
.GetSize()
591 panel
.Reparent(self
.splitter
)
592 self
.miniFrame
.GetSizer().Remove(panel
)
595 self
.SetDimensions(pos
.x
, pos
.y
, size
.width
+ sizePanel
.width
, size
.height
)
596 self
.splitter
.SplitVertically(tree
, panel
, conf
.sashPos
)
597 self
.miniFrame
.Show(False)
599 conf
.sashPos
= self
.splitter
.GetSashPosition()
600 pos
= self
.GetPosition()
601 size
= self
.GetSize()
602 sizePanel
= panel
.GetSize()
603 self
.splitter
.Unsplit(panel
)
604 sizer
= self
.miniFrame
.GetSizer()
605 panel
.Reparent(self
.miniFrame
)
607 sizer
.Add(panel
, 1, wxEXPAND
)
608 self
.miniFrame
.Show(True)
609 self
.miniFrame
.SetDimensions(conf
.panelX
, conf
.panelY
,
610 conf
.panelWidth
, conf
.panelHeight
)
613 self
.SetDimensions(pos
.x
, pos
.y
,
614 max(size
.width
- sizePanel
.width
, self
.minWidth
), size
.height
)
616 def OnShowTools(self
, evt
):
617 conf
.showTools
= evt
.IsChecked()
618 g
.tools
.Show(conf
.showTools
)
620 self
.toolsSizer
.Prepend(g
.tools
, 0, wxEXPAND
)
622 self
.toolsSizer
.Remove(g
.tools
)
623 self
.toolsSizer
.Layout()
625 def OnTest(self
, evt
):
626 if not tree
.selection
: return # key pressed event
627 tree
.ShowTestWindow(tree
.selection
)
629 def OnTestHide(self
, evt
):
630 tree
.CloseTestWindow()
632 # Find object by relative position
633 def FindObject(self
, item
, obj
):
634 # We simply perform depth-first traversal, sinse it's too much
635 # hassle to deal with all sizer/window combinations
636 w
= tree
.FindNodeObject(item
)
639 if tree
.ItemHasChildren(item
):
640 child
= tree
.GetFirstChild(item
)[0]
642 found
= self
.FindObject(child
, obj
)
643 if found
: return found
644 child
= tree
.GetNextSibling(child
)
647 def OnTestWinLeftDown(self
, evt
):
648 pos
= evt
.GetPosition()
649 self
.SetHandler(g
.testWin
)
650 g
.testWin
.Disconnect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
)
651 item
= self
.FindObject(g
.testWin
.item
, evt
.GetEventObject())
653 tree
.SelectItem(item
)
654 self
.tb
.ToggleTool(self
.ID_TOOL_LOCATE
, False)
656 self
.SetStatusText('Selected %s' % tree
.GetItemText(item
))
658 self
.SetStatusText('Locate failed!')
660 def SetHandler(self
, w
, h
=None):
663 w
.SetCursor(wxCROSS_CURSOR
)
666 w
.SetCursor(wxNullCursor
)
667 for ch
in w
.GetChildren():
668 self
.SetHandler(ch
, h
)
670 def OnLocate(self
, evt
):
672 if evt
.GetId() == self
.ID_LOCATE
or \
673 evt
.GetId() == self
.ID_TOOL_LOCATE
and evt
.IsChecked():
674 self
.SetHandler(g
.testWin
, g
.testWin
)
675 g
.testWin
.Connect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
, self
.OnTestWinLeftDown
)
676 if evt
.GetId() == self
.ID_LOCATE
:
677 self
.tb
.ToggleTool(self
.ID_TOOL_LOCATE
, True)
678 elif evt
.GetId() == self
.ID_TOOL_LOCATE
and not evt
.IsChecked():
679 self
.SetHandler(g
.testWin
, None)
680 g
.testWin
.Disconnect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
)
681 self
.SetStatusText('Click somewhere in your test window now')
683 def OnRefresh(self
, evt
):
684 # If modified, apply first
685 selection
= tree
.selection
687 xxx
= tree
.GetPyData(selection
)
688 if xxx
and panel
.IsModified():
689 tree
.Apply(xxx
, selection
)
692 tree
.CreateTestWin(g
.testWin
.item
)
693 panel
.modified
= False
694 tree
.needUpdate
= False
696 def OnAutoRefresh(self
, evt
):
697 conf
.autoRefresh
= evt
.IsChecked()
698 self
.menuBar
.Check(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
699 self
.tb
.ToggleTool(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
701 def OnAbout(self
, evt
):
705 (c) Roman Rolinsky <rollrom@users.sourceforge.net>
706 Homepage: http://xrced.sourceforge.net\
708 dlg
= wxMessageDialog(self
, str, 'About XRCed', wxOK | wxCENTRE
)
712 def OnReadme(self
, evt
):
713 text
= open(os
.path
.join(basePath
, 'README.txt'), 'r').read()
714 dlg
= ScrolledMessageDialog(self
, text
, "XRCed README")
718 # Simple emulation of python command line
719 def OnDebugCMD(self
, evt
):
723 exec raw_input('C:\> ')
728 (etype
, value
, tb
) =sys
.exc_info()
729 tblist
=traceback
.extract_tb(tb
)[1:]
730 msg
=' '.join(traceback
.format_exception_only(etype
, value
)
731 +traceback
.format_list(tblist
))
734 def OnCreate(self
, evt
):
735 selected
= tree
.selection
736 if tree
.ctrl
: appendChild
= False
737 else: appendChild
= not tree
.NeedInsert(selected
)
738 xxx
= tree
.GetPyData(selected
)
742 # If has previous item, insert after it, else append to parent
744 parentLeaf
= tree
.GetItemParent(selected
)
746 # If has next item, insert, else append to parent
747 nextItem
= tree
.GetNextSibling(selected
)
748 parentLeaf
= tree
.GetItemParent(selected
)
749 # Expanded container (must have children)
750 elif tree
.shift
and tree
.IsExpanded(selected
) \
751 and tree
.GetChildrenCount(selected
, False):
752 nextItem
= tree
.GetFirstChild(selected
)[0]
753 parentLeaf
= selected
755 nextItem
= wxTreeItemId()
756 parentLeaf
= selected
757 parent
= tree
.GetPyData(parentLeaf
)
758 if parent
.hasChild
: parent
= parent
.child
761 className
= pullDownMenu
.createMap
[evt
.GetId()]
762 xxx
= MakeEmptyXXX(parent
, className
)
764 # Set default name for top-level windows
765 if parent
.__class
__ == xxxMainNode
:
766 cl
= xxx
.treeObject().__class
__
767 frame
.maxIDs
[cl
] += 1
768 xxx
.treeObject().name
= '%s%d' % (defaultIDs
[cl
], frame
.maxIDs
[cl
])
769 xxx
.treeObject().element
.setAttribute('name', xxx
.treeObject().name
)
771 # Insert new node, register undo
773 newItem
= tree
.InsertNode(parentLeaf
, parent
, elem
, nextItem
)
774 undoMan
.RegisterUndo(UndoPasteCreate(parentLeaf
, parent
, newItem
, selected
))
775 tree
.EnsureVisible(newItem
)
776 tree
.SelectItem(newItem
)
777 if not tree
.IsVisible(newItem
):
778 tree
.ScrollTo(newItem
)
781 if g
.testWin
and tree
.IsHighlatable(newItem
):
783 tree
.needUpdate
= True
784 tree
.pendingHighLight
= newItem
786 tree
.pendingHighLight
= None
790 # Replace one object with another
791 def OnReplace(self
, evt
):
792 selected
= tree
.selection
793 xxx
= tree
.GetPyData(selected
).treeObject()
795 parent
= elem
.parentNode
796 parentXXX
= xxx
.parent
798 className
= pullDownMenu
.createMap
[evt
.GetId() - 1000]
799 # Create temporary empty node (with default values)
800 dummy
= MakeEmptyDOM(className
)
801 xxxClass
= xxxDict
[className
]
802 # Remove non-compatible children
803 if tree
.ItemHasChildren(selected
) and not xxxClass
.hasChildren
:
804 tree
.DeleteChildren(selected
)
805 nodes
= elem
.childNodes
[:]
808 if node
.nodeType
!= minidom
.Node
.ELEMENT_NODE
: continue
812 if not xxxClass
.hasChildren
:
814 elif tag
not in xxxClass
.allParams
and \
815 (not xxxClass
.hasStyle
or tag
not in xxxClass
.styles
):
820 elem
.removeChild(node
)
823 # Copy parameters present in dummy but not in elem
824 for node
in dummy
.childNodes
:
827 elem
.appendChild(node
.cloneNode(True))
830 elem
.setAttribute('class', className
)
831 if elem
.hasAttribute('subclass'):
832 elem
.removeAttribute('subclass') # clear subclassing
833 # Re-create xxx element
834 xxx
= MakeXXXFromDOM(parentXXX
, elem
)
835 # Update parent in child objects
836 if tree
.ItemHasChildren(selected
):
837 i
, cookie
= tree
.GetFirstChild(selected
)
839 x
= tree
.GetPyData(i
)
841 if x
.hasChild
: x
.child
.parent
= xxx
842 i
, cookie
= tree
.GetNextChild(selected
, cookie
)
845 if tree
.GetPyData(selected
).hasChild
: # child container
846 container
= tree
.GetPyData(selected
)
847 container
.child
= xxx
848 container
.hasChildren
= xxx
.hasChildren
849 container
.isSizer
= xxx
.isSizer
851 tree
.SetPyData(selected
, xxx
)
852 tree
.SetItemText(selected
, xxx
.treeName())
853 tree
.SetItemImage(selected
, xxx
.treeImage())
855 # Set default name for top-level windows
856 if parent
.__class
__ == xxxMainNode
:
857 cl
= xxx
.treeObject().__class
__
858 frame
.maxIDs
[cl
] += 1
859 xxx
.treeObject().name
= '%s%d' % (defaultIDs
[cl
], frame
.maxIDs
[cl
])
860 xxx
.treeObject().element
.setAttribute('name', xxx
.treeObject().name
)
867 #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected))
869 if g
.testWin
and tree
.IsHighlatable(selected
):
871 tree
.needUpdate
= True
872 tree
.pendingHighLight
= selected
874 tree
.pendingHighLight
= None
878 # Expand/collapse subtree
879 def OnExpand(self
, evt
):
880 if tree
.selection
: tree
.ExpandAll(tree
.selection
)
881 else: tree
.ExpandAll(tree
.root
)
882 def OnCollapse(self
, evt
):
883 if tree
.selection
: tree
.CollapseAll(tree
.selection
)
884 else: tree
.CollapseAll(tree
.root
)
886 def OnPullDownHighlight(self
, evt
):
887 menuId
= evt
.GetMenuId()
889 menu
= evt
.GetEventObject()
890 help = menu
.GetHelpString(menuId
)
891 self
.SetStatusText(help)
893 self
.SetStatusText('')
895 def OnUpdateUI(self
, evt
):
896 if evt
.GetId() in [wxID_CUT
, wxID_COPY
, self
.ID_DELETE
]:
897 evt
.Enable(tree
.selection
is not None and tree
.selection
!= tree
.root
)
898 elif evt
.GetId() in [wxID_PASTE
, self
.ID_TOOL_PASTE
]:
899 evt
.Enable((self
.clipboard
and tree
.selection
) != None)
900 elif evt
.GetId() == self
.ID_TEST
:
901 evt
.Enable(tree
.selection
is not None and tree
.selection
!= tree
.root
)
902 elif evt
.GetId() in [self
.ID_LOCATE
, self
.ID_TOOL_LOCATE
]:
903 evt
.Enable(g
.testWin
is not None)
904 elif evt
.GetId() == wxID_UNDO
: evt
.Enable(undoMan
.CanUndo())
905 elif evt
.GetId() == wxID_REDO
: evt
.Enable(undoMan
.CanRedo())
907 def OnIdle(self
, evt
):
908 if self
.inIdle
: return # Recursive call protection
913 self
.SetStatusText('Refreshing test window...')
915 tree
.CreateTestWin(g
.testWin
.item
)
917 self
.SetStatusText('')
918 tree
.needUpdate
= False
919 elif tree
.pendingHighLight
:
920 tree
.HighLight(tree
.pendingHighLight
)
925 # We don't let close panel window
926 def OnCloseMiniFrame(self
, evt
):
929 def OnCloseWindow(self
, evt
):
930 if not self
.AskSave(): return
931 if g
.testWin
: g
.testWin
.Destroy()
932 if not panel
.GetPageCount() == 2:
933 panel
.page2
.Destroy()
935 # If we don't do this, page does not get destroyed (a bug?)
937 if not self
.IsIconized():
938 conf
.x
, conf
.y
= self
.GetPosition()
939 conf
.width
, conf
.height
= self
.GetSize()
941 conf
.sashPos
= self
.splitter
.GetSashPosition()
943 conf
.panelX
, conf
.panelY
= self
.miniFrame
.GetPosition()
944 conf
.panelWidth
, conf
.panelHeight
= self
.miniFrame
.GetSize()
950 self
.clipboard
.unlink()
951 self
.clipboard
= None
953 self
.modified
= False
959 self
.SetTitle(progname
)
960 # Numbers for new controls
962 self
.maxIDs
[xxxPanel
] = self
.maxIDs
[xxxDialog
] = self
.maxIDs
[xxxFrame
] = \
963 self
.maxIDs
[xxxMenuBar
] = self
.maxIDs
[xxxMenu
] = self
.maxIDs
[xxxToolBar
] = \
964 self
.maxIDs
[xxxWizard
] = 0
966 def Open(self
, path
):
967 if not os
.path
.exists(path
):
968 wxLogError('File does not exists: %s' % path
)
970 # Try to read the file
974 dom
= minidom
.parse(f
)
976 # Set encoding global variable and default encoding
978 g
.currentEncoding
= dom
.encoding
979 wx
.SetDefaultPyEncoding(g
.currentEncoding
.encode())
981 g
.currentEncoding
= ''
983 self
.dataFile
= path
= os
.path
.abspath(path
)
984 dir = os
.path
.dirname(path
)
985 if dir: os
.chdir(dir)
987 self
.SetTitle(progname
+ ': ' + os
.path
.basename(path
))
989 # Nice exception printing
991 wxLogError(traceback
.format_exception(inf
[0], inf
[1], None)[-1])
992 wxLogError('Error reading file: %s' % path
)
997 def Indent(self
, node
, indent
= 0):
998 # Copy child list because it will change soon
999 children
= node
.childNodes
[:]
1000 # Main node doesn't need to be indented
1002 text
= self
.domCopy
.createTextNode('\n' + ' ' * indent
)
1003 node
.parentNode
.insertBefore(text
, node
)
1005 # Append newline after last child, except for text nodes
1006 if children
[-1].nodeType
== minidom
.Node
.ELEMENT_NODE
:
1007 text
= self
.domCopy
.createTextNode('\n' + ' ' * indent
)
1008 node
.appendChild(text
)
1009 # Indent children which are elements
1011 if n
.nodeType
== minidom
.Node
.ELEMENT_NODE
:
1012 self
.Indent(n
, indent
+ 2)
1014 def Save(self
, path
):
1018 if tree
.selection
and panel
.IsModified():
1019 self
.OnRefresh(wxCommandEvent())
1020 if g
.currentEncoding
:
1021 f
= codecs
.open(path
, 'wt', g
.currentEncoding
)
1023 f
= codecs
.open(path
, 'wt')
1024 # Make temporary copy for formatting it
1025 # !!! We can't clone dom node, it works only once
1026 #self.domCopy = tree.dom.cloneNode(True)
1027 self
.domCopy
= MyDocument()
1028 mainNode
= self
.domCopy
.appendChild(tree
.mainNode
.cloneNode(True))
1029 self
.Indent(mainNode
)
1030 self
.domCopy
.writexml(f
, encoding
= g
.currentEncoding
)
1032 self
.domCopy
.unlink()
1034 self
.modified
= False
1035 panel
.SetModified(False)
1037 wxLogError('Error writing file: %s' % path
)
1041 if not (self
.modified
or panel
.IsModified()): return True
1042 flags
= wxICON_EXCLAMATION | wxYES_NO | wxCANCEL | wxCENTRE
1043 dlg
= wxMessageDialog( self
, 'File is modified. Save before exit?',
1044 'Save before too late?', flags
)
1045 say
= dlg
.ShowModal()
1048 self
.OnSaveOrSaveAs(wxCommandEvent(wxID_SAVE
))
1049 # If save was successful, modified flag is unset
1050 if not self
.modified
: return True
1051 elif say
== wxID_NO
:
1052 self
.modified
= False
1053 panel
.SetModified(False)
1060 ################################################################################
1063 print >> sys
.stderr
, 'usage: xrced [-dhiv] [file]'
1068 # Process comand-line
1071 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'dhiv')
1079 print 'XRCed version', version
1082 except getopt
.GetoptError
:
1083 if wxPlatform
!= '__WXMAC__': # macs have some extra parameters
1084 print >> sys
.stderr
, 'Unknown option'
1088 self
.SetAppName('xrced')
1091 conf
= g
.conf
= wxConfig(style
= wxCONFIG_USE_LOCAL_FILE
)
1092 conf
.autoRefresh
= conf
.ReadInt('autorefresh', True)
1093 pos
= conf
.ReadInt('x', -1), conf
.ReadInt('y', -1)
1094 size
= conf
.ReadInt('width', 800), conf
.ReadInt('height', 600)
1095 conf
.embedPanel
= conf
.ReadInt('embedPanel', True)
1096 conf
.showTools
= conf
.ReadInt('showTools', True)
1097 conf
.sashPos
= conf
.ReadInt('sashPos', 200)
1098 # read recently used files
1099 recentfiles
=conf
.Read('recentFiles','')
1102 for fil
in recentfiles
.split('|'):
1103 conf
.recentfiles
[wxNewId()]=fil
1104 if not conf
.embedPanel
:
1105 conf
.panelX
= conf
.ReadInt('panelX', -1)
1106 conf
.panelY
= conf
.ReadInt('panelY', -1)
1108 conf
.panelX
= conf
.panelY
= -1
1109 conf
.panelWidth
= conf
.ReadInt('panelWidth', 200)
1110 conf
.panelHeight
= conf
.ReadInt('panelHeight', 200)
1111 conf
.panic
= not conf
.HasEntry('nopanic')
1113 wxFileSystem_AddHandler(wxMemoryFSHandler())
1114 wxInitAllImageHandlers()
1116 frame
= Frame(pos
, size
)
1119 # Load file after showing
1122 frame
.open = frame
.Open(args
[0])
1129 wc
= wxConfigBase_Get()
1130 wc
.WriteInt('autorefresh', conf
.autoRefresh
)
1131 wc
.WriteInt('x', conf
.x
)
1132 wc
.WriteInt('y', conf
.y
)
1133 wc
.WriteInt('width', conf
.width
)
1134 wc
.WriteInt('height', conf
.height
)
1135 wc
.WriteInt('embedPanel', conf
.embedPanel
)
1136 wc
.WriteInt('showTools', conf
.showTools
)
1137 if not conf
.embedPanel
:
1138 wc
.WriteInt('panelX', conf
.panelX
)
1139 wc
.WriteInt('panelY', conf
.panelY
)
1140 wc
.WriteInt('sashPos', conf
.sashPos
)
1141 wc
.WriteInt('panelWidth', conf
.panelWidth
)
1142 wc
.WriteInt('panelHeight', conf
.panelHeight
)
1143 wc
.WriteInt('nopanic', True)
1144 wc
.Write('recentFiles', '|'.join(conf
.recentfiles
.values()[-5:]))
1148 app
= App(0, useBestVisual
=False)
1149 #app.SetAssertMode(wxPYAPP_ASSERT_LOG)
1155 if __name__
== '__main__':