⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xrced.py

📁 Wxpython Implemented on Windows CE, Source code
💻 PY
📖 第 1 页 / 共 4 页
字号:
                    if g.testWin.highLight:
                        g.testWin.highLight.Remove()
                    tree.pendingHighLight = None
                    raise
            else:
                evt.Skip()
        finally:
            self.inIdle = False

    # We don't let close panel window
    def OnCloseMiniFrame(self, evt):
        return

    def OnIconize(self, evt):
        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()
            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 CreateLocalConf(self, path):
        name = os.path.splitext(path)[0]
        name += '.xcfg'
        return wx.FileConfig(localFilename=name)


    def Clear(self):
        self.dataFile = ''
        conf.localconf = None
        undoMan.Clear()
        self.SetModified(False)
        tree.Clear()
        panel.Clear()
        if g.testWin:
            g.testWin.Destroy()
            g.testWin = None
        # Numbers for new controls
        self.maxIDs = {}
        for cl in [xxxPanel, xxxDialog, xxxFrame,
                   xxxMenuBar, xxxMenu, xxxToolBar,
                   xxxWizard, xxxBitmap, xxxIcon]:
            self.maxIDs[cl] = 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):
            wx.LogError('File does not exists: %s' % path)
            return False
        # Try to read the file
        try:
            f = open(path)
            self.Clear()
            dom = minidom.parse(f)
            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.SetTitle(progname + ': ' + os.path.basename(path))
            conf.localconf = self.CreateLocalConf(self.dataFile)
        except:
            # Nice exception printing
            inf = sys.exc_info()
            wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1])
            wx.LogError('Error reading file: %s' % path)
            if debug: raise
            return False
        return True

    def Indent(self, node, indent = 0):
        # Copy child list because it will change soon
        children = node.childNodes[:]
        # Main node doesn't need to be indented
        if indent:
            text = self.domCopy.createTextNode('\n' + ' ' * indent)
            node.parentNode.insertBefore(text, node)
        if children:
            # Append newline after last child, except for text nodes
            if children[-1].nodeType == minidom.Node.ELEMENT_NODE:
                text = self.domCopy.createTextNode('\n' + ' ' * indent)
                node.appendChild(text)
            # Indent children which are elements
            for n in children:
                if n.nodeType == minidom.Node.ELEMENT_NODE:
                    self.Indent(n, indent + 2)

    def Save(self, path):
        try:
            import codecs
            # Apply changes
            if tree.selection and panel.IsModified():
                self.OnRefresh(wx.CommandEvent())
            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 = g.currentEncoding)
            f.close()
            self.domCopy.unlink()
            self.domCopy = None
            self.SetModified(False)
            panel.SetModified(False)
            conf.localconf.Flush()
        except:
            inf = sys.exc_info()
            wx.LogError(traceback.format_exception(inf[0], inf[1], None)[-1])
            wx.LogError('Error writing file: %s' % path)
            raise
            
    def AskSave(self):
        if not (self.modified or panel.IsModified()): return True
        flags = wx.ICON_EXCLAMATION | wx.YES_NO | wx.CANCEL | wx.CENTRE
        dlg = wx.MessageDialog( self, 'File is modified. Save before exit?',
                               'Save before too late?', flags )
        say = dlg.ShowModal()
        dlg.Destroy()
        wx.Yield()
        if say == wx.ID_YES:
            self.OnSaveOrSaveAs(wx.CommandEvent(wx.ID_SAVE))
            # If save was successful, modified flag is unset
            if not self.modified: return True
        elif say == wx.ID_NO:
            self.SetModified(False)
            panel.SetModified(False)
            return True
        return False

    def SaveUndo(self):
        pass                            # !!!

################################################################################

