]>
Commit | Line | Data |
---|---|---|
d14a1e28 RD |
1 | # Name: xrced.py |
2 | # Purpose: XRC editor, main module | |
3 | # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be> | |
4 | # Created: 20.08.2001 | |
5 | # RCS-ID: $Id$ | |
1fded56b | 6 | |
d14a1e28 | 7 | """ |
1fded56b | 8 | |
d14a1e28 RD |
9 | xrced -- Simple resource editor for XRC format used by wxWindows/wxPython |
10 | GUI toolkit. | |
11 | ||
12 | Usage: | |
13 | ||
14 | xrced [ -h ] [ -v ] [ XRC-file ] | |
15 | ||
16 | Options: | |
17 | ||
18 | -h output short usage info and exit | |
19 | ||
20 | -v output version info and exit | |
21 | """ | |
22 | ||
23 | ||
24 | from globals import * | |
016f67ba | 25 | import os, sys, getopt, re, traceback, tempfile, shutil |
d14a1e28 RD |
26 | |
27 | # Local modules | |
28 | from tree import * # imports xxx which imports params | |
29 | from panel import * | |
30 | from tools import * | |
31 | # Cleanup recursive import sideeffects, otherwise we can't create undoMan | |
32 | import undo | |
33 | undo.ParamPage = ParamPage | |
34 | undoMan = g.undoMan = UndoManager() | |
35 | ||
36 | # Set application path for loading resources | |
37 | if __name__ == '__main__': | |
38 | basePath = os.path.dirname(sys.argv[0]) | |
39 | else: | |
40 | basePath = os.path.dirname(__file__) | |
41 | ||
42 | # 1 adds CMD command to Help menu | |
43 | debug = 0 | |
44 | ||
45 | g.helpText = """\ | |
46 | <HTML><H2>Welcome to XRC<font color="blue">ed</font></H2><H3><font color="green">DON'T PANIC :)</font></H3> | |
47 | Read this note before clicking on anything!<P> | |
48 | To start select tree root, then popup menu with your right mouse button, | |
49 | select "Append Child", and then any command.<P> | |
50 | Or just press one of the buttons on the tools palette.<P> | |
51 | Enter XML ID, change properties, create children.<P> | |
52 | To test your interface select Test command (View menu).<P> | |
53 | Consult README file for the details.</HTML> | |
54 | """ | |
55 | ||
56 | defaultIDs = {xxxPanel:'PANEL', xxxDialog:'DIALOG', xxxFrame:'FRAME', | |
64bce500 RR |
57 | xxxMenuBar:'MENUBAR', xxxMenu:'MENU', xxxToolBar:'TOOLBAR', |
58 | xxxWizard:'WIZARD'} | |
d14a1e28 RD |
59 | |
60 | ################################################################################ | |
61 | ||
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) | |
289128a4 | 69 | text.SetFont(g.modernFont()) |
d14a1e28 RD |
70 | dc = wxWindowDC(text) |
71 | # !!! possible bug - GetTextExtent without font returns sysfont dims | |
289128a4 | 72 | w, h = dc.GetFullTextExtent(' ', g.modernFont())[:2] |
d14a1e28 RD |
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)) | |
364a2be0 | 76 | text.ShowPosition(1) |
d14a1e28 RD |
77 | ok.SetConstraints(Layoutf('b=b5#1;x%w50#1;w!80;h!25', (self,))) |
78 | self.SetAutoLayout(True) | |
79 | self.Fit() | |
80 | self.CenterOnScreen(wxBOTH) | |
81 | ||
82 | ################################################################################ | |
83 | ||
fd919451 RR |
84 | # Event handler for using during location |
85 | class Locator(wxEvtHandler): | |
86 | def ProcessEvent(self, evt): | |
87 | print evt | |
88 | ||
d14a1e28 RD |
89 | class Frame(wxFrame): |
90 | def __init__(self, pos, size): | |
91 | wxFrame.__init__(self, None, -1, '', pos, size) | |
92 | global frame | |
93 | frame = g.frame = self | |
94 | bar = self.CreateStatusBar(2) | |
95 | bar.SetStatusWidths([-1, 40]) | |
96 | self.SetIcon(images.getIconIcon()) | |
97 | ||
98 | # Idle flag | |
99 | self.inIdle = False | |
100 | ||
64bce500 RR |
101 | # Load our own resources |
102 | self.res = wxXmlResource('') | |
103 | # !!! Blocking of assert failure occuring in older unicode builds | |
104 | try: | |
105 | self.res.Load(os.path.join(basePath, 'xrced.xrc')) | |
106 | except wx._core.PyAssertionError: | |
107 | print 'PyAssertionError was ignored' | |
108 | ||
d14a1e28 RD |
109 | # Make menus |
110 | menuBar = wxMenuBar() | |
111 | ||
112 | menu = wxMenu() | |
113 | menu.Append(wxID_NEW, '&New\tCtrl-N', 'New file') | |
80389ff7 | 114 | menu.AppendSeparator() |
d14a1e28 | 115 | menu.Append(wxID_OPEN, '&Open...\tCtrl-O', 'Open XRC file') |
80389ff7 RR |
116 | self.recentMenu = wxMenu() |
117 | self.AppendRecent(self.recentMenu) | |
118 | menu.AppendMenu(-1, 'Open Recent', self.recentMenu, 'Open a recent file') | |
119 | menu.AppendSeparator() | |
d14a1e28 RD |
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') | |
80389ff7 | 124 | |
d14a1e28 RD |
125 | menuBar.Append(menu, '&File') |
126 | ||
127 | menu = wxMenu() | |
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') | |
64bce500 | 136 | menu.AppendSeparator() |
fd919451 | 137 | self.ID_LOCATE = wxNewId() |
016f67ba RR |
138 | self.ID_TOOL_LOCATE = wxNewId() |
139 | self.ID_TOOL_PASTE = wxNewId() | |
fd919451 | 140 | menu.Append(self.ID_LOCATE, '&Locate\tCtrl-L', 'Locate control in test window and select it') |
d14a1e28 RD |
141 | menuBar.Append(menu, '&Edit') |
142 | ||
143 | menu = wxMenu() | |
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() | |
fd919451 | 153 | menu.Append(self.ID_TEST, '&Test\tF5', 'Show test window') |
d14a1e28 RD |
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) | |
64bce500 RR |
160 | self.ID_TEST_HIDE = wxNewId() |
161 | menu.Append(self.ID_TEST_HIDE, '&Hide\tCtrl-H', 'Close test window') | |
d14a1e28 RD |
162 | menuBar.Append(menu, '&View') |
163 | ||
164 | menu = wxMenu() | |
165 | menu.Append(wxID_ABOUT, '&About...', 'About XCRed') | |
166 | self.ID_README = wxNewId() | |
167 | menu.Append(self.ID_README, '&Readme...', 'View the README file') | |
168 | if debug: | |
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') | |
173 | ||
174 | self.menuBar = menuBar | |
175 | self.SetMenuBar(menuBar) | |
176 | ||
177 | # Create toolbar | |
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') | |
016f67ba | 189 | tb.AddSimpleTool(self.ID_TOOL_PASTE, images.getPasteBitmap(), 'Paste', 'Paste') |
d14a1e28 | 190 | tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL)) |
016f67ba | 191 | tb.AddCheckTool(self.ID_TOOL_LOCATE, |
64bce500 RR |
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)) | |
d14a1e28 RD |
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) | |
203 | tb.Realize() | |
64bce500 | 204 | |
d14a1e28 RD |
205 | self.tb = tb |
206 | self.minWidth = tb.GetSize()[0] # minimal width is the size of toolbar | |
207 | ||
208 | # File | |
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) | |
214 | # Edit | |
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) | |
016f67ba | 220 | EVT_MENU(self, self.ID_TOOL_PASTE, self.OnPaste) |
d14a1e28 | 221 | EVT_MENU(self, self.ID_DELETE, self.OnCutDelete) |
fd919451 | 222 | EVT_MENU(self, self.ID_LOCATE, self.OnLocate) |
016f67ba | 223 | EVT_MENU(self, self.ID_TOOL_LOCATE, self.OnLocate) |
d14a1e28 RD |
224 | # View |
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) | |
64bce500 | 230 | EVT_MENU(self, self.ID_TEST_HIDE, self.OnTestHide) |
d14a1e28 RD |
231 | # Help |
232 | EVT_MENU(self, wxID_ABOUT, self.OnAbout) | |
233 | EVT_MENU(self, self.ID_README, self.OnReadme) | |
234 | ||
235 | # Update events | |
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) | |
64bce500 | 239 | EVT_UPDATE_UI(self, self.ID_LOCATE, self.OnUpdateUI) |
016f67ba RR |
240 | EVT_UPDATE_UI(self, self.ID_TOOL_LOCATE, self.OnUpdateUI) |
241 | EVT_UPDATE_UI(self, self.ID_TOOL_PASTE, self.OnUpdateUI) | |
d14a1e28 RD |
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) | |
247 | ||
248 | # Build interface | |
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) | |
256 | # Create tree | |
257 | global tree | |
258 | g.tree = tree = XML_Tree(splitter, -1) | |
259 | ||
260 | # Init pull-down menu data | |
261 | global pullDownMenu | |
262 | g.pullDownMenu = pullDownMenu = PullDownMenu(self) | |
263 | ||
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) | |
268 | ||
269 | tree.RegisterKeyEvents() | |
270 | ||
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 | |
282 | global panel | |
283 | if conf.embedPanel: | |
284 | panel = Panel(splitter) | |
285 | # Set plitter windows | |
286 | splitter.SplitVertically(tree, panel, conf.sashPos) | |
287 | else: | |
288 | panel = Panel(miniFrame) | |
289 | sizer2.Add(panel, 1, wxEXPAND) | |
290 | miniFrame.Show(True) | |
291 | splitter.Initialize(tree) | |
292 | sizer1.Add(splitter, 1, wxEXPAND) | |
293 | sizer.Add(sizer1, 1, wxEXPAND) | |
294 | self.SetAutoLayout(True) | |
295 | self.SetSizer(sizer) | |
296 | ||
297 | # Initialize | |
298 | self.clipboard = None | |
299 | self.Clear() | |
300 | ||
301 | # Other events | |
302 | EVT_IDLE(self, self.OnIdle) | |
303 | EVT_CLOSE(self, self.OnCloseWindow) | |
d14a1e28 RD |
304 | EVT_KEY_DOWN(self, tools.OnKeyDown) |
305 | EVT_KEY_UP(self, tools.OnKeyUp) | |
80389ff7 RR |
306 | |
307 | def AppendRecent(self, menu): | |
308 | # add recently used files to the menu | |
309 | for id,name in conf.recentfiles.iteritems(): | |
310 | menu.Append(id,name) | |
311 | EVT_MENU(self,id,self.OnRecentFile) | |
312 | return | |
313 | ||
314 | def OnRecentFile(self,evt): | |
315 | # open recently used file | |
316 | if not self.AskSave(): return | |
317 | wxBeginBusyCursor() | |
318 | try: | |
319 | path=conf.recentfiles[evt.GetId()] | |
320 | if self.Open(path): | |
321 | self.SetStatusText('Data loaded') | |
322 | else: | |
323 | self.SetStatusText('Failed') | |
324 | except KeyError: | |
325 | self.SetStatusText('No such file') | |
326 | wxEndBusyCursor() | |
d14a1e28 RD |
327 | |
328 | def OnNew(self, evt): | |
329 | if not self.AskSave(): return | |
330 | self.Clear() | |
331 | ||
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: | |
337 | path = dlg.GetPath() | |
338 | self.SetStatusText('Loading...') | |
339 | wxYield() | |
340 | wxBeginBusyCursor() | |
016f67ba RR |
341 | try: |
342 | if self.Open(path): | |
343 | self.SetStatusText('Data loaded') | |
344 | else: | |
345 | self.SetStatusText('Failed') | |
346 | self.SaveRecent(path) | |
347 | finally: | |
348 | wxEndBusyCursor() | |
d14a1e28 RD |
349 | dlg.Destroy() |
350 | ||
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' | |
fd919451 RR |
355 | dirname = os.path.dirname(self.dataFile) |
356 | dlg = wxFileDialog(self, 'Save As', dirname, defaultName, '*.xrc', | |
d14a1e28 RD |
357 | wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR) |
358 | if dlg.ShowModal() == wxID_OK: | |
359 | path = dlg.GetPath() | |
360 | dlg.Destroy() | |
361 | else: | |
362 | dlg.Destroy() | |
363 | return | |
364 | else: | |
365 | path = self.dataFile | |
366 | self.SetStatusText('Saving...') | |
367 | wxYield() | |
368 | wxBeginBusyCursor() | |
369 | try: | |
016f67ba RR |
370 | try: |
371 | tmpFile,tmpName = tempfile.mkstemp(prefix='xrced-') | |
372 | os.close(tmpFile) | |
373 | self.Save(tmpName) # save temporary file first | |
374 | shutil.move(tmpName, path) | |
375 | self.dataFile = path | |
376 | self.SetStatusText('Data saved') | |
377 | self.SaveRecent(path) | |
378 | except IOError: | |
379 | self.SetStatusText('Failed') | |
380 | finally: | |
381 | wxEndBusyCursor() | |
80389ff7 RR |
382 | |
383 | def SaveRecent(self,path): | |
384 | # append to recently used files | |
385 | if path not in conf.recentfiles.values(): | |
386 | newid = wxNewId() | |
387 | self.recentMenu.Append(newid, path) | |
388 | EVT_MENU(self, newid, self.OnRecentFile) | |
389 | conf.recentfiles[newid] = path | |
d14a1e28 RD |
390 | |
391 | def OnExit(self, evt): | |
392 | self.Close() | |
393 | ||
394 | def OnUndo(self, evt): | |
395 | # Extra check to not mess with idle updating | |
396 | if undoMan.CanUndo(): | |
397 | undoMan.Undo() | |
398 | ||
399 | def OnRedo(self, evt): | |
400 | if undoMan.CanRedo(): | |
401 | undoMan.Redo() | |
402 | ||
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') | |
409 | ||
410 | def OnPaste(self, evt): | |
411 | selected = tree.selection | |
412 | if not selected: return # key pressed event | |
413 | # For pasting with Ctrl pressed | |
016f67ba | 414 | appendChild = True |
d14a1e28 | 415 | if evt.GetId() == pullDownMenu.ID_PASTE_SIBLING: appendChild = False |
016f67ba RR |
416 | elif evt.GetId() == self.ID_TOOL_PASTE: |
417 | if g.tree.ctrl: appendChild = False | |
418 | else: appendChild = not tree.NeedInsert(selected) | |
d14a1e28 RD |
419 | else: appendChild = not tree.NeedInsert(selected) |
420 | xxx = tree.GetPyData(selected) | |
421 | if not appendChild: | |
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 | |
a4c013b2 | 428 | nextItem = tree.GetFirstChild(selected)[0] |
d14a1e28 RD |
429 | parentLeaf = selected |
430 | else: | |
431 | # No children or unexpanded item - appendChild stays True | |
432 | nextItem = wxTreeItemId() # no next item | |
433 | parentLeaf = selected | |
434 | parent = tree.GetPyData(parentLeaf).treeObject() | |
435 | ||
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) | |
440 | ||
441 | # Check compatibility | |
442 | error = False | |
443 | # Top-level | |
444 | x = xxx.treeObject() | |
64bce500 | 445 | if x.__class__ in [xxxDialog, xxxFrame, xxxMenuBar, xxxWizard]: |
d14a1e28 RD |
446 | # Top-level classes |
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: | |
452 | pass | |
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 | |
467 | if error: | |
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)) | |
472 | return | |
473 | ||
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) | |
493 | elem = sizerItemElem | |
494 | elif isinstance(parent, xxxNotebook) and not isChildContainer: | |
495 | pageElem = MakeEmptyDOM('notebookpage') | |
496 | pageElem.appendChild(elem) | |
497 | elem = pageElem | |
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) | |
506 | tree.Refresh() | |
507 | # Update view? | |
508 | if g.testWin and tree.IsHighlatable(newItem): | |
509 | if conf.autoRefresh: | |
510 | tree.needUpdate = True | |
511 | tree.pendingHighLight = newItem | |
512 | else: | |
513 | tree.pendingHighLight = None | |
514 | self.modified = True | |
515 | self.SetStatusText('Pasted') | |
516 | ||
517 | def OnCutDelete(self, evt): | |
518 | selected = tree.selection | |
519 | if not selected: return # key pressed event | |
520 | # Undo info | |
521 | if evt.GetId() == wxID_CUT: | |
522 | self.lastOp = 'CUT' | |
523 | status = 'Removed to clipboard' | |
524 | else: | |
525 | self.lastOp = 'DELETE' | |
526 | status = 'Deleted' | |
527 | # Delete testWin? | |
528 | if g.testWin: | |
529 | # If deleting top-level item, delete testWin | |
530 | if selected == g.testWin.item: | |
531 | g.testWin.Destroy() | |
532 | g.testWin = None | |
533 | else: | |
534 | # Remove highlight, update testWin | |
535 | if g.testWin.highLight: | |
536 | g.testWin.highLight.Remove() | |
537 | tree.needUpdate = True | |
538 | # Prepare undo data | |
539 | panel.Apply() | |
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 | |
548 | tree.Unselect() | |
549 | panel.Clear() | |
550 | self.modified = True | |
551 | self.SetStatusText(status) | |
552 | ||
2481bf3c RR |
553 | def OnSubclass(self, evt): |
554 | selected = tree.selection | |
555 | xxx = tree.GetPyData(selected).treeObject() | |
556 | elem = xxx.element | |
557 | subclass = xxx.subclass | |
558 | dlg = wxTextEntryDialog(self, 'Subclass:', defaultValue=subclass) | |
559 | if dlg.ShowModal() == wxID_OK: | |
560 | subclass = dlg.GetValue() | |
561 | if subclass: | |
562 | elem.setAttribute('subclass', subclass) | |
563 | self.modified = True | |
564 | elif elem.hasAttribute('subclass'): | |
565 | elem.removeAttribute('subclass') | |
566 | self.modified = True | |
567 | xxx.subclass = elem.getAttribute('subclass') | |
568 | tree.SetItemText(selected, xxx.treeName()) | |
569 | panel.pages[0].box.SetLabel(xxx.panelName()) | |
570 | dlg.Destroy() | |
571 | ||
d14a1e28 RD |
572 | def OnEmbedPanel(self, evt): |
573 | conf.embedPanel = evt.IsChecked() | |
574 | if conf.embedPanel: | |
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) | |
80389ff7 | 582 | self.miniFrame.GetSizer().Remove(panel) |
d14a1e28 RD |
583 | wxYield() |
584 | # Widen | |
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) | |
588 | else: | |
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) | |
596 | panel.Show(True) | |
597 | sizer.Add(panel, 1, wxEXPAND) | |
598 | self.miniFrame.Show(True) | |
599 | self.miniFrame.SetDimensions(conf.panelX, conf.panelY, | |
600 | conf.panelWidth, conf.panelHeight) | |
601 | wxYield() | |
602 | # Reduce width | |
603 | self.SetDimensions(pos.x, pos.y, | |
604 | max(size.width - sizePanel.width, self.minWidth), size.height) | |
605 | ||
606 | def OnShowTools(self, evt): | |
607 | conf.showTools = evt.IsChecked() | |
608 | g.tools.Show(conf.showTools) | |
609 | if conf.showTools: | |
610 | self.toolsSizer.Prepend(g.tools, 0, wxEXPAND) | |
611 | else: | |
612 | self.toolsSizer.Remove(g.tools) | |
613 | self.toolsSizer.Layout() | |
614 | ||
615 | def OnTest(self, evt): | |
616 | if not tree.selection: return # key pressed event | |
617 | tree.ShowTestWindow(tree.selection) | |
618 | ||
64bce500 RR |
619 | def OnTestHide(self, evt): |
620 | tree.CloseTestWindow() | |
621 | ||
fd919451 RR |
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) | |
627 | if w == obj: | |
628 | return item | |
629 | if tree.ItemHasChildren(item): | |
630 | child = tree.GetFirstChild(item)[0] | |
631 | while child: | |
632 | found = self.FindObject(child, obj) | |
633 | if found: return found | |
634 | child = tree.GetNextSibling(child) | |
635 | return None | |
636 | ||
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()) | |
642 | if item: | |
643 | tree.SelectItem(item) | |
016f67ba | 644 | self.tb.ToggleTool(self.ID_TOOL_LOCATE, False) |
64bce500 RR |
645 | if item: |
646 | self.SetStatusText('Selected %s' % tree.GetItemText(item)) | |
647 | else: | |
648 | self.SetStatusText('Locate failed!') | |
fd919451 RR |
649 | |
650 | def SetHandler(self, w, h=None): | |
651 | if h: | |
652 | w.SetEventHandler(h) | |
653 | w.SetCursor(wxCROSS_CURSOR) | |
654 | else: | |
655 | w.SetEventHandler(w) | |
656 | w.SetCursor(wxNullCursor) | |
657 | for ch in w.GetChildren(): | |
658 | self.SetHandler(ch, h) | |
659 | ||
660 | def OnLocate(self, evt): | |
661 | if g.testWin: | |
64bce500 | 662 | if evt.GetId() == self.ID_LOCATE or \ |
016f67ba | 663 | evt.GetId() == self.ID_TOOL_LOCATE and evt.IsChecked(): |
64bce500 RR |
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: | |
016f67ba RR |
667 | self.tb.ToggleTool(self.ID_TOOL_LOCATE, True) |
668 | elif evt.GetId() == self.ID_TOOL_LOCATE and not evt.IsChecked(): | |
64bce500 RR |
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') | |
fd919451 | 672 | |
d14a1e28 RD |
673 | def OnRefresh(self, evt): |
674 | # If modified, apply first | |
675 | selection = tree.selection | |
676 | if selection: | |
677 | xxx = tree.GetPyData(selection) | |
678 | if xxx and panel.IsModified(): | |
679 | tree.Apply(xxx, selection) | |
680 | if g.testWin: | |
681 | # (re)create | |
682 | tree.CreateTestWin(g.testWin.item) | |
683 | panel.modified = False | |
684 | tree.needUpdate = False | |
685 | ||
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) | |
690 | ||
691 | def OnAbout(self, evt): | |
692 | str = '''\ | |
693 | XRCed version %s | |
694 | ||
695 | (c) Roman Rolinsky <rollrom@users.sourceforge.net> | |
696 | Homepage: http://xrced.sourceforge.net\ | |
697 | ''' % version | |
698 | dlg = wxMessageDialog(self, str, 'About XRCed', wxOK | wxCENTRE) | |
699 | dlg.ShowModal() | |
700 | dlg.Destroy() | |
701 | ||
702 | def OnReadme(self, evt): | |
703 | text = open(os.path.join(basePath, 'README.txt'), 'r').read() | |
704 | dlg = ScrolledMessageDialog(self, text, "XRCed README") | |
705 | dlg.ShowModal() | |
706 | dlg.Destroy() | |
707 | ||
708 | # Simple emulation of python command line | |
709 | def OnDebugCMD(self, evt): | |
710 | import traceback | |
711 | while 1: | |
712 | try: | |
713 | exec raw_input('C:\> ') | |
714 | except EOFError: | |
715 | print '^D' | |
716 | break | |
717 | except: | |
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)) | |
722 | print msg | |
723 | ||
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) | |
729 | if not appendChild: | |
730 | # If insert before | |
731 | if tree.shift: | |
732 | # If has previous item, insert after it, else append to parent | |
733 | nextItem = selected | |
734 | parentLeaf = tree.GetItemParent(selected) | |
735 | else: | |
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): | |
a4c013b2 | 742 | nextItem = tree.GetFirstChild(selected)[0] |
d14a1e28 RD |
743 | parentLeaf = selected |
744 | else: | |
745 | nextItem = wxTreeItemId() | |
746 | parentLeaf = selected | |
747 | parent = tree.GetPyData(parentLeaf) | |
748 | if parent.hasChild: parent = parent.child | |
749 | ||
750 | # Create element | |
751 | className = pullDownMenu.createMap[evt.GetId()] | |
752 | xxx = MakeEmptyXXX(parent, className) | |
753 | ||
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) | |
760 | ||
761 | # Insert new node, register undo | |
762 | elem = xxx.element | |
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) | |
769 | tree.Refresh() | |
770 | # Update view? | |
771 | if g.testWin and tree.IsHighlatable(newItem): | |
772 | if conf.autoRefresh: | |
773 | tree.needUpdate = True | |
774 | tree.pendingHighLight = newItem | |
775 | else: | |
776 | tree.pendingHighLight = None | |
777 | tree.SetFocus() | |
778 | self.modified = True | |
779 | ||
780 | # Replace one object with another | |
781 | def OnReplace(self, evt): | |
782 | selected = tree.selection | |
783 | xxx = tree.GetPyData(selected).treeObject() | |
784 | elem = xxx.element | |
785 | parent = elem.parentNode | |
786 | parentXXX = xxx.parent | |
787 | # New class | |
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[:] | |
796 | tags = [] | |
797 | for node in nodes: | |
64bce500 | 798 | if node.nodeType != minidom.Node.ELEMENT_NODE: continue |
d14a1e28 RD |
799 | remove = False |
800 | tag = node.tagName | |
801 | if tag == 'object': | |
802 | if not xxxClass.hasChildren: | |
803 | remove = True | |
804 | elif tag not in xxxClass.allParams and \ | |
805 | (not xxxClass.hasStyle or tag not in xxxClass.styles): | |
806 | remove = True | |
807 | else: | |
808 | tags.append(tag) | |
809 | if remove: | |
810 | elem.removeChild(node) | |
811 | node.unlink() | |
812 | ||
813 | # Copy parameters present in dummy but not in elem | |
814 | for node in dummy.childNodes: | |
815 | tag = node.tagName | |
816 | if tag not in tags: | |
817 | elem.appendChild(node.cloneNode(True)) | |
818 | dummy.unlink() | |
819 | # Change class name | |
820 | elem.setAttribute('class', className) | |
64bce500 RR |
821 | if elem.hasAttribute('subclass'): |
822 | elem.removeAttribute('subclass') # clear subclassing | |
d14a1e28 RD |
823 | # Re-create xxx element |
824 | xxx = MakeXXXFromDOM(parentXXX, elem) | |
825 | # Update parent in child objects | |
826 | if tree.ItemHasChildren(selected): | |
a4c013b2 | 827 | i, cookie = tree.GetFirstChild(selected) |
d14a1e28 RD |
828 | while i.IsOk(): |
829 | x = tree.GetPyData(i) | |
830 | x.parent = xxx | |
831 | if x.hasChild: x.child.parent = xxx | |
832 | i, cookie = tree.GetNextChild(selected, cookie) | |
833 | ||
834 | # Update tree | |
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 | |
840 | else: | |
841 | tree.SetPyData(selected, xxx) | |
842 | tree.SetItemText(selected, xxx.treeName()) | |
843 | tree.SetItemImage(selected, xxx.treeImage()) | |
844 | ||
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) | |
851 | ||
852 | # Update panel | |
853 | g.panel.SetData(xxx) | |
854 | # Update tools | |
855 | g.tools.UpdateUI() | |
856 | ||
857 | #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) | |
858 | # Update view? | |
859 | if g.testWin and tree.IsHighlatable(selected): | |
860 | if conf.autoRefresh: | |
861 | tree.needUpdate = True | |
862 | tree.pendingHighLight = selected | |
863 | else: | |
864 | tree.pendingHighLight = None | |
865 | tree.SetFocus() | |
866 | self.modified = True | |
867 | ||
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) | |
875 | ||
876 | def OnPullDownHighlight(self, evt): | |
877 | menuId = evt.GetMenuId() | |
878 | if menuId != -1: | |
879 | menu = evt.GetEventObject() | |
880 | help = menu.GetHelpString(menuId) | |
881 | self.SetStatusText(help) | |
882 | else: | |
883 | self.SetStatusText('') | |
884 | ||
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) | |
016f67ba | 888 | elif evt.GetId() in [wxID_PASTE, self.ID_TOOL_PASTE]: |
d14a1e28 RD |
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) | |
016f67ba | 892 | elif evt.GetId() in [self.ID_LOCATE, self.ID_TOOL_LOCATE]: |
64bce500 | 893 | evt.Enable(g.testWin is not None) |
d14a1e28 RD |
894 | elif evt.GetId() == wxID_UNDO: evt.Enable(undoMan.CanUndo()) |
895 | elif evt.GetId() == wxID_REDO: evt.Enable(undoMan.CanRedo()) | |
896 | ||
897 | def OnIdle(self, evt): | |
898 | if self.inIdle: return # Recursive call protection | |
899 | self.inIdle = True | |
900 | if tree.needUpdate: | |
901 | if conf.autoRefresh: | |
902 | if g.testWin: | |
903 | self.SetStatusText('Refreshing test window...') | |
904 | # (re)create | |
905 | tree.CreateTestWin(g.testWin.item) | |
906 | wxYield() | |
907 | self.SetStatusText('') | |
908 | tree.needUpdate = False | |
909 | elif tree.pendingHighLight: | |
910 | tree.HighLight(tree.pendingHighLight) | |
911 | else: | |
912 | evt.Skip() | |
913 | self.inIdle = False | |
914 | ||
915 | # We don't let close panel window | |
916 | def OnCloseMiniFrame(self, evt): | |
917 | return | |
918 | ||
919 | def OnCloseWindow(self, evt): | |
920 | if not self.AskSave(): return | |
921 | if g.testWin: g.testWin.Destroy() | |
d14a1e28 RD |
922 | if not panel.GetPageCount() == 2: |
923 | panel.page2.Destroy() | |
80389ff7 RR |
924 | else: |
925 | # If we don't do this, page does not get destroyed (a bug?) | |
926 | panel.RemovePage(1) | |
3429f8d0 RD |
927 | if not self.IsIconized(): |
928 | conf.x, conf.y = self.GetPosition() | |
929 | conf.width, conf.height = self.GetSize() | |
930 | if conf.embedPanel: | |
931 | conf.sashPos = self.splitter.GetSashPosition() | |
932 | else: | |
933 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
934 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
d14a1e28 RD |
935 | evt.Skip() |
936 | ||
937 | def Clear(self): | |
938 | self.dataFile = '' | |
939 | if self.clipboard: | |
940 | self.clipboard.unlink() | |
941 | self.clipboard = None | |
942 | undoMan.Clear() | |
943 | self.modified = False | |
944 | tree.Clear() | |
945 | panel.Clear() | |
946 | if g.testWin: | |
947 | g.testWin.Destroy() | |
948 | g.testWin = None | |
949 | self.SetTitle(progname) | |
950 | # Numbers for new controls | |
951 | self.maxIDs = {} | |
952 | self.maxIDs[xxxPanel] = self.maxIDs[xxxDialog] = self.maxIDs[xxxFrame] = \ | |
64bce500 RR |
953 | self.maxIDs[xxxMenuBar] = self.maxIDs[xxxMenu] = self.maxIDs[xxxToolBar] = \ |
954 | self.maxIDs[xxxWizard] = 0 | |
d14a1e28 RD |
955 | |
956 | def Open(self, path): | |
957 | if not os.path.exists(path): | |
958 | wxLogError('File does not exists: %s' % path) | |
959 | return False | |
960 | # Try to read the file | |
961 | try: | |
962 | f = open(path) | |
963 | self.Clear() | |
d14a1e28 | 964 | dom = minidom.parse(f) |
d14a1e28 | 965 | f.close() |
016f67ba RR |
966 | # Set encoding global variable and default encoding |
967 | if dom.encoding: | |
968 | g.currentEncoding = dom.encoding | |
969 | wx.SetDefaultPyEncoding(g.currentEncoding.encode()) | |
d14a1e28 | 970 | # Change dir |
fd919451 | 971 | self.dataFile = path = os.path.abspath(path) |
d14a1e28 RD |
972 | dir = os.path.dirname(path) |
973 | if dir: os.chdir(dir) | |
974 | tree.SetData(dom) | |
d14a1e28 RD |
975 | self.SetTitle(progname + ': ' + os.path.basename(path)) |
976 | except: | |
977 | # Nice exception printing | |
978 | inf = sys.exc_info() | |
979 | wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1]) | |
980 | wxLogError('Error reading file: %s' % path) | |
016f67ba | 981 | if debug: raise |
d14a1e28 RD |
982 | return False |
983 | return True | |
984 | ||
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 | |
989 | if indent: | |
990 | text = self.domCopy.createTextNode('\n' + ' ' * indent) | |
991 | node.parentNode.insertBefore(text, node) | |
992 | if children: | |
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 | |
998 | for n in children: | |
999 | if n.nodeType == minidom.Node.ELEMENT_NODE: | |
1000 | self.Indent(n, indent + 2) | |
1001 | ||
1002 | def Save(self, path): | |
1003 | try: | |
7353d818 | 1004 | import codecs |
d14a1e28 RD |
1005 | # Apply changes |
1006 | if tree.selection and panel.IsModified(): | |
1007 | self.OnRefresh(wxCommandEvent()) | |
016f67ba RR |
1008 | if g.currentEncoding: |
1009 | f = codecs.open(path, 'w', g.currentEncoding) | |
1010 | else: | |
1011 | f = codecs.open(path, 'w') | |
d14a1e28 RD |
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) | |
7353d818 | 1018 | self.domCopy.writexml(f, encoding = g.currentEncoding) |
d14a1e28 RD |
1019 | f.close() |
1020 | self.domCopy.unlink() | |
1021 | self.domCopy = None | |
1022 | self.modified = False | |
1023 | panel.SetModified(False) | |
1024 | except: | |
1025 | wxLogError('Error writing file: %s' % path) | |
1026 | raise | |
1027 | ||
1028 | def AskSave(self): | |
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() | |
1034 | dlg.Destroy() | |
1035 | if say == wxID_YES: | |
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) | |
1042 | return True | |
1043 | return False | |
1044 | ||
1045 | def SaveUndo(self): | |
1046 | pass # !!! | |
1047 | ||
1048 | ################################################################################ | |
1049 | ||
1050 | def usage(): | |
1051 | print >> sys.stderr, 'usage: xrced [-dhiv] [file]' | |
1052 | ||
1053 | class App(wxApp): | |
1054 | def OnInit(self): | |
1055 | global debug | |
1056 | # Process comand-line | |
364a2be0 | 1057 | opts = args = None |
d14a1e28 RD |
1058 | try: |
1059 | opts, args = getopt.getopt(sys.argv[1:], 'dhiv') | |
1c01bc8e RD |
1060 | for o,a in opts: |
1061 | if o == '-h': | |
1062 | usage() | |
1063 | sys.exit(0) | |
1064 | elif o == '-d': | |
1065 | debug = True | |
1066 | elif o == '-v': | |
1067 | print 'XRCed version', version | |
1068 | sys.exit(0) | |
1069 | ||
d14a1e28 RD |
1070 | except getopt.GetoptError: |
1071 | if wxPlatform != '__WXMAC__': # macs have some extra parameters | |
1072 | print >> sys.stderr, 'Unknown option' | |
1073 | usage() | |
1074 | sys.exit(1) | |
d14a1e28 RD |
1075 | |
1076 | self.SetAppName('xrced') | |
1077 | # Settings | |
1078 | global conf | |
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) | |
80389ff7 RR |
1086 | # read recently used files |
1087 | recentfiles=conf.Read('recentFiles','') | |
1088 | conf.recentfiles={} | |
1089 | if recentfiles: | |
1090 | for fil in recentfiles.split('|'): | |
1091 | conf.recentfiles[wxNewId()]=fil | |
d14a1e28 RD |
1092 | if not conf.embedPanel: |
1093 | conf.panelX = conf.ReadInt('panelX', -1) | |
1094 | conf.panelY = conf.ReadInt('panelY', -1) | |
1095 | else: | |
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') | |
1100 | # Add handlers | |
1101 | wxFileSystem_AddHandler(wxMemoryFSHandler()) | |
1102 | wxInitAllImageHandlers() | |
1103 | # Create main frame | |
1104 | frame = Frame(pos, size) | |
1105 | frame.Show(True) | |
d14a1e28 RD |
1106 | |
1107 | # Load file after showing | |
1108 | if args: | |
1109 | conf.panic = False | |
1110 | frame.open = frame.Open(args[0]) | |
1111 | ||
1112 | return True | |
1113 | ||
1114 | def OnExit(self): | |
1115 | # Write config | |
1116 | global conf | |
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) | |
80389ff7 | 1132 | wc.Write('recentFiles', '|'.join(conf.recentfiles.values()[-5:])) |
d14a1e28 RD |
1133 | wc.Flush() |
1134 | ||
1135 | def main(): | |
1136 | app = App(0, useBestVisual=False) | |
a4c013b2 | 1137 | #app.SetAssertMode(wxPYAPP_ASSERT_LOG) |
d14a1e28 RD |
1138 | app.MainLoop() |
1139 | app.OnExit() | |
1140 | global conf | |
1141 | del conf | |
1142 | ||
1143 | if __name__ == '__main__': | |
1144 | main() |