]> git.saurik.com Git - wxWidgets.git/blobdiff - wxPython/wx/tools/XRCed/xrced.py
Get/SetTitle only for wxTopLevelWindow (wxMGL part).
[wxWidgets.git] / wxPython / wx / tools / XRCed / xrced.py
index 8b44b5e2cf6dc41a368d9ff03a09c429f8457633..a68597b7fd51e55943f7b06da312732ecb75a257 100644 (file)
@@ -20,9 +20,8 @@ Options:
     -v          output version info and exit
 """
 
-
 from globals import *
-import os, sys, getopt, re, traceback
+import os, sys, getopt, re, traceback, tempfile, shutil
 
 # Local modules
 from tree import *                      # imports xxx which imports params
@@ -54,7 +53,10 @@ Consult README file for the details.</HTML>
 """
 
 defaultIDs = {xxxPanel:'PANEL', xxxDialog:'DIALOG', xxxFrame:'FRAME',
-              xxxMenuBar:'MENUBAR', xxxMenu:'MENU', xxxToolBar:'TOOLBAR'}
+              xxxMenuBar:'MENUBAR', xxxMenu:'MENU', xxxToolBar:'TOOLBAR',
+              xxxWizard:'WIZARD'}
+
+defaultName = 'UNTITLED.xrc'
 
 ################################################################################
 
@@ -65,13 +67,14 @@ class ScrolledMessageDialog(wxDialog):
         wxDialog.__init__(self, parent, -1, caption, pos, size)
         text = wxTextCtrl(self, -1, msg, wxDefaultPosition,
                              wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY)
-        text.SetFont(modernFont)
+        text.SetFont(g.modernFont())
         dc = wxWindowDC(text)
         # !!! possible bug - GetTextExtent without font returns sysfont dims
-        w, h = dc.GetFullTextExtent(' ', modernFont)[:2]
+        w, h = dc.GetFullTextExtent(' ', g.modernFont())[:2]
         ok = wxButton(self, wxID_OK, "OK")
         text.SetConstraints(Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self,ok)))
         text.SetSize((w * 80 + 30, h * 40))
+        text.ShowPosition(1)
         ok.SetConstraints(Layoutf('b=b5#1;x%w50#1;w!80;h!25', (self,)))
         self.SetAutoLayout(True)
         self.Fit()
@@ -79,6 +82,11 @@ class ScrolledMessageDialog(wxDialog):
 
 ################################################################################
 
+# Event handler for using during location
+class Locator(wxEvtHandler):
+    def ProcessEvent(self, evt):
+        print evt
+
 class Frame(wxFrame):
     def __init__(self, pos, size):
         wxFrame.__init__(self, None, -1, '', pos, size)
@@ -91,16 +99,30 @@ class Frame(wxFrame):
         # Idle flag
         self.inIdle = False
 
+        # Load our own resources
+        self.res = wxXmlResource('')
+        # !!! Blocking of assert failure occurring in older unicode builds
+        try:
+            self.res.Load(os.path.join(basePath, 'xrced.xrc'))
+        except wx._core.PyAssertionError:
+            print 'PyAssertionError was ignored'
+
         # Make menus
         menuBar = wxMenuBar()
 
         menu = wxMenu()
         menu.Append(wxID_NEW, '&New\tCtrl-N', 'New file')
+        menu.AppendSeparator()
         menu.Append(wxID_OPEN, '&Open...\tCtrl-O', 'Open XRC file')
+        self.recentMenu = wxMenu()
+        self.AppendRecent(self.recentMenu)
+        menu.AppendMenu(-1, 'Open Recent', self.recentMenu, 'Open a recent file')
+        menu.AppendSeparator()
         menu.Append(wxID_SAVE, '&Save\tCtrl-S', 'Save XRC file')
         menu.Append(wxID_SAVEAS, 'Save &As...', 'Save XRC file under different name')
         menu.AppendSeparator()
         menu.Append(wxID_EXIT, '&Quit\tCtrl-Q', 'Exit application')
+
         menuBar.Append(menu, '&File')
 
         menu = wxMenu()
@@ -112,9 +134,11 @@ class Frame(wxFrame):
         menu.Append(wxID_PASTE, '&Paste\tCtrl-V', 'Paste from the clipboard')
         self.ID_DELETE = wxNewId()
         menu.Append(self.ID_DELETE, '&Delete\tCtrl-D', 'Delete object')
-#        menu.AppendSeparator()
-        ID_SELECT = wxNewId()
-#        menu.Append(ID_SELECT, '&Select', 'Select object')
+        menu.AppendSeparator()
+        self.ID_LOCATE = wxNewId()
+        self.ID_TOOL_LOCATE = wxNewId()
+        self.ID_TOOL_PASTE = wxNewId()
+        menu.Append(self.ID_LOCATE, '&Locate\tCtrl-L', 'Locate control in test window and select it')
         menuBar.Append(menu, '&Edit')
 
         menu = wxMenu()
@@ -127,13 +151,15 @@ class Frame(wxFrame):
         menu.Check(self.ID_SHOW_TOOLS, conf.showTools)
         menu.AppendSeparator()
         self.ID_TEST = wxNewId()
-        menu.Append(self.ID_TEST, '&Test\tF5', 'Test window')
+        menu.Append(self.ID_TEST, '&Test\tF5', 'Show test window')
         self.ID_REFRESH = wxNewId()
         menu.Append(self.ID_REFRESH, '&Refresh\tCtrl-R', 'Refresh test window')
         self.ID_AUTO_REFRESH = wxNewId()
         menu.Append(self.ID_AUTO_REFRESH, '&Auto-refresh\tCtrl-A',
                     'Toggle auto-refresh mode', True)
         menu.Check(self.ID_AUTO_REFRESH, conf.autoRefresh)
+        self.ID_TEST_HIDE = wxNewId()
+        menu.Append(self.ID_TEST_HIDE, '&Hide\tCtrl-H', 'Close test window')
         menuBar.Append(menu, '&View')
 
         menu = wxMenu()
@@ -151,17 +177,30 @@ class Frame(wxFrame):
 
         # Create toolbar
         tb = self.CreateToolBar(wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT)
-        tb.SetToolBitmapSize((24, 23))
-        tb.AddSimpleTool(wxID_NEW, images.getNewBitmap(), 'New', 'New file')
-        tb.AddSimpleTool(wxID_OPEN, images.getOpenBitmap(), 'Open', 'Open file')
-        tb.AddSimpleTool(wxID_SAVE, images.getSaveBitmap(), 'Save', 'Save file')
+        tb.SetToolBitmapSize((24,24))
+        new_bmp  = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_TOOLBAR)
+        open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR)
+        save_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR)
+        undo_bmp = wx.ArtProvider.GetBitmap(wx.ART_UNDO, wx.ART_TOOLBAR)
+        redo_bmp = wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_TOOLBAR)
+        cut_bmp  = wx.ArtProvider.GetBitmap(wx.ART_CUT, wx.ART_TOOLBAR)
+        copy_bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_TOOLBAR)
+        paste_bmp= wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_TOOLBAR)
+        
+        tb.AddSimpleTool(wxID_NEW, new_bmp, 'New', 'New file')
+        tb.AddSimpleTool(wxID_OPEN, open_bmp, 'Open', 'Open file')
+        tb.AddSimpleTool(wxID_SAVE, save_bmp, 'Save', 'Save file')
+        tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
+        tb.AddSimpleTool(wxID_UNDO, undo_bmp, 'Undo', 'Undo')
+        tb.AddSimpleTool(wxID_REDO, redo_bmp, 'Redo', 'Redo')
         tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
-        tb.AddSimpleTool(wxID_UNDO, images.getUndoBitmap(), 'Undo', 'Undo')
-        tb.AddSimpleTool(wxID_REDO, images.getRedoBitmap(), 'Redo', 'Redo')
+        tb.AddSimpleTool(wxID_CUT, cut_bmp, 'Cut', 'Cut')
+        tb.AddSimpleTool(wxID_COPY, copy_bmp, 'Copy', 'Copy')
+        tb.AddSimpleTool(self.ID_TOOL_PASTE, paste_bmp, 'Paste', 'Paste')
         tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
-        tb.AddSimpleTool(wxID_CUT, images.getCutBitmap(), 'Cut', 'Cut')
-        tb.AddSimpleTool(wxID_COPY, images.getCopyBitmap(), 'Copy', 'Copy')
-        tb.AddSimpleTool(wxID_PASTE, images.getPasteBitmap(), 'Paste', 'Paste')
+        tb.AddSimpleTool(self.ID_TOOL_LOCATE,
+                        images.getLocateBitmap(), #images.getLocateArmedBitmap(),
+                        'Locate', 'Locate control in test window and select it', True)
         tb.AddControl(wxStaticLine(tb, -1, size=(-1,23), style=wxLI_VERTICAL))
         tb.AddSimpleTool(self.ID_TEST, images.getTestBitmap(), 'Test', 'Test window')
         tb.AddSimpleTool(self.ID_REFRESH, images.getRefreshBitmap(),
@@ -172,6 +211,7 @@ class Frame(wxFrame):
             tb.AddSeparator()   # otherwise auto-refresh sticks in status line
         tb.ToggleTool(self.ID_AUTO_REFRESH, conf.autoRefresh)
         tb.Realize()
         self.tb = tb
         self.minWidth = tb.GetSize()[0] # minimal width is the size of toolbar
 
@@ -187,22 +227,29 @@ class Frame(wxFrame):
         EVT_MENU(self, wxID_CUT, self.OnCutDelete)
         EVT_MENU(self, wxID_COPY, self.OnCopy)
         EVT_MENU(self, wxID_PASTE, self.OnPaste)
+        EVT_MENU(self, self.ID_TOOL_PASTE, self.OnPaste)
         EVT_MENU(self, self.ID_DELETE, self.OnCutDelete)
-        EVT_MENU(self, ID_SELECT, self.OnSelect)
+        EVT_MENU(self, self.ID_LOCATE, self.OnLocate)
+        EVT_MENU(self, self.ID_TOOL_LOCATE, self.OnLocate)
         # View
         EVT_MENU(self, self.ID_EMBED_PANEL, self.OnEmbedPanel)
         EVT_MENU(self, self.ID_SHOW_TOOLS, self.OnShowTools)
         EVT_MENU(self, self.ID_TEST, self.OnTest)
         EVT_MENU(self, self.ID_REFRESH, self.OnRefresh)
         EVT_MENU(self, self.ID_AUTO_REFRESH, self.OnAutoRefresh)
+        EVT_MENU(self, self.ID_TEST_HIDE, self.OnTestHide)
         # Help
         EVT_MENU(self, wxID_ABOUT, self.OnAbout)
         EVT_MENU(self, self.ID_README, self.OnReadme)
 
         # Update events
+        EVT_UPDATE_UI(self, wxID_SAVE, self.OnUpdateUI)
         EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateUI)
         EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateUI)
         EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateUI)
