]>
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 | |
29a41103 | 9 | xrced -- Simple resource editor for XRC format used by wxWidgets/wxPython |
d14a1e28 RD |
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 |
28e65e0f | 25 | from xml.parsers import expat |
d14a1e28 RD |
26 | |
27 | # Local modules | |
28 | from tree import * # imports xxx which imports params | |
29 | from panel import * | |
30 | from tools import * | |
75aa1946 | 31 | from params import genericStyles |
d14a1e28 RD |
32 | # Cleanup recursive import sideeffects, otherwise we can't create undoMan |
33 | import undo | |
34 | undo.ParamPage = ParamPage | |
35 | undoMan = g.undoMan = UndoManager() | |
36 | ||
37 | # Set application path for loading resources | |
38 | if __name__ == '__main__': | |
39 | basePath = os.path.dirname(sys.argv[0]) | |
40 | else: | |
41 | basePath = os.path.dirname(__file__) | |
42 | ||
43 | # 1 adds CMD command to Help menu | |
44 | debug = 0 | |
45 | ||
46 | g.helpText = """\ | |
47 | <HTML><H2>Welcome to XRC<font color="blue">ed</font></H2><H3><font color="green">DON'T PANIC :)</font></H3> | |
48 | Read this note before clicking on anything!<P> | |
49 | To start select tree root, then popup menu with your right mouse button, | |
50 | select "Append Child", and then any command.<P> | |
51 | Or just press one of the buttons on the tools palette.<P> | |
52 | Enter XML ID, change properties, create children.<P> | |
53 | To test your interface select Test command (View menu).<P> | |
54 | Consult README file for the details.</HTML> | |
55 | """ | |
56 | ||
57 | defaultIDs = {xxxPanel:'PANEL', xxxDialog:'DIALOG', xxxFrame:'FRAME', | |
64bce500 | 58 | xxxMenuBar:'MENUBAR', xxxMenu:'MENU', xxxToolBar:'TOOLBAR', |
306b6fe9 | 59 | xxxWizard:'WIZARD', xxxBitmap:'BITMAP', xxxIcon:'ICON'} |
d14a1e28 | 60 | |
6cb85701 RR |
61 | defaultName = 'UNTITLED.xrc' |
62 | ||
d14a1e28 RD |
63 | ################################################################################ |
64 | ||
65 | # ScrolledMessageDialog - modified from wxPython lib to set fixed-width font | |
29a41103 RD |
66 | class ScrolledMessageDialog(wx.Dialog): |
67 | def __init__(self, parent, msg, caption, pos = wx.DefaultPosition, size = (500,300)): | |
68 | from wx.lib.layoutf import Layoutf | |
69 | wx.Dialog.__init__(self, parent, -1, caption, pos, size) | |
70 | text = wx.TextCtrl(self, -1, msg, wx.DefaultPosition, | |
71 | wx.DefaultSize, wx.TE_MULTILINE | wx.TE_READONLY) | |
289128a4 | 72 | text.SetFont(g.modernFont()) |
29a41103 | 73 | dc = wx.WindowDC(text) |
d14a1e28 | 74 | # !!! possible bug - GetTextExtent without font returns sysfont dims |
289128a4 | 75 | w, h = dc.GetFullTextExtent(' ', g.modernFont())[:2] |
29a41103 | 76 | ok = wx.Button(self, wx.ID_OK, "OK") |
d14a1e28 RD |
77 | text.SetConstraints(Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self,ok))) |
78 | text.SetSize((w * 80 + 30, h * 40)) | |
364a2be0 | 79 | text.ShowPosition(1) |
d14a1e28 RD |
80 | ok.SetConstraints(Layoutf('b=b5#1;x%w50#1;w!80;h!25', (self,))) |
81 | self.SetAutoLayout(True) | |
82 | self.Fit() | |
29a41103 | 83 | self.CenterOnScreen(wx.BOTH) |
d14a1e28 RD |
84 | |
85 | ################################################################################ | |
86 | ||
fd919451 | 87 | # Event handler for using during location |
29a41103 | 88 | class Locator(wx.EvtHandler): |
fd919451 RR |
89 | def ProcessEvent(self, evt): |
90 | print evt | |
91 | ||
29a41103 | 92 | class Frame(wx.Frame): |
d14a1e28 | 93 | def __init__(self, pos, size): |
29a41103 | 94 | wx.Frame.__init__(self, None, -1, '', pos, size) |
d14a1e28 RD |
95 | global frame |
96 | frame = g.frame = self | |
97 | bar = self.CreateStatusBar(2) | |
98 | bar.SetStatusWidths([-1, 40]) | |
99 | self.SetIcon(images.getIconIcon()) | |
100 | ||
101 | # Idle flag | |
102 | self.inIdle = False | |
103 | ||
64bce500 | 104 | # Load our own resources |
29a41103 | 105 | self.res = xrc.XmlResource('') |
d6922577 | 106 | # !!! Blocking of assert failure occurring in older unicode builds |
64bce500 | 107 | try: |
f65bb0f8 | 108 | quietlog = wx.LogNull() |
64bce500 RR |
109 | self.res.Load(os.path.join(basePath, 'xrced.xrc')) |
110 | except wx._core.PyAssertionError: | |
111 | print 'PyAssertionError was ignored' | |
112 | ||
d14a1e28 | 113 | # Make menus |
29a41103 | 114 | menuBar = wx.MenuBar() |
d14a1e28 | 115 | |
29a41103 RD |
116 | menu = wx.Menu() |
117 | menu.Append(wx.ID_NEW, '&New\tCtrl-N', 'New file') | |
80389ff7 | 118 | menu.AppendSeparator() |
29a41103 RD |
119 | menu.Append(wx.ID_OPEN, '&Open...\tCtrl-O', 'Open XRC file') |
120 | self.recentMenu = wx.Menu() | |
80389ff7 RR |
121 | self.AppendRecent(self.recentMenu) |
122 | menu.AppendMenu(-1, 'Open Recent', self.recentMenu, 'Open a recent file') | |
123 | menu.AppendSeparator() | |
29a41103 RD |
124 | menu.Append(wx.ID_SAVE, '&Save\tCtrl-S', 'Save XRC file') |
125 | menu.Append(wx.ID_SAVEAS, 'Save &As...', 'Save XRC file under different name') | |
126 | self.ID_GENERATE_PYTHON = wx.NewId() | |
73b2a9a7 RD |
127 | menu.Append(self.ID_GENERATE_PYTHON, '&Generate Python...', |
128 | 'Generate a Python module that uses this XRC') | |
d14a1e28 | 129 | menu.AppendSeparator() |
29a41103 | 130 | menu.Append(wx.ID_EXIT, '&Quit\tCtrl-Q', 'Exit application') |
80389ff7 | 131 | |
d14a1e28 RD |
132 | menuBar.Append(menu, '&File') |
133 | ||
29a41103 RD |
134 | menu = wx.Menu() |
135 | menu.Append(wx.ID_UNDO, '&Undo\tCtrl-Z', 'Undo') | |
136 | menu.Append(wx.ID_REDO, '&Redo\tCtrl-Y', 'Redo') | |
d14a1e28 | 137 | menu.AppendSeparator() |
29a41103 RD |
138 | menu.Append(wx.ID_CUT, 'Cut\tCtrl-X', 'Cut to the clipboard') |
139 | menu.Append(wx.ID_COPY, '&Copy\tCtrl-C', 'Copy to the clipboard') | |
140 | menu.Append(wx.ID_PASTE, '&Paste\tCtrl-V', 'Paste from the clipboard') | |
141 | self.ID_DELETE = wx.NewId() | |
d14a1e28 | 142 | menu.Append(self.ID_DELETE, '&Delete\tCtrl-D', 'Delete object') |
64bce500 | 143 | menu.AppendSeparator() |
29a41103 RD |
144 | self.ID_LOCATE = wx.NewId() |
145 | self.ID_TOOL_LOCATE = wx.NewId() | |
146 | self.ID_TOOL_PASTE = wx.NewId() | |
fd919451 | 147 | menu.Append(self.ID_LOCATE, '&Locate\tCtrl-L', 'Locate control in test window and select it') |
d14a1e28 RD |
148 | menuBar.Append(menu, '&Edit') |
149 | ||
29a41103 RD |
150 | menu = wx.Menu() |
151 | self.ID_EMBED_PANEL = wx.NewId() | |
d14a1e28 RD |
152 | menu.Append(self.ID_EMBED_PANEL, '&Embed Panel', |
153 | 'Toggle embedding properties panel in the main window', True) | |
154 | menu.Check(self.ID_EMBED_PANEL, conf.embedPanel) | |
29a41103 | 155 | self.ID_SHOW_TOOLS = wx.NewId() |
d14a1e28 RD |
156 | menu.Append(self.ID_SHOW_TOOLS, 'Show &Tools', 'Toggle tools', True) |
157 | menu.Check(self.ID_SHOW_TOOLS, conf.showTools) | |
158 | menu.AppendSeparator() | |
29a41103 | 159 | self.ID_TEST = wx.NewId() |
fd919451 | 160 | menu.Append(self.ID_TEST, '&Test\tF5', 'Show test window') |
29a41103 | 161 | self.ID_REFRESH = wx.NewId() |
d14a1e28 | 162 | menu.Append(self.ID_REFRESH, '&Refresh\tCtrl-R', 'Refresh test window') |
29a41103 | 163 | self.ID_AUTO_REFRESH = wx.NewId() |
d14a1e28 RD |
164 | menu.Append(self.ID_AUTO_REFRESH, '&Auto-refresh\tCtrl-A', |
165 | 'Toggle auto-refresh mode', True) | |
166 | menu.Check(self.ID_AUTO_REFRESH, conf.autoRefresh) | |
29a41103 | 167 | self.ID_TEST_HIDE = wx.NewId() |
64bce500 | 168 | menu.Append(self.ID_TEST_HIDE, '&Hide\tCtrl-H', 'Close test window') |
d14a1e28 RD |
169 | menuBar.Append(menu, '&View') |
170 | ||
75aa1946 RR |
171 | menu = wx.Menu() |
172 | self.ID_MOVEUP = wx.NewId() | |
173 | menu.Append(self.ID_MOVEUP, '&Up', 'Move before previous sibling') | |
174 | self.ID_MOVEDOWN = wx.NewId() | |
175 | menu.Append(self.ID_MOVEDOWN, '&Down', 'Move after next sibling') | |
176 | self.ID_MOVELEFT = wx.NewId() | |
177 | menu.Append(self.ID_MOVELEFT, '&Make sibling', 'Make sibling of parent') | |
178 | self.ID_MOVERIGHT = wx.NewId() | |
179 | menu.Append(self.ID_MOVERIGHT, '&Make child', 'Make child of previous sibling') | |
180 | menuBar.Append(menu, '&Move') | |
181 | ||
29a41103 RD |
182 | menu = wx.Menu() |
183 | menu.Append(wx.ID_ABOUT, '&About...', 'About XCRed') | |
184 | self.ID_README = wx.NewId() | |
d14a1e28 RD |
185 | menu.Append(self.ID_README, '&Readme...', 'View the README file') |
186 | if debug: | |
29a41103 | 187 | self.ID_DEBUG_CMD = wx.NewId() |
d14a1e28 | 188 | menu.Append(self.ID_DEBUG_CMD, 'CMD', 'Python command line') |
29a41103 | 189 | wx.EVT_MENU(self, self.ID_DEBUG_CMD, self.OnDebugCMD) |
d14a1e28 RD |
190 | menuBar.Append(menu, '&Help') |
191 | ||
192 | self.menuBar = menuBar | |
193 | self.SetMenuBar(menuBar) | |
194 | ||
195 | # Create toolbar | |
29a41103 | 196 | tb = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT) |
5c3a23e1 | 197 | tb.SetToolBitmapSize((24,24)) |
6ac94a48 | 198 | new_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_TOOLBAR) |
5c3a23e1 RD |
199 | open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR) |
200 | save_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR) | |
201 | undo_bmp = wx.ArtProvider.GetBitmap(wx.ART_UNDO, wx.ART_TOOLBAR) | |
202 | redo_bmp = wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_TOOLBAR) | |
203 | cut_bmp = wx.ArtProvider.GetBitmap(wx.ART_CUT, wx.ART_TOOLBAR) | |
204 | copy_bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_TOOLBAR) | |
205 | paste_bmp= wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_TOOLBAR) | |
6c75a4cf | 206 | |
29a41103 RD |
207 | tb.AddSimpleTool(wx.ID_NEW, new_bmp, 'New', 'New file') |
208 | tb.AddSimpleTool(wx.ID_OPEN, open_bmp, 'Open', 'Open file') | |
209 | tb.AddSimpleTool(wx.ID_SAVE, save_bmp, 'Save', 'Save file') | |
210 | tb.AddControl(wx.StaticLine(tb, -1, size=(-1,23), style=wx.LI_VERTICAL)) | |
211 | tb.AddSimpleTool(wx.ID_UNDO, undo_bmp, 'Undo', 'Undo') | |
212 | tb.AddSimpleTool(wx.ID_REDO, redo_bmp, 'Redo', 'Redo') | |
213 | tb.AddControl(wx.StaticLine(tb, -1, size=(-1,23), style=wx.LI_VERTICAL)) | |
214 | tb.AddSimpleTool(wx.ID_CUT, cut_bmp, 'Cut', 'Cut') | |
215 | tb.AddSimpleTool(wx.ID_COPY, copy_bmp, 'Copy', 'Copy') | |
6c75a4cf | 216 | tb.AddSimpleTool(self.ID_TOOL_PASTE, paste_bmp, 'Paste', 'Paste') |
29a41103 | 217 | tb.AddControl(wx.StaticLine(tb, -1, size=(-1,23), style=wx.LI_VERTICAL)) |
9a69d0aa RR |
218 | tb.AddSimpleTool(self.ID_TOOL_LOCATE, |
219 | images.getLocateBitmap(), #images.getLocateArmedBitmap(), | |
220 | 'Locate', 'Locate control in test window and select it', True) | |
29a41103 | 221 | tb.AddControl(wx.StaticLine(tb, -1, size=(-1,23), style=wx.LI_VERTICAL)) |
d14a1e28 RD |
222 | tb.AddSimpleTool(self.ID_TEST, images.getTestBitmap(), 'Test', 'Test window') |
223 | tb.AddSimpleTool(self.ID_REFRESH, images.getRefreshBitmap(), | |
224 | 'Refresh', 'Refresh view') | |
225 | tb.AddSimpleTool(self.ID_AUTO_REFRESH, images.getAutoRefreshBitmap(), | |
226 | 'Auto-refresh', 'Toggle auto-refresh mode', True) | |
75aa1946 RR |
227 | tb.AddControl(wx.StaticLine(tb, -1, size=(-1,23), style=wx.LI_VERTICAL)) |
228 | tb.AddSimpleTool(self.ID_MOVEUP, images.getToolMoveUpBitmap(), | |
229 | 'Up', 'Move before previous sibling') | |
230 | tb.AddSimpleTool(self.ID_MOVEDOWN, images.getToolMoveDownBitmap(), | |
231 | 'Down', 'Move after next sibling') | |
232 | tb.AddSimpleTool(self.ID_MOVELEFT, images.getToolMoveLeftBitmap(), | |
233 | 'Make Sibling', 'Make sibling of parent') | |
234 | tb.AddSimpleTool(self.ID_MOVERIGHT, images.getToolMoveRightBitmap(), | |
235 | 'Make Child', 'Make child of previous sibling') | |
29a41103 | 236 | # if wx.Platform == '__WXGTK__': |
306b6fe9 | 237 | # tb.AddSeparator() # otherwise auto-refresh sticks in status line |
d14a1e28 RD |
238 | tb.ToggleTool(self.ID_AUTO_REFRESH, conf.autoRefresh) |
239 | tb.Realize() | |
64bce500 | 240 | |
d14a1e28 RD |
241 | self.tb = tb |
242 | self.minWidth = tb.GetSize()[0] # minimal width is the size of toolbar | |
243 | ||
244 | # File | |
29a41103 RD |
245 | wx.EVT_MENU(self, wx.ID_NEW, self.OnNew) |
246 | wx.EVT_MENU(self, wx.ID_OPEN, self.OnOpen) | |
247 | wx.EVT_MENU(self, wx.ID_SAVE, self.OnSaveOrSaveAs) | |
248 | wx.EVT_MENU(self, wx.ID_SAVEAS, self.OnSaveOrSaveAs) | |
249 | wx.EVT_MENU(self, self.ID_GENERATE_PYTHON, self.OnGeneratePython) | |
250 | wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit) | |
d14a1e28 | 251 | # Edit |
29a41103 RD |
252 | wx.EVT_MENU(self, wx.ID_UNDO, self.OnUndo) |
253 | wx.EVT_MENU(self, wx.ID_REDO, self.OnRedo) | |
254 | wx.EVT_MENU(self, wx.ID_CUT, self.OnCutDelete) | |
255 | wx.EVT_MENU(self, wx.ID_COPY, self.OnCopy) | |
256 | wx.EVT_MENU(self, wx.ID_PASTE, self.OnPaste) | |
257 | wx.EVT_MENU(self, self.ID_TOOL_PASTE, self.OnPaste) | |
258 | wx.EVT_MENU(self, self.ID_DELETE, self.OnCutDelete) | |
259 | wx.EVT_MENU(self, self.ID_LOCATE, self.OnLocate) | |
260 | wx.EVT_MENU(self, self.ID_TOOL_LOCATE, self.OnLocate) | |
d14a1e28 | 261 | # View |
29a41103 RD |
262 | wx.EVT_MENU(self, self.ID_EMBED_PANEL, self.OnEmbedPanel) |
263 | wx.EVT_MENU(self, self.ID_SHOW_TOOLS, self.OnShowTools) | |
264 | wx.EVT_MENU(self, self.ID_TEST, self.OnTest) | |
265 | wx.EVT_MENU(self, self.ID_REFRESH, self.OnRefresh) | |
266 | wx.EVT_MENU(self, self.ID_AUTO_REFRESH, self.OnAutoRefresh) | |
267 | wx.EVT_MENU(self, self.ID_TEST_HIDE, self.OnTestHide) | |
75aa1946 RR |
268 | # Move |
269 | wx.EVT_MENU(self, self.ID_MOVEUP, self.OnMoveUp) | |
270 | wx.EVT_MENU(self, self.ID_MOVEDOWN, self.OnMoveDown) | |
271 | wx.EVT_MENU(self, self.ID_MOVELEFT, self.OnMoveLeft) | |
272 | wx.EVT_MENU(self, self.ID_MOVERIGHT, self.OnMoveRight) | |
d14a1e28 | 273 | # Help |
29a41103 RD |
274 | wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout) |
275 | wx.EVT_MENU(self, self.ID_README, self.OnReadme) | |
d14a1e28 RD |
276 | |
277 | # Update events | |
29a41103 RD |
278 | wx.EVT_UPDATE_UI(self, wx.ID_SAVE, self.OnUpdateUI) |
279 | wx.EVT_UPDATE_UI(self, wx.ID_CUT, self.OnUpdateUI) | |
280 | wx.EVT_UPDATE_UI(self, wx.ID_COPY, self.OnUpdateUI) | |
281 | wx.EVT_UPDATE_UI(self, wx.ID_PASTE, self.OnUpdateUI) | |
282 | wx.EVT_UPDATE_UI(self, self.ID_LOCATE, self.OnUpdateUI) | |
283 | wx.EVT_UPDATE_UI(self, self.ID_TOOL_LOCATE, self.OnUpdateUI) | |
284 | wx.EVT_UPDATE_UI(self, self.ID_TOOL_PASTE, self.OnUpdateUI) | |
285 | wx.EVT_UPDATE_UI(self, wx.ID_UNDO, self.OnUpdateUI) | |
286 | wx.EVT_UPDATE_UI(self, wx.ID_REDO, self.OnUpdateUI) | |
287 | wx.EVT_UPDATE_UI(self, self.ID_DELETE, self.OnUpdateUI) | |
288 | wx.EVT_UPDATE_UI(self, self.ID_TEST, self.OnUpdateUI) | |
289 | wx.EVT_UPDATE_UI(self, self.ID_REFRESH, self.OnUpdateUI) | |
d14a1e28 RD |
290 | |
291 | # Build interface | |
29a41103 RD |
292 | sizer = wx.BoxSizer(wx.VERTICAL) |
293 | sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND) | |
d14a1e28 | 294 | # Horizontal sizer for toolbar and splitter |
29a41103 RD |
295 | self.toolsSizer = sizer1 = wx.BoxSizer() |
296 | splitter = wx.SplitterWindow(self, -1, style=wx.SP_3DSASH) | |
d14a1e28 RD |
297 | self.splitter = splitter |
298 | splitter.SetMinimumPaneSize(100) | |
299 | # Create tree | |
300 | global tree | |
301 | g.tree = tree = XML_Tree(splitter, -1) | |
302 | ||
303 | # Init pull-down menu data | |
304 | global pullDownMenu | |
305 | g.pullDownMenu = pullDownMenu = PullDownMenu(self) | |
306 | ||
307 | # Vertical toolbar for GUI buttons | |
308 | g.tools = tools = Tools(self) | |
309 | tools.Show(conf.showTools) | |
29a41103 | 310 | if conf.showTools: sizer1.Add(tools, 0, wx.EXPAND) |
d14a1e28 RD |
311 | |
312 | tree.RegisterKeyEvents() | |
313 | ||
314 | # !!! frame styles are broken | |
315 | # Miniframe for not embedded mode | |
29a41103 | 316 | miniFrame = wx.Frame(self, -1, 'Properties & Style', |
d14a1e28 RD |
317 | (conf.panelX, conf.panelY), |
318 | (conf.panelWidth, conf.panelHeight)) | |
319 | self.miniFrame = miniFrame | |
29a41103 | 320 | sizer2 = wx.BoxSizer() |
d14a1e28 RD |
321 | miniFrame.SetAutoLayout(True) |
322 | miniFrame.SetSizer(sizer2) | |
29a41103 | 323 | wx.EVT_CLOSE(self.miniFrame, self.OnCloseMiniFrame) |
d14a1e28 RD |
324 | # Create panel for parameters |
325 | global panel | |
326 | if conf.embedPanel: | |
327 | panel = Panel(splitter) | |
328 | # Set plitter windows | |
329 | splitter.SplitVertically(tree, panel, conf.sashPos) | |
330 | else: | |
331 | panel = Panel(miniFrame) | |
29a41103 | 332 | sizer2.Add(panel, 1, wx.EXPAND) |
d14a1e28 RD |
333 | miniFrame.Show(True) |
334 | splitter.Initialize(tree) | |
29a41103 RD |
335 | sizer1.Add(splitter, 1, wx.EXPAND) |
336 | sizer.Add(sizer1, 1, wx.EXPAND) | |
d14a1e28 RD |
337 | self.SetAutoLayout(True) |
338 | self.SetSizer(sizer) | |
339 | ||
340 | # Initialize | |
d14a1e28 RD |
341 | self.Clear() |
342 | ||
343 | # Other events | |
29a41103 RD |
344 | wx.EVT_IDLE(self, self.OnIdle) |
345 | wx.EVT_CLOSE(self, self.OnCloseWindow) | |
346 | wx.EVT_KEY_DOWN(self, tools.OnKeyDown) | |
347 | wx.EVT_KEY_UP(self, tools.OnKeyUp) | |
348 | wx.EVT_ICONIZE(self, self.OnIconize) | |
80389ff7 RR |
349 | |
350 | def AppendRecent(self, menu): | |
351 | # add recently used files to the menu | |
352 | for id,name in conf.recentfiles.iteritems(): | |
353 | menu.Append(id,name) | |
29a41103 | 354 | wx.EVT_MENU(self,id,self.OnRecentFile) |
80389ff7 RR |
355 | return |
356 | ||
357 | def OnRecentFile(self,evt): | |
358 | # open recently used file | |
359 | if not self.AskSave(): return | |
29a41103 | 360 | wx.BeginBusyCursor() |
80389ff7 RR |
361 | try: |
362 | path=conf.recentfiles[evt.GetId()] | |
363 | if self.Open(path): | |
364 | self.SetStatusText('Data loaded') | |
365 | else: | |
366 | self.SetStatusText('Failed') | |
367 | except KeyError: | |
368 | self.SetStatusText('No such file') | |
29a41103 | 369 | wx.EndBusyCursor() |
d14a1e28 RD |
370 | |
371 | def OnNew(self, evt): | |
372 | if not self.AskSave(): return | |
373 | self.Clear() | |
374 | ||
375 | def OnOpen(self, evt): | |
376 | if not self.AskSave(): return | |
29a41103 RD |
377 | dlg = wx.FileDialog(self, 'Open', os.path.dirname(self.dataFile), |
378 | '', '*.xrc', wx.OPEN | wx.CHANGE_DIR) | |
379 | if dlg.ShowModal() == wx.ID_OK: | |
d14a1e28 RD |
380 | path = dlg.GetPath() |
381 | self.SetStatusText('Loading...') | |
29a41103 | 382 | wx.BeginBusyCursor() |
016f67ba RR |
383 | try: |
384 | if self.Open(path): | |
385 | self.SetStatusText('Data loaded') | |
386 | else: | |
387 | self.SetStatusText('Failed') | |
388 | self.SaveRecent(path) | |
389 | finally: | |
29a41103 | 390 | wx.EndBusyCursor() |
d14a1e28 RD |
391 | dlg.Destroy() |
392 | ||
393 | def OnSaveOrSaveAs(self, evt): | |
29a41103 | 394 | if evt.GetId() == wx.ID_SAVEAS or not self.dataFile: |
6cb85701 RR |
395 | if self.dataFile: name = '' |
396 | else: name = defaultName | |
207ebbbd | 397 | dirname = os.path.abspath(os.path.dirname(self.dataFile)) |
29a41103 RD |
398 | dlg = wx.FileDialog(self, 'Save As', dirname, name, '*.xrc', |
399 | wx.SAVE | wx.OVERWRITE_PROMPT | wx.CHANGE_DIR) | |
400 | if dlg.ShowModal() == wx.ID_OK: | |
d14a1e28 | 401 | path = dlg.GetPath() |
cc202d9b RD |
402 | if isinstance(path, unicode): |
403 | path = path.encode(sys.getfilesystemencoding()) | |
d14a1e28 RD |
404 | dlg.Destroy() |
405 | else: | |
406 | dlg.Destroy() | |
407 | return | |
73b2a9a7 RD |
408 | |
409 | if conf.localconf: | |
410 | # if we already have a localconf then it needs to be | |
411 | # copied to a new config with the new name | |
412 | lc = conf.localconf | |
413 | nc = self.CreateLocalConf(path) | |
414 | flag, key, idx = lc.GetFirstEntry() | |
415 | while flag: | |
416 | nc.Write(key, lc.Read(key)) | |
417 | flag, key, idx = lc.GetNextEntry(idx) | |
418 | conf.localconf = nc | |
419 | else: | |
420 | # otherwise create a new one | |
421 | conf.localconf = self.CreateLocalConf(path) | |
d14a1e28 RD |
422 | else: |
423 | path = self.dataFile | |
424 | self.SetStatusText('Saving...') | |
29a41103 | 425 | wx.BeginBusyCursor() |
d14a1e28 | 426 | try: |
016f67ba RR |
427 | try: |
428 | tmpFile,tmpName = tempfile.mkstemp(prefix='xrced-') | |
429 | os.close(tmpFile) | |
430 | self.Save(tmpName) # save temporary file first | |
431 | shutil.move(tmpName, path) | |
432 | self.dataFile = path | |
73b2a9a7 RD |
433 | if conf.localconf.ReadBool("autogenerate", False): |
434 | pypath = conf.localconf.Read("filename") | |
435 | embed = conf.localconf.ReadBool("embedResource", False) | |
7e05216c RD |
436 | genGettext = conf.localconf.ReadBool("genGettext", False) |
437 | self.GeneratePython(self.dataFile, pypath, embed, genGettext) | |
73b2a9a7 | 438 | |
016f67ba RR |
439 | self.SetStatusText('Data saved') |
440 | self.SaveRecent(path) | |
441 | except IOError: | |
442 | self.SetStatusText('Failed') | |
443 | finally: | |
29a41103 | 444 | wx.EndBusyCursor() |
80389ff7 RR |
445 | |
446 | def SaveRecent(self,path): | |
447 | # append to recently used files | |
448 | if path not in conf.recentfiles.values(): | |
29a41103 | 449 | newid = wx.NewId() |
80389ff7 | 450 | self.recentMenu.Append(newid, path) |
29a41103 | 451 | wx.EVT_MENU(self, newid, self.OnRecentFile) |
80389ff7 | 452 | conf.recentfiles[newid] = path |
d14a1e28 | 453 | |
7e05216c | 454 | def GeneratePython(self, dataFile, pypath, embed, genGettext): |
73b2a9a7 RD |
455 | try: |
456 | import wx.tools.pywxrc | |
457 | rescomp = wx.tools.pywxrc.XmlResourceCompiler() | |
0fe9c329 | 458 | rescomp.MakePythonModule([dataFile], pypath, embed, genGettext) |
73b2a9a7 RD |
459 | except: |
460 | inf = sys.exc_info() | |
29a41103 RD |
461 | wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1]) |
462 | wx.LogError('Error generating python code : %s' % pypath) | |
73b2a9a7 RD |
463 | raise |
464 | ||
465 | ||
466 | def OnGeneratePython(self, evt): | |
467 | if self.modified or not conf.localconf: | |
468 | wx.MessageBox("Save the XRC file first!", "Error") | |
469 | return | |
470 | ||
471 | dlg = PythonOptions(self, conf.localconf, self.dataFile) | |
472 | dlg.ShowModal() | |
473 | dlg.Destroy() | |
474 | ||
475 | ||
d14a1e28 RD |
476 | def OnExit(self, evt): |
477 | self.Close() | |
478 | ||
479 | def OnUndo(self, evt): | |
480 | # Extra check to not mess with idle updating | |
481 | if undoMan.CanUndo(): | |
482 | undoMan.Undo() | |
483 | ||
484 | def OnRedo(self, evt): | |
485 | if undoMan.CanRedo(): | |
486 | undoMan.Redo() | |
487 | ||
488 | def OnCopy(self, evt): | |
489 | selected = tree.selection | |
490 | if not selected: return # key pressed event | |
491 | xxx = tree.GetPyData(selected) | |
f65bb0f8 RD |
492 | if wx.TheClipboard.Open(): |
493 | data = wx.CustomDataObject('XRCED') | |
ebaaf8f6 RR |
494 | # Set encoding in header |
495 | # (False,True) | |
28e65e0f | 496 | s = xxx.element.toxml(encoding=expat.native_encoding) |
ebaaf8f6 | 497 | data.SetData(cPickle.dumps(s)) |
f65bb0f8 RD |
498 | wx.TheClipboard.SetData(data) |
499 | wx.TheClipboard.Close() | |
500 | self.SetStatusText('Copied') | |
501 | else: | |
502 | wx.MessageBox("Unable to open the clipboard", "Error") | |
d14a1e28 RD |
503 | |
504 | def OnPaste(self, evt): | |
505 | selected = tree.selection | |
506 | if not selected: return # key pressed event | |
507 | # For pasting with Ctrl pressed | |
016f67ba | 508 | appendChild = True |
d14a1e28 | 509 | if evt.GetId() == pullDownMenu.ID_PASTE_SIBLING: appendChild = False |
016f67ba RR |
510 | elif evt.GetId() == self.ID_TOOL_PASTE: |
511 | if g.tree.ctrl: appendChild = False | |
512 | else: appendChild = not tree.NeedInsert(selected) | |
d14a1e28 RD |
513 | else: appendChild = not tree.NeedInsert(selected) |
514 | xxx = tree.GetPyData(selected) | |
515 | if not appendChild: | |
516 | # If has next item, insert, else append to parent | |
517 | nextItem = tree.GetNextSibling(selected) | |
518 | parentLeaf = tree.GetItemParent(selected) | |
519 | # Expanded container (must have children) | |
520 | elif tree.IsExpanded(selected) and tree.GetChildrenCount(selected, False): | |
521 | # Insert as first child | |
a4c013b2 | 522 | nextItem = tree.GetFirstChild(selected)[0] |
d14a1e28 RD |
523 | parentLeaf = selected |
524 | else: | |
525 | # No children or unexpanded item - appendChild stays True | |
29a41103 | 526 | nextItem = wx.TreeItemId() # no next item |
d14a1e28 RD |
527 | parentLeaf = selected |
528 | parent = tree.GetPyData(parentLeaf).treeObject() | |
529 | ||
af52e185 | 530 | # Create a copy of clipboard pickled element |
f65bb0f8 RD |
531 | success = False |
532 | if wx.TheClipboard.Open(): | |
533 | data = wx.CustomDataObject('XRCED') | |
534 | if wx.TheClipboard.IsSupported(data.GetFormat()): | |
535 | success = wx.TheClipboard.GetData(data) | |
af52e185 | 536 | wx.TheClipboard.Close() |
f65bb0f8 RD |
537 | |
538 | if not success: | |
539 | wx.MessageBox( | |
540 | "There is no data in the clipboard in the required format", | |
541 | "Error") | |
af52e185 | 542 | return |
f65bb0f8 | 543 | |
1893848e RR |
544 | xml = cPickle.loads(data.GetData()) # xml representation of element |
545 | elem = minidom.parseString(xml).childNodes[0] | |
75aa1946 | 546 | |
d14a1e28 RD |
547 | # Tempopary xxx object to test things |
548 | xxx = MakeXXXFromDOM(parent, elem) | |
75aa1946 | 549 | |
d14a1e28 | 550 | # Check compatibility |
75aa1946 | 551 | if not self.ItemsAreCompatible(parent, xxx.treeObject()): return |
d14a1e28 RD |
552 | |
553 | # Check parent and child relationships. | |
554 | # If parent is sizer or notebook, child is of wrong class or | |
555 | # parent is normal window, child is child container then detach child. | |
556 | isChildContainer = isinstance(xxx, xxxChildContainer) | |
306b6fe9 | 557 | parentIsBook = parent.__class__ in [xxxNotebook, xxxChoicebook, xxxListbook] |
d14a1e28 RD |
558 | if isChildContainer and \ |
559 | ((parent.isSizer and not isinstance(xxx, xxxSizerItem)) or \ | |
306b6fe9 RR |
560 | (parentIsBook and not isinstance(xxx, xxxPage)) or \ |
561 | not (parent.isSizer or parentIsBook)): | |
d14a1e28 RD |
562 | elem.removeChild(xxx.child.element) # detach child |
563 | elem.unlink() # delete child container | |
564 | elem = xxx.child.element # replace | |
565 | # This may help garbage collection | |
566 | xxx.child.parent = None | |
567 | isChildContainer = False | |
568 | # Parent is sizer or notebook, child is not child container | |
569 | if parent.isSizer and not isChildContainer and not isinstance(xxx, xxxSpacer): | |
570 | # Create sizer item element | |
64b9ac75 | 571 | sizerItemElem = MakeEmptyDOM(parent.itemTag) |
d14a1e28 RD |
572 | sizerItemElem.appendChild(elem) |
573 | elem = sizerItemElem | |
574 | elif isinstance(parent, xxxNotebook) and not isChildContainer: | |
575 | pageElem = MakeEmptyDOM('notebookpage') | |
576 | pageElem.appendChild(elem) | |
577 | elem = pageElem | |
306b6fe9 RR |
578 | elif isinstance(parent, xxxChoicebook) and not isChildContainer: |
579 | pageElem = MakeEmptyDOM('choicebookpage') | |
580 | pageElem.appendChild(elem) | |
581 | elem = pageElem | |
582 | elif isinstance(parent, xxxListbook) and not isChildContainer: | |
583 | pageElem = MakeEmptyDOM('listbookpage') | |
584 | pageElem.appendChild(elem) | |
585 | elem = pageElem | |
d14a1e28 RD |
586 | # Insert new node, register undo |
587 | newItem = tree.InsertNode(parentLeaf, parent, elem, nextItem) | |
588 | undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) | |
589 | # Scroll to show new item (!!! redundant?) | |
590 | tree.EnsureVisible(newItem) | |
591 | tree.SelectItem(newItem) | |
592 | if not tree.IsVisible(newItem): | |
593 | tree.ScrollTo(newItem) | |
594 | tree.Refresh() | |
595 | # Update view? | |
596 | if g.testWin and tree.IsHighlatable(newItem): | |
597 | if conf.autoRefresh: | |
598 | tree.needUpdate = True | |
599 | tree.pendingHighLight = newItem | |
600 | else: | |
601 | tree.pendingHighLight = None | |
6cb85701 | 602 | self.SetModified() |
d14a1e28 RD |
603 | self.SetStatusText('Pasted') |
604 | ||
75aa1946 RR |
605 | |
606 | def ItemsAreCompatible(self, parent, child): | |
607 | # Check compatibility | |
608 | error = False | |
609 | # Top-level | |
610 | if child.__class__ in [xxxDialog, xxxFrame, xxxWizard]: | |
611 | # Top-level classes | |
612 | if parent.__class__ != xxxMainNode: error = True | |
613 | elif child.__class__ == xxxMenuBar: | |
614 | # Menubar can be put in frame or dialog | |
615 | if parent.__class__ not in [xxxMainNode, xxxFrame, xxxDialog]: error = True | |
616 | elif child.__class__ == xxxToolBar: | |
617 | # Toolbar can be top-level of child of panel or frame | |
618 | if parent.__class__ not in [xxxMainNode, xxxPanel, xxxFrame] and \ | |
619 | not parent.isSizer: error = True | |
620 | elif child.__class__ == xxxPanel and parent.__class__ == xxxMainNode: | |
621 | pass | |
622 | elif child.__class__ == xxxSpacer: | |
623 | if not parent.isSizer: error = True | |
624 | elif child.__class__ == xxxSeparator: | |
625 | if not parent.__class__ in [xxxMenu, xxxToolBar]: error = True | |
626 | elif child.__class__ == xxxTool: | |
627 | if parent.__class__ != xxxToolBar: error = True | |
628 | elif child.__class__ == xxxMenu: | |
629 | if not parent.__class__ in [xxxMainNode, xxxMenuBar, xxxMenu]: error = True | |
630 | elif child.__class__ == xxxMenuItem: | |
631 | if not parent.__class__ in [xxxMenuBar, xxxMenu]: error = True | |
632 | elif child.isSizer and parent.__class__ in [xxxNotebook, xxxChoicebook, xxxListbook]: | |
633 | error = True | |
634 | else: # normal controls can be almost anywhere | |
635 | if parent.__class__ == xxxMainNode or \ | |
636 | parent.__class__ in [xxxMenuBar, xxxMenu]: error = True | |
637 | if error: | |
638 | if parent.__class__ == xxxMainNode: parentClass = 'root' | |
639 | else: parentClass = parent.className | |
640 | wx.LogError('Incompatible parent/child: parent is %s, child is %s!' % | |
641 | (parentClass, child.className)) | |
642 | return False | |
643 | return True | |
644 | ||
645 | def OnMoveUp(self, evt): | |
646 | selected = tree.selection | |
647 | if not selected: return | |
648 | ||
649 | index = tree.ItemIndex(selected) | |
650 | if index == 0: return # No previous sibling found | |
651 | ||
652 | # Undo info | |
653 | self.lastOp = 'MOVEUP' | |
654 | status = 'Moved before previous sibling' | |
655 | ||
656 | # Prepare undo data | |
657 | panel.Apply() | |
658 | ||
659 | parent = tree.GetItemParent(selected) | |
660 | elem = tree.RemoveLeaf(selected) | |
661 | nextItem = tree.GetFirstChild(parent)[0] | |
662 | for i in range(index - 1): nextItem = tree.GetNextSibling(nextItem) | |
663 | selected = tree.InsertNode(parent, tree.GetPyData(parent).treeObject(), elem, nextItem) | |
664 | newIndex = tree.ItemIndex(selected) | |
665 | tree.SelectItem(selected) | |
666 | ||
667 | undoMan.RegisterUndo(UndoMove(parent, index, parent, newIndex)) | |
668 | ||
669 | self.modified = True | |
670 | self.SetStatusText(status) | |
671 | ||
672 | return | |
673 | ||
674 | def OnMoveDown(self, evt): | |
675 | selected = tree.selection | |
676 | if not selected: return | |
677 | ||
678 | index = tree.ItemIndex(selected) | |
679 | next = tree.GetNextSibling(selected) | |
680 | if not next: return | |
681 | ||
682 | # Undo info | |
683 | self.lastOp = 'MOVEDOWN' | |
684 | status = 'Moved after next sibling' | |
685 | ||
686 | # Prepare undo data | |
687 | panel.Apply() | |
688 | ||
689 | parent = tree.GetItemParent(selected) | |
690 | elem = tree.RemoveLeaf(selected) | |
691 | nextItem = tree.GetFirstChild(parent)[0] | |
692 | for i in range(index + 1): nextItem = tree.GetNextSibling(nextItem) | |
693 | selected = tree.InsertNode(parent, tree.GetPyData(parent).treeObject(), elem, nextItem) | |
694 | newIndex = tree.ItemIndex(selected) | |
695 | tree.SelectItem(selected) | |
696 | ||
697 | undoMan.RegisterUndo(UndoMove(parent, index, parent, newIndex)) | |
698 | ||
699 | self.modified = True | |
700 | self.SetStatusText(status) | |
701 | ||
702 | return | |
703 | ||
704 | def OnMoveLeft(self, evt): | |
705 | selected = tree.selection | |
706 | if not selected: return | |
707 | ||
708 | oldParent = tree.GetItemParent(selected) | |
709 | if not oldParent: return | |
710 | pparent = tree.GetItemParent(oldParent) | |
711 | if not pparent: return | |
712 | ||
713 | # Check compatibility | |
714 | if not self.ItemsAreCompatible(tree.GetPyData(pparent).treeObject(), tree.GetPyData(selected).treeObject()): return | |
715 | ||
716 | # Undo info | |
717 | self.lastOp = 'MOVELEFT' | |
718 | status = 'Made next sibling of parent' | |
719 | ||
720 | oldIndex = tree.ItemIndex(selected) | |
721 | elem = tree.RemoveLeaf(selected) | |
722 | nextItem = tree.GetFirstChild(pparent)[0] | |
723 | parentIndex = tree.ItemIndex(oldParent) | |
724 | for i in range(parentIndex + 1): nextItem = tree.GetNextSibling(nextItem) | |
725 | ||
726 | # Check parent and child relationships. | |
727 | # If parent is sizer or notebook, child is of wrong class or | |
728 | # parent is normal window, child is child container then detach child. | |
729 | parent = tree.GetPyData(pparent).treeObject() | |
730 | xxx = MakeXXXFromDOM(parent, elem) | |
731 | isChildContainer = isinstance(xxx, xxxChildContainer) | |
732 | if isChildContainer and \ | |
733 | ((parent.isSizer and not isinstance(xxx, xxxSizerItem)) or \ | |
734 | (isinstance(parent, xxxNotebook) and not isinstance(xxx, xxxNotebookPage)) or \ | |
735 | not (parent.isSizer or isinstance(parent, xxxNotebook))): | |
736 | elem.removeChild(xxx.child.element) # detach child | |
737 | elem.unlink() # delete child container | |
738 | elem = xxx.child.element # replace | |
739 | # This may help garbage collection | |
740 | xxx.child.parent = None | |
741 | isChildContainer = False | |
742 | # Parent is sizer or notebook, child is not child container | |
743 | if parent.isSizer and not isChildContainer and not isinstance(xxx, xxxSpacer): | |
744 | # Create sizer item element | |
745 | sizerItemElem = MakeEmptyDOM('sizeritem') | |
746 | sizerItemElem.appendChild(elem) | |
747 | elem = sizerItemElem | |
748 | elif isinstance(parent, xxxNotebook) and not isChildContainer: | |
749 | pageElem = MakeEmptyDOM('notebookpage') | |
750 | pageElem.appendChild(elem) | |
751 | elem = pageElem | |
752 | ||
753 | selected = tree.InsertNode(pparent, tree.GetPyData(pparent).treeObject(), elem, nextItem) | |
754 | newIndex = tree.ItemIndex(selected) | |
755 | tree.SelectItem(selected) | |
756 | ||
757 | undoMan.RegisterUndo(UndoMove(oldParent, oldIndex, pparent, newIndex)) | |
758 | ||
759 | self.modified = True | |
760 | self.SetStatusText(status) | |
761 | ||
762 | def OnMoveRight(self, evt): | |
763 | selected = tree.selection | |
764 | if not selected: return | |
765 | ||
766 | oldParent = tree.GetItemParent(selected) | |
767 | if not oldParent: return | |
768 | ||
769 | newParent = tree.GetPrevSibling(selected) | |
770 | if not newParent: return | |
771 | ||
772 | parent = tree.GetPyData(newParent).treeObject() | |
773 | ||
774 | # Check compatibility | |
775 | if not self.ItemsAreCompatible(parent, tree.GetPyData(selected).treeObject()): return | |
776 | ||
777 | # Undo info | |
778 | self.lastOp = 'MOVERIGHT' | |
779 | status = 'Made last child of previous sibling' | |
780 | ||
781 | oldIndex = tree.ItemIndex(selected) | |
782 | elem = tree.RemoveLeaf(selected) | |
783 | ||
784 | # Check parent and child relationships. | |
785 | # If parent is sizer or notebook, child is of wrong class or | |
786 | # parent is normal window, child is child container then detach child. | |
787 | xxx = MakeXXXFromDOM(parent, elem) | |
788 | isChildContainer = isinstance(xxx, xxxChildContainer) | |
789 | if isChildContainer and \ | |
790 | ((parent.isSizer and not isinstance(xxx, xxxSizerItem)) or \ | |
791 | (isinstance(parent, xxxNotebook) and not isinstance(xxx, xxxNotebookPage)) or \ | |
792 | not (parent.isSizer or isinstance(parent, xxxNotebook))): | |
793 | elem.removeChild(xxx.child.element) # detach child | |
794 | elem.unlink() # delete child container | |
795 | elem = xxx.child.element # replace | |
796 | # This may help garbage collection | |
797 | xxx.child.parent = None | |
798 | isChildContainer = False | |
799 | # Parent is sizer or notebook, child is not child container | |
800 | if parent.isSizer and not isChildContainer and not isinstance(xxx, xxxSpacer): | |
801 | # Create sizer item element | |
802 | sizerItemElem = MakeEmptyDOM('sizeritem') | |
803 | sizerItemElem.appendChild(elem) | |
804 | elem = sizerItemElem | |
805 | elif isinstance(parent, xxxNotebook) and not isChildContainer: | |
806 | pageElem = MakeEmptyDOM('notebookpage') | |
807 | pageElem.appendChild(elem) | |
808 | elem = pageElem | |
809 | ||
810 | selected = tree.InsertNode(newParent, tree.GetPyData(newParent).treeObject(), elem, wx.TreeItemId()) | |
811 | ||
812 | newIndex = tree.ItemIndex(selected) | |
813 | tree.SelectItem(selected) | |
814 | ||
815 | undoMan.RegisterUndo(UndoMove(oldParent, oldIndex, newParent, newIndex)) | |
816 | ||
817 | self.modified = True | |
818 | self.SetStatusText(status) | |
819 | ||
f65bb0f8 | 820 | |
d14a1e28 RD |
821 | def OnCutDelete(self, evt): |
822 | selected = tree.selection | |
823 | if not selected: return # key pressed event | |
824 | # Undo info | |
29a41103 | 825 | if evt.GetId() == wx.ID_CUT: |
d14a1e28 RD |
826 | self.lastOp = 'CUT' |
827 | status = 'Removed to clipboard' | |
828 | else: | |
829 | self.lastOp = 'DELETE' | |
830 | status = 'Deleted' | |
831 | # Delete testWin? | |
832 | if g.testWin: | |
833 | # If deleting top-level item, delete testWin | |
834 | if selected == g.testWin.item: | |
835 | g.testWin.Destroy() | |
836 | g.testWin = None | |
837 | else: | |
838 | # Remove highlight, update testWin | |
839 | if g.testWin.highLight: | |
840 | g.testWin.highLight.Remove() | |
841 | tree.needUpdate = True | |
842 | # Prepare undo data | |
843 | panel.Apply() | |
844 | index = tree.ItemFullIndex(selected) | |
845 | parent = tree.GetPyData(tree.GetItemParent(selected)).treeObject() | |
846 | elem = tree.RemoveLeaf(selected) | |
847 | undoMan.RegisterUndo(UndoCutDelete(index, parent, elem)) | |
29a41103 | 848 | if evt.GetId() == wx.ID_CUT: |
f65bb0f8 RD |
849 | if wx.TheClipboard.Open(): |
850 | data = wx.CustomDataObject('XRCED') | |
ebaaf8f6 | 851 | # (False, True) |
28e65e0f | 852 | s = elem.toxml(encoding=expat.native_encoding) |
ebaaf8f6 | 853 | data.SetData(cPickle.dumps(s)) |
f65bb0f8 RD |
854 | wx.TheClipboard.SetData(data) |
855 | wx.TheClipboard.Close() | |
856 | else: | |
857 | wx.MessageBox("Unable to open the clipboard", "Error") | |
d14a1e28 | 858 | tree.pendingHighLight = None |
6cb85701 RR |
859 | tree.UnselectAll() |
860 | tree.selection = None | |
861 | # Update tools | |
862 | g.tools.UpdateUI() | |
d14a1e28 | 863 | panel.Clear() |
6cb85701 | 864 | self.SetModified() |
d14a1e28 RD |
865 | self.SetStatusText(status) |
866 | ||
2481bf3c RR |
867 | def OnSubclass(self, evt): |
868 | selected = tree.selection | |
869 | xxx = tree.GetPyData(selected).treeObject() | |
870 | elem = xxx.element | |
871 | subclass = xxx.subclass | |
29a41103 RD |
872 | dlg = wx.TextEntryDialog(self, 'Subclass:', defaultValue=subclass) |
873 | if dlg.ShowModal() == wx.ID_OK: | |
2481bf3c RR |
874 | subclass = dlg.GetValue() |
875 | if subclass: | |
876 | elem.setAttribute('subclass', subclass) | |
2481bf3c RR |
877 | elif elem.hasAttribute('subclass'): |
878 | elem.removeAttribute('subclass') | |
6cb85701 | 879 | self.SetModified() |
2481bf3c RR |
880 | xxx.subclass = elem.getAttribute('subclass') |
881 | tree.SetItemText(selected, xxx.treeName()) | |
882 | panel.pages[0].box.SetLabel(xxx.panelName()) | |
883 | dlg.Destroy() | |
884 | ||
d14a1e28 RD |
885 | def OnEmbedPanel(self, evt): |
886 | conf.embedPanel = evt.IsChecked() | |
887 | if conf.embedPanel: | |
888 | # Remember last dimentions | |
889 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
890 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
891 | size = self.GetSize() | |
892 | pos = self.GetPosition() | |
893 | sizePanel = panel.GetSize() | |
894 | panel.Reparent(self.splitter) | |
80389ff7 | 895 | self.miniFrame.GetSizer().Remove(panel) |
d14a1e28 RD |
896 | # Widen |
897 | self.SetDimensions(pos.x, pos.y, size.width + sizePanel.width, size.height) | |
898 | self.splitter.SplitVertically(tree, panel, conf.sashPos) | |
899 | self.miniFrame.Show(False) | |
900 | else: | |
901 | conf.sashPos = self.splitter.GetSashPosition() | |
902 | pos = self.GetPosition() | |
903 | size = self.GetSize() | |
904 | sizePanel = panel.GetSize() | |
905 | self.splitter.Unsplit(panel) | |
906 | sizer = self.miniFrame.GetSizer() | |
907 | panel.Reparent(self.miniFrame) | |
908 | panel.Show(True) | |
29a41103 | 909 | sizer.Add(panel, 1, wx.EXPAND) |
d14a1e28 RD |
910 | self.miniFrame.Show(True) |
911 | self.miniFrame.SetDimensions(conf.panelX, conf.panelY, | |
912 | conf.panelWidth, conf.panelHeight) | |
d14a1e28 RD |
913 | # Reduce width |
914 | self.SetDimensions(pos.x, pos.y, | |
915 | max(size.width - sizePanel.width, self.minWidth), size.height) | |
916 | ||
917 | def OnShowTools(self, evt): | |
918 | conf.showTools = evt.IsChecked() | |
919 | g.tools.Show(conf.showTools) | |
920 | if conf.showTools: | |
29a41103 | 921 | self.toolsSizer.Prepend(g.tools, 0, wx.EXPAND) |
d14a1e28 RD |
922 | else: |
923 | self.toolsSizer.Remove(g.tools) | |
924 | self.toolsSizer.Layout() | |
925 | ||
926 | def OnTest(self, evt): | |
927 | if not tree.selection: return # key pressed event | |
928 | tree.ShowTestWindow(tree.selection) | |
929 | ||
64bce500 RR |
930 | def OnTestHide(self, evt): |
931 | tree.CloseTestWindow() | |
932 | ||
fd919451 RR |
933 | # Find object by relative position |
934 | def FindObject(self, item, obj): | |
935 | # We simply perform depth-first traversal, sinse it's too much | |
936 | # hassle to deal with all sizer/window combinations | |
937 | w = tree.FindNodeObject(item) | |
29a41103 | 938 | if w == obj or isinstance(w, wx.GBSizerItem) and w.GetWindow() == obj: |
fd919451 RR |
939 | return item |
940 | if tree.ItemHasChildren(item): | |
941 | child = tree.GetFirstChild(item)[0] | |
942 | while child: | |
943 | found = self.FindObject(child, obj) | |
944 | if found: return found | |
945 | child = tree.GetNextSibling(child) | |
946 | return None | |
947 | ||
948 | def OnTestWinLeftDown(self, evt): | |
949 | pos = evt.GetPosition() | |
950 | self.SetHandler(g.testWin) | |
29a41103 | 951 | g.testWin.Disconnect(wx.ID_ANY, wx.ID_ANY, wx.wxEVT_LEFT_DOWN) |
fd919451 RR |
952 | item = self.FindObject(g.testWin.item, evt.GetEventObject()) |
953 | if item: | |
20002db0 | 954 | tree.EnsureVisible(item) |
fd919451 | 955 | tree.SelectItem(item) |
016f67ba | 956 | self.tb.ToggleTool(self.ID_TOOL_LOCATE, False) |
64bce500 RR |
957 | if item: |
958 | self.SetStatusText('Selected %s' % tree.GetItemText(item)) | |
959 | else: | |
960 | self.SetStatusText('Locate failed!') | |
fd919451 RR |
961 | |
962 | def SetHandler(self, w, h=None): | |
963 | if h: | |
964 | w.SetEventHandler(h) | |
29a41103 | 965 | w.SetCursor(wx.CROSS_CURSOR) |
fd919451 RR |
966 | else: |
967 | w.SetEventHandler(w) | |
29a41103 | 968 | w.SetCursor(wx.NullCursor) |
fd919451 RR |
969 | for ch in w.GetChildren(): |
970 | self.SetHandler(ch, h) | |
971 | ||
972 | def OnLocate(self, evt): | |
973 | if g.testWin: | |
64bce500 | 974 | if evt.GetId() == self.ID_LOCATE or \ |
016f67ba | 975 | evt.GetId() == self.ID_TOOL_LOCATE and evt.IsChecked(): |
64bce500 | 976 | self.SetHandler(g.testWin, g.testWin) |
29a41103 | 977 | g.testWin.Connect(wx.ID_ANY, wx.ID_ANY, wx.wxEVT_LEFT_DOWN, self.OnTestWinLeftDown) |
64bce500 | 978 | if evt.GetId() == self.ID_LOCATE: |
016f67ba RR |
979 | self.tb.ToggleTool(self.ID_TOOL_LOCATE, True) |
980 | elif evt.GetId() == self.ID_TOOL_LOCATE and not evt.IsChecked(): | |
64bce500 | 981 | self.SetHandler(g.testWin, None) |
29a41103 | 982 | g.testWin.Disconnect(wx.ID_ANY, wx.ID_ANY, wx.wxEVT_LEFT_DOWN) |
64bce500 | 983 | self.SetStatusText('Click somewhere in your test window now') |
fd919451 | 984 | |
d14a1e28 RD |
985 | def OnRefresh(self, evt): |
986 | # If modified, apply first | |
987 | selection = tree.selection | |
988 | if selection: | |
989 | xxx = tree.GetPyData(selection) | |
990 | if xxx and panel.IsModified(): | |
991 | tree.Apply(xxx, selection) | |
992 | if g.testWin: | |
993 | # (re)create | |
994 | tree.CreateTestWin(g.testWin.item) | |
995 | panel.modified = False | |
996 | tree.needUpdate = False | |
997 | ||
998 | def OnAutoRefresh(self, evt): | |
999 | conf.autoRefresh = evt.IsChecked() | |
1000 | self.menuBar.Check(self.ID_AUTO_REFRESH, conf.autoRefresh) | |
1001 | self.tb.ToggleTool(self.ID_AUTO_REFRESH, conf.autoRefresh) | |
1002 | ||
1003 | def OnAbout(self, evt): | |
1004 | str = '''\ | |
1005 | XRCed version %s | |
1006 | ||
1007 | (c) Roman Rolinsky <rollrom@users.sourceforge.net> | |
1008 | Homepage: http://xrced.sourceforge.net\ | |
1009 | ''' % version | |
29a41103 | 1010 | dlg = wx.MessageDialog(self, str, 'About XRCed', wx.OK | wx.CENTRE) |
d14a1e28 RD |
1011 | dlg.ShowModal() |
1012 | dlg.Destroy() | |
1013 | ||
1014 | def OnReadme(self, evt): | |
1015 | text = open(os.path.join(basePath, 'README.txt'), 'r').read() | |
1016 | dlg = ScrolledMessageDialog(self, text, "XRCed README") | |
1017 | dlg.ShowModal() | |
1018 | dlg.Destroy() | |
1019 | ||
1020 | # Simple emulation of python command line | |
1021 | def OnDebugCMD(self, evt): | |
d14a1e28 RD |
1022 | while 1: |
1023 | try: | |
1024 | exec raw_input('C:\> ') | |
1025 | except EOFError: | |
1026 | print '^D' | |
1027 | break | |
1028 | except: | |
1029 | (etype, value, tb) =sys.exc_info() | |
1030 | tblist =traceback.extract_tb(tb)[1:] | |
1031 | msg =' '.join(traceback.format_exception_only(etype, value) | |
1032 | +traceback.format_list(tblist)) | |
1033 | print msg | |
1034 | ||
1035 | def OnCreate(self, evt): | |
1036 | selected = tree.selection | |
1037 | if tree.ctrl: appendChild = False | |
1038 | else: appendChild = not tree.NeedInsert(selected) | |
1039 | xxx = tree.GetPyData(selected) | |
1040 | if not appendChild: | |
1041 | # If insert before | |
1042 | if tree.shift: | |
1043 | # If has previous item, insert after it, else append to parent | |
1044 | nextItem = selected | |
1045 | parentLeaf = tree.GetItemParent(selected) | |
1046 | else: | |
1047 | # If has next item, insert, else append to parent | |
1048 | nextItem = tree.GetNextSibling(selected) | |
1049 | parentLeaf = tree.GetItemParent(selected) | |
1050 | # Expanded container (must have children) | |
1051 | elif tree.shift and tree.IsExpanded(selected) \ | |
1052 | and tree.GetChildrenCount(selected, False): | |
a4c013b2 | 1053 | nextItem = tree.GetFirstChild(selected)[0] |
d14a1e28 RD |
1054 | parentLeaf = selected |
1055 | else: | |
29a41103 | 1056 | nextItem = wx.TreeItemId() |
d14a1e28 RD |
1057 | parentLeaf = selected |
1058 | parent = tree.GetPyData(parentLeaf) | |
1059 | if parent.hasChild: parent = parent.child | |
1060 | ||
6cb85701 RR |
1061 | # Create object_ref? |
1062 | if evt.GetId() == ID_NEW.REF: | |
29a41103 | 1063 | ref = wx.GetTextFromUser('Create reference to:', 'Create reference') |
6cb85701 RR |
1064 | if not ref: return |
1065 | xxx = MakeEmptyRefXXX(parent, ref) | |
1066 | else: | |
1067 | # Create empty element | |
1068 | className = pullDownMenu.createMap[evt.GetId()] | |
1069 | xxx = MakeEmptyXXX(parent, className) | |
d14a1e28 RD |
1070 | |
1071 | # Set default name for top-level windows | |
1072 | if parent.__class__ == xxxMainNode: | |
1073 | cl = xxx.treeObject().__class__ | |
1074 | frame.maxIDs[cl] += 1 | |
64b9ac75 RR |
1075 | xxx.setTreeName('%s%d' % (defaultIDs[cl], frame.maxIDs[cl])) |
1076 | # And for some other standard controls | |
1077 | elif parent.__class__ == xxxStdDialogButtonSizer: | |
1078 | xxx.setTreeName(pullDownMenu.stdButtonIDs[evt.GetId()][0]) | |
1079 | # We can even set label | |
1080 | obj = xxx.treeObject() | |
1081 | elem = g.tree.dom.createElement('label') | |
1082 | elem.appendChild(g.tree.dom.createTextNode(pullDownMenu.stdButtonIDs[evt.GetId()][1])) | |
1083 | obj.params['label'] = xxxParam(elem) | |
1084 | xxx.treeObject().element.appendChild(elem) | |
d14a1e28 RD |
1085 | |
1086 | # Insert new node, register undo | |
1087 | elem = xxx.element | |
1088 | newItem = tree.InsertNode(parentLeaf, parent, elem, nextItem) | |
1089 | undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) | |
1090 | tree.EnsureVisible(newItem) | |
1091 | tree.SelectItem(newItem) | |
1092 | if not tree.IsVisible(newItem): | |
1093 | tree.ScrollTo(newItem) | |
1094 | tree.Refresh() | |
1095 | # Update view? | |
1096 | if g.testWin and tree.IsHighlatable(newItem): | |
1097 | if conf.autoRefresh: | |
1098 | tree.needUpdate = True | |
1099 | tree.pendingHighLight = newItem | |
1100 | else: | |
1101 | tree.pendingHighLight = None | |
1102 | tree.SetFocus() | |
6cb85701 RR |
1103 | self.SetModified() |
1104 | ||
d14a1e28 RD |
1105 | # Replace one object with another |
1106 | def OnReplace(self, evt): | |
1107 | selected = tree.selection | |
1108 | xxx = tree.GetPyData(selected).treeObject() | |
1109 | elem = xxx.element | |
1110 | parent = elem.parentNode | |
baba4aa5 | 1111 | undoMan.RegisterUndo(UndoReplace(selected)) |
d14a1e28 RD |
1112 | # New class |
1113 | className = pullDownMenu.createMap[evt.GetId() - 1000] | |
75aa1946 | 1114 | |
d14a1e28 RD |
1115 | # Create temporary empty node (with default values) |
1116 | dummy = MakeEmptyDOM(className) | |
baba4aa5 RR |
1117 | if className == 'spacer' and xxx.className != 'spacer': |
1118 | klass = xxxSpacer | |
1119 | elif xxx.className == 'spacer' and className != 'spacer': | |
1120 | klass = xxxSizerItem | |
1121 | else: | |
1122 | klass = xxxDict[className] | |
d14a1e28 | 1123 | # Remove non-compatible children |
baba4aa5 | 1124 | if tree.ItemHasChildren(selected) and not klass.hasChildren: |
d14a1e28 RD |
1125 | tree.DeleteChildren(selected) |
1126 | nodes = elem.childNodes[:] | |
1127 | tags = [] | |
1128 | for node in nodes: | |
64bce500 | 1129 | if node.nodeType != minidom.Node.ELEMENT_NODE: continue |
d14a1e28 RD |
1130 | remove = False |
1131 | tag = node.tagName | |
1132 | if tag == 'object': | |
baba4aa5 RR |
1133 | if not klass.hasChildren: remove = True |
1134 | elif tag not in klass.allParams and \ | |
1135 | (not klass.hasStyle or tag not in klass.styles): | |
d14a1e28 RD |
1136 | remove = True |
1137 | else: | |
1138 | tags.append(tag) | |
1139 | if remove: | |
1140 | elem.removeChild(node) | |
1141 | node.unlink() | |
1142 | ||
baba4aa5 RR |
1143 | # Remove sizeritem child if spacer |
1144 | if className == 'spacer' and xxx.className != 'spacer': | |
1145 | sizeritem = elem.parentNode | |
1146 | assert sizeritem.getAttribute('class') == 'sizeritem' | |
1147 | sizeritem.removeChild(elem) | |
1148 | elem.unlink() | |
1149 | elem = sizeritem | |
75aa1946 | 1150 | tree.GetPyData(selected).hasChild = False |
baba4aa5 RR |
1151 | elif xxx.className == 'spacer' and className != 'spacer': |
1152 | # Create sizeritem element | |
1153 | assert xxx.parent.isSizer | |
1154 | elem.setAttribute('class', 'sizeritem') | |
1155 | node = MakeEmptyDOM(className) | |
1156 | elem.appendChild(node) | |
1157 | # Replace to point to new object | |
1158 | xxx = xxxSizerItem(xxx.parent, elem) | |
1159 | elem = node | |
1160 | tree.SetPyData(selected, xxx) | |
1161 | xxx = xxx.child | |
1162 | else: | |
1163 | # Copy parameters present in dummy but not in elem | |
1164 | for node in dummy.childNodes: | |
1165 | if node.tagName not in tags: elem.appendChild(node.cloneNode(True)) | |
d14a1e28 | 1166 | dummy.unlink() |
baba4aa5 | 1167 | |
d14a1e28 | 1168 | # Change class name |
baba4aa5 | 1169 | elem.setAttribute('class', className) |
64bce500 RR |
1170 | if elem.hasAttribute('subclass'): |
1171 | elem.removeAttribute('subclass') # clear subclassing | |
d14a1e28 | 1172 | # Re-create xxx element |
baba4aa5 | 1173 | xxx = MakeXXXFromDOM(xxx.parent, elem) |
75aa1946 RR |
1174 | # Remove incompatible style flags |
1175 | if 'style' in xxx.params: | |
1176 | styles = map(string.strip, xxx.params['style'].value().split('|')) | |
1177 | newStyles = [s for s in styles if s in klass.winStyles or s in genericStyles] | |
1178 | if newStyles != styles: | |
1179 | if newStyles: | |
1180 | value = reduce(lambda a,b: a+'|'+b, newStyles) | |
1181 | else: | |
1182 | value = '' | |
1183 | xxx.params['style'].update(value) | |
1184 | ||
d14a1e28 RD |
1185 | # Update parent in child objects |
1186 | if tree.ItemHasChildren(selected): | |
a4c013b2 | 1187 | i, cookie = tree.GetFirstChild(selected) |
d14a1e28 RD |
1188 | while i.IsOk(): |
1189 | x = tree.GetPyData(i) | |
1190 | x.parent = xxx | |
1191 | if x.hasChild: x.child.parent = xxx | |
1192 | i, cookie = tree.GetNextChild(selected, cookie) | |
baba4aa5 | 1193 | |
d14a1e28 RD |
1194 | # Update tree |
1195 | if tree.GetPyData(selected).hasChild: # child container | |
1196 | container = tree.GetPyData(selected) | |
75aa1946 | 1197 | container.resetChild(xxx) |
baba4aa5 | 1198 | xxx = container |
d14a1e28 RD |
1199 | else: |
1200 | tree.SetPyData(selected, xxx) | |
1201 | tree.SetItemText(selected, xxx.treeName()) | |
1202 | tree.SetItemImage(selected, xxx.treeImage()) | |
1203 | ||
1204 | # Set default name for top-level windows | |
1205 | if parent.__class__ == xxxMainNode: | |
1206 | cl = xxx.treeObject().__class__ | |
1207 | frame.maxIDs[cl] += 1 | |
64b9ac75 | 1208 | xxx.setTreeName('%s%d' % (defaultIDs[cl], frame.maxIDs[cl])) |
d14a1e28 RD |
1209 | |
1210 | # Update panel | |
1211 | g.panel.SetData(xxx) | |
1212 | # Update tools | |
1213 | g.tools.UpdateUI() | |
1214 | ||
57c48fc4 | 1215 | #undoMan.RegisterUndo(UndoPasteCreate(parentLeaf, parent, newItem, selected)) |
d14a1e28 RD |
1216 | # Update view? |
1217 | if g.testWin and tree.IsHighlatable(selected): | |
1218 | if conf.autoRefresh: | |
1219 | tree.needUpdate = True | |
1220 | tree.pendingHighLight = selected | |
1221 | else: | |
1222 | tree.pendingHighLight = None | |
1223 | tree.SetFocus() | |
6cb85701 | 1224 | self.SetModified() |
d14a1e28 RD |
1225 | |
1226 | # Expand/collapse subtree | |
1227 | def OnExpand(self, evt): | |
1228 | if tree.selection: tree.ExpandAll(tree.selection) | |
1229 | else: tree.ExpandAll(tree.root) | |
1230 | def OnCollapse(self, evt): | |
1231 | if tree.selection: tree.CollapseAll(tree.selection) | |
1232 | else: tree.CollapseAll(tree.root) | |
1233 | ||
1234 | def OnPullDownHighlight(self, evt): | |
1235 | menuId = evt.GetMenuId() | |
1236 | if menuId != -1: | |
1237 | menu = evt.GetEventObject() | |
1238 | help = menu.GetHelpString(menuId) | |
1239 | self.SetStatusText(help) | |
1240 | else: | |
1241 | self.SetStatusText('') | |
1242 | ||
1243 | def OnUpdateUI(self, evt): | |
29a41103 | 1244 | if evt.GetId() in [wx.ID_CUT, wx.ID_COPY, self.ID_DELETE]: |
d14a1e28 | 1245 | evt.Enable(tree.selection is not None and tree.selection != tree.root) |
29a41103 | 1246 | elif evt.GetId() == wx.ID_SAVE: |
6cb85701 | 1247 | evt.Enable(self.modified) |
29a41103 | 1248 | elif evt.GetId() in [wx.ID_PASTE, self.ID_TOOL_PASTE]: |
af52e185 | 1249 | evt.Enable(tree.selection is not None) |
d14a1e28 RD |
1250 | elif evt.GetId() == self.ID_TEST: |
1251 | evt.Enable(tree.selection is not None and tree.selection != tree.root) | |
016f67ba | 1252 | elif evt.GetId() in [self.ID_LOCATE, self.ID_TOOL_LOCATE]: |
64bce500 | 1253 | evt.Enable(g.testWin is not None) |
29a41103 RD |
1254 | elif evt.GetId() == wx.ID_UNDO: evt.Enable(undoMan.CanUndo()) |
1255 | elif evt.GetId() == wx.ID_REDO: evt.Enable(undoMan.CanRedo()) | |
d14a1e28 RD |
1256 | |
1257 | def OnIdle(self, evt): | |
1258 | if self.inIdle: return # Recursive call protection | |
1259 | self.inIdle = True | |
306b6fe9 RR |
1260 | try: |
1261 | if tree.needUpdate: | |
1262 | if conf.autoRefresh: | |
1263 | if g.testWin: | |
1264 | self.SetStatusText('Refreshing test window...') | |
1265 | # (re)create | |
1266 | tree.CreateTestWin(g.testWin.item) | |
1267 | self.SetStatusText('') | |
1268 | tree.needUpdate = False | |
1269 | elif tree.pendingHighLight: | |
1270 | try: | |
1271 | tree.HighLight(tree.pendingHighLight) | |
1272 | except: | |
1273 | # Remove highlight if any problem | |
1274 | if g.testWin.highLight: | |
1275 | g.testWin.highLight.Remove() | |
1276 | tree.pendingHighLight = None | |
1277 | raise | |
1278 | else: | |
1279 | evt.Skip() | |
1280 | finally: | |
1281 | self.inIdle = False | |
d14a1e28 RD |
1282 | |
1283 | # We don't let close panel window | |
1284 | def OnCloseMiniFrame(self, evt): | |
1285 | return | |
1286 | ||
4483a6ed RR |
1287 | def OnIconize(self, evt): |
1288 | conf.x, conf.y = self.GetPosition() | |
1289 | conf.width, conf.height = self.GetSize() | |
1290 | if conf.embedPanel: | |
1291 | conf.sashPos = self.splitter.GetSashPosition() | |
1292 | else: | |
1293 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
1294 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
1295 | self.miniFrame.Iconize() | |
1296 | evt.Skip() | |
1297 | ||
d14a1e28 RD |
1298 | def OnCloseWindow(self, evt): |
1299 | if not self.AskSave(): return | |
1300 | if g.testWin: g.testWin.Destroy() | |
d14a1e28 RD |
1301 | if not panel.GetPageCount() == 2: |
1302 | panel.page2.Destroy() | |
80389ff7 RR |
1303 | else: |
1304 | # If we don't do this, page does not get destroyed (a bug?) | |
1305 | panel.RemovePage(1) | |
3429f8d0 RD |
1306 | if not self.IsIconized(): |
1307 | conf.x, conf.y = self.GetPosition() | |
1308 | conf.width, conf.height = self.GetSize() | |
1309 | if conf.embedPanel: | |
1310 | conf.sashPos = self.splitter.GetSashPosition() | |
1311 | else: | |
1312 | conf.panelX, conf.panelY = self.miniFrame.GetPosition() | |
1313 | conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize() | |
d14a1e28 RD |
1314 | evt.Skip() |
1315 | ||
73b2a9a7 RD |
1316 | |
1317 | def CreateLocalConf(self, path): | |
1318 | name = os.path.splitext(path)[0] | |
1319 | name += '.xcfg' | |
1320 | return wx.FileConfig(localFilename=name) | |
1321 | ||
1322 | ||
d14a1e28 RD |
1323 | def Clear(self): |
1324 | self.dataFile = '' | |
73b2a9a7 | 1325 | conf.localconf = None |
d14a1e28 | 1326 | undoMan.Clear() |
6cb85701 | 1327 | self.SetModified(False) |
d14a1e28 RD |
1328 | tree.Clear() |
1329 | panel.Clear() | |
1330 | if g.testWin: | |
1331 | g.testWin.Destroy() | |
1332 | g.testWin = None | |
d14a1e28 RD |
1333 | # Numbers for new controls |
1334 | self.maxIDs = {} | |
306b6fe9 RR |
1335 | for cl in [xxxPanel, xxxDialog, xxxFrame, |
1336 | xxxMenuBar, xxxMenu, xxxToolBar, | |
1337 | xxxWizard, xxxBitmap, xxxIcon]: | |
1338 | self.maxIDs[cl] = 0 | |
d14a1e28 | 1339 | |
6cb85701 RR |
1340 | def SetModified(self, state=True): |
1341 | self.modified = state | |
1342 | name = os.path.basename(self.dataFile) | |
1343 | if not name: name = defaultName | |
1344 | if state: | |
1345 | self.SetTitle(progname + ': ' + name + ' *') | |
1346 | else: | |
1347 | self.SetTitle(progname + ': ' + name) | |
1348 | ||
d14a1e28 RD |
1349 | def Open(self, path): |
1350 | if not os.path.exists(path): | |
29a41103 | 1351 | wx.LogError('File does not exists: %s' % path) |
d14a1e28 RD |
1352 | return False |
1353 | # Try to read the file | |
1354 | try: | |
1355 | f = open(path) | |
1356 | self.Clear() | |
d14a1e28 | 1357 | dom = minidom.parse(f) |
d14a1e28 | 1358 | f.close() |
016f67ba RR |
1359 | # Set encoding global variable and default encoding |
1360 | if dom.encoding: | |
1361 | g.currentEncoding = dom.encoding | |
1362 | wx.SetDefaultPyEncoding(g.currentEncoding.encode()) | |
9a69d0aa RR |
1363 | else: |
1364 | g.currentEncoding = '' | |
d14a1e28 | 1365 | # Change dir |
fd919451 | 1366 | self.dataFile = path = os.path.abspath(path) |
d14a1e28 RD |
1367 | dir = os.path.dirname(path) |
1368 | if dir: os.chdir(dir) | |
1369 | tree.SetData(dom) | |
d14a1e28 | 1370 | self.SetTitle(progname + ': ' + os.path.basename(path)) |
73b2a9a7 | 1371 | conf.localconf = self.CreateLocalConf(self.dataFile) |
d14a1e28 RD |
1372 | except: |
1373 | # Nice exception printing | |
1374 | inf = sys.exc_info() | |
29a41103 RD |
1375 | wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1]) |
1376 | wx.LogError('Error reading file: %s' % path) | |
016f67ba | 1377 | if debug: raise |
d14a1e28 RD |
1378 | return False |
1379 | return True | |
1380 | ||
1381 | def Indent(self, node, indent = 0): | |
1382 | # Copy child list because it will change soon | |
1383 | children = node.childNodes[:] | |
1384 | # Main node doesn't need to be indented | |
1385 | if indent: | |
1386 | text = self.domCopy.createTextNode('\n' + ' ' * indent) | |
1387 | node.parentNode.insertBefore(text, node) | |
1388 | if children: | |
1389 | # Append newline after last child, except for text nodes | |
1390 | if children[-1].nodeType == minidom.Node.ELEMENT_NODE: | |
1391 | text = self.domCopy.createTextNode('\n' + ' ' * indent) | |
1392 | node.appendChild(text) | |
1393 | # Indent children which are elements | |
1394 | for n in children: | |
1395 | if n.nodeType == minidom.Node.ELEMENT_NODE: | |
1396 | self.Indent(n, indent + 2) | |
1397 | ||
1398 | def Save(self, path): | |
1399 | try: | |
7353d818 | 1400 | import codecs |
d14a1e28 RD |
1401 | # Apply changes |
1402 | if tree.selection and panel.IsModified(): | |
29a41103 | 1403 | self.OnRefresh(wx.CommandEvent()) |
016f67ba | 1404 | if g.currentEncoding: |
9a69d0aa | 1405 | f = codecs.open(path, 'wt', g.currentEncoding) |
016f67ba | 1406 | else: |
9a69d0aa | 1407 | f = codecs.open(path, 'wt') |
d14a1e28 RD |
1408 | # Make temporary copy for formatting it |
1409 | # !!! We can't clone dom node, it works only once | |
1410 | #self.domCopy = tree.dom.cloneNode(True) | |
1411 | self.domCopy = MyDocument() | |
1412 | mainNode = self.domCopy.appendChild(tree.mainNode.cloneNode(True)) | |
34b29ae7 RR |
1413 | # Remove first child (test element) |
1414 | testElem = mainNode.firstChild | |
1415 | mainNode.removeChild(testElem) | |
1416 | testElem.unlink() | |
d14a1e28 | 1417 | self.Indent(mainNode) |
7353d818 | 1418 | self.domCopy.writexml(f, encoding = g.currentEncoding) |
d14a1e28 RD |
1419 | f.close() |
1420 | self.domCopy.unlink() | |
1421 | self.domCopy = None | |
6cb85701 | 1422 | self.SetModified(False) |
d14a1e28 | 1423 | panel.SetModified(False) |
73b2a9a7 | 1424 | conf.localconf.Flush() |
d14a1e28 | 1425 | except: |
4eb5bfc6 | 1426 | inf = sys.exc_info() |
29a41103 RD |
1427 | wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1]) |
1428 | wx.LogError('Error writing file: %s' % path) | |
d14a1e28 | 1429 | raise |
73b2a9a7 | 1430 | |
d14a1e28 RD |
1431 | def AskSave(self): |
1432 | if not (self.modified or panel.IsModified()): return True | |
29a41103 RD |
1433 | flags = wx.ICON_EXCLAMATION | wx.YES_NO | wx.CANCEL | wx.CENTRE |
1434 | dlg = wx.MessageDialog( self, 'File is modified. Save before exit?', | |
d14a1e28 RD |
1435 | 'Save before too late?', flags ) |
1436 | say = dlg.ShowModal() | |
1437 | dlg.Destroy() | |
29a41103 RD |
1438 | wx.Yield() |
1439 | if say == wx.ID_YES: | |
1440 | self.OnSaveOrSaveAs(wx.CommandEvent(wx.ID_SAVE)) | |
d14a1e28 RD |
1441 | # If save was successful, modified flag is unset |
1442 | if not self.modified: return True | |
29a41103 | 1443 | elif say == wx.ID_NO: |
6cb85701 | 1444 | self.SetModified(False) |
d14a1e28 RD |
1445 | panel.SetModified(False) |
1446 | return True | |
1447 | return False | |
1448 | ||
1449 | def SaveUndo(self): | |
1450 | pass # !!! | |
1451 | ||
1452 | ################################################################################ | |
1453 | ||
73b2a9a7 RD |
1454 | class PythonOptions(wx.Dialog): |
1455 | ||
1456 | def __init__(self, parent, cfg, dataFile): | |
1457 | pre = wx.PreDialog() | |
1458 | g.frame.res.LoadOnDialog(pre, parent, "PYTHON_OPTIONS") | |
1459 | self.PostCreate(pre) | |
1460 | ||
1461 | self.cfg = cfg | |
1462 | self.dataFile = dataFile | |
1463 | ||
29a41103 RD |
1464 | self.AutoGenerateCB = xrc.XRCCTRL(self, "AutoGenerateCB") |
1465 | self.EmbedCB = xrc.XRCCTRL(self, "EmbedCB") | |
1466 | self.GettextCB = xrc.XRCCTRL(self, "GettextCB") | |
1467 | self.MakeXRSFileCB = xrc.XRCCTRL(self, "MakeXRSFileCB") | |
1468 | self.FileNameTC = xrc.XRCCTRL(self, "FileNameTC") | |
1469 | self.BrowseBtn = xrc.XRCCTRL(self, "BrowseBtn") | |
1470 | self.GenerateBtn = xrc.XRCCTRL(self, "GenerateBtn") | |
1471 | self.SaveOptsBtn = xrc.XRCCTRL(self, "SaveOptsBtn") | |
73b2a9a7 RD |
1472 | |
1473 | self.Bind(wx.EVT_BUTTON, self.OnBrowse, self.BrowseBtn) | |
1474 | self.Bind(wx.EVT_BUTTON, self.OnGenerate, self.GenerateBtn) | |
1475 | self.Bind(wx.EVT_BUTTON, self.OnSaveOpts, self.SaveOptsBtn) | |
1476 | ||
1477 | if self.cfg.Read("filename", "") != "": | |
1478 | self.FileNameTC.SetValue(self.cfg.Read("filename")) | |
1479 | else: | |
93894584 | 1480 | name = os.path.splitext(os.path.split(dataFile)[1])[0] |
73b2a9a7 RD |
1481 | name += '_xrc.py' |
1482 | self.FileNameTC.SetValue(name) | |
1483 | self.AutoGenerateCB.SetValue(self.cfg.ReadBool("autogenerate", False)) | |
1484 | self.EmbedCB.SetValue(self.cfg.ReadBool("embedResource", False)) | |
1485 | self.MakeXRSFileCB.SetValue(self.cfg.ReadBool("makeXRS", False)) | |
1486 | self.GettextCB.SetValue(self.cfg.ReadBool("genGettext", False)) | |
1487 | ||
1488 | ||
1489 | def OnBrowse(self, evt): | |
1490 | path = self.FileNameTC.GetValue() | |
1491 | dirname = os.path.abspath(os.path.dirname(path)) | |
1492 | name = os.path.split(path)[1] | |
29a41103 RD |
1493 | dlg = wx.FileDialog(self, 'Save As', dirname, name, '*.py', |
1494 | wx.SAVE | wx.OVERWRITE_PROMPT) | |
1495 | if dlg.ShowModal() == wx.ID_OK: | |
73b2a9a7 RD |
1496 | path = dlg.GetPath() |
1497 | self.FileNameTC.SetValue(path) | |
1498 | dlg.Destroy() | |
1499 | ||
1500 | ||
1501 | def OnGenerate(self, evt): | |
1502 | pypath = self.FileNameTC.GetValue() | |
1503 | embed = self.EmbedCB.GetValue() | |
7e05216c RD |
1504 | genGettext = self.GettextCB.GetValue() |
1505 | frame.GeneratePython(self.dataFile, pypath, embed, genGettext) | |
73b2a9a7 RD |
1506 | self.OnSaveOpts() |
1507 | ||
1508 | ||
1509 | def OnSaveOpts(self, evt=None): | |
1510 | self.cfg.Write("filename", self.FileNameTC.GetValue()) | |
1511 | self.cfg.WriteBool("autogenerate", self.AutoGenerateCB.GetValue()) | |
1512 | self.cfg.WriteBool("embedResource", self.EmbedCB.GetValue()) | |
1513 | self.cfg.WriteBool("makeXRS", self.MakeXRSFileCB.GetValue()) | |
1514 | self.cfg.WriteBool("genGettext", self.GettextCB.GetValue()) | |
1515 | ||
1516 | self.EndModal(wx.ID_OK) | |
1517 | ||
1518 | ||
1519 | ################################################################################ | |
1520 | ||
d14a1e28 RD |
1521 | def usage(): |
1522 | print >> sys.stderr, 'usage: xrced [-dhiv] [file]' | |
1523 | ||
29a41103 | 1524 | class App(wx.App): |
d14a1e28 | 1525 | def OnInit(self): |
306b6fe9 | 1526 | # Check version |
29a41103 RD |
1527 | if wx.VERSION[:3] < MinWxVersion: |
1528 | wx.LogWarning('''\ | |
1529 | This version of XRCed may not work correctly on your version of wxWidgets. \ | |
1530 | Please upgrade wxWidgets to %d.%d.%d or higher.''' % MinWxVersion) | |
d14a1e28 RD |
1531 | global debug |
1532 | # Process comand-line | |
364a2be0 | 1533 | opts = args = None |
d14a1e28 RD |
1534 | try: |
1535 | opts, args = getopt.getopt(sys.argv[1:], 'dhiv') | |
1c01bc8e RD |
1536 | for o,a in opts: |
1537 | if o == '-h': | |
1538 | usage() | |
1539 | sys.exit(0) | |
1540 | elif o == '-d': | |
1541 | debug = True | |
1542 | elif o == '-v': | |
1543 | print 'XRCed version', version | |
1544 | sys.exit(0) | |
1545 | ||
d14a1e28 | 1546 | except getopt.GetoptError: |
29a41103 | 1547 | if wx.Platform != '__WXMAC__': # macs have some extra parameters |
d14a1e28 RD |
1548 | print >> sys.stderr, 'Unknown option' |
1549 | usage() | |
1550 | sys.exit(1) | |
d14a1e28 RD |
1551 | |
1552 | self.SetAppName('xrced') | |
1553 | # Settings | |
1554 | global conf | |
29a41103 | 1555 | conf = g.conf = wx.Config(style = wx.CONFIG_USE_LOCAL_FILE) |
73b2a9a7 | 1556 | conf.localconf = None |
d14a1e28 RD |
1557 | conf.autoRefresh = conf.ReadInt('autorefresh', True) |
1558 | pos = conf.ReadInt('x', -1), conf.ReadInt('y', -1) | |
1559 | size = conf.ReadInt('width', 800), conf.ReadInt('height', 600) | |
1560 | conf.embedPanel = conf.ReadInt('embedPanel', True) | |
1561 | conf.showTools = conf.ReadInt('showTools', True) | |
1562 | conf.sashPos = conf.ReadInt('sashPos', 200) | |
80389ff7 RR |
1563 | # read recently used files |
1564 | recentfiles=conf.Read('recentFiles','') | |
1565 | conf.recentfiles={} | |
1566 | if recentfiles: | |
1567 | for fil in recentfiles.split('|'): | |
29a41103 | 1568 | conf.recentfiles[wx.NewId()]=fil |
d14a1e28 RD |
1569 | if not conf.embedPanel: |
1570 | conf.panelX = conf.ReadInt('panelX', -1) | |
1571 | conf.panelY = conf.ReadInt('panelY', -1) | |
1572 | else: | |
1573 | conf.panelX = conf.panelY = -1 | |
1574 | conf.panelWidth = conf.ReadInt('panelWidth', 200) | |
1575 | conf.panelHeight = conf.ReadInt('panelHeight', 200) | |
1576 | conf.panic = not conf.HasEntry('nopanic') | |
1577 | # Add handlers | |
29a41103 | 1578 | wx.FileSystem.AddHandler(wx.MemoryFSHandler()) |
d14a1e28 RD |
1579 | # Create main frame |
1580 | frame = Frame(pos, size) | |
1581 | frame.Show(True) | |
d14a1e28 RD |
1582 | |
1583 | # Load file after showing | |
1584 | if args: | |
1585 | conf.panic = False | |
1586 | frame.open = frame.Open(args[0]) | |
1587 | ||
1588 | return True | |
1589 | ||
1590 | def OnExit(self): | |
1591 | # Write config | |
1592 | global conf | |
73b2a9a7 | 1593 | wc = conf |
d14a1e28 RD |
1594 | wc.WriteInt('autorefresh', conf.autoRefresh) |
1595 | wc.WriteInt('x', conf.x) | |
1596 | wc.WriteInt('y', conf.y) | |
1597 | wc.WriteInt('width', conf.width) | |
1598 | wc.WriteInt('height', conf.height) | |
1599 | wc.WriteInt('embedPanel', conf.embedPanel) | |
1600 | wc.WriteInt('showTools', conf.showTools) | |
1601 | if not conf.embedPanel: | |
1602 | wc.WriteInt('panelX', conf.panelX) | |
1603 | wc.WriteInt('panelY', conf.panelY) | |
1604 | wc.WriteInt('sashPos', conf.sashPos) | |
1605 | wc.WriteInt('panelWidth', conf.panelWidth) | |
1606 | wc.WriteInt('panelHeight', conf.panelHeight) | |
1607 | wc.WriteInt('nopanic', True) | |
80389ff7 | 1608 | wc.Write('recentFiles', '|'.join(conf.recentfiles.values()[-5:])) |
d14a1e28 RD |
1609 | wc.Flush() |
1610 | ||
1611 | def main(): | |
1612 | app = App(0, useBestVisual=False) | |
29a41103 | 1613 | #app.SetAssertMode(wx.PYAPP_ASSERT_LOG) |
d14a1e28 RD |
1614 | app.MainLoop() |
1615 | app.OnExit() | |
1616 | global conf | |
1617 | del conf | |
1618 | ||
1619 | if __name__ == '__main__': | |
1620 | main() |