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