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
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'}
59 ################################################################################
61 # ScrolledMessageDialog - modified from wxPython lib to set fixed-width font
62 class ScrolledMessageDialog(wxDialog
):
63 def __init__(self
, parent
, msg
, caption
, pos
= wxDefaultPosition
, size
= (500,300)):
64 from wxPython
.lib
.layoutf
import Layoutf
65 wxDialog
.__init
__(self
, parent
, -1, caption
, pos
, size
)
66 text
= wxTextCtrl(self
, -1, msg
, wxDefaultPosition
,
67 wxDefaultSize
, wxTE_MULTILINE | wxTE_READONLY
)
68 text
.SetFont(g
.modernFont())
70 # !!! possible bug - GetTextExtent without font returns sysfont dims
71 w
, h
= dc
.GetFullTextExtent(' ', g
.modernFont())[:2]
72 ok
= wxButton(self
, wxID_OK
, "OK")
73 text
.SetConstraints(Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self
,ok
)))
74 text
.SetSize((w
* 80 + 30, h
* 40))
75 ok
.SetConstraints(Layoutf('b=b5#1;x%w50#1;w!80;h!25', (self
,)))
76 self
.SetAutoLayout(True)
78 self
.CenterOnScreen(wxBOTH
)
80 ################################################################################
82 # Event handler for using during location
83 class Locator(wxEvtHandler
):
84 def ProcessEvent(self
, evt
):
88 def __init__(self
, pos
, size
):
89 wxFrame
.__init
__(self
, None, -1, '', pos
, size
)
91 frame
= g
.frame
= self
92 bar
= self
.CreateStatusBar(2)
93 bar
.SetStatusWidths([-1, 40])
94 self
.SetIcon(images
.getIconIcon())
100 menuBar
= wxMenuBar()
103 menu
.Append(wxID_NEW
, '&New\tCtrl-N', 'New file')
104 menu
.AppendSeparator()
105 menu
.Append(wxID_OPEN
, '&Open...\tCtrl-O', 'Open XRC file')
106 self
.recentMenu
= wxMenu()
107 self
.AppendRecent(self
.recentMenu
)
108 menu
.AppendMenu(-1, 'Open Recent', self
.recentMenu
, 'Open a recent file')
109 menu
.AppendSeparator()
110 menu
.Append(wxID_SAVE
, '&Save\tCtrl-S', 'Save XRC file')
111 menu
.Append(wxID_SAVEAS
, 'Save &As...', 'Save XRC file under different name')
112 menu
.AppendSeparator()
113 menu
.Append(wxID_EXIT
, '&Quit\tCtrl-Q', 'Exit application')
115 menuBar
.Append(menu
, '&File')
118 menu
.Append(wxID_UNDO
, '&Undo\tCtrl-Z', 'Undo')
119 menu
.Append(wxID_REDO
, '&Redo\tCtrl-Y', 'Redo')
120 menu
.AppendSeparator()
121 menu
.Append(wxID_CUT
, 'Cut\tCtrl-X', 'Cut to the clipboard')
122 menu
.Append(wxID_COPY
, '&Copy\tCtrl-C', 'Copy to the clipboard')
123 menu
.Append(wxID_PASTE
, '&Paste\tCtrl-V', 'Paste from the clipboard')
124 self
.ID_DELETE
= wxNewId()
125 menu
.Append(self
.ID_DELETE
, '&Delete\tCtrl-D', 'Delete object')
126 # menu.AppendSeparator()
127 self
.ID_LOCATE
= wxNewId()
128 menu
.Append(self
.ID_LOCATE
, '&Locate\tCtrl-L', 'Locate control in test window and select it')
129 menuBar
.Append(menu
, '&Edit')
132 self
.ID_EMBED_PANEL
= wxNewId()
133 menu
.Append(self
.ID_EMBED_PANEL
, '&Embed Panel',
134 'Toggle embedding properties panel in the main window', True)
135 menu
.Check(self
.ID_EMBED_PANEL
, conf
.embedPanel
)
136 self
.ID_SHOW_TOOLS
= wxNewId()
137 menu
.Append(self
.ID_SHOW_TOOLS
, 'Show &Tools', 'Toggle tools', True)
138 menu
.Check(self
.ID_SHOW_TOOLS
, conf
.showTools
)
139 menu
.AppendSeparator()
140 self
.ID_TEST
= wxNewId()
141 menu
.Append(self
.ID_TEST
, '&Test\tF5', 'Show test window')
142 self
.ID_REFRESH
= wxNewId()
143 menu
.Append(self
.ID_REFRESH
, '&Refresh\tCtrl-R', 'Refresh test window')
144 self
.ID_AUTO_REFRESH
= wxNewId()
145 menu
.Append(self
.ID_AUTO_REFRESH
, '&Auto-refresh\tCtrl-A',
146 'Toggle auto-refresh mode', True)
147 menu
.Check(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
148 menuBar
.Append(menu
, '&View')
151 menu
.Append(wxID_ABOUT
, '&About...', 'About XCRed')
152 self
.ID_README
= wxNewId()
153 menu
.Append(self
.ID_README
, '&Readme...', 'View the README file')
155 self
.ID_DEBUG_CMD
= wxNewId()
156 menu
.Append(self
.ID_DEBUG_CMD
, 'CMD', 'Python command line')
157 EVT_MENU(self
, self
.ID_DEBUG_CMD
, self
.OnDebugCMD
)
158 menuBar
.Append(menu
, '&Help')
160 self
.menuBar
= menuBar
161 self
.SetMenuBar(menuBar
)
164 tb
= self
.CreateToolBar(wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT
)
165 tb
.SetToolBitmapSize((24, 23))
166 tb
.AddSimpleTool(wxID_NEW
, images
.getNewBitmap(), 'New', 'New file')
167 tb
.AddSimpleTool(wxID_OPEN
, images
.getOpenBitmap(), 'Open', 'Open file')
168 tb
.AddSimpleTool(wxID_SAVE
, images
.getSaveBitmap(), 'Save', 'Save file')
169 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
170 tb
.AddSimpleTool(wxID_UNDO
, images
.getUndoBitmap(), 'Undo', 'Undo')
171 tb
.AddSimpleTool(wxID_REDO
, images
.getRedoBitmap(), 'Redo', 'Redo')
172 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
173 tb
.AddSimpleTool(wxID_CUT
, images
.getCutBitmap(), 'Cut', 'Cut')
174 tb
.AddSimpleTool(wxID_COPY
, images
.getCopyBitmap(), 'Copy', 'Copy')
175 tb
.AddSimpleTool(wxID_PASTE
, images
.getPasteBitmap(), 'Paste', 'Paste')
176 tb
.AddControl(wxStaticLine(tb
, -1, size
=(-1,23), style
=wxLI_VERTICAL
))
177 tb
.AddSimpleTool(self
.ID_TEST
, images
.getTestBitmap(), 'Test', 'Test window')
178 tb
.AddSimpleTool(self
.ID_REFRESH
, images
.getRefreshBitmap(),
179 'Refresh', 'Refresh view')
180 tb
.AddSimpleTool(self
.ID_AUTO_REFRESH
, images
.getAutoRefreshBitmap(),
181 'Auto-refresh', 'Toggle auto-refresh mode', True)
182 if wxPlatform
== '__WXGTK__':
183 tb
.AddSeparator() # otherwise auto-refresh sticks in status line
184 tb
.ToggleTool(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
187 self
.minWidth
= tb
.GetSize()[0] # minimal width is the size of toolbar
190 EVT_MENU(self
, wxID_NEW
, self
.OnNew
)
191 EVT_MENU(self
, wxID_OPEN
, self
.OnOpen
)
192 EVT_MENU(self
, wxID_SAVE
, self
.OnSaveOrSaveAs
)
193 EVT_MENU(self
, wxID_SAVEAS
, self
.OnSaveOrSaveAs
)
194 EVT_MENU(self
, wxID_EXIT
, self
.OnExit
)
196 EVT_MENU(self
, wxID_UNDO
, self
.OnUndo
)
197 EVT_MENU(self
, wxID_REDO
, self
.OnRedo
)
198 EVT_MENU(self
, wxID_CUT
, self
.OnCutDelete
)
199 EVT_MENU(self
, wxID_COPY
, self
.OnCopy
)
200 EVT_MENU(self
, wxID_PASTE
, self
.OnPaste
)
201 EVT_MENU(self
, self
.ID_DELETE
, self
.OnCutDelete
)
202 EVT_MENU(self
, self
.ID_LOCATE
, self
.OnLocate
)
204 EVT_MENU(self
, self
.ID_EMBED_PANEL
, self
.OnEmbedPanel
)
205 EVT_MENU(self
, self
.ID_SHOW_TOOLS
, self
.OnShowTools
)
206 EVT_MENU(self
, self
.ID_TEST
, self
.OnTest
)
207 EVT_MENU(self
, self
.ID_REFRESH
, self
.OnRefresh
)
208 EVT_MENU(self
, self
.ID_AUTO_REFRESH
, self
.OnAutoRefresh
)
210 EVT_MENU(self
, wxID_ABOUT
, self
.OnAbout
)
211 EVT_MENU(self
, self
.ID_README
, self
.OnReadme
)
214 EVT_UPDATE_UI(self
, wxID_CUT
, self
.OnUpdateUI
)
215 EVT_UPDATE_UI(self
, wxID_COPY
, self
.OnUpdateUI
)
216 EVT_UPDATE_UI(self
, wxID_PASTE
, self
.OnUpdateUI
)
217 EVT_UPDATE_UI(self
, wxID_UNDO
, self
.OnUpdateUI
)
218 EVT_UPDATE_UI(self
, wxID_REDO
, self
.OnUpdateUI
)
219 EVT_UPDATE_UI(self
, self
.ID_DELETE
, self
.OnUpdateUI
)
220 EVT_UPDATE_UI(self
, self
.ID_TEST
, self
.OnUpdateUI
)
221 EVT_UPDATE_UI(self
, self
.ID_REFRESH
, self
.OnUpdateUI
)
224 sizer
= wxBoxSizer(wxVERTICAL
)
225 sizer
.Add(wxStaticLine(self
, -1), 0, wxEXPAND
)
226 # Horizontal sizer for toolbar and splitter
227 self
.toolsSizer
= sizer1
= wxBoxSizer()
228 splitter
= wxSplitterWindow(self
, -1, style
=wxSP_3DSASH
)
229 self
.splitter
= splitter
230 splitter
.SetMinimumPaneSize(100)
233 g
.tree
= tree
= XML_Tree(splitter
, -1)
235 # Init pull-down menu data
237 g
.pullDownMenu
= pullDownMenu
= PullDownMenu(self
)
239 # Vertical toolbar for GUI buttons
240 g
.tools
= tools
= Tools(self
)
241 tools
.Show(conf
.showTools
)
242 if conf
.showTools
: sizer1
.Add(tools
, 0, wxEXPAND
)
244 tree
.RegisterKeyEvents()
246 # !!! frame styles are broken
247 # Miniframe for not embedded mode
248 miniFrame
= wxFrame(self
, -1, 'Properties Panel',
249 (conf
.panelX
, conf
.panelY
),
250 (conf
.panelWidth
, conf
.panelHeight
))
251 self
.miniFrame
= miniFrame
252 sizer2
= wxBoxSizer()
253 miniFrame
.SetAutoLayout(True)
254 miniFrame
.SetSizer(sizer2
)
255 EVT_CLOSE(self
.miniFrame
, self
.OnCloseMiniFrame
)
256 # Create panel for parameters
259 panel
= Panel(splitter
)
260 # Set plitter windows
261 splitter
.SplitVertically(tree
, panel
, conf
.sashPos
)
263 panel
= Panel(miniFrame
)
264 sizer2
.Add(panel
, 1, wxEXPAND
)
266 splitter
.Initialize(tree
)
267 sizer1
.Add(splitter
, 1, wxEXPAND
)
268 sizer
.Add(sizer1
, 1, wxEXPAND
)
269 self
.SetAutoLayout(True)
273 self
.clipboard
= None
277 EVT_IDLE(self
, self
.OnIdle
)
278 EVT_CLOSE(self
, self
.OnCloseWindow
)
279 EVT_KEY_DOWN(self
, tools
.OnKeyDown
)
280 EVT_KEY_UP(self
, tools
.OnKeyUp
)
282 def AppendRecent(self
, menu
):
283 # add recently used files to the menu
284 for id,name
in conf
.recentfiles
.iteritems():
286 EVT_MENU(self
,id,self
.OnRecentFile
)
289 def OnRecentFile(self
,evt
):
290 # open recently used file
291 if not self
.AskSave(): return
294 path
=conf
.recentfiles
[evt
.GetId()]
296 self
.SetStatusText('Data loaded')
298 self
.SetStatusText('Failed')
300 self
.SetStatusText('No such file')
303 def OnNew(self
, evt
):
304 if not self
.AskSave(): return
307 def OnOpen(self
, evt
):
308 if not self
.AskSave(): return
309 dlg
= wxFileDialog(self
, 'Open', os
.path
.dirname(self
.dataFile
),
310 '', '*.xrc', wxOPEN | wxCHANGE_DIR
)
311 if dlg
.ShowModal() == wxID_OK
:
313 self
.SetStatusText('Loading...')
317 self
.SetStatusText('Data loaded')
319 self
.SetStatusText('Failed')
320 self
.SaveRecent(path
)
324 def OnSaveOrSaveAs(self
, evt
):
325 if evt
.GetId() == wxID_SAVEAS
or not self
.dataFile
:
326 if self
.dataFile
: defaultName
= ''
327 else: defaultName
= 'UNTITLED.xrc'
328 dirname
= os
.path
.dirname(self
.dataFile
)
329 dlg
= wxFileDialog(self
, 'Save As', dirname
, defaultName
, '*.xrc',
330 wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR
)
331 if dlg
.ShowModal() == wxID_OK
:
339 self
.SetStatusText('Saving...')
345 self
.SetStatusText('Data saved')
346 self
.SaveRecent(path
)
348 self
.SetStatusText('Failed')
351 def SaveRecent(self
,path
):
352 # append to recently used files
353 if path
not in conf
.recentfiles
.values():
355 self
.recentMenu
.Append(newid
, path
)
356 EVT_MENU(self
, newid
, self
.OnRecentFile
)
357 conf
.recentfiles
[newid
] = path
359 def OnExit(self
, evt
):
362 def OnUndo(self
, evt
):
363 # Extra check to not mess with idle updating
364 if undoMan
.CanUndo():
367 def OnRedo(self
, evt
):
368 if undoMan
.CanRedo():
371 def OnCopy(self
, evt
):
372 selected
= tree
.selection
373 if not selected
: return # key pressed event
374 xxx
= tree
.GetPyData(selected
)
375 self
.clipboard
= xxx
.element
.cloneNode(True)
376 self
.SetStatusText('Copied')
378 def OnPaste(self
, evt
):
379 selected
= tree
.selection
380 if not selected
: return # key pressed event
381 # For pasting with Ctrl pressed
382 if evt
.GetId() == pullDownMenu
.ID_PASTE_SIBLING
: appendChild
= False
383 else: appendChild
= not tree
.NeedInsert(selected
)
384 xxx
= tree
.GetPyData(selected
)
386 # If has next item, insert, else append to parent
387 nextItem
= tree
.GetNextSibling(selected
)
388 parentLeaf
= tree
.GetItemParent(selected
)
389 # Expanded container (must have children)
390 elif tree
.IsExpanded(selected
) and tree
.GetChildrenCount(selected
, False):
391 # Insert as first child
392 nextItem
= tree
.GetFirstChild(selected
)[0]
393 parentLeaf
= selected
395 # No children or unexpanded item - appendChild stays True
396 nextItem
= wxTreeItemId() # no next item
397 parentLeaf
= selected
398 parent
= tree
.GetPyData(parentLeaf
).treeObject()
400 # Create a copy of clipboard element
401 elem
= self
.clipboard
.cloneNode(True)
402 # Tempopary xxx object to test things
403 xxx
= MakeXXXFromDOM(parent
, elem
)
405 # Check compatibility
409 if x
.__class
__ in [xxxDialog
, xxxFrame
, xxxMenuBar
]:
411 if parent
.__class
__ != xxxMainNode
: error
= True
412 elif x
.__class
__ == xxxToolBar
:
413 # Toolbar can be top-level of child of panel or frame
414 if parent
.__class
__ not in [xxxMainNode
, xxxPanel
, xxxFrame
]: error
= True
415 elif x
.__class
__ == xxxPanel
and parent
.__class
__ == xxxMainNode
:
417 elif x
.__class
__ == xxxSpacer
:
418 if not parent
.isSizer
: error
= True
419 elif x
.__class
__ == xxxSeparator
:
420 if not parent
.__class
__ in [xxxMenu
, xxxToolBar
]: error
= True
421 elif x
.__class
__ == xxxTool
:
422 if parent
.__class
__ != xxxToolBar
: error
= True
423 elif x
.__class
__ == xxxMenu
:
424 if not parent
.__class
__ in [xxxMainNode
, xxxMenuBar
, xxxMenu
]: error
= True
425 elif x
.__class
__ == xxxMenuItem
:
426 if not parent
.__class
__ in [xxxMenuBar
, xxxMenu
]: error
= True
427 elif x
.isSizer
and parent
.__class
__ == xxxNotebook
: error
= True
428 else: # normal controls can be almost anywhere
429 if parent
.__class
__ == xxxMainNode
or \
430 parent
.__class
__ in [xxxMenuBar
, xxxMenu
]: error
= True
432 if parent
.__class
__ == xxxMainNode
: parentClass
= 'root'
433 else: parentClass
= parent
.className
434 wxLogError('Incompatible parent/child: parent is %s, child is %s!' %
435 (parentClass
, x
.className
))
438 # Check parent and child relationships.
439 # If parent is sizer or notebook, child is of wrong class or
440 # parent is normal window, child is child container then detach child.
441 isChildContainer
= isinstance(xxx
, xxxChildContainer
)
442 if isChildContainer
and \
443 ((parent
.isSizer
and not isinstance(xxx
, xxxSizerItem
)) or \
444 (isinstance(parent
, xxxNotebook
) and not isinstance(xxx
, xxxNotebookPage
)) or \
445 not (parent
.isSizer
or isinstance(parent
, xxxNotebook
))):
446 elem
.removeChild(xxx
.child
.element
) # detach child
447 elem
.unlink() # delete child container
448 elem
= xxx
.child
.element
# replace
449 # This may help garbage collection
450 xxx
.child
.parent
= None
451 isChildContainer
= False
452 # Parent is sizer or notebook, child is not child container
453 if parent
.isSizer
and not isChildContainer
and not isinstance(xxx
, xxxSpacer
):
454 # Create sizer item element
455 sizerItemElem
= MakeEmptyDOM('sizeritem')
456 sizerItemElem
.appendChild(elem
)
458 elif isinstance(parent
, xxxNotebook
) and not isChildContainer
:
459 pageElem
= MakeEmptyDOM('notebookpage')
460 pageElem
.appendChild(elem
)
462 # Insert new node, register undo
463 newItem
= tree
.InsertNode(parentLeaf
, parent
, elem
, nextItem
)
464 undoMan
.RegisterUndo(UndoPasteCreate(parentLeaf
, parent
, newItem
, selected
))
465 # Scroll to show new item (!!! redundant?)
466 tree
.EnsureVisible(newItem
)
467 tree
.SelectItem(newItem
)
468 if not tree
.IsVisible(newItem
):
469 tree
.ScrollTo(newItem
)
472 if g
.testWin
and tree
.IsHighlatable(newItem
):
474 tree
.needUpdate
= True
475 tree
.pendingHighLight
= newItem
477 tree
.pendingHighLight
= None
479 self
.SetStatusText('Pasted')
481 def OnCutDelete(self
, evt
):
482 selected
= tree
.selection
483 if not selected
: return # key pressed event
485 if evt
.GetId() == wxID_CUT
:
487 status
= 'Removed to clipboard'
489 self
.lastOp
= 'DELETE'
493 # If deleting top-level item, delete testWin
494 if selected
== g
.testWin
.item
:
498 # Remove highlight, update testWin
499 if g
.testWin
.highLight
:
500 g
.testWin
.highLight
.Remove()
501 tree
.needUpdate
= True
504 index
= tree
.ItemFullIndex(selected
)
505 parent
= tree
.GetPyData(tree
.GetItemParent(selected
)).treeObject()
506 elem
= tree
.RemoveLeaf(selected
)
507 undoMan
.RegisterUndo(UndoCutDelete(index
, parent
, elem
))
508 if evt
.GetId() == wxID_CUT
:
509 if self
.clipboard
: self
.clipboard
.unlink()
510 self
.clipboard
= elem
.cloneNode(True)
511 tree
.pendingHighLight
= None
515 self
.SetStatusText(status
)
517 def OnSubclass(self
, evt
):
518 selected
= tree
.selection
519 xxx
= tree
.GetPyData(selected
).treeObject()
521 subclass
= xxx
.subclass
522 dlg
= wxTextEntryDialog(self
, 'Subclass:', defaultValue
=subclass
)
523 if dlg
.ShowModal() == wxID_OK
:
524 subclass
= dlg
.GetValue()
526 elem
.setAttribute('subclass', subclass
)
528 elif elem
.hasAttribute('subclass'):
529 elem
.removeAttribute('subclass')
531 xxx
.subclass
= elem
.getAttribute('subclass')
532 tree
.SetItemText(selected
, xxx
.treeName())
533 panel
.pages
[0].box
.SetLabel(xxx
.panelName())
536 def OnEmbedPanel(self
, evt
):
537 conf
.embedPanel
= evt
.IsChecked()
539 # Remember last dimentions
540 conf
.panelX
, conf
.panelY
= self
.miniFrame
.GetPosition()
541 conf
.panelWidth
, conf
.panelHeight
= self
.miniFrame
.GetSize()
542 size
= self
.GetSize()
543 pos
= self
.GetPosition()
544 sizePanel
= panel
.GetSize()
545 panel
.Reparent(self
.splitter
)
546 self
.miniFrame
.GetSizer().Remove(panel
)
549 self
.SetDimensions(pos
.x
, pos
.y
, size
.width
+ sizePanel
.width
, size
.height
)
550 self
.splitter
.SplitVertically(tree
, panel
, conf
.sashPos
)
551 self
.miniFrame
.Show(False)
553 conf
.sashPos
= self
.splitter
.GetSashPosition()
554 pos
= self
.GetPosition()
555 size
= self
.GetSize()
556 sizePanel
= panel
.GetSize()
557 self
.splitter
.Unsplit(panel
)
558 sizer
= self
.miniFrame
.GetSizer()
559 panel
.Reparent(self
.miniFrame
)
561 sizer
.Add(panel
, 1, wxEXPAND
)
562 self
.miniFrame
.Show(True)
563 self
.miniFrame
.SetDimensions(conf
.panelX
, conf
.panelY
,
564 conf
.panelWidth
, conf
.panelHeight
)
567 self
.SetDimensions(pos
.x
, pos
.y
,
568 max(size
.width
- sizePanel
.width
, self
.minWidth
), size
.height
)
570 def OnShowTools(self
, evt
):
571 conf
.showTools
= evt
.IsChecked()
572 g
.tools
.Show(conf
.showTools
)
574 self
.toolsSizer
.Prepend(g
.tools
, 0, wxEXPAND
)
576 self
.toolsSizer
.Remove(g
.tools
)
577 self
.toolsSizer
.Layout()
579 def OnTest(self
, evt
):
580 if not tree
.selection
: return # key pressed event
581 tree
.ShowTestWindow(tree
.selection
)
583 # Find object by relative position
584 def FindObject(self
, item
, obj
):
585 # We simply perform depth-first traversal, sinse it's too much
586 # hassle to deal with all sizer/window combinations
587 w
= tree
.FindNodeObject(item
)
590 if tree
.ItemHasChildren(item
):
591 child
= tree
.GetFirstChild(item
)[0]
593 found
= self
.FindObject(child
, obj
)
594 if found
: return found
595 child
= tree
.GetNextSibling(child
)
598 def OnTestWinLeftDown(self
, evt
):
599 pos
= evt
.GetPosition()
600 self
.SetHandler(g
.testWin
)
601 g
.testWin
.Disconnect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
)
602 item
= self
.FindObject(g
.testWin
.item
, evt
.GetEventObject())
604 tree
.SelectItem(item
)
606 def SetHandler(self
, w
, h
=None):
609 w
.SetCursor(wxCROSS_CURSOR
)
612 w
.SetCursor(wxNullCursor
)
613 for ch
in w
.GetChildren():
614 self
.SetHandler(ch
, h
)
616 def OnLocate(self
, evt
):
618 self
.SetHandler(g
.testWin
, g
.testWin
)
619 g
.testWin
.Connect(wxID_ANY
, wxID_ANY
, wxEVT_LEFT_DOWN
, self
.OnTestWinLeftDown
)
621 def OnRefresh(self
, evt
):
622 # If modified, apply first
623 selection
= tree
.selection
625 xxx
= tree
.GetPyData(selection
)
626 if xxx
and panel
.IsModified():
627 tree
.Apply(xxx
, selection
)
630 tree
.CreateTestWin(g
.testWin
.item
)
631 panel
.modified
= False
632 tree
.needUpdate
= False
634 def OnAutoRefresh(self
, evt
):
635 conf
.autoRefresh
= evt
.IsChecked()
636 self
.menuBar
.Check(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
637 self
.tb
.ToggleTool(self
.ID_AUTO_REFRESH
, conf
.autoRefresh
)
639 def OnAbout(self
, evt
):
643 (c) Roman Rolinsky <rollrom@users.sourceforge.net>
644 Homepage: http://xrced.sourceforge.net\
646 dlg
= wxMessageDialog(self
, str, 'About XRCed', wxOK | wxCENTRE
)
650 def OnReadme(self
, evt
):
651 text
= open(os
.path
.join(basePath
, 'README.txt'), 'r').read()
652 dlg
= ScrolledMessageDialog(self
, text
, "XRCed README")
656 # Simple emulation of python command line
657 def OnDebugCMD(self
, evt
):
661 exec raw_input('C:\> ')
666 (etype
, value
, tb
) =sys
.exc_info()
667 tblist
=traceback
.extract_tb(tb
)[1:]
668 msg
=' '.join(traceback
.format_exception_only(etype
, value
)
669 +traceback
.format_list(tblist
))
672 def OnCreate(self
, evt
):
673 selected
= tree
.selection
674 if tree
.ctrl
: appendChild
= False
675 else: appendChild
= not tree
.NeedInsert(selected
)
676 xxx
= tree
.GetPyData(selected
)
680 # If has previous item, insert after it, else append to parent
682 parentLeaf
= tree
.GetItemParent(selected
)
684 # If has next item, insert, else append to parent
685 nextItem
= tree
.GetNextSibling(selected
)
686 parentLeaf
= tree
.GetItemParent(selected
)
687 # Expanded container (must have children)
688 elif tree
.shift
and tree
.IsExpanded(selected
) \
689 and tree
.GetChildrenCount(selected
, False):
690 nextItem
= tree
.GetFirstChild(selected
)[0]
691 parentLeaf
= selected
693 nextItem
= wxTreeItemId()
694 parentLeaf
= selected
695 parent
= tree
.GetPyData(parentLeaf
)
696 if parent
.hasChild
: parent
= parent
.child
699 className
= pullDownMenu
.createMap
[evt
.GetId()]
700 xxx
= MakeEmptyXXX(parent
, className
)
702 # Set default name for top-level windows
703 if parent
.__class
__ == xxxMainNode
:
704 cl
= xxx
.treeObject().__class
__
705 frame
.maxIDs
[cl
] += 1
706 xxx
.treeObject().name
= '%s%d' % (defaultIDs
[cl
], frame
.maxIDs
[cl
])
707 xxx
.treeObject().element
.setAttribute('name', xxx
.treeObject().name
)
709 # Insert new node, register undo
711 newItem
= tree
.InsertNode(parentLeaf
, parent
, elem
, nextItem
)
712 undoMan
.RegisterUndo(UndoPasteCreate(parentLeaf
, parent
, newItem
, selected
))
713 tree
.EnsureVisible(newItem
)
714 tree
.SelectItem(newItem
)
715 if not tree
.IsVisible(newItem
):
716 tree
.ScrollTo(newItem
)
719 if g
.testWin
and tree
.IsHighlatable(newItem
):
721 tree
.needUpdate
= True
722 tree
.pendingHighLight
= newItem
724 tree
.pendingHighLight
= None
728 # Replace one object with another
729 def OnReplace(self
, evt
):
730 selected
= tree
.selection
731 xxx
= tree
.GetPyData(selected
).treeObject()
733 parent
= elem
.parentNode
734 parentXXX
= xxx
.parent
736 className
= pullDownMenu
.createMap
[evt
.GetId() - 1000]
737 # Create temporary empty node (with default values)
738 dummy
= MakeEmptyDOM(className
)
739 xxxClass
= xxxDict
[className
]
740 # Remove non-compatible children
741 if tree
.ItemHasChildren(selected
) and not xxxClass
.hasChildren
:
742 tree
.DeleteChildren(selected
)
743 nodes
= elem
.childNodes
[:]
749 if not xxxClass
.hasChildren
:
751 elif tag
not in xxxClass
.allParams
and \
752 (not xxxClass
.hasStyle
or tag
not in xxxClass
.styles
):
757 elem
.removeChild(node
)
760 # Copy parameters present in dummy but not in elem
761 for node
in dummy
.childNodes
:
764 elem
.appendChild(node
.cloneNode(True))
767 elem
.setAttribute('class', className
)
768 # Re-create xxx element
769 xxx
= MakeXXXFromDOM(parentXXX
, elem
)
770 # Update parent in child objects
771 if tree
.ItemHasChildren(selected
):
772 i
, cookie
= tree
.GetFirstChild(selected
)
774 x
= tree
.GetPyData(i
)
776 if x
.hasChild
: x
.child
.parent
= xxx
777 i
, cookie
= tree
.GetNextChild(selected
, cookie
)
780 if tree
.GetPyData(selected
).hasChild
: # child container
781 container
= tree
.GetPyData(selected
)
782 container
.child
= xxx
783 container
.hasChildren
= xxx
.hasChildren
784 container
.isSizer
= xxx
.isSizer
786 tree
.SetPyData(selected
, xxx
)
787 tree
.SetItemText(selected
, xxx
.treeName())
788 tree
.SetItemImage(selected
, xxx
.treeImage())
790 # Set default name for top-level windows
791 if parent
.__class
__ == xxxMainNode
:
792 cl
= xxx
.treeObject().__class
__
793 frame
.maxIDs
[cl
] += 1
794 xxx
.treeObject().name
= '%s%d' % (defaultIDs
[cl
], frame
.maxIDs
[cl
])
795 xxx
.treeObject().element
.setAttribute('name', xxx
.treeObject().name
)
802 #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected))
804 if g
.testWin
and tree
.IsHighlatable(selected
):
806 tree
.needUpdate
= True
807 tree
.pendingHighLight
= selected
809 tree
.pendingHighLight
= None
813 # Expand/collapse subtree
814 def OnExpand(self
, evt
):
815 if tree
.selection
: tree
.ExpandAll(tree
.selection
)
816 else: tree
.ExpandAll(tree
.root
)
817 def OnCollapse(self
, evt
):
818 if tree
.selection
: tree
.CollapseAll(tree
.selection
)
819 else: tree
.CollapseAll(tree
.root
)
821 def OnPullDownHighlight(self
, evt
):
822 menuId
= evt
.GetMenuId()
824 menu
= evt
.GetEventObject()
825 help = menu
.GetHelpString(menuId
)
826 self
.SetStatusText(help)
828 self
.SetStatusText('')
830 def OnUpdateUI(self
, evt
):
831 if evt
.GetId() in [wxID_CUT
, wxID_COPY
, self
.ID_DELETE
]:
832 evt
.Enable(tree
.selection
is not None and tree
.selection
!= tree
.root
)
833 elif evt
.GetId() == wxID_PASTE
:
834 evt
.Enable((self
.clipboard
and tree
.selection
) != None)
835 elif evt
.GetId() == self
.ID_TEST
:
836 evt
.Enable(tree
.selection
is not None and tree
.selection
!= tree
.root
)
837 elif evt
.GetId() == wxID_UNDO
: evt
.Enable(undoMan
.CanUndo())
838 elif evt
.GetId() == wxID_REDO
: evt
.Enable(undoMan
.CanRedo())
840 def OnIdle(self
, evt
):
841 if self
.inIdle
: return # Recursive call protection
846 self
.SetStatusText('Refreshing test window...')
848 tree
.CreateTestWin(g
.testWin
.item
)
850 self
.SetStatusText('')
851 tree
.needUpdate
= False
852 elif tree
.pendingHighLight
:
853 tree
.HighLight(tree
.pendingHighLight
)
858 # We don't let close panel window
859 def OnCloseMiniFrame(self
, evt
):
862 def OnCloseWindow(self
, evt
):
863 if not self
.AskSave(): return
864 if g
.testWin
: g
.testWin
.Destroy()
865 if not panel
.GetPageCount() == 2:
866 panel
.page2
.Destroy()
868 # If we don't do this, page does not get destroyed (a bug?)
870 if not self
.IsIconized():
871 conf
.x
, conf
.y
= self
.GetPosition()
872 conf
.width
, conf
.height
= self
.GetSize()
874 conf
.sashPos
= self
.splitter
.GetSashPosition()
876 conf
.panelX
, conf
.panelY
= self
.miniFrame
.GetPosition()
877 conf
.panelWidth
, conf
.panelHeight
= self
.miniFrame
.GetSize()
883 self
.clipboard
.unlink()
884 self
.clipboard
= None
886 self
.modified
= False
892 self
.SetTitle(progname
)
893 # Numbers for new controls
895 self
.maxIDs
[xxxPanel
] = self
.maxIDs
[xxxDialog
] = self
.maxIDs
[xxxFrame
] = \
896 self
.maxIDs
[xxxMenuBar
] = self
.maxIDs
[xxxMenu
] = self
.maxIDs
[xxxToolBar
] = 0
898 def Open(self
, path
):
899 if not os
.path
.exists(path
):
900 wxLogError('File does not exists: %s' % path
)
902 # Try to read the file
906 dom
= minidom
.parse(f
)
908 # Set encoding global variable
909 if dom
.encoding
: g
.currentEncoding
= dom
.encoding
911 self
.dataFile
= path
= os
.path
.abspath(path
)
912 dir = os
.path
.dirname(path
)
913 if dir: os
.chdir(dir)
915 self
.SetTitle(progname
+ ': ' + os
.path
.basename(path
))
917 # Nice exception printing
919 wxLogError(traceback
.format_exception(inf
[0], inf
[1], None)[-1])
920 wxLogError('Error reading file: %s' % path
)
924 def Indent(self
, node
, indent
= 0):
925 # Copy child list because it will change soon
926 children
= node
.childNodes
[:]
927 # Main node doesn't need to be indented
929 text
= self
.domCopy
.createTextNode('\n' + ' ' * indent
)
930 node
.parentNode
.insertBefore(text
, node
)
932 # Append newline after last child, except for text nodes
933 if children
[-1].nodeType
== minidom
.Node
.ELEMENT_NODE
:
934 text
= self
.domCopy
.createTextNode('\n' + ' ' * indent
)
935 node
.appendChild(text
)
936 # Indent children which are elements
938 if n
.nodeType
== minidom
.Node
.ELEMENT_NODE
:
939 self
.Indent(n
, indent
+ 2)
941 def Save(self
, path
):
945 if tree
.selection
and panel
.IsModified():
946 self
.OnRefresh(wxCommandEvent())
947 f
= codecs
.open(path
, 'w', g
.currentEncoding
)
948 # Make temporary copy for formatting it
949 # !!! We can't clone dom node, it works only once
950 #self.domCopy = tree.dom.cloneNode(True)
951 self
.domCopy
= MyDocument()
952 mainNode
= self
.domCopy
.appendChild(tree
.mainNode
.cloneNode(True))
953 self
.Indent(mainNode
)
954 self
.domCopy
.writexml(f
, encoding
= g
.currentEncoding
)
956 self
.domCopy
.unlink()
958 self
.modified
= False
959 panel
.SetModified(False)
961 wxLogError('Error writing file: %s' % path
)
965 if not (self
.modified
or panel
.IsModified()): return True
966 flags
= wxICON_EXCLAMATION | wxYES_NO | wxCANCEL | wxCENTRE
967 dlg
= wxMessageDialog( self
, 'File is modified. Save before exit?',
968 'Save before too late?', flags
)
969 say
= dlg
.ShowModal()
972 self
.OnSaveOrSaveAs(wxCommandEvent(wxID_SAVE
))
973 # If save was successful, modified flag is unset
974 if not self
.modified
: return True
976 self
.modified
= False
977 panel
.SetModified(False)
984 ################################################################################
987 print >> sys
.stderr
, 'usage: xrced [-dhiv] [file]'
992 # Process comand-line
995 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'dhiv')
1003 print 'XRCed version', version
1006 except getopt
.GetoptError
:
1007 if wxPlatform
!= '__WXMAC__': # macs have some extra parameters
1008 print >> sys
.stderr
, 'Unknown option'
1012 self
.SetAppName('xrced')
1015 conf
= g
.conf
= wxConfig(style
= wxCONFIG_USE_LOCAL_FILE
)
1016 conf
.autoRefresh
= conf
.ReadInt('autorefresh', True)
1017 pos
= conf
.ReadInt('x', -1), conf
.ReadInt('y', -1)
1018 size
= conf
.ReadInt('width', 800), conf
.ReadInt('height', 600)
1019 conf
.embedPanel
= conf
.ReadInt('embedPanel', True)
1020 conf
.showTools
= conf
.ReadInt('showTools', True)
1021 conf
.sashPos
= conf
.ReadInt('sashPos', 200)
1022 # read recently used files
1023 recentfiles
=conf
.Read('recentFiles','')
1026 for fil
in recentfiles
.split('|'):
1027 conf
.recentfiles
[wxNewId()]=fil
1028 if not conf
.embedPanel
:
1029 conf
.panelX
= conf
.ReadInt('panelX', -1)
1030 conf
.panelY
= conf
.ReadInt('panelY', -1)
1032 conf
.panelX
= conf
.panelY
= -1
1033 conf
.panelWidth
= conf
.ReadInt('panelWidth', 200)
1034 conf
.panelHeight
= conf
.ReadInt('panelHeight', 200)
1035 conf
.panic
= not conf
.HasEntry('nopanic')
1037 wxFileSystem_AddHandler(wxMemoryFSHandler())
1038 wxInitAllImageHandlers()
1040 frame
= Frame(pos
, size
)
1042 # Load resources from XRC file (!!! should be transformed to .py later?)
1043 frame
.res
= wxXmlResource('')
1044 # !!! Temporary blocking of assert failure occuring in unicode build
1046 frame
.res
.Load(os
.path
.join(basePath
, 'xrced.xrc'))
1047 except wx
._core
.PyAssertionError
:
1050 # Load file after showing
1053 frame
.open = frame
.Open(args
[0])
1060 wc
= wxConfigBase_Get()
1061 wc
.WriteInt('autorefresh', conf
.autoRefresh
)
1062 wc
.WriteInt('x', conf
.x
)
1063 wc
.WriteInt('y', conf
.y
)
1064 wc
.WriteInt('width', conf
.width
)
1065 wc
.WriteInt('height', conf
.height
)
1066 wc
.WriteInt('embedPanel', conf
.embedPanel
)
1067 wc
.WriteInt('showTools', conf
.showTools
)
1068 if not conf
.embedPanel
:
1069 wc
.WriteInt('panelX', conf
.panelX
)
1070 wc
.WriteInt('panelY', conf
.panelY
)
1071 wc
.WriteInt('sashPos', conf
.sashPos
)
1072 wc
.WriteInt('panelWidth', conf
.panelWidth
)
1073 wc
.WriteInt('panelHeight', conf
.panelHeight
)
1074 wc
.WriteInt('nopanic', True)
1075 wc
.Write('recentFiles', '|'.join(conf
.recentfiles
.values()[-5:]))
1079 app
= App(0, useBestVisual
=False)
1080 #app.SetAssertMode(wxPYAPP_ASSERT_LOG)
1086 if __name__
== '__main__':