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