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

📄 docview.py

📁 Wxpython Implemented on Windows CE, Source code
💻 PY
📖 第 1 页 / 共 5 页
字号:
                msgTitle = _("Application")
            res = wx.MessageBox(_("'%s' has been modified outside of %s.  Overwrite '%s' with current changes?") % (self.GetPrintableName(), msgTitle, self.GetPrintableName()),
                                msgTitle,
                                wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION,
                                self.GetDocumentWindow())
    
            if res == wx.NO:
                return True
            elif res == wx.YES:
                pass
            else: # elif res == wx.CANCEL:
                return False
        
        if not self._documentFile or not self._savedYet:
            return self.SaveAs()
        return self.OnSaveDocument(self._documentFile)


    def SaveAs(self):
        """
        Prompts the user for a file to save to, and then calls OnSaveDocument.
        """
        docTemplate = self.GetDocumentTemplate()
        if not docTemplate:
            return False

        descr = docTemplate.GetDescription() + _(" (") + docTemplate.GetFileFilter() + _(") |") + docTemplate.GetFileFilter()  # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk
        filename = wx.FileSelector(_("Save As"),
                                   docTemplate.GetDirectory(),
                                   FileNameFromPath(self.GetFilename()),
                                   docTemplate.GetDefaultExtension(),
                                   wildcard = descr,
                                   flags = wx.SAVE | wx.OVERWRITE_PROMPT,
                                   parent = self.GetDocumentWindow())
        if filename == "":
            return False

        name, ext = os.path.splitext(filename)
        if ext == "":
            filename += '.' + docTemplate.GetDefaultExtension()

        self.SetFilename(filename)
        self.SetTitle(FileNameFromPath(filename))

        for view in self._documentViews:
            view.OnChangeFilename()

        if not self.OnSaveDocument(filename):
            return False

        if docTemplate.FileMatchesTemplate(filename):
            self.GetDocumentManager().AddFileToHistory(filename)
            
        return True


    def OnSaveDocument(self, filename):
        """
        Constructs an output file for the given filename (which must
        not be empty), and calls SaveObject. If SaveObject returns true, the
        document is set to unmodified; otherwise, an error message box is
        displayed.
        """
        if not filename:
            return False

        msgTitle = wx.GetApp().GetAppName()
        if not msgTitle:
            msgTitle = _("File Error")

        backupFilename = None
        fileObject = None
        copied = False
        try:
            # if current file exists, move it to a safe place temporarily
            if os.path.exists(filename):

                # Check if read-only.
                if not os.access(filename, os.W_OK):
                    wx.MessageBox("Could not save '%s'.  No write permission to overwrite existing file." % FileNameFromPath(filename),
                                  msgTitle,
                                  wx.OK | wx.ICON_EXCLAMATION,
                                  self.GetDocumentWindow())
                    return False

                i = 1
                backupFilename = "%s.bak%s" % (filename, i)
                while os.path.exists(backupFilename):
                    i += 1
                    backupFilename = "%s.bak%s" % (filename, i)
                shutil.copy(filename, backupFilename)
                copied = True

            fileObject = file(filename, 'w')
            self.SaveObject(fileObject)
            fileObject.close()
            fileObject = None
            
            if backupFilename:
                os.remove(backupFilename)
        except:
            # for debugging purposes
            import traceback
            traceback.print_exc()

            if fileObject:
                fileObject.close()  # file is still open, close it, need to do this before removal 

            # save failed, remove copied file
            if backupFilename and copied:
                os.remove(backupFilename)

            wx.MessageBox("Could not save '%s'.  %s" % (FileNameFromPath(filename), sys.exc_value),
                          msgTitle,
                          wx.OK | wx.ICON_EXCLAMATION,
                          self.GetDocumentWindow())
            return False

        self.SetDocumentModificationDate()
        self.SetFilename(filename, True)
        self.Modify(False)
        self.SetDocumentSaved(True)
        #if wx.Platform == '__WXMAC__':  # Not yet implemented in wxPython
        #    wx.FileName(file).MacSetDefaultTypeAndCreator()
        return True


    def OnOpenDocument(self, filename):
        """
        Constructs an input file for the given filename (which must not
        be empty), and calls LoadObject. If LoadObject returns true, the
        document is set to unmodified; otherwise, an error message box is
        displayed. The document's views are notified that the filename has
        changed, to give windows an opportunity to update their titles. All of
        the document's views are then updated.
        """
        if not self.OnSaveModified():
            return False

        msgTitle = wx.GetApp().GetAppName()
        if not msgTitle:
            msgTitle = _("File Error")

        fileObject = file(filename, 'r')
        try:
            self.LoadObject(fileObject)
            fileObject.close()
            fileObject = None
        except:
            # for debugging purposes
            import traceback
            traceback.print_exc()

            if fileObject:
                fileObject.close()  # file is still open, close it 

            wx.MessageBox("Could not open '%s'.  %s" % (FileNameFromPath(filename), sys.exc_value),
                          msgTitle,
                          wx.OK | wx.ICON_EXCLAMATION,
                          self.GetDocumentWindow())
            return False

        self.SetDocumentModificationDate()
        self.SetFilename(filename, True)
        self.Modify(False)
        self.SetDocumentSaved(True)
        self.UpdateAllViews()
        return True


    def LoadObject(self, file):
        """
        Override this function and call it from your own LoadObject before
        loading your own data. LoadObject is called by the framework
        automatically when the document contents need to be loaded.

        Note that the wxPython version simply sends you a Python file object,
        so you can use pickle.
        """
        return True


    def SaveObject(self, file):
        """
        Override this function and call it from your own SaveObject before
        saving your own data. SaveObject is called by the framework
        automatically when the document contents need to be saved.

        Note that the wxPython version simply sends you a Python file object,
        so you can use pickle.
        """
        return True


    def Revert(self):
        """
        Override this function to revert the document to its last saved state.
        """
        return False


    def GetPrintableName(self):
        """
        Copies a suitable document name into the supplied name buffer.
        The default function uses the title, or if there is no title, uses the
        filename; or if no filename, the string 'Untitled'.
        """
        if self._documentTitle:
            return self._documentTitle
        elif self._documentFile:
            return FileNameFromPath(self._documentFile)
        else:
            return _("Untitled")


    def GetDocumentWindow(self):
        """
        Intended to return a suitable window for using as a parent for
        document-related dialog boxes. By default, uses the frame associated
        with the first view.
        """
        if len(self._documentViews) > 0:
            return self._documentViews[0].GetFrame()
        else:
            return wx.GetApp().GetTopWindow()


    def OnCreateCommandProcessor(self):
        """
        Override this function if you want a different (or no) command
        processor to be created when the document is created. By default, it
        returns an instance of wxCommandProcessor.
        """
        return CommandProcessor()


    def OnSaveModified(self):
        """
        If the document has been modified, prompts the user to ask if the
        changes should be changed. If the user replies Yes, the Save function
        is called. If No, the document is marked as unmodified and the
        function succeeds. If Cancel, the function fails.
        """
        if not self.IsModified():
            return True

        """ check for file modification outside of application """
        if not self.IsDocumentModificationDateCorrect():
            msgTitle = wx.GetApp().GetAppName()
            if not msgTitle:
                msgTitle = _("Warning")
            res = wx.MessageBox(_("'%s' has been modified outside of %s.  Overwrite '%s' with current changes?") % (self.GetPrintableName(), msgTitle, self.GetPrintableName()),
                                msgTitle,
                                wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION,
                                self.GetDocumentWindow())
    
            if res == wx.NO:
                self.Modify(False)
                return True
            elif res == wx.YES:
                return wx.lib.docview.Document.Save(self)
            else: # elif res == wx.CANCEL:
                return False

        msgTitle = wx.GetApp().GetAppName()
        if not msgTitle:
            msgTitle = _("Warning")

        res = wx.MessageBox(_("Save changes to '%s'?") % self.GetPrintableName(),
                            msgTitle,
                            wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION,
                            self.GetDocumentWindow())

        if res == wx.NO:
            self.Modify(False)
            return True
        elif res == wx.YES:
            return self.Save()
        else: # elif res == wx.CANCEL:
            return False


    def Draw(context):
        """
        Called by printing framework to draw the view.
        """
        return True


    def AddView(self, view):
        """
        If the view is not already in the list of views, adds the view and
        calls OnChangedViewList.
        """
        if not view in self._documentViews:
            self._documentViews.append(view)
            self.OnChangedViewList()
        return True


    def RemoveView(self, view):
        """
        Removes the view from the document's list of views, and calls
        OnChangedViewList.
        """
        if view in self._documentViews:
            self._documentViews.remove(view)
            self.OnChangedViewList()
        return True


    def OnCreate(self, path, flags):
        """
        The default implementation calls DeleteContents (an empty
        implementation) sets the modified flag to false. Override this to
        supply additional behaviour when the document is opened with Open.
        """
        if flags & DOC_NO_VIEW:
            return True
        return self.GetDocumentTemplate().CreateView(self, flags)


    def OnChangedViewList(self):
        """
        Called when a view is added to or deleted from this document. The
        default implementation saves and deletes the document if no views
        exist (the last one has just been removed).
        """
        if len(self._documentViews) == 0:
            if self.OnSaveModified():
                pass # C version does a delete but Python will garbage collect


    def UpdateAllViews(self, sender = None, hint = None):
        """
        Updates all views. If sender is non-NULL, does not update this view.
        hint represents optional information to allow a view to optimize its
        update.
        """
        for view in self._documentViews:
            if view != sender:
                view.OnUpdate(sender, hint)


    def NotifyClosing(self):
        """
        Notifies the views that the document is going to close.
        """
        for view in self._documentViews:
            view.OnClosingDocument()


    def SetFilename(self, filename, notifyViews = False):
        """
        Sets the filename for this document. Usually called by the framework.
        If notifyViews is true, wxView.OnChangeFilename is called for all
        views.
        """
        self._documentFile = filename
        if notifyViews:
            for view in self._documentViews:
                view.OnChangeFilename()


    def GetWriteable(self):
        """
        Returns true if the document can be written to its accociated file path.
        This method has been added to wxPython and is not in wxWindows.
        """
        if not self._writeable:
            return False 
        if not self._documentFile:  # Doesn't exist, do a save as
            return True
        else:
            return os.access(self._documentFile, os.W_OK)


    def SetWriteable(self, writeable):
        """
        Set to False if the document can not be saved.  This will disable the ID_SAVE_AS
        event and is useful for custom documents that should not be saveable.  The ID_SAVE
        event can be disabled by never Modifying the document.  This method has been added

⌨️ 快捷键说明

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