class PythonOptions(wx.Dialog):

    def __init__(self, parent, cfg, dataFile):
        pre = wx.PreDialog()
        g.frame.res.LoadOnDialog(pre, parent, "PYTHON_OPTIONS")
        self.PostCreate(pre)

        self.cfg = cfg
        self.dataFile = dataFile

        self.AutoGenerateCB = xrc.XRCCTRL(self, "AutoGenerateCB")
        self.EmbedCB = xrc.XRCCTRL(self, "EmbedCB")
        self.GettextCB = xrc.XRCCTRL(self, "GettextCB")
        self.MakeXRSFileCB = xrc.XRCCTRL(self, "MakeXRSFileCB")
        self.FileNameTC = xrc.XRCCTRL(self, "FileNameTC")
        self.BrowseBtn = xrc.XRCCTRL(self, "BrowseBtn")
        self.GenerateBtn = xrc.XRCCTRL(self, "GenerateBtn")
        self.SaveOptsBtn = xrc.XRCCTRL(self, "SaveOptsBtn")

        self.Bind(wx.EVT_BUTTON, self.OnBrowse, self.BrowseBtn)
        self.Bind(wx.EVT_BUTTON, self.OnGenerate, self.GenerateBtn)
        self.Bind(wx.EVT_BUTTON, self.OnSaveOpts, self.SaveOptsBtn)

        if self.cfg.Read("filename", "") != "":
            self.FileNameTC.SetValue(self.cfg.Read("filename"))
        else:
            name = os.path.splitext(dataFile)[0]
            name += '_xrc.py'
            self.FileNameTC.SetValue(name)
        self.AutoGenerateCB.SetValue(self.cfg.ReadBool("autogenerate", False))
        self.EmbedCB.SetValue(self.cfg.ReadBool("embedResource", False))
        self.MakeXRSFileCB.SetValue(self.cfg.ReadBool("makeXRS", False))
        self.GettextCB.SetValue(self.cfg.ReadBool("genGettext", False))
        
                  
    def OnBrowse(self, evt):
        path = self.FileNameTC.GetValue()
        dirname = os.path.abspath(os.path.dirname(path))
        name = os.path.split(path)[1]
        dlg = wx.FileDialog(self, 'Save As', dirname, name, '*.py',
                               wx.SAVE | wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.FileNameTC.SetValue(path)
        dlg.Destroy()
    

    def OnGenerate(self, evt):
        pypath = self.FileNameTC.GetValue()
        embed = self.EmbedCB.GetValue()
        genGettext = self.GettextCB.GetValue()
        frame.GeneratePython(self.dataFile, pypath, embed, genGettext)
        self.OnSaveOpts()

    
    def OnSaveOpts(self, evt=None):
        self.cfg.Write("filename", self.FileNameTC.GetValue())
        self.cfg.WriteBool("autogenerate", self.AutoGenerateCB.GetValue())
        self.cfg.WriteBool("embedResource", self.EmbedCB.GetValue())
        self.cfg.WriteBool("makeXRS", self.MakeXRSFileCB.GetValue())
        self.cfg.WriteBool("genGettext", self.GettextCB.GetValue())

        self.EndModal(wx.ID_OK)
    
        
################################################################################

def usage():
    print >> sys.stderr, 'usage: xrced [-dhiv] [file]'

class App(wx.App):
    def OnInit(self):
        # Check version
        if wx.VERSION[:3] < MinWxVersion:
            wx.LogWarning('''\
This version of XRCed may not work correctly on your version of wxWidgets. \
Please upgrade wxWidgets to %d.%d.%d or higher.''' % MinWxVersion)
        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 wx.Platform != '__WXMAC__': # macs have some extra parameters
                print >> sys.stderr, 'Unknown option'
                usage()
                sys.exit(1)

        self.SetAppName('xrced')
        # Settings
        global conf
        conf = g.conf = wx.Config(style = wx.CONFIG_USE_LOCAL_FILE)
        conf.localconf = None
        conf.autoRefresh = conf.ReadInt('autorefresh', True)
        pos = conf.ReadInt('x', -1), conf.ReadInt('y', -1)
        size = conf.ReadInt('width', 800), conf.ReadInt('height', 600)
        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[wx.NewId()]=fil
        if not conf.embedPanel:
            conf.panelX = conf.ReadInt('panelX', -1)
            conf.panelY = conf.ReadInt('panelY', -1)
        else:
            conf.panelX = conf.panelY = -1
        conf.panelWidth = conf.ReadInt('panelWidth', 200)
        conf.panelHeight = conf.ReadInt('panelHeight', 200)
        conf.panic = not conf.HasEntry('nopanic')
        # Add handlers
        wx.FileSystem.AddHandler(wx.MemoryFSHandler())
        # Create main frame
        frame = Frame(pos, size)
        frame.Show(True)

        # Load file after showing
        if args:
            conf.panic = False
            frame.open = frame.Open(args[0])

        return True

    def OnExit(self):
        # Write config
        global conf
        wc = conf
        wc.WriteInt('autorefresh', conf.autoRefresh)
        wc.WriteInt('x', conf.x)
        wc.WriteInt('y', conf.y)
        wc.WriteInt('width', conf.width)
        wc.WriteInt('height', conf.height)
        wc.WriteInt('embedPanel', conf.embedPanel)
        wc.WriteInt('showTools', conf.showTools)
        if not conf.embedPanel:
            wc.WriteInt('panelX', conf.panelX)
            wc.WriteInt('panelY', conf.panelY)
        wc.WriteInt('sashPos', conf.sashPos)
        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():
    app = App(0, useBestVisual=False)
    #app.SetAssertMode(wx.PYAPP_ASSERT_LOG)
    app.MainLoop()
    app.OnExit()
    global conf
    del conf

if __name__ == '__main__':
    main()

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -