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 * |
af52e185 | 24 | import os, sys, getopt, re, traceback, tempfile, shutil, cPickle |
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 | 56 | xxxMenuBar:'MENUBAR', xxxMenu:'MENU', xxxToolBar:'TOOLBAR', |
306b6fe9 | 57 | xxxWizard:'WIZARD', xxxBitmap:'BITMAP', xxxIcon:'ICON'} |
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) | |
306b6fe9 RR |
210 | # if wxPlatform == '__WXGTK__': |
211 | # tb.AddSeparator() # otherwise auto-refresh sticks in status line | |
d14a1e28 RD |
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 | |
d14a1e28 RD |
309 | self.Clear() |
310 | ||
311 | # Other events | |
312 | EVT_IDLE(self, self.OnIdle) | |
313 | EVT_CLOSE(self, self.OnCloseWindow) | |
d14a1e28 RD |
314 | EVT_KEY_DOWN(self, tools.OnKeyDown) |
315 | EVT_KEY_UP(self, tools.OnKeyUp) | |
4483a6ed | 316 | EVT_ICONIZE(self, self.OnIconize) |
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...') | |
d14a1e28 | 350 | wxBeginBusyCursor() |
016f67ba RR |
351 | try: |
352 | if self.Open(path): | |
353 | self.SetStatusText('Data loaded') | |
354 | else: | |
355 | self.SetStatusText('Failed') | |
356 | self.SaveRecent(path) | |
357 | finally: | |
358 | wxEndBusyCursor() | |
d14a1e28 RD |
359 | dlg.Destroy() |
360 | ||
361 | def OnSaveOrSaveAs(self, evt): | |
362 | if evt.GetId() == wxID_SAVEAS or not self.dataFile: | |
6cb85701 RR |
363 | if self.dataFile: name = '' |
364 | else: name = defaultName | |
207ebbbd | 365 | dirname = os.path.abspath(os.path.dirname(self.dataFile)) |
6cb85701 | 366 | dlg = wxFileDialog(self, 'Save As', dirname, name, '*.xrc', |
d14a1e28 RD |
367 | wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR) |
368 | if dlg.ShowModal() == wxID_OK: | |
369 | path = dlg.GetPath() | |
370 | dlg.Destroy() | |
371 | else: | |
372 | dlg.Destroy() | |
373 | return | |
374 | else: | |
375 | path = self.dataFile | |
376 | self.SetStatusText('Saving...') | |
d14a1e28 RD |
377 | wxBeginBusyCursor() |
378 | try: | |
016f67ba RR |
379 | try: |
380 | tmpFile,tmpName = tempfile.mkstemp(prefix='xrced-') | |
381 | os.close(tmpFile) | |
382 | self.Save(tmpName) # save temporary file first | |
383 | shutil.move(tmpName, path) | |
384 | self.dataFile = path | |
385 | self.SetStatusText('Data saved') | |
386 | self.SaveRecent(path) | |
387 | except IOError: | |
388 | self.SetStatusText('Failed') | |
389 | finally: | |
390 | wxEndBusyCursor() | |
80389ff7 RR |
391 | |
392 | def SaveRecent(self,path): | |
393 | # append to recently used files | |
394 | if path not in conf.recentfiles.values(): | |
395 | newid = wxNewId() | |
396 | self.recentMenu.Append(newid, path) | |
397 | EVT_MENU(self, newid, self.OnRecentFile) | |
398 | conf.recentfiles[newid] = path | |
d14a1e28 RD |
399 | |
400 | def OnExit(self, evt): | |
401 | self.Close() | |
402 | ||
403 | def OnUndo(self, evt): | |
404 | # Extra check to not mess with idle updating | |
405 | if undoMan.CanUndo(): | |
406 | undoMan.Undo() | |
407 | ||
408 | def OnRedo(self, evt): | |
409 | if undoMan.CanRedo(): | |
410 | undoMan.Redo() | |
411 | ||
412 | def OnCopy(self, evt): | |
413 | selected = tree.selection | |
414 | if not selected: return # key pressed event | |
415 | xxx = tree.GetPyData(selected) | |
af52e185 RR |
416 | wx.TheClipboard.Open() |
417 | data = wx.CustomDataObject('XRCED') | |
1893848e | 418 | data.SetData(cPickle.dumps(xxx.element.toxml())) |
af52e185 RR |
419 | wx.TheClipboard.SetData(data) |
420 | wx.TheClipboard.Close() | |
d14a1e28 RD |
421 | self.SetStatusText('Copied') |
422 | ||
423 | def OnPaste(self, evt): | |
424 | selected = tree.selection | |
425 | if not selected: return # key pressed event | |
426 | # For pasting with Ctrl pressed | |
016f67ba | 427 | appendChild = True |
d14a1e28 | 428 | if evt.GetId() == pullDownMenu.ID_PASTE_SIBLING: appendChild = False |
016f67ba RR |
429 | elif evt.GetId() == self.ID_TOOL_PASTE: |
430 | if g.tree.ctrl: appendChild = False | |
431 | else: appendChild = not tree.NeedInsert(selected) | |
d14a1e28 RD |
432 | else: appendChild = not tree.NeedInsert(selected) |
433 | xxx = tree.GetPyData(selected) | |
434 | if not appendChild: | |
435 | # If has next item, insert, else append to parent | |
436 | nextItem = tree.GetNextSibling(selected) | |
437 | parentLeaf = tree.GetItemParent(selected) | |
438 | # Expanded container (must have children) | |
439 | elif tree.IsExpanded(selected) and tree.GetChildrenCount(selected, False): | |
440 | # Insert as first child | |
a4c013b2 | 441 | nextItem = tree.GetFirstChild(selected)[0] |
d14a1e28 RD |
442 | parentLeaf = selected |
443 | else: | |
444 | # No children or unexpanded item - appendChild stays True | |
445 | nextItem = wxTreeItemId() # no next item | |
446 | parentLeaf = selected | |
447 | parent = tree.GetPyData(parentLeaf).treeObject() | |
448 | ||
af52e185 RR |
449 | # Create a copy of clipboard pickled element |
450 | wx.TheClipboard.Open() | |
451 | data = wx.CustomDataObject('XRCED') | |
452 | if not wx.TheClipboard.IsSupported(data.GetFormat()): | |
453 | wx.TheClipboard.Close() | |
454 | wx.LogError('unsupported clipboard format') | |
455 | return | |
456 | wx.TheClipboard.GetData(data) | |
457 | wx.TheClipboard.Close() | |
1893848e RR |
458 | xml = cPickle.loads(data.GetData()) # xml representation of element |
459 | elem = minidom.parseString(xml).childNodes[0] | |
d14a1e28 RD |
460 | # Tempopary xxx object to test things |
461 | xxx = MakeXXXFromDOM(parent, elem) | |
d14a1e28 RD |
462 | # Check compatibility |
463 | error = False | |
464 | # Top-level | |
465 | x = xxx.treeObject() | |
6165053b | 466 | if x.__class__ in [xxxDialog, xxxFrame, xxxWizard]: |
d14a1e28 RD |
467 | # Top-level classes |
468 | if parent.__class__ != xxxMainNode: error = True | |
6165053b RR |
469 | elif x.__class__ == xxxMenuBar: |
470 | # Menubar can be put in frame or dialog | |
471 | if parent.__class__ not in [xxxMainNode, xxxFrame, xxxDialog]: error = True | |
d14a1e28 RD |
472 | elif x.__class__ == xxxToolBar: |
473 | # Toolbar can be top-level of child of panel or frame | |
207ebbbd RR |
474 | if parent.__class__ not in [xxxMainNode, xxxPanel, xxxFrame] and \ |
475 | not parent.isSizer: error = True | |
d14a1e28 RD |
476 | elif x.__class__ == xxxPanel and parent.__class__ == xxxMainNode: |
477 | pass | |
478 | elif x.__class__ == xxxSpacer: | |
479 | if not parent.isSizer: error = True | |
480 | elif x.__class__ == xxxSeparator: | |
481 | if not parent.__class__ in [xxxMenu, xxxToolBar]: error = True | |
482 | elif x.__class__ == xxxTool: | |
483 | if parent.__class__ != xxxToolBar: error = True | |
484 | elif x.__class__ == xxxMenu: | |
485 | if not parent.__class__ in [xxxMainNode, xxxMenuBar, xxxMenu]: error = True | |
486 | elif x.__class__ == xxxMenuItem: | |
487 | if not parent.__class__ in [xxxMenuBar, xxxMenu]: error = True | |
306b6fe9 RR |
488 | elif x.isSizer and parent.__class__ in [xxxNotebook, xxxChoicebook, xxxListbook]: |
489 | error = True | |
d14a1e28 RD |
490 | else: # normal controls can be almost anywhere |
491 | if parent.__class__ == xxxMainNode or \ | |
492 | parent.__class__ in [xxxMenuBar, xxxMenu]: error = True | |
493 | if error: | |
494 | if parent.__class__ == xxxMainNode: parentClass = 'root' | |
495 | else: parentClass = parent.className | |
496 | wxLogError('Incompatible parent/child: parent is %s, child is %s!' % | |
497 | (parentClass, x.className)) | |
498 | return | |
499 | ||
500 | # Check parent and child relationships. | |
501 | # If parent is sizer or notebook, child is of wrong class or | |
502 | # parent is normal window, child is child container then detach child. | |
503 | isChildContainer = isinstance(xxx, xxxChildContainer) | |
306b6fe9 | 504 | parentIsBook = parent.__class__ in [xxxNotebook, xxxChoicebook, xxxListbook] |
d14a1e28 RD |
505 | if isChildContainer and \ |
506 | ((parent.isSizer and not isinstance(xxx, xxxSizerItem)) or \ | |
306b6fe9 RR |
507 | (parentIsBook and not isinstance(xxx, xxxPage)) or \ |
508 | not (parent.isSizer or parentIsBook)): | |
d14a1e28 RD |
509 | elem.removeChild(xxx.child.element) # detach child |
510 | elem.unlink() # delete child container | |
511 | elem = xxx.child.element # replace | |
512 | # This may help garbage collection | |
513 | xxx.child.parent = None | |
514 | isChildContainer = False | |
515 | # Parent is sizer or notebook, child is not child container | |
516 | if parent.isSizer and not isChildContainer and not isinstance(xxx, xxxSpacer): | |
517 | # Create sizer item element | |
64b9ac75 | 518 | sizerItemElem = MakeEmptyDOM(parent.itemTag) |
d14a1e28 RD |
519 | sizerItemElem.appendChild(elem) |
520 | elem = sizerItemElem | |
521 | elif isinstance(parent, xxxNotebook) and not isChildContainer: | |
522 | pageElem = MakeEmptyDOM('notebookpage') | |
523 | pageElem.appendChild(elem) | |
524 | elem = pageElem | |
306b6fe9 RR |
525 | elif isinstance(parent, xxxChoicebook) and not isChildContainer: |
526 | pageElem = MakeEmptyDOM('choicebookpage') | |
527 | pageElem.appendChild(elem) | |
528 | elem = pageElem | |
529 | elif isinstance(parent, xxxListbook) and not isChildContainer: | |
530 | pageElem = MakeEmptyDOM('listbookpage') | |
531 | pageElem.appendChild(elem) | |
532 | elem = pageElem | |
d14a1e28 RD |
533 | # Insert new node, register undo |
534 | newItem = tree.InsertNode(parentLeaf, parent, elem, nextItem) | |
535 | undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) | |
536 | # Scroll to show new item (!!! redundant?) | |
537 | tree.EnsureVisible(newItem) | |
538 | tree.SelectItem(newItem) | |
539 | if not tree.IsVisible(newItem): | |
540 | tree.ScrollTo(newItem) | |
541 | tree.Refresh() | |
542 | # Update view? | |
543 | if g.testWin and tree.IsHighlatable(newItem): | |
544 | if conf.autoRefresh: | |
545 | tree.needUpdate = True | |
546 | tree.pendingHighLight = newItem | |
547 | else: | |
548 | tree.pendingHighLight = None | |
6cb85701 | 549 | self.SetModified() |
d14a1e28 RD |
550 | self.SetStatusText('Pasted') |
551 | ||
552 | def OnCutDelete(self, evt): | |
553 | selected = tree.selection | |
554 | if not selected: return # key pressed event | |
555 | # Undo info | |
556 | if evt.GetId() == wxID_CUT: | |
557 | self.lastOp = 'CUT' | |
558 | status = 'Removed to clipboard' | |
559 | else: | |
560 | self.lastOp = 'DELETE' | |
561 | status = 'Deleted' | |
562 | # Delete testWin? | |
563 | if g.testWin: | |
564 | # If deleting top-level item, delete testWin | |
565 | if selected == g.testWin.item: | |
566 | g.testWin.Destroy() | |
567 | g.testWin = None | |
568 | else: | |
569 | # Remove highlight, update testWin | |
570 | if g.testWin.highLight: | |
571 | g.testWin.highLight.Remove() | |
572 | tree.needUpdate = True | |
573 | # Prepare undo data | |
574 | panel.Apply() | |
575 | index = tree.ItemFullIndex(selected) | |
576 | parent = tree.GetPyData(tree.GetItemParent(selected)).treeObject() | |
577 | elem = tree.RemoveLeaf(selected) | |
578 | undoMan.RegisterUndo(UndoCutDelete(index, parent, elem)) | |
579 | if evt.GetId() == wxID_CUT: | |
af52e185 RR |
580 | wx.TheClipboard.Open() |
581 | data = wx.CustomDataObject('XRCED') | |
6165053b | 582 | data.SetData(cPickle.dumps(elem.toxml())) |
af52e185 RR |
583 | wx.TheClipboard.SetData(data) |
584 | wx.TheClipboard.Close() | |
d14a1e28 | 585 | tree.pendingHighLight = None |
6cb85701 RR |
586 | tree.UnselectAll() |
587 | tree.selection = None | |
588 | # Update tools | |
589 | g.tools.UpdateUI() | |
d14a1e28 | 590 | panel.Clear() |
6cb85701 | 591 | self.SetModified() |
d14a1e28 RD |
592 | self.SetStatusText(status) |
593 | ||
2481bf3c RR |
594 | def OnSubclass(self, evt): |
595 | selected = tree.selection | |
596 | xxx = tree.GetPyData(selected).treeObject() | |
597 | elem = xxx.element | |
598 | subclass = xxx.subclass | |
599 | dlg = wxTextEntryDialog(self, 'Subclass:', defaultValue=subclass) | |
600 | if dlg.ShowModal() == wxID_OK: | |
601 | subclass = dlg.GetValue() | |
602 | if subclass: | |
603 | elem.setAttribute('subclass', subclass) | |
2481bf3c RR |
604 | elif elem.hasAttribute('subclass'): |
605 | elem.removeAttribute('subclass') | |
6cb85701 | 606 | self.SetModified() |
2481bf3c RR |
607 | xxx.subclass = elem.getAttribute('subclass') |
608 | tree.SetItemText(selected, xxx.treeName()) | |
609 | panel.pages[0].box.SetLabel(xxx.panelName()) | |
610 | dlg.Destroy() | |
611 | ||
d14a1e28 RD |
612 | def OnEmbedPanel(self, evt): |
613 | conf.embedPanel = evt.IsChecked() | |
614 | if conf.embedPanel: | |
615 | # Remember last dimentions | |
616 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
617 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
618 | size = self.GetSize() | |
619 | pos = self.GetPosition() | |
620 | sizePanel = panel.GetSize() | |
621 | panel.Reparent(self.splitter) | |
80389ff7 | 622 | self.miniFrame.GetSizer().Remove(panel) |
d14a1e28 RD |
623 | # Widen |
624 | self.SetDimensions(pos.x, pos.y, size.width + sizePanel.width, size.height) | |
625 | self.splitter.SplitVertically(tree, panel, conf.sashPos) | |
626 | self.miniFrame.Show(False) | |
627 | else: | |
628 | conf.sashPos = self.splitter.GetSashPosition() | |
629 | pos = self.GetPosition() | |
630 | size = self.GetSize() | |
631 | sizePanel = panel.GetSize() | |
632 | self.splitter.Unsplit(panel) | |
633 | sizer = self.miniFrame.GetSizer() | |
634 | panel.Reparent(self.miniFrame) | |
635 | panel.Show(True) | |
636 | sizer.Add(panel, 1, wxEXPAND) | |
637 | self.miniFrame.Show(True) | |
638 | self.miniFrame.SetDimensions(conf.panelX, conf.panelY, | |
639 | conf.panelWidth, conf.panelHeight) | |
d14a1e28 RD |
640 | # Reduce width |
641 | self.SetDimensions(pos.x, pos.y, | |
642 | max(size.width - sizePanel.width, self.minWidth), size.height) | |
643 | ||
644 | def OnShowTools(self, evt): | |
645 | conf.showTools = evt.IsChecked() | |
646 | g.tools.Show(conf.showTools) | |
647 | if conf.showTools: | |
648 | self.toolsSizer.Prepend(g.tools, 0, wxEXPAND) | |
649 | else: | |
650 | self.toolsSizer.Remove(g.tools) | |
651 | self.toolsSizer.Layout() | |
652 | ||
653 | def OnTest(self, evt): | |
654 | if not tree.selection: return # key pressed event | |
655 | tree.ShowTestWindow(tree.selection) | |
656 | ||
64bce500 RR |
657 | def OnTestHide(self, evt): |
658 | tree.CloseTestWindow() | |
659 | ||
fd919451 RR |
660 | # Find object by relative position |
661 | def FindObject(self, item, obj): | |
662 | # We simply perform depth-first traversal, sinse it's too much | |
663 | # hassle to deal with all sizer/window combinations | |
664 | w = tree.FindNodeObject(item) | |
665 | if w == obj: | |
666 | return item | |
667 | if tree.ItemHasChildren(item): | |
668 | child = tree.GetFirstChild(item)[0] | |
669 | while child: | |
670 | found = self.FindObject(child, obj) | |
671 | if found: return found | |
672 | child = tree.GetNextSibling(child) | |
673 | return None | |
674 | ||
675 | def OnTestWinLeftDown(self, evt): | |
676 | pos = evt.GetPosition() | |
677 | self.SetHandler(g.testWin) | |
678 | g.testWin.Disconnect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN) | |
679 | item = self.FindObject(g.testWin.item, evt.GetEventObject()) | |
680 | if item: | |
681 | tree.SelectItem(item) | |
016f67ba | 682 | self.tb.ToggleTool(self.ID_TOOL_LOCATE, False) |
64bce500 RR |
683 | if item: |
684 | self.SetStatusText('Selected %s' % tree.GetItemText(item)) | |
685 | else: | |
686 | self.SetStatusText('Locate failed!') | |
fd919451 RR |
687 | |
688 | def SetHandler(self, w, h=None): | |
689 | if h: | |
690 | w.SetEventHandler(h) | |
691 | w.SetCursor(wxCROSS_CURSOR) | |
692 | else: | |
693 | w.SetEventHandler(w) | |
694 | w.SetCursor(wxNullCursor) | |
695 | for ch in w.GetChildren(): | |
696 | self.SetHandler(ch, h) | |
697 | ||
698 | def OnLocate(self, evt): | |
699 | if g.testWin: | |
64bce500 | 700 | if evt.GetId() == self.ID_LOCATE or \ |
016f67ba | 701 | evt.GetId() == self.ID_TOOL_LOCATE and evt.IsChecked(): |
64bce500 RR |
702 | self.SetHandler(g.testWin, g.testWin) |
703 | g.testWin.Connect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN, self.OnTestWinLeftDown) | |
704 | if evt.GetId() == self.ID_LOCATE: | |
016f67ba RR |
705 | self.tb.ToggleTool(self.ID_TOOL_LOCATE, True) |
706 | elif evt.GetId() == self.ID_TOOL_LOCATE and not evt.IsChecked(): | |
64bce500 RR |
707 | self.SetHandler(g.testWin, None) |
708 | g.testWin.Disconnect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN) | |
709 | self.SetStatusText('Click somewhere in your test window now') | |
fd919451 | 710 | |
d14a1e28 RD |
711 | def OnRefresh(self, evt): |
712 | # If modified, apply first | |
713 | selection = tree.selection | |
714 | if selection: | |
715 | xxx = tree.GetPyData(selection) | |
716 | if xxx and panel.IsModified(): | |
717 | tree.Apply(xxx, selection) | |
718 | if g.testWin: | |
719 | # (re)create | |
720 | tree.CreateTestWin(g.testWin.item) | |
721 | panel.modified = False | |
722 | tree.needUpdate = False | |
723 | ||
724 | def OnAutoRefresh(self, evt): | |
725 | conf.autoRefresh = evt.IsChecked() | |
726 | self.menuBar.Check(self.ID_AUTO_REFRESH, conf.autoRefresh) | |
727 | self.tb.ToggleTool(self.ID_AUTO_REFRESH, conf.autoRefresh) | |
728 | ||
729 | def OnAbout(self, evt): | |
730 | str = '''\ | |
731 | XRCed version %s | |
732 | ||
733 | (c) Roman Rolinsky <rollrom@users.sourceforge.net> | |
734 | Homepage: http://xrced.sourceforge.net\ | |
735 | ''' % version | |
736 | dlg = wxMessageDialog(self, str, 'About XRCed', wxOK | wxCENTRE) | |
737 | dlg.ShowModal() | |
738 | dlg.Destroy() | |
739 | ||
740 | def OnReadme(self, evt): | |
741 | text = open(os.path.join(basePath, 'README.txt'), 'r').read() | |
742 | dlg = ScrolledMessageDialog(self, text, "XRCed README") | |
743 | dlg.ShowModal() | |
744 | dlg.Destroy() | |
745 | ||
746 | # Simple emulation of python command line | |
747 | def OnDebugCMD(self, evt): | |
d14a1e28 RD |
748 | while 1: |
749 | try: | |
750 | exec raw_input('C:\> ') | |
751 | except EOFError: | |
752 | print '^D' | |
753 | break | |
754 | except: | |
755 | (etype, value, tb) =sys.exc_info() | |
756 | tblist =traceback.extract_tb(tb)[1:] | |
757 | msg =' '.join(traceback.format_exception_only(etype, value) | |
758 | +traceback.format_list(tblist)) | |
759 | print msg | |
760 | ||
761 | def OnCreate(self, evt): | |
762 | selected = tree.selection | |
763 | if tree.ctrl: appendChild = False | |
764 | else: appendChild = not tree.NeedInsert(selected) | |
765 | xxx = tree.GetPyData(selected) | |
766 | if not appendChild: | |
767 | # If insert before | |
768 | if tree.shift: | |
769 | # If has previous item, insert after it, else append to parent | |
770 | nextItem = selected | |
771 | parentLeaf = tree.GetItemParent(selected) | |
772 | else: | |
773 | # If has next item, insert, else append to parent | |
774 | nextItem = tree.GetNextSibling(selected) | |
775 | parentLeaf = tree.GetItemParent(selected) | |
776 | # Expanded container (must have children) | |
777 | elif tree.shift and tree.IsExpanded(selected) \ | |
778 | and tree.GetChildrenCount(selected, False): | |
a4c013b2 | 779 | nextItem = tree.GetFirstChild(selected)[0] |
d14a1e28 RD |
780 | parentLeaf = selected |
781 | else: | |
782 | nextItem = wxTreeItemId() | |
783 | parentLeaf = selected | |
784 | parent = tree.GetPyData(parentLeaf) | |
785 | if parent.hasChild: parent = parent.child | |
786 | ||
6cb85701 RR |
787 | # Create object_ref? |
788 | if evt.GetId() == ID_NEW.REF: | |
789 | ref = wxGetTextFromUser('Create reference to:', 'Create reference') | |
790 | if not ref: return | |
791 | xxx = MakeEmptyRefXXX(parent, ref) | |
792 | else: | |
793 | # Create empty element | |
794 | className = pullDownMenu.createMap[evt.GetId()] | |
795 | xxx = MakeEmptyXXX(parent, className) | |
d14a1e28 RD |
796 | |
797 | # Set default name for top-level windows | |
798 | if parent.__class__ == xxxMainNode: | |
799 | cl = xxx.treeObject().__class__ | |
800 | frame.maxIDs[cl] += 1 | |
64b9ac75 RR |
801 | xxx.setTreeName('%s%d' % (defaultIDs[cl], frame.maxIDs[cl])) |
802 | # And for some other standard controls | |
803 | elif parent.__class__ == xxxStdDialogButtonSizer: | |
804 | xxx.setTreeName(pullDownMenu.stdButtonIDs[evt.GetId()][0]) | |
805 | # We can even set label | |
806 | obj = xxx.treeObject() | |
807 | elem = g.tree.dom.createElement('label') | |
808 | elem.appendChild(g.tree.dom.createTextNode(pullDownMenu.stdButtonIDs[evt.GetId()][1])) | |
809 | obj.params['label'] = xxxParam(elem) | |
810 | xxx.treeObject().element.appendChild(elem) | |
d14a1e28 RD |
811 | |
812 | # Insert new node, register undo | |
813 | elem = xxx.element | |
814 | newItem = tree.InsertNode(parentLeaf, parent, elem, nextItem) | |
815 | undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) | |
816 | tree.EnsureVisible(newItem) | |
817 | tree.SelectItem(newItem) | |
818 | if not tree.IsVisible(newItem): | |
819 | tree.ScrollTo(newItem) | |
820 | tree.Refresh() | |
821 | # Update view? | |
822 | if g.testWin and tree.IsHighlatable(newItem): | |
823 | if conf.autoRefresh: | |
824 | tree.needUpdate = True | |
825 | tree.pendingHighLight = newItem | |
826 | else: | |
827 | tree.pendingHighLight = None | |
828 | tree.SetFocus() | |
6cb85701 RR |
829 | self.SetModified() |
830 | ||
d14a1e28 RD |
831 | # Replace one object with another |
832 | def OnReplace(self, evt): | |
833 | selected = tree.selection | |
834 | xxx = tree.GetPyData(selected).treeObject() | |
835 | elem = xxx.element | |
836 | parent = elem.parentNode | |
baba4aa5 | 837 | undoMan.RegisterUndo(UndoReplace(selected)) |
d14a1e28 RD |
838 | # New class |
839 | className = pullDownMenu.createMap[evt.GetId() - 1000] | |
840 | # Create temporary empty node (with default values) | |
841 | dummy = MakeEmptyDOM(className) | |
baba4aa5 RR |
842 | if className == 'spacer' and xxx.className != 'spacer': |
843 | klass = xxxSpacer | |
844 | elif xxx.className == 'spacer' and className != 'spacer': | |
845 | klass = xxxSizerItem | |
846 | else: | |
847 | klass = xxxDict[className] | |
d14a1e28 | 848 | # Remove non-compatible children |
baba4aa5 | 849 | if tree.ItemHasChildren(selected) and not klass.hasChildren: |
d14a1e28 RD |
850 | tree.DeleteChildren(selected) |
851 | nodes = elem.childNodes[:] | |
852 | tags = [] | |
853 | for node in nodes: | |
64bce500 | 854 | if node.nodeType != minidom.Node.ELEMENT_NODE: continue |
d14a1e28 RD |
855 | remove = False |
856 | tag = node.tagName | |
857 | if tag == 'object': | |
baba4aa5 RR |
858 | if not klass.hasChildren: remove = True |
859 | elif tag not in klass.allParams and \ | |
860 | (not klass.hasStyle or tag not in klass.styles): | |
d14a1e28 RD |
861 | remove = True |
862 | else: | |
863 | tags.append(tag) | |
864 | if remove: | |
865 | elem.removeChild(node) | |
866 | node.unlink() | |
867 | ||
baba4aa5 RR |
868 | # Remove sizeritem child if spacer |
869 | if className == 'spacer' and xxx.className != 'spacer': | |
870 | sizeritem = elem.parentNode | |
871 | assert sizeritem.getAttribute('class') == 'sizeritem' | |
872 | sizeritem.removeChild(elem) | |
873 | elem.unlink() | |
874 | elem = sizeritem | |
875 | tree.GetPyData(selected).hasChild = false | |
876 | elif xxx.className == 'spacer' and className != 'spacer': | |
877 | # Create sizeritem element | |
878 | assert xxx.parent.isSizer | |
879 | elem.setAttribute('class', 'sizeritem') | |
880 | node = MakeEmptyDOM(className) | |
881 | elem.appendChild(node) | |
882 | # Replace to point to new object | |
883 | xxx = xxxSizerItem(xxx.parent, elem) | |
884 | elem = node | |
885 | tree.SetPyData(selected, xxx) | |
886 | xxx = xxx.child | |
887 | else: | |
888 | # Copy parameters present in dummy but not in elem | |
889 | for node in dummy.childNodes: | |
890 | if node.tagName not in tags: elem.appendChild(node.cloneNode(True)) | |
d14a1e28 | 891 | dummy.unlink() |
baba4aa5 | 892 | |
d14a1e28 | 893 | # Change class name |
baba4aa5 | 894 | elem.setAttribute('class', className) |
64bce500 RR |
895 | if elem.hasAttribute('subclass'): |
896 | elem.removeAttribute('subclass') # clear subclassing | |
d14a1e28 | 897 | # Re-create xxx element |
baba4aa5 | 898 | xxx = MakeXXXFromDOM(xxx.parent, elem) |
d14a1e28 RD |
899 | # Update parent in child objects |
900 | if tree.ItemHasChildren(selected): | |
a4c013b2 | 901 | i, cookie = tree.GetFirstChild(selected) |
d14a1e28 RD |
902 | while i.IsOk(): |
903 | x = tree.GetPyData(i) | |
904 | x.parent = xxx | |
905 | if x.hasChild: x.child.parent = xxx | |
906 | i, cookie = tree.GetNextChild(selected, cookie) | |
baba4aa5 | 907 | |
d14a1e28 RD |
908 | # Update tree |
909 | if tree.GetPyData(selected).hasChild: # child container | |
910 | container = tree.GetPyData(selected) | |
911 | container.child = xxx | |
912 | container.hasChildren = xxx.hasChildren | |
913 | container.isSizer = xxx.isSizer | |
baba4aa5 | 914 | xxx = container |
d14a1e28 RD |
915 | else: |
916 | tree.SetPyData(selected, xxx) | |
917 | tree.SetItemText(selected, xxx.treeName()) | |
918 | tree.SetItemImage(selected, xxx.treeImage()) | |
919 | ||
920 | # Set default name for top-level windows | |
921 | if parent.__class__ == xxxMainNode: | |
922 | cl = xxx.treeObject().__class__ | |
923 | frame.maxIDs[cl] += 1 | |
64b9ac75 | 924 | xxx.setTreeName('%s%d' % (defaultIDs[cl], frame.maxIDs[cl])) |
d14a1e28 RD |
925 | |
926 | # Update panel | |
927 | g.panel.SetData(xxx) | |
928 | # Update tools | |
929 | g.tools.UpdateUI() | |
930 | ||
57c48fc4 | 931 | #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) |
d14a1e28 RD |
932 | # Update view? |
933 | if g.testWin and tree.IsHighlatable(selected): | |
934 | if conf.autoRefresh: | |
935 | tree.needUpdate = True | |
936 | tree.pendingHighLight = selected | |
937 | else: | |
938 | tree.pendingHighLight = None | |
939 | tree.SetFocus() | |
6cb85701 | 940 | self.SetModified() |
d14a1e28 RD |
941 | |
942 | # Expand/collapse subtree | |
943 | def OnExpand(self, evt): | |
944 | if tree.selection: tree.ExpandAll(tree.selection) | |
945 | else: tree.ExpandAll(tree.root) | |
946 | def OnCollapse(self, evt): | |
947 | if tree.selection: tree.CollapseAll(tree.selection) | |
948 | else: tree.CollapseAll(tree.root) | |
949 | ||
950 | def OnPullDownHighlight(self, evt): | |
951 | menuId = evt.GetMenuId() | |
952 | if menuId != -1: | |
953 | menu = evt.GetEventObject() | |
954 | help = menu.GetHelpString(menuId) | |
955 | self.SetStatusText(help) | |
956 | else: | |
957 | self.SetStatusText('') | |
958 | ||
959 | def OnUpdateUI(self, evt): | |
960 | if evt.GetId() in [wxID_CUT, wxID_COPY, self.ID_DELETE]: | |
961 | evt.Enable(tree.selection is not None and tree.selection != tree.root) | |
6cb85701 RR |
962 | elif evt.GetId() == wxID_SAVE: |
963 | evt.Enable(self.modified) | |
016f67ba | 964 | elif evt.GetId() in [wxID_PASTE, self.ID_TOOL_PASTE]: |
af52e185 | 965 | evt.Enable(tree.selection is not None) |
d14a1e28 RD |
966 | elif evt.GetId() == self.ID_TEST: |
967 | evt.Enable(tree.selection is not None and tree.selection != tree.root) | |
016f67ba | 968 | elif evt.GetId() in [self.ID_LOCATE, self.ID_TOOL_LOCATE]: |
64bce500 | 969 | evt.Enable(g.testWin is not None) |
d14a1e28 RD |
970 | elif evt.GetId() == wxID_UNDO: evt.Enable(undoMan.CanUndo()) |
971 | elif evt.GetId() == wxID_REDO: evt.Enable(undoMan.CanRedo()) | |
972 | ||
973 | def OnIdle(self, evt): | |
974 | if self.inIdle: return # Recursive call protection | |
975 | self.inIdle = True | |
306b6fe9 RR |
976 | try: |
977 | if tree.needUpdate: | |
978 | if conf.autoRefresh: | |
979 | if g.testWin: | |
980 | self.SetStatusText('Refreshing test window...') | |
981 | # (re)create | |
982 | tree.CreateTestWin(g.testWin.item) | |
983 | self.SetStatusText('') | |
984 | tree.needUpdate = False | |
985 | elif tree.pendingHighLight: | |
986 | try: | |
987 | tree.HighLight(tree.pendingHighLight) | |
988 | except: | |
989 | # Remove highlight if any problem | |
990 | if g.testWin.highLight: | |
991 | g.testWin.highLight.Remove() | |
992 | tree.pendingHighLight = None | |
993 | raise | |
994 | else: | |
995 | evt.Skip() | |
996 | finally: | |
997 | self.inIdle = False | |
d14a1e28 RD |
998 | |
999 | # We don't let close panel window | |
1000 | def OnCloseMiniFrame(self, evt): | |
1001 | return | |
1002 | ||
4483a6ed RR |
1003 | def OnIconize(self, evt): |
1004 | conf.x, conf.y = self.GetPosition() | |
1005 | conf.width, conf.height = self.GetSize() | |
1006 | if conf.embedPanel: | |
1007 | conf.sashPos = self.splitter.GetSashPosition() | |
1008 | else: | |
1009 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
1010 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
1011 | self.miniFrame.Iconize() | |
1012 | evt.Skip() | |
1013 | ||
d14a1e28 RD |
1014 | def OnCloseWindow(self, evt): |
1015 | if not self.AskSave(): return | |
1016 | if g.testWin: g.testWin.Destroy() | |
d14a1e28 RD |
1017 | if not panel.GetPageCount() == 2: |
1018 | panel.page2.Destroy() | |
80389ff7 RR |
1019 | else: |
1020 | # If we don't do this, page does not get destroyed (a bug?) | |
1021 | panel.RemovePage(1) | |
3429f8d0 RD |
1022 | if not self.IsIconized(): |
1023 | conf.x, conf.y = self.GetPosition() | |
1024 | conf.width, conf.height = self.GetSize() | |
1025 | if conf.embedPanel: | |
1026 | conf.sashPos = self.splitter.GetSashPosition() | |
1027 | else: | |
1028 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
1029 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
d14a1e28 RD |
1030 | evt.Skip() |
1031 | ||
1032 | def Clear(self): | |
1033 | self.dataFile = '' | |
d14a1e28 | 1034 | undoMan.Clear() |
6cb85701 | 1035 | self.SetModified(False) |
d14a1e28 RD |
1036 | tree.Clear() |
1037 | panel.Clear() | |
1038 | if g.testWin: | |
1039 | g.testWin.Destroy() | |
1040 | g.testWin = None | |
d14a1e28 RD |
1041 | # Numbers for new controls |
1042 | self.maxIDs = {} | |
306b6fe9 RR |
1043 | for cl in [xxxPanel, xxxDialog, xxxFrame, |
1044 | xxxMenuBar, xxxMenu, xxxToolBar, | |
1045 | xxxWizard, xxxBitmap, xxxIcon]: | |
1046 | self.maxIDs[cl] = 0 | |
d14a1e28 | 1047 | |
6cb85701 RR |
1048 | def SetModified(self, state=True): |
1049 | self.modified = state | |
1050 | name = os.path.basename(self.dataFile) | |
1051 | if not name: name = defaultName | |
1052 | if state: | |
1053 | self.SetTitle(progname + ': ' + name + ' *') | |
1054 | else: | |
1055 | self.SetTitle(progname + ': ' + name) | |
1056 | ||
d14a1e28 RD |
1057 | def Open(self, path): |
1058 | if not os.path.exists(path): | |
1059 | wxLogError('File does not exists: %s' % path) | |
1060 | return False | |
1061 | # Try to read the file | |
1062 | try: | |
1063 | f = open(path) | |
1064 | self.Clear() | |
d14a1e28 | 1065 | dom = minidom.parse(f) |
d14a1e28 | 1066 | f.close() |
016f67ba RR |
1067 | # Set encoding global variable and default encoding |
1068 | if dom.encoding: | |
1069 | g.currentEncoding = dom.encoding | |
1070 | wx.SetDefaultPyEncoding(g.currentEncoding.encode()) | |
9a69d0aa RR |
1071 | else: |
1072 | g.currentEncoding = '' | |
d14a1e28 | 1073 | # Change dir |
fd919451 | 1074 | self.dataFile = path = os.path.abspath(path) |
d14a1e28 RD |
1075 | dir = os.path.dirname(path) |
1076 | if dir: os.chdir(dir) | |
1077 | tree.SetData(dom) | |
d14a1e28 RD |
1078 | self.SetTitle(progname + ': ' + os.path.basename(path)) |
1079 | except: | |
1080 | # Nice exception printing | |
1081 | inf = sys.exc_info() | |
1082 | wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1]) | |
1083 | wxLogError('Error reading file: %s' % path) | |
016f67ba | 1084 | if debug: raise |
d14a1e28 RD |
1085 | return False |
1086 | return True | |
1087 | ||
1088 | def Indent(self, node, indent = 0): | |
1089 | # Copy child list because it will change soon | |
1090 | children = node.childNodes[:] | |
1091 | # Main node doesn't need to be indented | |
1092 | if indent: | |
1093 | text = self.domCopy.createTextNode('\n' + ' ' * indent) | |
1094 | node.parentNode.insertBefore(text, node) | |
1095 | if children: | |
1096 | # Append newline after last child, except for text nodes | |
1097 | if children[-1].nodeType == minidom.Node.ELEMENT_NODE: | |
1098 | text = self.domCopy.createTextNode('\n' + ' ' * indent) | |
1099 | node.appendChild(text) | |
1100 | # Indent children which are elements | |
1101 | for n in children: | |
1102 | if n.nodeType == minidom.Node.ELEMENT_NODE: | |
1103 | self.Indent(n, indent + 2) | |
1104 | ||
1105 | def Save(self, path): | |
1106 | try: | |
7353d818 | 1107 | import codecs |
d14a1e28 RD |
1108 | # Apply changes |
1109 | if tree.selection and panel.IsModified(): | |
1110 | self.OnRefresh(wxCommandEvent()) | |
016f67ba | 1111 | if g.currentEncoding: |
9a69d0aa | 1112 | f = codecs.open(path, 'wt', g.currentEncoding) |
016f67ba | 1113 | else: |
9a69d0aa | 1114 | f = codecs.open(path, 'wt') |
d14a1e28 RD |
1115 | # Make temporary copy for formatting it |
1116 | # !!! We can't clone dom node, it works only once | |
1117 | #self.domCopy = tree.dom.cloneNode(True) | |
1118 | self.domCopy = MyDocument() | |
1119 | mainNode = self.domCopy.appendChild(tree.mainNode.cloneNode(True)) | |
34b29ae7 RR |
1120 | # Remove first child (test element) |
1121 | testElem = mainNode.firstChild | |
1122 | mainNode.removeChild(testElem) | |
1123 | testElem.unlink() | |
d14a1e28 | 1124 | self.Indent(mainNode) |
7353d818 | 1125 | self.domCopy.writexml(f, encoding = g.currentEncoding) |
d14a1e28 RD |
1126 | f.close() |
1127 | self.domCopy.unlink() | |
1128 | self.domCopy = None | |
6cb85701 | 1129 | self.SetModified(False) |
d14a1e28 RD |
1130 | panel.SetModified(False) |
1131 | except: | |
4eb5bfc6 RD |
1132 | inf = sys.exc_info() |
1133 | wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1]) | |
d14a1e28 RD |
1134 | wxLogError('Error writing file: %s' % path) |
1135 | raise | |
1136 | ||
1137 | def AskSave(self): | |
1138 | if not (self.modified or panel.IsModified()): return True | |
1139 | flags = wxICON_EXCLAMATION | wxYES_NO | wxCANCEL | wxCENTRE | |
1140 | dlg = wxMessageDialog( self, 'File is modified. Save before exit?', | |
1141 | 'Save before too late?', flags ) | |
1142 | say = dlg.ShowModal() | |
1143 | dlg.Destroy() | |
1144 | if say == wxID_YES: | |
1145 | self.OnSaveOrSaveAs(wxCommandEvent(wxID_SAVE)) | |
1146 | # If save was successful, modified flag is unset | |
1147 | if not self.modified: return True | |
1148 | elif say == wxID_NO: | |
6cb85701 | 1149 | self.SetModified(False) |
d14a1e28 RD |
1150 | panel.SetModified(False) |
1151 | return True | |
1152 | return False | |
1153 | ||
1154 | def SaveUndo(self): | |
1155 | pass # !!! | |
1156 | ||
1157 | ################################################################################ | |
1158 | ||
1159 | def usage(): | |
1160 | print >> sys.stderr, 'usage: xrced [-dhiv] [file]' | |
1161 | ||
1162 | class App(wxApp): | |
1163 | def OnInit(self): | |
306b6fe9 RR |
1164 | # Check version |
1165 | if wxVERSION[:3] < MinWxVersion: | |
1166 | wxLogWarning('''\ | |
1167 | This version of XRCed may not work correctly on your version of wxWindows. \ | |
1168 | Please upgrade wxWindows to %d.%d.%d or higher.''' % MinWxVersion) | |
d14a1e28 RD |
1169 | global debug |
1170 | # Process comand-line | |
364a2be0 | 1171 | opts = args = None |
d14a1e28 RD |
1172 | try: |
1173 | opts, args = getopt.getopt(sys.argv[1:], 'dhiv') | |
1c01bc8e RD |
1174 | for o,a in opts: |
1175 | if o == '-h': | |
1176 | usage() | |
1177 | sys.exit(0) | |
1178 | elif o == '-d': | |
1179 | debug = True | |
1180 | elif o == '-v': | |
1181 | print 'XRCed version', version | |
1182 | sys.exit(0) | |
1183 | ||
d14a1e28 RD |
1184 | except getopt.GetoptError: |
1185 | if wxPlatform != '__WXMAC__': # macs have some extra parameters | |
1186 | print >> sys.stderr, 'Unknown option' | |
1187 | usage() | |
1188 | sys.exit(1) | |
d14a1e28 RD |
1189 | |
1190 | self.SetAppName('xrced') | |
1191 | # Settings | |
1192 | global conf | |
1193 | conf = g.conf = wxConfig(style = wxCONFIG_USE_LOCAL_FILE) | |
1194 | conf.autoRefresh = conf.ReadInt('autorefresh', True) | |
1195 | pos = conf.ReadInt('x', -1), conf.ReadInt('y', -1) | |
1196 | size = conf.ReadInt('width', 800), conf.ReadInt('height', 600) | |
1197 | conf.embedPanel = conf.ReadInt('embedPanel', True) | |
1198 | conf.showTools = conf.ReadInt('showTools', True) | |
1199 | conf.sashPos = conf.ReadInt('sashPos', 200) | |
80389ff7 RR |
1200 | # read recently used files |
1201 | recentfiles=conf.Read('recentFiles','') | |
1202 | conf.recentfiles={} | |
1203 | if recentfiles: | |
1204 | for fil in recentfiles.split('|'): | |
1205 | conf.recentfiles[wxNewId()]=fil | |
d14a1e28 RD |
1206 | if not conf.embedPanel: |
1207 | conf.panelX = conf.ReadInt('panelX', -1) | |
1208 | conf.panelY = conf.ReadInt('panelY', -1) | |
1209 | else: | |
1210 | conf.panelX = conf.panelY = -1 | |
1211 | conf.panelWidth = conf.ReadInt('panelWidth', 200) | |
1212 | conf.panelHeight = conf.ReadInt('panelHeight', 200) | |
1213 | conf.panic = not conf.HasEntry('nopanic') | |
1214 | # Add handlers | |
1215 | wxFileSystem_AddHandler(wxMemoryFSHandler()) | |
1216 | wxInitAllImageHandlers() | |
1217 | # Create main frame | |
1218 | frame = Frame(pos, size) | |
1219 | frame.Show(True) | |
d14a1e28 RD |
1220 | |
1221 | # Load file after showing | |
1222 | if args: | |
1223 | conf.panic = False | |
1224 | frame.open = frame.Open(args[0]) | |
1225 | ||
1226 | return True | |
1227 | ||
1228 | def OnExit(self): | |
1229 | # Write config | |
1230 | global conf | |
1231 | wc = wxConfigBase_Get() | |
1232 | wc.WriteInt('autorefresh', conf.autoRefresh) | |
1233 | wc.WriteInt('x', conf.x) | |
1234 | wc.WriteInt('y', conf.y) | |
1235 | wc.WriteInt('width', conf.width) | |
1236 | wc.WriteInt('height', conf.height) | |
1237 | wc.WriteInt('embedPanel', conf.embedPanel) | |
1238 | wc.WriteInt('showTools', conf.showTools) | |
1239 | if not conf.embedPanel: | |
1240 | wc.WriteInt('panelX', conf.panelX) | |
1241 | wc.WriteInt('panelY', conf.panelY) | |
1242 | wc.WriteInt('sashPos', conf.sashPos) | |
1243 | wc.WriteInt('panelWidth', conf.panelWidth) | |
1244 | wc.WriteInt('panelHeight', conf.panelHeight) | |
1245 | wc.WriteInt('nopanic', True) | |
80389ff7 | 1246 | wc.Write('recentFiles', '|'.join(conf.recentfiles.values()[-5:])) |
d14a1e28 RD |
1247 | wc.Flush() |
1248 | ||
1249 | def main(): | |
1250 | app = App(0, useBestVisual=False) | |
a4c013b2 | 1251 | #app.SetAssertMode(wxPYAPP_ASSERT_LOG) |
d14a1e28 RD |
1252 | app.MainLoop() |
1253 | app.OnExit() | |
1254 | global conf | |
1255 | del conf | |
1256 | ||
1257 | if __name__ == '__main__': | |
1258 | main() |