+        EVT_UPDATE_UI(self, self.ID_LOCATE, self.OnUpdateUI)
+        EVT_UPDATE_UI(self, self.ID_TOOL_LOCATE, self.OnUpdateUI)
+        EVT_UPDATE_UI(self, self.ID_TOOL_PASTE, self.OnUpdateUI)
         EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateUI)
         EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateUI)
         EVT_UPDATE_UI(self, self.ID_DELETE, self.OnUpdateUI)
@@ -234,7 +281,7 @@ class Frame(wxFrame):
 
         # !!! frame styles are broken
         # Miniframe for not embedded mode
-        miniFrame = wxFrame(self, -1, 'Properties Panel',
+        miniFrame = wxFrame(self, -1, 'Properties & Style',
                             (conf.panelX, conf.panelY),
                             (conf.panelWidth, conf.panelHeight))
         self.miniFrame = miniFrame
@@ -265,9 +312,30 @@ class Frame(wxFrame):
         # Other events
         EVT_IDLE(self, self.OnIdle)
         EVT_CLOSE(self, self.OnCloseWindow)
-        EVT_LEFT_DOWN(self, self.OnLeftDown)
         EVT_KEY_DOWN(self, tools.OnKeyDown)
         EVT_KEY_UP(self, tools.OnKeyUp)
+        EVT_ICONIZE(self, self.OnIconize)
+    
+    def AppendRecent(self, menu):
+        # add recently used files to the menu
+        for id,name in conf.recentfiles.iteritems():
+            menu.Append(id,name)
+            EVT_MENU(self,id,self.OnRecentFile)
+        return 
+        
+    def OnRecentFile(self,evt):
+        # open recently used file
+        if not self.AskSave(): return
+        wxBeginBusyCursor()
+        try:
+            path=conf.recentfiles[evt.GetId()]
+            if self.Open(path):
+                self.SetStatusText('Data loaded')
+            else:
+                self.SetStatusText('Failed')
+        except KeyError:
+            self.SetStatusText('No such file')
+        wxEndBusyCursor()
 
     def OnNew(self, evt):
         if not self.AskSave(): return
@@ -280,21 +348,23 @@ class Frame(wxFrame):
         if dlg.ShowModal() == wxID_OK:
             path = dlg.GetPath()
             self.SetStatusText('Loading...')
-            wxYield()
             wxBeginBusyCursor()
-            if self.Open(path):
-                self.SetStatusText('Data loaded')
-            else:
-                self.SetStatusText('Failed')
-            wxEndBusyCursor()
+            try:
+                if self.Open(path):
+                    self.SetStatusText('Data loaded')
+                else:
+                    self.SetStatusText('Failed')
+                self.SaveRecent(path)
+            finally:
+                wxEndBusyCursor()
         dlg.Destroy()
 
     def OnSaveOrSaveAs(self, evt):
         if evt.GetId() == wxID_SAVEAS or not self.dataFile:
-            if self.dataFile: defaultName = ''
-            else: defaultName = 'UNTITLED.xrc'
-            dlg = wxFileDialog(self, 'Save As', os.path.dirname(self.dataFile),
-                               defaultName, '*.xrc',
+            if self.dataFile: name = ''
+            else: name = defaultName
+            dirname = os.path.abspath(os.path.dirname(self.dataFile))
+            dlg = wxFileDialog(self, 'Save As', dirname, name, '*.xrc',
                                wxSAVE | wxOVERWRITE_PROMPT | wxCHANGE_DIR)
             if dlg.ShowModal() == wxID_OK:
                 path = dlg.GetPath()
@@ -305,15 +375,28 @@ class Frame(wxFrame):
         else:
             path = self.dataFile
         self.SetStatusText('Saving...')
-        wxYield()
         wxBeginBusyCursor()
         try:
-            self.Save(path)
-            self.dataFile = path
-            self.SetStatusText('Data saved')
-        except IOError:
-            self.SetStatusText('Failed')
-        wxEndBusyCursor()
+            try:
+                tmpFile,tmpName = tempfile.mkstemp(prefix='xrced-')
+                os.close(tmpFile)
+                self.Save(tmpName) # save temporary file first
+                shutil.move(tmpName, path)
+                self.dataFile = path
+                self.SetStatusText('Data saved')
+                self.SaveRecent(path)
+            except IOError:
+                self.SetStatusText('Failed')
+        finally:
+            wxEndBusyCursor()        
+
+    def SaveRecent(self,path):
+        # append to recently used files
+        if path not in conf.recentfiles.values():
+            newid = wxNewId()
+            self.recentMenu.Append(newid, path)
+            EVT_MENU(self, newid, self.OnRecentFile)
+            conf.recentfiles[newid] = path
 
     def OnExit(self, evt):
         self.Close()
@@ -338,7 +421,11 @@ class Frame(wxFrame):
         selected = tree.selection
         if not selected: return         # key pressed event
         # For pasting with Ctrl pressed
+        appendChild = True
         if evt.GetId() == pullDownMenu.ID_PASTE_SIBLING: appendChild = False
+        elif evt.GetId() == self.ID_TOOL_PASTE:
+            if g.tree.ctrl: appendChild = False
+            else: appendChild = not tree.NeedInsert(selected)
         else: appendChild = not tree.NeedInsert(selected)
         xxx = tree.GetPyData(selected)
         if not appendChild:
@@ -365,12 +452,13 @@ class Frame(wxFrame):
         error = False
         # Top-level
         x = xxx.treeObject()
-        if x.__class__ in [xxxDialog, xxxFrame, xxxMenuBar]:
+        if x.__class__ in [xxxDialog, xxxFrame, xxxMenuBar, xxxWizard]:
             # Top-level classes
             if parent.__class__ != xxxMainNode: error = True
         elif x.__class__ == xxxToolBar:
             # Toolbar can be top-level of child of panel or frame
-            if parent.__class__ not in [xxxMainNode, xxxPanel, xxxFrame]: error = True
+            if parent.__class__ not in [xxxMainNode, xxxPanel, xxxFrame] and \
+               not parent.isSizer: error = True
         elif x.__class__ == xxxPanel and parent.__class__ == xxxMainNode:
             pass
         elif x.__class__ == xxxSpacer:
@@ -411,7 +499,7 @@ class Frame(wxFrame):
         # Parent is sizer or notebook, child is not child container
         if parent.isSizer and not isChildContainer and not isinstance(xxx, xxxSpacer):
             # Create sizer item element
-            sizerItemElem = MakeEmptyDOM('sizeritem')
+            sizerItemElem = MakeEmptyDOM(parent.itemTag)
             sizerItemElem.appendChild(elem)
             elem = sizerItemElem
         elif isinstance(parent, xxxNotebook) and not isChildContainer:
@@ -434,7 +522,7 @@ class Frame(wxFrame):
                 tree.pendingHighLight = newItem
             else:
                 tree.pendingHighLight = None
-        self.modified = True
+        self.SetModified()
         self.SetStatusText('Pasted')
 
     def OnCutDelete(self, evt):
@@ -468,9 +556,12 @@ class Frame(wxFrame):
             if self.clipboard: self.clipboard.unlink()
             self.clipboard = elem.cloneNode(True)
         tree.pendingHighLight = None
-        tree.Unselect()
+        tree.UnselectAll()
+        tree.selection = None
+        # Update tools
+        g.tools.UpdateUI()
         panel.Clear()
-        self.modified = True
+        self.SetModified()
         self.SetStatusText(status)
 
     def OnSubclass(self, evt):
@@ -483,26 +574,14 @@ class Frame(wxFrame):
             subclass = dlg.GetValue()
             if subclass:
                 elem.setAttribute('subclass', subclass)
-                self.modified = True
             elif elem.hasAttribute('subclass'):
                 elem.removeAttribute('subclass')
-                self.modified = True
+            self.SetModified()
             xxx.subclass = elem.getAttribute('subclass')
             tree.SetItemText(selected, xxx.treeName())
             panel.pages[0].box.SetLabel(xxx.panelName())
         dlg.Destroy()
 
-    def OnSelect(self, evt):
-        print >> sys.stderr, 'Xperimental function!'
-        wxYield()
-        self.SetCursor(wxCROSS_CURSOR)
-        self.CaptureMouse()
-
-    def OnLeftDown(self, evt):
-        pos = evt.GetPosition()
-        self.SetCursor(wxNullCursor)
-        self.ReleaseMouse()
-
     def OnEmbedPanel(self, evt):
         conf.embedPanel = evt.IsChecked()
         if conf.embedPanel:
@@ -513,8 +592,7 @@ class Frame(wxFrame):
             pos = self.GetPosition()
             sizePanel = panel.GetSize()
             panel.Reparent(self.splitter)
-            self.miniFrame.GetSizer().RemoveWindow(panel)
-            wxYield()
+            self.miniFrame.GetSizer().Remove(panel)
             # Widen
             self.SetDimensions(pos.x, pos.y, size.width + sizePanel.width, size.height)
             self.splitter.SplitVertically(tree, panel, conf.sashPos)
@@ -532,7 +610,6 @@ class Frame(wxFrame):
             self.miniFrame.Show(True)
             self.miniFrame.SetDimensions(conf.panelX, conf.panelY,
                                          conf.panelWidth, conf.panelHeight)
-            wxYield()
             # Reduce width
             self.SetDimensions(pos.x, pos.y,
                                max(size.width - sizePanel.width, self.minWidth), size.height)
@@ -550,6 +627,60 @@ class Frame(wxFrame):
         if not tree.selection: return   # key pressed event
         tree.ShowTestWindow(tree.selection)
 
+    def OnTestHide(self, evt):
+        tree.CloseTestWindow()
+
+    # Find object by relative position
+    def FindObject(self, item, obj):
+        # We simply perform depth-first traversal, sinse it's too much
+        # hassle to deal with all sizer/window combinations
+        w = tree.FindNodeObject(item)
+        if w == obj:
+            return item
+        if tree.ItemHasChildren(item):
+            child = tree.GetFirstChild(item)[0]
+            while child:
+                found = self.FindObject(child, obj)
+                if found: return found
+                child = tree.GetNextSibling(child)
+        return None
+
+    def OnTestWinLeftDown(self, evt):
+        pos = evt.GetPosition()
+        self.SetHandler(g.testWin)
+        g.testWin.Disconnect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN)
+        item = self.FindObject(g.testWin.item, evt.GetEventObject())
+        if item:
+            tree.SelectItem(item)
+        self.tb.ToggleTool(self.ID_TOOL_LOCATE, False)
+        if item:
+            self.SetStatusText('Selected %s' % tree.GetItemText(item))
+        else:
+            self.SetStatusText('Locate failed!')
+
+    def SetHandler(self, w, h=None):
+        if h:
+            w.SetEventHandler(h)
+            w.SetCursor(wxCROSS_CURSOR)
+        else:
+            w.SetEventHandler(w)
+            w.SetCursor(wxNullCursor)
+        for ch in w.GetChildren():
+            self.SetHandler(ch, h)
+
+    def OnLocate(self, evt):
+        if g.testWin:
+            if evt.GetId() == self.ID_LOCATE or \
+               evt.GetId() == self.ID_TOOL_LOCATE and evt.IsChecked():
+                self.SetHandler(g.testWin, g.testWin)
+                g.testWin.Connect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN, self.OnTestWinLeftDown)
+                if evt.GetId() == self.ID_LOCATE:
+                    self.tb.ToggleTool(self.ID_TOOL_LOCATE, True)
+            elif evt.GetId() == self.ID_TOOL_LOCATE and not evt.IsChecked():
+                self.SetHandler(g.testWin, None)
+                g.testWin.Disconnect(wxID_ANY, wxID_ANY, wxEVT_LEFT_DOWN)
+            self.SetStatusText('Click somewhere in your test window now')
+
     def OnRefresh(self, evt):
         # If modified, apply first
         selection = tree.selection
