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