@@ -587,7 +718,6 @@ Homepage: http://xrced.sourceforge.net\
 
     # Simple emulation of python command line
     def OnDebugCMD(self, evt):
-        import traceback
         while 1:
             try:
                 exec raw_input('C:\> ')
@@ -627,16 +757,30 @@ Homepage: http://xrced.sourceforge.net\
         parent = tree.GetPyData(parentLeaf)
         if parent.hasChild: parent = parent.child
 
-        # Create element
-        className = pullDownMenu.createMap[evt.GetId()]
-        xxx = MakeEmptyXXX(parent, className)
+        # Create object_ref?
+        if evt.GetId() == ID_NEW.REF:
+            ref = wxGetTextFromUser('Create reference to:', 'Create reference')
+            if not ref: return
+            xxx = MakeEmptyRefXXX(parent, ref)
+        else:
+            # Create empty element
+            className = pullDownMenu.createMap[evt.GetId()]
+            xxx = MakeEmptyXXX(parent, className)
 
         # Set default name for top-level windows
         if parent.__class__ == xxxMainNode:
             cl = xxx.treeObject().__class__
             frame.maxIDs[cl] += 1
-            xxx.treeObject().name = '%s%d' % (defaultIDs[cl], frame.maxIDs[cl])
-            xxx.treeObject().element.setAttribute('name', xxx.treeObject().name)
+            xxx.setTreeName('%s%d' % (defaultIDs[cl], frame.maxIDs[cl]))
+        # And for some other standard controls
+        elif parent.__class__ == xxxStdDialogButtonSizer:
+            xxx.setTreeName(pullDownMenu.stdButtonIDs[evt.GetId()][0])
+            # We can even set label
+            obj = xxx.treeObject()
+            elem = g.tree.dom.createElement('label')
+            elem.appendChild(g.tree.dom.createTextNode(pullDownMenu.stdButtonIDs[evt.GetId()][1]))
+            obj.params['label'] = xxxParam(elem)
+            xxx.treeObject().element.appendChild(elem)
 
         # Insert new node, register undo
         elem = xxx.element
@@ -655,7 +799,7 @@ Homepage: http://xrced.sourceforge.net\
             else:
                 tree.pendingHighLight = None
         tree.SetFocus()
-        self.modified = True
+        self.SetModified()
 
     # Replace one object with another
     def OnReplace(self, evt):
@@ -663,25 +807,30 @@ Homepage: http://xrced.sourceforge.net\
         xxx = tree.GetPyData(selected).treeObject()
         elem = xxx.element
         parent = elem.parentNode
-        parentXXX = xxx.parent
+        undoMan.RegisterUndo(UndoReplace(selected))
         # New class
         className = pullDownMenu.createMap[evt.GetId() - 1000]
         # Create temporary empty node (with default values)
         dummy = MakeEmptyDOM(className)
-        xxxClass = xxxDict[className]
+        if className == 'spacer' and xxx.className != 'spacer':
+            klass = xxxSpacer
+        elif xxx.className == 'spacer' and className != 'spacer':
+            klass = xxxSizerItem
+        else:
+            klass = xxxDict[className]
         # Remove non-compatible children
-        if tree.ItemHasChildren(selected) and not xxxClass.hasChildren:
+        if tree.ItemHasChildren(selected) and not klass.hasChildren:
             tree.DeleteChildren(selected)
         nodes = elem.childNodes[:]
         tags = []
         for node in nodes:
+            if node.nodeType != minidom.Node.ELEMENT_NODE: continue
             remove = False
             tag = node.tagName
             if tag == 'object':
-                if not xxxClass.hasChildren:
-                    remove = True
-            elif tag not in xxxClass.allParams and \
-                     (not xxxClass.hasStyle or tag not in xxxClass.styles):
+                if not klass.hasChildren:  remove = True
+            elif tag not in klass.allParams and \
+                     (not klass.hasStyle or tag not in klass.styles):
                 remove = True
             else:
                 tags.append(tag)
@@ -689,16 +838,37 @@ Homepage: http://xrced.sourceforge.net\
                 elem.removeChild(node)
                 node.unlink()
         
-        # Copy parameters present in dummy but not in elem
-        for node in dummy.childNodes:
-            tag = node.tagName
-            if tag not in tags:
-                elem.appendChild(node.cloneNode(True))
+        # Remove sizeritem child if spacer
+        if className == 'spacer' and xxx.className != 'spacer':
+            sizeritem = elem.parentNode
+            assert sizeritem.getAttribute('class') == 'sizeritem'
+            sizeritem.removeChild(elem)
+            elem.unlink()
+            elem = sizeritem
+            tree.GetPyData(selected).hasChild = false
+        elif xxx.className == 'spacer' and className != 'spacer':
+            # Create sizeritem element
+            assert xxx.parent.isSizer
+            elem.setAttribute('class', 'sizeritem')
+            node = MakeEmptyDOM(className)
+            elem.appendChild(node)
+            # Replace to point to new object
+            xxx = xxxSizerItem(xxx.parent, elem)
+            elem = node
+            tree.SetPyData(selected, xxx)
+            xxx = xxx.child
+        else:
+            # Copy parameters present in dummy but not in elem
+            for node in dummy.childNodes:
+                if node.tagName not in tags:  elem.appendChild(node.cloneNode(True))
         dummy.unlink()
+        
         # Change class name
-        elem.setAttribute('class', className)        
+        elem.setAttribute('class', className)
+        if elem.hasAttribute('subclass'):
+            elem.removeAttribute('subclass') # clear subclassing
         # Re-create xxx element
-        xxx = MakeXXXFromDOM(parentXXX, elem)
+        xxx = MakeXXXFromDOM(xxx.parent, elem)
         # Update parent in child objects
         if tree.ItemHasChildren(selected):
             i, cookie = tree.GetFirstChild(selected)
@@ -707,13 +877,14 @@ Homepage: http://xrced.sourceforge.net\
                 x.parent = xxx
                 if x.hasChild: x.child.parent = xxx
                 i, cookie = tree.GetNextChild(selected, cookie)
-    
+
         # Update tree
         if tree.GetPyData(selected).hasChild: # child container
             container = tree.GetPyData(selected)
             container.child = xxx
             container.hasChildren = xxx.hasChildren
             container.isSizer = xxx.isSizer
+            xxx = container
         else:
             tree.SetPyData(selected, xxx)
         tree.SetItemText(selected, xxx.treeName())
@@ -723,8 +894,7 @@ Homepage: http://xrced.sourceforge.net\
         if parent.__class__ == xxxMainNode:
             cl = xxx.treeObject().__class__
             frame.maxIDs[cl] += 1
-            xxx.treeObject().name = '%s%d' % (defaultIDs[cl], frame.maxIDs[cl])
-            xxx.treeObject().element.setAttribute('name', xxx.treeObject().name)
+            xxx.setTreeName('%s%d' % (defaultIDs[cl], frame.maxIDs[cl]))
 
         # Update panel
         g.panel.SetData(xxx)
@@ -740,7 +910,7 @@ Homepage: http://xrced.sourceforge.net\
             else:
                 tree.pendingHighLight = None
         tree.SetFocus()
-        self.modified = True
+        self.SetModified()
 
     # Expand/collapse subtree
     def OnExpand(self, evt):
@@ -762,10 +932,14 @@ Homepage: http://xrced.sourceforge.net\
     def OnUpdateUI(self, evt):
         if evt.GetId() in [wxID_CUT, wxID_COPY, self.ID_DELETE]:
             evt.Enable(tree.selection is not None and tree.selection != tree.root)
-        elif evt.GetId() == wxID_PASTE:
+        elif evt.GetId() == wxID_SAVE:
+            evt.Enable(self.modified)
+        elif evt.GetId() in [wxID_PASTE, self.ID_TOOL_PASTE]:
             evt.Enable((self.clipboard and tree.selection) != None)
         elif evt.GetId() == self.ID_TEST:
             evt.Enable(tree.selection is not None and tree.selection != tree.root)
+        elif evt.GetId() in [self.ID_LOCATE, self.ID_TOOL_LOCATE]:
+            evt.Enable(g.testWin is not None)
         elif evt.GetId() == wxID_UNDO:  evt.Enable(undoMan.CanUndo())
         elif evt.GetId() == wxID_REDO:  evt.Enable(undoMan.CanRedo())
 
@@ -778,7 +952,6 @@ Homepage: http://xrced.sourceforge.net\
                     self.SetStatusText('Refreshing test window...')
                     # (re)create
                     tree.CreateTestWin(g.testWin.item)
-                    wxYield()
                     self.SetStatusText('')
                 tree.needUpdate = False
         elif tree.pendingHighLight:
@@ -791,13 +964,7 @@ Homepage: http://xrced.sourceforge.net\
     def OnCloseMiniFrame(self, evt):
         return
 
-    def OnCloseWindow(self, evt):
-        if not self.AskSave(): return
-        if g.testWin: g.testWin.Destroy()
-        # Destroy cached windows
-        panel.cacheParent.Destroy()
-        if not panel.GetPageCount() == 2:
-            panel.page2.Destroy()
+    def OnIconize(self, evt):
         conf.x, conf.y = self.GetPosition()
         conf.width, conf.height = self.GetSize()
         if conf.embedPanel:
@@ -805,6 +972,25 @@ Homepage: http://xrced.sourceforge.net\
         else:
             conf.panelX, conf.panelY = self.miniFrame.GetPosition()
             conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize()
+            self.miniFrame.Iconize()
+        evt.Skip()
+
+    def OnCloseWindow(self, evt):
+        if not self.AskSave(): return
+        if g.testWin: g.testWin.Destroy()
+        if not panel.GetPageCount() == 2:
+            panel.page2.Destroy()
+        else:
+            # If we don't do this, page does not get destroyed (a bug?)
+            panel.RemovePage(1)
+        if not self.IsIconized():
+            conf.x, conf.y = self.GetPosition()
+            conf.width, conf.height = self.GetSize()
+            if conf.embedPanel:
+                conf.sashPos = self.splitter.GetSashPosition()
+            else:
+                conf.panelX, conf.panelY = self.miniFrame.GetPosition()
+                conf.panelWidth, conf.panelHeight = self.miniFrame.GetSize()
         evt.Skip()
 
     def Clear(self):
@@ -813,17 +999,26 @@ Homepage: http://xrced.sourceforge.net\
             self.clipboard.unlink()
             self.clipboard = None
         undoMan.Clear()
-        self.modified = False
+        self.SetModified(False)
         tree.Clear()
         panel.Clear()
         if g.testWin:
             g.testWin.Destroy()
             g.testWin = None
-        self.SetTitle(progname)
         # Numbers for new controls
         self.maxIDs = {}
         self.maxIDs[xxxPanel] = self.maxIDs[xxxDialog] = self.maxIDs[xxxFrame] = \
-        self.maxIDs[xxxMenuBar] = self.maxIDs[xxxMenu] = self.maxIDs[xxxToolBar] = 0
+        self.maxIDs[xxxMenuBar] = self.maxIDs[xxxMenu] = self.maxIDs[xxxToolBar] = \
+        self.maxIDs[xxxWizard] = 0
+
+    def SetModified(self, state=True):
+        self.modified = state
+        name = os.path.basename(self.dataFile)
+        if not name: name = defaultName
+        if state:
+            self.SetTitle(progname + ': ' + name + ' *')
+        else:
+            self.SetTitle(progname + ': ' + name)
 
     def Open(self, path):
         if not os.path.exists(path):
@@ -833,32 +1028,26 @@ Homepage: http://xrced.sourceforge.net\
         try:
             f = open(path)
             self.Clear()
-            # Parse first line to get encoding (!! hack, I don't know a better way)
-            line = f.readline()
-            mo = re.match(r'^<\?xml ([^<>]* )?encoding="(?P<encd>[^<>].*)"\?>', line)
-            # Build wx tree
-            f.seek(0)
             dom = minidom.parse(f)
-            # Set encoding global variable and document encoding property
-            if mo:
-                dom.encoding = g.currentEncoding = mo.group('encd')
-                if dom.encoding not in ['ascii', sys.getdefaultencoding()]:
-                    wxLogWarning('Encoding is different from system default')
-            else:
-                g.currentEncoding = 'ascii'
-                dom.encoding = ''
             f.close()
+            # Set encoding global variable and default encoding
+            if dom.encoding:
+                g.currentEncoding = dom.encoding
+                wx.SetDefaultPyEncoding(g.currentEncoding.encode())
+            else:
+                g.currentEncoding = ''
             # Change dir
+            self.dataFile = path = os.path.abspath(path)
             dir = os.path.dirname(path)
             if dir: os.chdir(dir)
             tree.SetData(dom)
-            self.dataFile = path
             self.SetTitle(progname + ': ' + os.path.basename(path))
         except:
             # Nice exception printing
             inf = sys.exc_info()
             wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1])
             wxLogError('Error reading file: %s' % path)
+            if debug: raise
             return False
         return True
 
@@ -881,23 +1070,33 @@ Homepage: http://xrced.sourceforge.net\
 
     def Save(self, path):
         try:
+            import codecs
             # Apply changes
             if tree.selection and panel.IsModified():
                 self.OnRefresh(wxCommandEvent())
-            f = open(path, 'w')
+            if g.currentEncoding:
+                f = codecs.open(path, 'wt', g.currentEncoding)
+            else:
+                f = codecs.open(path, 'wt')
             # Make temporary copy for formatting it
             # !!! We can't clone dom node, it works only once
             #self.domCopy = tree.dom.cloneNode(True)
             self.domCopy = MyDocument()
             mainNode = self.domCopy.appendChild(tree.mainNode.cloneNode(True))
+            # Remove first child (test element)
+            testElem = mainNode.firstChild
+            mainNode.removeChild(testElem)
+            testElem.unlink()
             self.Indent(mainNode)
-            self.domCopy.writexml(f, encoding=tree.rootObj.params['encoding'].value())
+            self.domCopy.writexml(f, encoding = g.currentEncoding)
             f.close()
             self.domCopy.unlink()
             self.domCopy = None
-            self.modified = False
+            self.SetModified(False)
             panel.SetModified(False)
         except:
+            inf = sys.exc_info()
+            wxLogError(traceback.format_exception(inf[0], inf[1], None)[-1])
             wxLogError('Error writing file: %s' % path)
             raise
 
@@ -913,7 +1112,7 @@ Homepage: http://xrced.sourceforge.net\
             # If save was successful, modified flag is unset
             if not self.modified: return True
         elif say == wxID_NO:
-            self.modified = False
+            self.SetModified(False)
             panel.SetModified(False)
             return True
         return False
@@ -930,22 +1129,24 @@ class App(wxApp):
     def OnInit(self):
         global debug
         # Process comand-line
+        opts = args = None
         try:
             opts, args = getopt.getopt(sys.argv[1:], 'dhiv')
+            for o,a in opts:
+                if o == '-h':
+                    usage()
+                    sys.exit(0)
+                elif o == '-d':
+                    debug = True
+                elif o == '-v':
+                    print 'XRCed version', version
+                    sys.exit(0)
+            
         except getopt.GetoptError:
             if wxPlatform != '__WXMAC__': # macs have some extra parameters
                 print >> sys.stderr, 'Unknown option'
                 usage()
                 sys.exit(1)
-        for o,a in opts:
-            if o == '-h':
-                usage()
-                sys.exit(0)
-            elif o == '-d':
-                debug = True
-            elif o == '-v':
-                print 'XRCed version', version
-                sys.exit(0)
 
         self.SetAppName('xrced')
         # Settings
@@ -957,6 +1158,12 @@ class App(wxApp):
         conf.embedPanel = conf.ReadInt('embedPanel', True)
         conf.showTools = conf.ReadInt('showTools', True)
         conf.sashPos = conf.ReadInt('sashPos', 200)
+        # read recently used files
+        recentfiles=conf.Read('recentFiles','')
+        conf.recentfiles={}
+        if recentfiles:
+            for fil in recentfiles.split('|'):
+                conf.recentfiles[wxNewId()]=fil
         if not conf.embedPanel:
             conf.panelX = conf.ReadInt('panelX', -1)
             conf.panelY = conf.ReadInt('panelY', -1)
@@ -971,9 +1178,6 @@ class App(wxApp):
         # Create main frame
         frame = Frame(pos, size)
         frame.Show(True)
-        # Load resources from XRC file (!!! should be transformed to .py later?)
-        frame.res = wxXmlResource('')
-        frame.res.Load(os.path.join(basePath, 'xrced.xrc'))
 
         # Load file after showing
         if args:
@@ -1000,6 +1204,7 @@ class App(wxApp):
         wc.WriteInt('panelWidth', conf.panelWidth)
         wc.WriteInt('panelHeight', conf.panelHeight)
         wc.WriteInt('nopanic', True)
+        wc.Write('recentFiles', '|'.join(conf.recentfiles.values()[-5:]))
         wc.Flush()
 
 def main():