X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/4e5d278c12ccc50bb04d9ca20ec97ca380a7d94b..c306c1e0f6c9e675aba8206f56cbf261d2506e41:/wxPython/wx/lib/docview.py diff --git a/wxPython/wx/lib/docview.py b/wxPython/wx/lib/docview.py index 9512cf5226..83423dbf1b 100644 --- a/wxPython/wx/lib/docview.py +++ b/wxPython/wx/lib/docview.py @@ -1,23 +1,19 @@ #---------------------------------------------------------------------------- # Name: docview.py -# Purpose: Port of the wxWidgets docview classes +# Purpose: Port of the wxWindows docview classes # # Author: Peter Yared # # Created: 5/15/03 # CVS-ID: $Id$ -# Copyright: (c) 2003-2005 ActiveGrid, Inc. (Port of wxWindows classes by Julian Smart et al) +# Copyright: (c) 2003-2006 ActiveGrid, Inc. (Port of wxWindows classes by Julian Smart et al) # License: wxWindows license #---------------------------------------------------------------------------- -""" -A port of the wxWidgets doc/view classes to Python. - -:see: `pydocview` -""" import os import os.path +import shutil import wx import sys _ = wx.GetTranslation @@ -32,10 +28,12 @@ DOC_MDI = 2 DOC_NEW = 4 DOC_SILENT = 8 DOC_OPEN_ONCE = 16 +DOC_NO_VIEW = 32 DEFAULT_DOCMAN_FLAGS = DOC_SDI & DOC_OPEN_ONCE TEMPLATE_VISIBLE = 1 TEMPLATE_INVISIBLE = 2 +TEMPLATE_NO_CREATE = (4 | TEMPLATE_VISIBLE) DEFAULT_TEMPLATE_FLAGS = TEMPLATE_VISIBLE MAX_FILE_HISTORY = 9 @@ -78,10 +76,9 @@ def PathOnly(path): class Document(wx.EvtHandler): """ - The document class can be used to model an application's - file-based data. It is part of the document/view framework, and - cooperates with the `View`, `DocTemplate` and `DocManager` - classes. + The document class can be used to model an application's file-based data. It + is part of the document/view framework supported by wxWindows, and cooperates + with the wxView, wxDocTemplate and wxDocManager classes. Note this wxPython version also keeps track of the modification date of the document and if it changes on disk outside of the application, we will warn the @@ -89,7 +86,7 @@ class Document(wx.EvtHandler): """ - def __init__(self, parent = None): + def __init__(self, parent=None): """ Constructor. Define your own default constructor to initialize application-specific data. @@ -148,10 +145,10 @@ class Document(wx.EvtHandler): def GetDocumentName(self): """ - The document type name given to the `DocTemplate` constructor, + The document type name given to the wxDocTemplate constructor, copied to this document when the document is created. If several document templates are created that use the same document type, this - variable is used in `DocManager.CreateView` to collate a list of + variable is used in wxDocManager::CreateView to collate a list of alternative view types that can be used on this kind of document. """ return self._documentTypeName @@ -159,10 +156,10 @@ class Document(wx.EvtHandler): def SetDocumentName(self, name): """ - Sets the document type name given to the `DocTemplate` constructor, + Sets he document type name given to the wxDocTemplate constructor, copied to this document when the document is created. If several document templates are created that use the same document type, this - variable is used in `DocManager.CreateView` to collate a list of + variable is used in wxDocManager::CreateView to collate a list of alternative view types that can be used on this kind of document. Do not change the value of this variable. """ @@ -171,14 +168,16 @@ class Document(wx.EvtHandler): def GetDocumentSaved(self): """ - Returns True if the document has been saved. + Returns True if the document has been saved. This method has been + added to wxPython and is not in wxWindows. """ return self._savedYet - def SetDocumentSaved(self, saved = True): + def SetDocumentSaved(self, saved=True): """ - Sets whether the document has been saved. + Sets whether the document has been saved. This method has been + added to wxPython and is not in wxWindows. """ self._savedYet = saved @@ -194,7 +193,7 @@ class Document(wx.EvtHandler): """ Sets the command processor to be used for this document. The document will then be responsible for its deletion. Normally you should not - call this; override `OnCreateCommandProcessor` instead. + call this; override OnCreateCommandProcessor instead. """ self._commandProcessor = processor @@ -214,15 +213,18 @@ class Document(wx.EvtHandler): Call with true to mark the document as modified since the last save, false otherwise. You may need to override this if your document view maintains its own record of being modified (for example if using - `wx.TextCtrl` to view and edit the document). + xTextWindow to view and edit the document). + This method has been extended to notify its views that the dirty flag has changed. """ self._documentModified = modify + self.UpdateAllViews(hint=("modify", self, self._documentModified)) def SetDocumentModificationDate(self): """ Saves the file's last modification date. This is used to check if the file has been modified outside of the application. + This method has been added to wxPython and is not in wxWindows. """ self._documentModificationDate = os.path.getmtime(self.GetFilename()) @@ -231,10 +233,21 @@ class Document(wx.EvtHandler): """ Returns the file's modification date when it was loaded from disk. This is used to check if the file has been modified outside of the application. + This method has been added to wxPython and is not in wxWindows. """ return self._documentModificationDate + def IsDocumentModificationDateCorrect(self): + """ + Returns False if the file has been modified outside of the application. + This method has been added to wxPython and is not in wxWindows. + """ + if not os.path.exists(self.GetFilename()): # document must be in memory only and can't be out of date + return True + return self._documentModificationDate == os.path.getmtime(self.GetFilename()) + + def GetViews(self): """ Returns the list whose elements are the views on the document. @@ -270,6 +283,7 @@ class Document(wx.EvtHandler): Destructor. Removes itself from the document manager. """ self.DeleteContents() + self._documentModificationDate = None if self.GetDocumentManager(): self.GetDocumentManager().RemoveDocument(self) wx.EvtHandler.Destroy(self) @@ -277,10 +291,9 @@ class Document(wx.EvtHandler): def Close(self): """ - Closes the document, by calling `OnSaveModified` and then (if - this returns True) `OnCloseDocument`. This does not normally - delete the document object: use DeleteAllViews to do this - implicitly. + Closes the document, by calling OnSaveModified and then (if this true) + OnCloseDocument. This does not normally delete the document object: + use DeleteAllViews to do this implicitly. """ if self.OnSaveModified(): if self.OnCloseDocument(): @@ -293,10 +306,9 @@ class Document(wx.EvtHandler): def OnCloseDocument(self): """ - The default implementation calls `DeleteContents` (an empty - implementation) sets the modified flag to false. Override this - to supply additional behaviour when the document is closed - with `Close`. + The default implementation calls DeleteContents (an empty + implementation) sets the modified flag to false. Override this to + supply additional behaviour when the document is closed with Close. """ self.NotifyClosing() self.DeleteContents() @@ -306,9 +318,9 @@ class Document(wx.EvtHandler): def DeleteAllViews(self): """ - Calls `View.Close` and deletes each view. Deleting the final view will - implicitly delete the document itself, because the `View` destructor - calls `RemoveView`. This in turns calls `Document.OnChangedViewList`, + Calls wxView.Close and deletes each view. Deleting the final view will + implicitly delete the document itself, because the wxView destructor + calls RemoveView. This in turns calls wxDocument::OnChangedViewList, whose default implemention is to save and delete the document if no views exist. """ @@ -342,10 +354,9 @@ class Document(wx.EvtHandler): def OnNewDocument(self): """ - The default implementation calls `OnSaveModified` and - `DeleteContents`, makes a default title for the document, and - notifies the views that the filename (in fact, the title) has - changed. + The default implementation calls OnSaveModified and DeleteContents, + makes a default title for the document, and notifies the views that + the filename (in fact, the title) has changed. """ if not self.OnSaveModified() or not self.OnCloseDocument(): return False @@ -359,14 +370,14 @@ class Document(wx.EvtHandler): def Save(self): """ - Saves the document by calling `OnSaveDocument` if there is an - associated filename, or `SaveAs` if there is no filename. + Saves the document by calling OnSaveDocument if there is an associated + filename, or SaveAs if there is no filename. """ if not self.IsModified(): # and self._savedYet: This was here, but if it is not modified who cares if it hasn't been saved yet? return True """ check for file modification outside of application """ - if os.path.exists(self.GetFilename()) and os.path.getmtime(self.GetFilename()) != self.GetDocumentModificationDate(): + if not self.IsDocumentModificationDateCorrect(): msgTitle = wx.GetApp().GetAppName() if not msgTitle: msgTitle = _("Application") @@ -389,7 +400,7 @@ class Document(wx.EvtHandler): def SaveAs(self): """ - Prompts the user for a file to save to, and then calls `OnSaveDocument`. + Prompts the user for a file to save to, and then calls OnSaveDocument. """ docTemplate = self.GetDocumentTemplate() if not docTemplate: @@ -428,9 +439,9 @@ class Document(wx.EvtHandler): 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. + 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 @@ -440,6 +451,8 @@ class Document(wx.EvtHandler): 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): @@ -457,19 +470,27 @@ class Document(wx.EvtHandler): while os.path.exists(backupFilename): i += 1 backupFilename = "%s.bak%s" % (filename, i) - os.rename(filename, backupFilename) + shutil.copy(filename, backupFilename) + copied = True fileObject = file(filename, 'w') self.SaveObject(fileObject) - + fileObject.close() + fileObject = None + if backupFilename: os.remove(backupFilename) except: - # save failed, restore old file - if backupFilename: - os.remove(filename) - os.rename(backupFilename, filename) - self.SetDocumentModificationDate() + # 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, @@ -477,9 +498,9 @@ class Document(wx.EvtHandler): self.GetDocumentWindow()) return False + self.SetDocumentModificationDate() self.SetFilename(filename, True) self.Modify(False) - self.SetDocumentModificationDate() self.SetDocumentSaved(True) #if wx.Platform == '__WXMAC__': # Not yet implemented in wxPython # wx.FileName(file).MacSetDefaultTypeAndCreator() @@ -489,7 +510,7 @@ class Document(wx.EvtHandler): 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 + 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 @@ -505,16 +526,25 @@ class Document(wx.EvtHandler): 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.SetDocumentModificationDate() self.SetDocumentSaved(True) self.UpdateAllViews() return True @@ -522,26 +552,24 @@ class Document(wx.EvtHandler): 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. + 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. + 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. + 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. + Note that the wxPython version simply sends you a Python file object, + so you can use pickle. """ return True @@ -582,25 +610,24 @@ class Document(wx.EvtHandler): 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 `CommandProcessor`. + 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 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 os.path.exists(self.GetFilename()) and os.path.getmtime(self.GetFilename()) != self.GetDocumentModificationDate(): + if not self.IsDocumentModificationDateCorrect(): msgTitle = wx.GetApp().GetAppName() if not msgTitle: msgTitle = _("Warning") @@ -645,7 +672,7 @@ class Document(wx.EvtHandler): def AddView(self, view): """ If the view is not already in the list of views, adds the view and - calls `OnChangedViewList`. + calls OnChangedViewList. """ if not view in self._documentViews: self._documentViews.append(view) @@ -656,7 +683,7 @@ class Document(wx.EvtHandler): def RemoveView(self, view): """ Removes the view from the document's list of views, and calls - `OnChangedViewList`. + OnChangedViewList. """ if view in self._documentViews: self._documentViews.remove(view) @@ -666,10 +693,12 @@ class Document(wx.EvtHandler): def OnCreate(self, path, flags): """ - The default implementation calls `DeleteContents` (an empty + The default implementation calls DeleteContents (an empty implementation) sets the modified flag to false. Override this to - supply additional behaviour when the document is closed with Close. + supply additional behaviour when the document is opened with Open. """ + if flags & DOC_NO_VIEW: + return True return self.GetDocumentTemplate().CreateView(self, flags) @@ -686,7 +715,7 @@ class Document(wx.EvtHandler): def UpdateAllViews(self, sender = None, hint = None): """ - Updates all views. If sender is non-None, does not update this view. + 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. """ @@ -706,7 +735,7 @@ class Document(wx.EvtHandler): def SetFilename(self, filename, notifyViews = False): """ Sets the filename for this document. Usually called by the framework. - If notifyViews is true, `View.OnChangeFilename` is called for all + If notifyViews is true, wxView.OnChangeFilename is called for all views. """ self._documentFile = filename @@ -730,19 +759,20 @@ class Document(wx.EvtHandler): 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. + 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 + to wxPython and is not in wxWindows. """ self._writeable = writeable class View(wx.EvtHandler): """ - The view class can be used to model the viewing and editing - component of an application's file-based data. It cooperates - with the `Document`, `DocTemplate` and `DocManager` classes. + The view class can be used to model the viewing and editing component of + an application's file-based data. It is part of the document/view + framework supported by wxWindows, and cooperates with the wxDocument, + wxDocTemplate and wxDocManager classes. """ def __init__(self): @@ -789,7 +819,7 @@ class View(wx.EvtHandler): def OnActivateView(self, activate, activeView, deactiveView): """ - Called when a view is activated by means of `View.Activate`. The + Called when a view is activated by means of wxView::Activate. The default implementation does nothing. """ pass @@ -814,21 +844,27 @@ class View(wx.EvtHandler): def OnPrint(self, dc, info): """ Override this to print the view for the printing framework. The - default implementation calls `View.OnDraw`. + default implementation calls View.OnDraw. """ self.OnDraw(dc) def OnUpdate(self, sender, hint): """ - Called when the view should be updated. sender is a reference to the - view that sent the update request, or None if no single view requested + Called when the view should be updated. sender is a pointer to the + view that sent the update request, or NULL if no single view requested the update (for instance, when the document is opened). hint is as yet unused but may in future contain application-specific information for making updating more efficient. """ - pass - + if hint: + if hint[0] == "modify": # if dirty flag changed, update the view's displayed title + frame = self.GetFrame() + if frame and hasattr(frame, "OnTitleIsModified"): + frame.OnTitleIsModified() + return True + return False + def OnChangeFilename(self): """ @@ -870,7 +906,7 @@ class View(wx.EvtHandler): def GetViewName(self): """ - Gets the name associated with the view (passed to the `DocTemplate` + Gets the name associated with the view (passed to the wxDocTemplate constructor). Not currently used by the framework. """ return self._viewTypeName @@ -883,9 +919,9 @@ class View(wx.EvtHandler): self._viewTypeName = name - def Close(self, deleteWindow = True): + def Close(self, deleteWindow=True): """ - Closes the view by calling `OnClose`. If deleteWindow is true, this + Closes the view by calling OnClose. If deleteWindow is true, this function should delete the window associated with the view. """ if self.OnClose(deleteWindow = deleteWindow): @@ -894,28 +930,28 @@ class View(wx.EvtHandler): return False - def Activate(self, activate = True): + def Activate(self, activate=True): """ - Call this from your view frame's EVT_ACTIVATE handler to tell - the framework which view is currently active. If your - windowing system doesn't support EVT_ACTIVATE, you may need to - call this function from an EVT_MENU handler, or any place - where you know the view must be active, and the framework will - need to get the current view. + Call this from your view frame's OnActivate member to tell the + framework which view is currently active. If your windowing system + doesn't call OnActivate, you may need to call this function from + OnMenuCommand or any place where you know the view must be active, and + the framework will need to get the current view. + + The prepackaged view frame wxDocChildFrame calls wxView.Activate from + its OnActivate member and from its OnMenuCommand member. """ if self.GetDocument() and self.GetDocumentManager(): - self.OnActivateView(activate, - self, - self.GetDocumentManager().GetCurrentView()) + self.OnActivateView(activate, self, self.GetDocumentManager().GetCurrentView()) self.GetDocumentManager().ActivateView(self, activate) - def OnClose(self, deleteWindow = True): + def OnClose(self, deleteWindow=True): """ Implements closing behaviour. The default implementation calls - `Document.Close` to close the associated document. Does not delete the + wxDocument.Close to close the associated document. Does not delete the view. The application may wish to do some cleaning up operations in - this function, if a call to `Document.Close` succeeded. For example, + this function, if a call to wxDocument::Close succeeded. For example, if your application's all share the same window, you need to disassociate the window from the view and perhaps clear the window. If deleteWindow is true, delete the frame associated with the view. @@ -928,11 +964,11 @@ class View(wx.EvtHandler): def OnCreate(self, doc, flags): """ - `DocManager` or `Document` creates a `View` via a `DocTemplate`. Just - after the `DocTemplate` creates the `View`, it calls `View.OnCreate`. - In its `OnCreate` member function, the `View` can create a - `DocChildFrame` or a derived class. This `DocChildFrame` provides user - interface elements to view and/or edit the contents of the `Document`. + wxDocManager or wxDocument creates a wxView via a wxDocTemplate. Just + after the wxDocTemplate creates the wxView, it calls wxView::OnCreate. + In its OnCreate member function, the wxView can create a + wxDocChildFrame or a derived class. This wxDocChildFrame provides user + interface elements to view and/or edit the contents of the wxDocument. By default, simply returns true. If the function returns false, the view will be deleted. @@ -942,23 +978,24 @@ class View(wx.EvtHandler): def OnCreatePrintout(self): """ - Returns a `wx.Printout` object for the purposes of printing. It should + Returns a wxPrintout object for the purposes of printing. It should create a new object every time it is called; the framework will delete objects it creates. - By default, this function returns an instance of `DocPrintout`, which - prints and previews one page by calling `View.OnDraw`. + By default, this function returns an instance of wxDocPrintout, which + prints and previews one page by calling wxView.OnDraw. - Override to return an instance of a class other than `DocPrintout`. + Override to return an instance of a class other than wxDocPrintout. """ - return DocPrintout(self) + return DocPrintout(self, self.GetDocument().GetPrintableName()) def GetFrame(self): """ Gets the frame associated with the view (if any). Note that this - "frame" is not a `wx.Frame` at all in the generic MDI implementation - which uses the notebook pages instead of the frames. + "frame" is not a wxFrame at all in the generic MDI implementation + which uses the notebook pages instead of the frames and this is why + this method returns a wxWindow and not a wxFrame. """ return self._viewFrame @@ -966,7 +1003,9 @@ class View(wx.EvtHandler): def SetFrame(self, frame): """ Sets the frame associated with this view. The application should call - this if possible, to tell the view about the frame. + this if possible, to tell the view about the frame. See GetFrame for + the explanation about the mismatch between the "Frame" in the method + name and the type of its parameter. """ self._viewFrame = frame @@ -983,57 +1022,51 @@ class View(wx.EvtHandler): class DocTemplate(wx.Object): """ - The `DocTemplate` class is used to model the relationship between - a document class and a view class. + The wxDocTemplate class is used to model the relationship between a + document class and a view class. """ - def __init__(self, manager, description, filter, dir, ext, - docTypeName, viewTypeName, docType, viewType, - flags = DEFAULT_TEMPLATE_FLAGS, icon = None): + def __init__(self, manager, description, filter, dir, ext, docTypeName, viewTypeName, docType, viewType, flags=DEFAULT_TEMPLATE_FLAGS, icon=None): """ Constructor. Create instances dynamically near the start of your - application after creating a `DocManager` instance, and before doing + application after creating a wxDocManager instance, and before doing any document or view operations. - :param manager: the document manager object which manages this template. + manager is the document manager object which manages this template. - :param description: a short description of what the template - is for. This string will be displayed in the file filter - list of Windows file selectors. + description is a short description of what the template is for. This + string will be displayed in the file filter list of Windows file + selectors. - :param filter: an appropriate file filter such as \*.txt. + filter is an appropriate file filter such as \*.txt. - :param dir: the default directory to use for file selectors. + dir is the default directory to use for file selectors. - :param ext: the default file extension (such as txt). + ext is the default file extension (such as txt). - :param docTypeName: a name that should be unique for a given - type of document, used for gathering a list of views - relevant to a particular document. + docTypeName is a name that should be unique for a given type of + document, used for gathering a list of views relevant to a + particular document. - :param viewTypeName: a name that should be unique for a given view. + viewTypeName is a name that should be unique for a given view. - :param docType: a Python class. If this is not supplied, you - will need to derive a new `DocTemplate` class and override - the `CreateDocument` member to return a new document - instance on demand. + docClass is a Python class. If this is not supplied, you will need to + derive a new wxDocTemplate class and override the CreateDocument + member to return a new document instance on demand. - :param viewType: a Python class. If this is not supplied, you - will need to derive a new `DocTemplate` class and override - the `CreateView` member to return a new view instance on - demand. + viewClass is a Python class. If this is not supplied, you will need to + derive a new wxDocTemplate class and override the CreateView member to + return a new view instance on demand. - :param flags: a bit list of the following - - * TEMPLATE_VISIBLE: The template may be displayed to the - user in dialogs. + flags is a bit list of the following: + wx.TEMPLATE_VISIBLE The template may be displayed to the user in + dialogs. - * TEMPLATE_INVISIBLE: The template may not be displayed - to the user in dialogs. + wx.TEMPLATE_INVISIBLE The template may not be displayed to the user in + dialogs. - * DEFAULT_TEMPLATE_FLAGS: Defined as TEMPLATE_VISIBLE. - + wx.DEFAULT_TEMPLATE_FLAGS Defined as wxTEMPLATE_VISIBLE. """ self._docManager = manager self._description = description @@ -1052,8 +1085,8 @@ class DocTemplate(wx.Object): def GetDefaultExtension(self): """ - Returns the default file extension for the document data, as - passed to the document template constructor. + Returns the default file extension for the document data, as passed to + the document template constructor. """ return self._defaultExt @@ -1067,8 +1100,8 @@ class DocTemplate(wx.Object): def GetDescription(self): """ - Returns the text description of this template, as passed to - the document template constructor. + Returns the text description of this template, as passed to the + document template constructor. """ return self._description @@ -1082,8 +1115,8 @@ class DocTemplate(wx.Object): def GetDirectory(self): """ - Returns the default directory, as passed to the document - template constructor. + Returns the default directory, as passed to the document template + constructor. """ return self._directory @@ -1097,8 +1130,8 @@ class DocTemplate(wx.Object): def GetDocumentManager(self): """ - Returns the document manager instance for which this template - was created. + Returns the document manager instance for which this template was + created. """ return self._docManager @@ -1145,14 +1178,16 @@ class DocTemplate(wx.Object): def GetIcon(self): """ Returns the icon, as passed to the document template - constructor. + constructor. This method has been added to wxPython and is + not in wxWindows. """ return self._icon def SetIcon(self, flags): """ - Sets the icon. + Sets the icon. This method has been added to wxPython and is not + in wxWindows. """ self._icon = icon @@ -1181,6 +1216,16 @@ class DocTemplate(wx.Object): return (self._flags & TEMPLATE_VISIBLE) == TEMPLATE_VISIBLE + def IsNewable(self): + """ + Returns true if the document template can be shown in "New" dialogs, + false otherwise. + + This method has been added to wxPython and is not in wxWindows. + """ + return (self._flags & TEMPLATE_NO_CREATE) != TEMPLATE_NO_CREATE + + def GetDocumentName(self): """ Returns the document type name, as passed to the document template @@ -1218,10 +1263,9 @@ class DocTemplate(wx.Object): def CreateView(self, doc, flags): """ - Creates a new instance of the associated document view. If you - have not supplied a class to the template constructor, you - will need to override this function to return an appropriate - view instance. + Creates a new instance of the associated document view. If you have + not supplied a class to the template constructor, you will need to + override this function to return an appropriate view instance. """ view = self._viewType() view.SetDocument(doc) @@ -1239,31 +1283,31 @@ class DocTemplate(wx.Object): """ ext = FindExtension(path) if not ext: return False - return ext in self.GetFileFilter() - # return self.GetDefaultExtension() == FindExtension(path) + + extList = self.GetFileFilter().replace('*','').split(';') + return ext in extList class DocManager(wx.EvtHandler): """ - The `DocManager` class is part of the document/view framework and - cooperates with the `View`, `Document` and `DocTemplate` classes. + The wxDocManager class is part of the document/view framework supported by + wxWindows, and cooperates with the wxView, wxDocument and wxDocTemplate + classes. """ - def __init__(self, flags = DEFAULT_DOCMAN_FLAGS, initialize = True): + def __init__(self, flags=DEFAULT_DOCMAN_FLAGS, initialize=True): """ - Constructor. Create a document manager instance dynamically - near the start of your application before doing any document - or view operations. + Constructor. Create a document manager instance dynamically near the + start of your application before doing any document or view operations. - :param flags: used to indicate whether the document manager is - in DOC_SDI or DOC_MDI mode. + flags is used in the Python version to indicate whether the document + manager is in DOC_SDI or DOC_MDI mode. - :param initialize: if true, the `Initialize` function will be - called to create a default history list object. If you - derive from DocManager, you may wish to call the base - constructor with false, and then call `Initialize` in your - own constructor, to allow your own `Initialize` or - `OnCreateFileHistory` functions to be called. + If initialize is true, the Initialize function will be called to + create a default history list object. If you derive from wxDocManager, + you may wish to call the base constructor with false, and then call + Initialize in your own constructor, to allow your own Initialize or + OnCreateFileHistory functions to be called. """ wx.EvtHandler.__init__(self) @@ -1318,12 +1362,13 @@ class DocManager(wx.EvtHandler): def GetFlags(self): """ - Returns the document manager's flags. + Returns the document manager's flags. This method has been + added to wxPython and is not in wxWindows. """ return self._flags - def CloseDocument(self, doc, force = True): + def CloseDocument(self, doc, force=True): """ Closes the specified document. """ @@ -1335,20 +1380,21 @@ class DocManager(wx.EvtHandler): return False - def CloseDocuments(self, force = True): + def CloseDocuments(self, force=True): """ Closes all currently opened documents. """ for document in self._docs[::-1]: # Close in lifo (reverse) order. We clone the list to make sure we go through all docs even as they are deleted if not self.CloseDocument(document, force): return False - document.DeleteAllViews() # Implicitly delete the document when the last view is removed + if document: + document.DeleteAllViews() # Implicitly delete the document when the last view is removed return True - def Clear(self, force = True): + def Clear(self, force=True): """ - Closes all currently opened document by calling `CloseDocuments` and + Closes all currently opened document by callling CloseDocuments and clears the document manager's templates. """ if not self.CloseDocuments(force): @@ -1359,13 +1405,16 @@ class DocManager(wx.EvtHandler): def Initialize(self): """ - Initializes data; currently just calls `OnCreateFileHistory`. Some data + Initializes data; currently just calls OnCreateFileHistory. Some data cannot always be initialized in the constructor because the programmer must be given the opportunity to override functionality. In fact - Initialize is called from the `DocManager` constructor, but this can - be prevented by passing false to the second argument, allowing the + Initialize is called from the wxDocManager constructor, but this can + be vetoed by passing false to the second argument, allowing the derived class's constructor to call Initialize, possibly calling a - different `OnCreateFileHistory` from the default. + different OnCreateFileHistory from the default. + + The bottom line: if you're not deriving from Initialize, forget it and + construct wxDocManager with no arguments. """ self.OnCreateFileHistory() return True @@ -1374,7 +1423,7 @@ class DocManager(wx.EvtHandler): def OnCreateFileHistory(self): """ A hook to allow a derived class to create a different type of file - history. Called from `Initialize`. + history. Called from Initialize. """ self._fileHistory = wx.FileHistory() @@ -1396,7 +1445,7 @@ class DocManager(wx.EvtHandler): """ return self.CloseDocuments(force = False) - + def OnFileNew(self, event): """ Creates a new document and reads in the selected file. @@ -1414,8 +1463,8 @@ class DocManager(wx.EvtHandler): def OnFileRevert(self, event): """ - Reverts the current document by calling `Document.Save` for - the current document. + Reverts the current document by calling wxDocument.Save for the current + document. """ doc = self.GetCurrentDocument() if not doc: @@ -1425,8 +1474,8 @@ class DocManager(wx.EvtHandler): def OnFileSave(self, event): """ - Saves the current document by calling `Document.Save` for the - current document. + Saves the current document by calling wxDocument.Save for the current + document. """ doc = self.GetCurrentDocument() if not doc: @@ -1436,7 +1485,7 @@ class DocManager(wx.EvtHandler): def OnFileSaveAs(self, event): """ - Calls `Document.SaveAs` for the current document. + Calls wxDocument.SaveAs for the current document. """ doc = self.GetCurrentDocument() if not doc: @@ -1446,8 +1495,8 @@ class DocManager(wx.EvtHandler): def OnPrint(self, event): """ - Prints the current document by calling its - `View.OnCreatePrintout` method. + Prints the current document by calling its View's OnCreatePrintout + method. """ view = self.GetCurrentView() if not view: @@ -1455,9 +1504,14 @@ class DocManager(wx.EvtHandler): printout = view.OnCreatePrintout() if printout: - pdd = wx.PrintDialogData() + if not hasattr(self, "printData"): + self.printData = wx.PrintData() + self.printData.SetPaperId(wx.PAPER_LETTER) + self.printData.SetPrintMode(wx.PRINT_MODE_PRINTER) + + pdd = wx.PrintDialogData(self.printData) printer = wx.Printer(pdd) - printer.Print(view.GetFrame(), printout) # , True) + printer.Print(view.GetFrame(), printout) def OnPrintSetup(self, event): @@ -1470,16 +1524,26 @@ class DocManager(wx.EvtHandler): else: parentWin = wx.GetApp().GetTopWindow() - data = wx.PrintDialogData() + if not hasattr(self, "printData"): + self.printData = wx.PrintData() + self.printData.SetPaperId(wx.PAPER_LETTER) + + data = wx.PrintDialogData(self.printData) printDialog = wx.PrintDialog(parentWin, data) printDialog.GetPrintDialogData().SetSetupDialog(True) printDialog.ShowModal() - # TODO: Confirm that we don't have to remember PrintDialogData + + # this makes a copy of the wx.PrintData instead of just saving + # a reference to the one inside the PrintDialogData that will + # be destroyed when the dialog is destroyed + self.printData = wx.PrintData(printDialog.GetPrintDialogData().GetPrintData()) + + printDialog.Destroy() def OnPreview(self, event): """ - Previews the current document by calling its `View.OnCreatePrintout` + Previews the current document by calling its View's OnCreatePrintout method. """ view = self.GetCurrentView() @@ -1488,13 +1552,22 @@ class DocManager(wx.EvtHandler): printout = view.OnCreatePrintout() if printout: + if not hasattr(self, "printData"): + self.printData = wx.PrintData() + self.printData.SetPaperId(wx.PAPER_LETTER) + self.printData.SetPrintMode(wx.PRINT_MODE_PREVIEW) + + data = wx.PrintDialogData(self.printData) # Pass two printout objects: for preview, and possible printing. - preview = wx.PrintPreview(printout, view.OnCreatePrintout()) + preview = wx.PrintPreview(printout, view.OnCreatePrintout(), data) + if not preview.Ok(): + wx.MessageBox(_("Unable to display print preview.")) + return # wxWindows source doesn't use base frame's pos, size, and icon, but did it this way so it would work like MS Office etc. mimicFrame = wx.GetApp().GetTopWindow() frame = wx.PreviewFrame(preview, mimicFrame, _("Print Preview"), mimicFrame.GetPosition(), mimicFrame.GetSize()) frame.SetIcon(mimicFrame.GetIcon()) - frame.SetTitle(mimicFrame.GetTitle() + _(" - Preview")) + frame.SetTitle(_("%s - %s - Preview") % (mimicFrame.GetTitle(), view.GetDocument().GetPrintableName())) frame.Initialize() frame.Show(True) @@ -1580,7 +1653,7 @@ class DocManager(wx.EvtHandler): if doc and doc.GetCommandProcessor(): doc.GetCommandProcessor().SetMenuStrings() else: - event.SetText(_("Undo") + '\t' + _('Ctrl+Z')) + event.SetText(_("&Undo\tCtrl+Z")) def OnUpdateRedo(self, event): @@ -1592,7 +1665,7 @@ class DocManager(wx.EvtHandler): if doc and doc.GetCommandProcessor(): doc.GetCommandProcessor().SetMenuStrings() else: - event.SetText(_("Redo") + '\t' + _('Ctrl+Y')) + event.SetText(_("&Redo\tCtrl+Y")) def OnUpdatePrint(self, event): @@ -1629,11 +1702,9 @@ class DocManager(wx.EvtHandler): def GetLastActiveView(self): """ - Returns the last active view. This is used in the SDI - framework where dialogs can be mistaken for a view and causes - the framework to deactivete the current view. This happens - when something like a custom dialog box used to operate on the - current view is shown. + Returns the last active view. This is used in the SDI framework where dialogs can be mistaken for a view + and causes the framework to deactivete the current view. This happens when something like a custom dialog box used + to operate on the current view is shown. """ if len(self._docs) >= 1: return self._lastActiveView @@ -1643,11 +1714,10 @@ class DocManager(wx.EvtHandler): def ProcessEvent(self, event): """ - Processes an event, searching event tables and calling zero or - more suitable event handler function(s). Note that the - ProcessEvent method is called from the wxPython docview - framework directly since wxPython does not have a virtual - ProcessEvent function. + Processes an event, searching event tables and calling zero or more + suitable event handler function(s). Note that the ProcessEvent + method is called from the wxPython docview framework directly since + wxPython does not have a virtual ProcessEvent function. """ view = self.GetCurrentView() if view: @@ -1696,11 +1766,10 @@ class DocManager(wx.EvtHandler): def ProcessUpdateUIEvent(self, event): """ - Processes a UI event, searching event tables and calling zero - or more suitable event handler function(s). Note that the - ProcessEvent method is called from the wxPython docview - framework directly since wxPython does not have a virtual - ProcessEvent function. + Processes a UI event, searching event tables and calling zero or more + suitable event handler function(s). Note that the ProcessEvent + method is called from the wxPython docview framework directly since + wxPython does not have a virtual ProcessEvent function. """ id = event.GetId() view = self.GetCurrentView() @@ -1747,30 +1816,34 @@ class DocManager(wx.EvtHandler): return False - def CreateDocument(self, path, flags = 0): + def CreateDocument(self, path, flags=0): """ Creates a new document in a manner determined by the flags parameter, which can be: - * DOC_NEW: Creates a fresh document. - * DOC_SILENT: Silently loads the given document file. - - If DOC_NEW is present, a new document will be created and - returned, possibly after asking the user for a template to use - if there is more than one document template. If DOC_SILENT is - present, a new document will be created and the given file - loaded into it. If neither of these flags is present, the user - will be presented with a file selector for the file to load, - and the template to use will be determined by the extension - (Windows) or by popping up a template choice list (other + wx.lib.docview.DOC_NEW Creates a fresh document. + wx.lib.docview.DOC_SILENT Silently loads the given document file. + + If wx.lib.docview.DOC_NEW is present, a new document will be created and returned, + possibly after asking the user for a template to use if there is more + than one document template. If wx.lib.docview.DOC_SILENT is present, a new document + will be created and the given file loaded into it. If neither of these + flags is present, the user will be presented with a file selector for + the file to load, and the template to use will be determined by the + extension (Windows) or by popping up a template choice list (other platforms). - If the maximum number of documents has been reached, this - function will delete the oldest currently loaded document - before creating a new one. + If the maximum number of documents has been reached, this function + will delete the oldest currently loaded document before creating a new + one. - wxPython version supports the document manager's DOC_OPEN_ONCE - flag. + wxPython version supports the document manager's wx.lib.docview.DOC_OPEN_ONCE + and wx.lib.docview.DOC_NO_VIEW flag. + + if wx.lib.docview.DOC_OPEN_ONCE is present, trying to open the same file multiple + times will just return the same document. + if wx.lib.docview.DOC_NO_VIEW is present, opening a file will generate the document, + but not generate a corresponding view. """ templates = [] for temp in self._templates: @@ -1785,16 +1858,13 @@ class DocManager(wx.EvtHandler): return None if flags & DOC_NEW: + for temp in templates[:]: + if not temp.IsNewable(): + templates.remove(temp) if len(templates) == 1: temp = templates[0] - newDoc = temp.CreateDocument(path, flags) - if newDoc: - newDoc.SetDocumentName(temp.GetDocumentName()) - newDoc.SetDocumentTemplate(temp) - newDoc.OnNewDocument() - return newDoc - - temp = self.SelectDocumentType(templates) + else: + temp = self.SelectDocumentType(templates) if temp: newDoc = temp.CreateDocument(path, flags) if newDoc: @@ -1811,11 +1881,34 @@ class DocManager(wx.EvtHandler): temp, path = self.SelectDocumentPath(templates, path, flags) # Existing document - if self.GetFlags() & DOC_OPEN_ONCE: + if path and self.GetFlags() & DOC_OPEN_ONCE: for document in self._docs: - if document.GetFilename() == path: + if document.GetFilename() and os.path.normcase(document.GetFilename()) == os.path.normcase(path): + """ check for file modification outside of application """ + if not document.IsDocumentModificationDateCorrect(): + msgTitle = wx.GetApp().GetAppName() + if not msgTitle: + msgTitle = _("Warning") + shortName = document.GetPrintableName() + res = wx.MessageBox(_("'%s' has been modified outside of %s. Reload '%s' from file system?") % (shortName, msgTitle, shortName), + msgTitle, + wx.YES_NO | wx.ICON_QUESTION, + self.FindSuitableParent()) + if res == wx.YES: + if not self.CloseDocument(document, False): + wx.MessageBox(_("Couldn't reload '%s'. Unable to close current '%s'.") % (shortName, shortName)) + return None + return self.CreateDocument(path, flags) + elif res == wx.NO: # don't ask again + document.SetDocumentModificationDate() + firstView = document.GetFirstView() - if firstView and firstView.GetFrame(): + if not firstView and not (flags & DOC_NO_VIEW): + document.GetDocumentTemplate().CreateView(document, flags) + document.UpdateAllViews() + firstView = document.GetFirstView() + + if firstView and firstView.GetFrame() and not (flags & DOC_NO_VIEW): firstView.GetFrame().SetFocus() # Not in wxWindows code but useful nonetheless if hasattr(firstView.GetFrame(), "IsIconized") and firstView.GetFrame().IsIconized(): # Not in wxWindows code but useful nonetheless firstView.GetFrame().Iconize(False) @@ -1828,7 +1921,9 @@ class DocManager(wx.EvtHandler): newDoc.SetDocumentTemplate(temp) if not newDoc.OnOpenDocument(path): newDoc.DeleteAllViews() # Implicitly deleted by DeleteAllViews - newDoc.GetFirstView().GetFrame().Destroy() # DeleteAllViews doesn't get rid of the frame, so we'll explicitly destroy it. + frame = newDoc.GetFirstView().GetFrame() + if frame: + frame.Destroy() # DeleteAllViews doesn't get rid of the frame, so we'll explicitly destroy it. return None self.AddFileToHistory(path) return newDoc @@ -1836,7 +1931,7 @@ class DocManager(wx.EvtHandler): return None - def CreateView(self, document, flags = 0): + def CreateView(self, doc, flags=0): """ Creates a new view for the given document. If more than one view is allowed for the document (by virtue of multiple templates mentioning @@ -1869,21 +1964,21 @@ class DocManager(wx.EvtHandler): def DeleteTemplate(self, template, flags): """ - Placeholder, not yet implemented + Placeholder, not yet implemented in wxWindows. """ pass def FlushDoc(self, doc): """ - Placeholder, not yet implemented + Placeholder, not yet implemented in wxWindows. """ return False def MatchTemplate(self, path): """ - Placeholder, not yet implemented + Placeholder, not yet implemented in wxWindows. """ return None @@ -1997,7 +2092,7 @@ class DocManager(wx.EvtHandler): self._fileHistory.Save(config) - def FileHistoryAddFilesToMenu(self, menu = None): + def FileHistoryAddFilesToMenu(self, menu=None): """ Appends the files in the history list, to all menus managed by the file history object. @@ -2027,11 +2122,17 @@ class DocManager(wx.EvtHandler): Given a path, try to find template that matches the extension. This is only an approximate method of finding a template for creating a document. + + Note this wxPython verson looks for and returns a default template if no specific template is found. """ + default = None for temp in self._templates: if temp.FileMatchesTemplate(path): return temp - return None + + if "*.*" in temp.GetFileFilter(): + default = temp + return default def FindSuitableParent(self): @@ -2058,44 +2159,35 @@ class DocManager(wx.EvtHandler): On other platforms, if there is more than one document template a choice list is popped up, followed by a file selector. - This function is used in `DocManager.CreateDocument`. + This function is used in wxDocManager.CreateDocument. """ if wx.Platform == "__WXMSW__" or wx.Platform == "__WXGTK__" or wx.Platform == "__WXMAC__": - allfilter = '' descr = '' for temp in templates: if temp.IsVisible(): if len(descr) > 0: descr = descr + _('|') - allfilter = allfilter + _(';') descr = descr + temp.GetDescription() + _(" (") + temp.GetFileFilter() + _(") |") + temp.GetFileFilter() # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk - allfilter = allfilter + temp.GetFileFilter() - descr = _("All") + _(" (") + allfilter + _(") |") + allfilter + _('|') + descr # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk + descr = _("All|*.*|%s") % descr # spacing is important, make sure there is no space after the "|", it causes a bug on wx_gtk else: descr = _("*.*") - path = wx.FileSelector(_("Select a File"), - self._lastDirectory, - _(""), - wildcard = descr, - flags = wx.HIDE_READONLY, - parent = self.FindSuitableParent()) - if path: - if not FileExists(path): - msgTitle = wx.GetApp().GetAppName() - if not msgTitle: - msgTitle = _("File Error") - wx.MessageBox("Could not open '%s'." % FileNameFromPath(path), - msgTitle, - wx.OK | wx.ICON_EXCLAMATION, - parent) - return (None, None) - self._lastDirectory = PathOnly(path) - + dlg = wx.FileDialog(self.FindSuitableParent(), + _("Select a File"), + wildcard=descr, + style=wx.OPEN|wx.FILE_MUST_EXIST|wx.CHANGE_DIR) + # dlg.CenterOnParent() # wxBug: caused crash with wx.FileDialog + if dlg.ShowModal() == wx.ID_OK: + path = dlg.GetPath() + else: + path = None + dlg.Destroy() + + if path: theTemplate = self.FindTemplateForPath(path) return (theTemplate, path) - - return (None, None) + + return (None, None) def OnOpenFileFailure(self): @@ -2105,18 +2197,19 @@ class DocManager(wx.EvtHandler): pass - def SelectDocumentType(self, temps, sort = False): + def SelectDocumentType(self, temps, sort=False): """ Returns a document template by asking the user (if there is more than - one template). This function is used in `DocManager.CreateDocument`. + one template). This function is used in wxDocManager.CreateDocument. + + Parameters - :param temps: list of templates from which to choose a desired template. + templates - list of templates from which to choose a desired template. - :param sort: If more than one template is passed in in - templates, then this parameter indicates whether the list - of templates that the user will have to choose from is - sorted or not when shown the choice box dialog. Default - is false. + sort - If more than one template is passed in in templates, then this + parameter indicates whether the list of templates that the user will + have to choose from is sorted or not when shown the choice box dialog. + Default is false. """ templates = [] for temp in temps: @@ -2152,14 +2245,9 @@ class DocManager(wx.EvtHandler): return templates[res] - def SelectViewType(self, temps, sort = False): + def SelectViewType(self, temps, sort=False): """ - Returns a document template by asking the user (if there is - more than one template), displaying a list of valid - views. This function is used in `DocManager.CreateView`. The - dialog normally will not appear because the array of templates - only contains those relevant to the document in question, and - often there will only be one such. + Returns a document template by asking the user (if there is more than one template), displaying a list of valid views. This function is used in wxDocManager::CreateView. The dialog normally will not appear because the array of templates only contains those relevant to the document in question, and often there will only be one such. """ templates = [] strings = [] @@ -2190,7 +2278,8 @@ class DocManager(wx.EvtHandler): def GetTemplates(self): """ - Returns the document manager's template list. + Returns the document manager's template list. This method has been added to + wxPython and is not in wxWindows. """ return self._templates @@ -2226,7 +2315,7 @@ class DocManager(wx.EvtHandler): self._docs.remove(doc) - def ActivateView(self, view, activate = True, deleting = False): + def ActivateView(self, view, activate=True, deleting=False): """ Sets the current view. """ @@ -2265,19 +2354,15 @@ class DocManager(wx.EvtHandler): class DocParentFrame(wx.Frame): """ - The DocParentFrame class provides a default top-level frame for - applications using the document/view framework. This class can - only be used for SDI (not MDI) parent frames. + The wxDocParentFrame class provides a default top-level frame for + applications using the document/view framework. This class can only be + used for SDI (not MDI) parent frames. - It cooperates with the `View`, `Document`, `DocManager` and - `DocTemplate` classes. + It cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplates + classes. """ - def __init__(self, manager, frame, id, title, - pos = wx.DefaultPosition, - size = wx.DefaultSize, - style = wx.DEFAULT_FRAME_STYLE, - name = "frame"): + def __init__(self, manager, frame, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): """ Constructor. Note that the event table must be rebuilt for the frame since the EvtHandler is not virtual. @@ -2377,17 +2462,17 @@ class DocParentFrame(wx.Frame): class DocChildFrame(wx.Frame): """ - The `DocChildFrame` class provides a default frame for displaying - documents on separate windows. This class can only be used for SDI - (not MDI) child frames. + The wxDocChildFrame class provides a default frame for displaying + documents on separate windows. This class can only be used for SDI (not + MDI) child frames. - The class is part of the document/view framework and cooperates - with the `View`, `Document`, `DocManager` and `DocTemplate` + The class is part of the document/view framework supported by wxWindows, + and cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplate classes. """ - def __init__(self, doc, view, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"): + def __init__(self, doc, view, frame, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): """ Constructor. Note that the event table must be rebuilt for the frame since the EvtHandler is not virtual. @@ -2524,16 +2609,16 @@ class DocChildFrame(wx.Frame): class DocMDIParentFrame(wx.MDIParentFrame): """ - The `DocMDIParentFrame` class provides a default top-level frame - for applications using the document/view framework. This class can - only be used for MDI parent frames. + The wxDocMDIParentFrame class provides a default top-level frame for + applications using the document/view framework. This class can only be + used for MDI parent frames. - It cooperates with the `View`, `Document`, `DocManager` and - `DocTemplate` classes. + It cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplate + classes. """ - def __init__(self, manager, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"): + def __init__(self, manager, frame, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): """ Constructor. Note that the event table must be rebuilt for the frame since the EvtHandler is not virtual. @@ -2633,17 +2718,17 @@ class DocMDIParentFrame(wx.MDIParentFrame): class DocMDIChildFrame(wx.MDIChildFrame): """ - The `DocMDIChildFrame` class provides a default frame for - displaying documents on separate windows. This class can only be - used for MDI child frames. + The wxDocMDIChildFrame class provides a default frame for displaying + documents on separate windows. This class can only be used for MDI child + frames. - The class is part of the document/view framework and cooperates - with the `View`, `Document`, `DocManager` and `DocTemplate` + The class is part of the document/view framework supported by wxWindows, + and cooperates with the wxView, wxDocument, wxDocManager and wxDocTemplate classes. """ - def __init__(self, doc, view, frame, id, title, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = "frame"): + def __init__(self, doc, view, frame, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): """ Constructor. Note that the event table must be rebuilt for the frame since the EvtHandler is not virtual. @@ -2726,6 +2811,7 @@ class DocMDIChildFrame(wx.MDIChildFrame): self._childView.Activate(event.GetActive()) self._activated = 0 + def OnCloseWindow(self, event): """ Closes and deletes the current view and document. @@ -2741,8 +2827,10 @@ class DocMDIChildFrame(wx.MDIChildFrame): self._childView.Activate(False) self._childView.Destroy() self._childView = None - if self._childDocument: - self._childDocument.Destroy() # This isn't in the wxWindows codebase but the document needs to be disposed of somehow + if self._childDocument: # This isn't in the wxWindows codebase but the document needs to be disposed of somehow + self._childDocument.DeleteContents() + if self._childDocument.GetDocumentManager(): + self._childDocument.GetDocumentManager().RemoveDocument(self._childDocument) self._childDocument = None self.Destroy() else: @@ -2779,18 +2867,40 @@ class DocMDIChildFrame(wx.MDIChildFrame): self._childView = view + def OnTitleIsModified(self): + """ + Add/remove to the frame's title an indication that the document is dirty. + If the document is dirty, an '*' is appended to the title + This method has been added to wxPython and is not in wxWindows. + """ + title = self.GetTitle() + if title: + if self.GetDocument().IsModified(): + if title.endswith("*"): + return + else: + title = title + "*" + self.SetTitle(title) + else: + if title.endswith("*"): + title = title[:-1] + self.SetTitle(title) + else: + return + + class DocPrintout(wx.Printout): """ - `DocPrintout` is a default Printout that prints the first page of - a document view. + DocPrintout is a default Printout that prints the first page of a document + view. """ - def __init__(self, view, title = "Printout"): + def __init__(self, view, title="Printout"): """ Constructor. """ - wx.Printout.__init__(self) + wx.Printout.__init__(self, title) self._printoutView = view @@ -2825,15 +2935,6 @@ class DocPrintout(wx.Printout): return pageNum == 1 - def OnBeginDocument(self, startPage, endPage): - """ - Not quite sure why this was overridden, but it was in wxWindows! :) - """ - if not wx.Printout.base_OnBeginDocument(self, startPage, endPage): - return False - return True - - def GetPageInfo(self): """ Indicates that the DocPrintout only has a single page. @@ -2851,28 +2952,25 @@ class DocPrintout(wx.Printout): class Command(wx.Object): """ - `Command` is a base class for modelling an application command, - which is an action usually performed by selecting a menu item, - pressing a toolbar button or any other means provided by the - application to change the data or view. + wxCommand is a base class for modelling an application command, which is + an action usually performed by selecting a menu item, pressing a toolbar + button or any other means provided by the application to change the data + or view. """ def __init__(self, canUndo = False, name = None): """ - Constructor. Command is an abstract class, so you will need to - derive a new class and call this constructor from your own - constructor. + Constructor. wxCommand is an abstract class, so you will need to + derive a new class and call this constructor from your own constructor. - :param canUndo: tells the command processor whether this - command is undo-able. You can achieve the same - functionality by overriding the `CanUndo` member function - (if for example the criteria for undoability is context- - dependent). + canUndo tells the command processor whether this command is undo-able. + You can achieve the same functionality by overriding the CanUndo member + function (if for example the criteria for undoability is context- + dependent). - :param name: must be supplied for the command processor to - display the command name in the application's edit menu. - + name must be supplied for the command processor to display the command + name in the application's edit menu. """ self._canUndo = canUndo self._name = name @@ -2894,52 +2992,48 @@ class Command(wx.Object): def Do(self): """ - Override this member function to execute the appropriate - action when called. Return true to indicate that the action - has taken place, false otherwise. Returning false will - indicate to the command processor that the action is not - undoable and should not be added to the command history. + Override this member function to execute the appropriate action when + called. Return true to indicate that the action has taken place, false + otherwise. Returning false will indicate to the command processor that + the action is not undoable and should not be added to the command + history. """ return True def Undo(self): """ - Override this member function to un-execute a previous - `Do`. Return true to indicate that the action has taken place, - false otherwise. Returning false will indicate to the command - processor that the action is not redoable and no change should - be made to the command history. + Override this member function to un-execute a previous Do. Return true + to indicate that the action has taken place, false otherwise. Returning + false will indicate to the command processor that the action is not + redoable and no change should be made to the command history. - How you implement this command is totally application - dependent, but typical strategies include: + How you implement this command is totally application dependent, but + typical strategies include: - * Perform an inverse operation on the last modified piece - of data in the document. When redone, a copy of data - stored in command is pasted back or some operation - reapplied. This relies on the fact that you know the - ordering of Undos; the user can never Undo at an - arbitrary position in he command history. + Perform an inverse operation on the last modified piece of data in the + document. When redone, a copy of data stored in command is pasted back + or some operation reapplied. This relies on the fact that you know the + ordering of Undos; the user can never Undo at an arbitrary position in + he command history. - * Restore the entire document state (perhaps using - document transactioning). Potentially very inefficient, - but possibly easier to code if the user interface and - data are complex, and an 'inverse execute' operation is - hard to write. + Restore the entire document state (perhaps using document + transactioning). Potentially very inefficient, but possibly easier to + code if the user interface and data are complex, and an 'inverse + execute' operation is hard to write. """ return True class CommandProcessor(wx.Object): """ - `CommandProcessor` is a class that maintains a history of - `Command` instancess, with undo/redo functionality - built-in. Derive a new class from this if you want different - behaviour. + wxCommandProcessor is a class that maintains a history of wxCommands, with + undo/redo functionality built-in. Derive a new class from this if you want + different behaviour. """ - def __init__(self, maxCommands = -1): + def __init__(self, maxCommands=-1): """ Constructor. maxCommands may be set to a positive integer to limit the number of commands stored to it, otherwise (and by default) the @@ -3000,11 +3094,10 @@ class CommandProcessor(wx.Object): def SetEditMenu(self, menu): """ - Tells the command processor to update the Undo and Redo items - on this menu as appropriate. Set this to None if the menu is - about to be destroyed and command operations may still be - performed, or the command processor may try to access an - invalid pointer. + Tells the command processor to update the Undo and Redo items on this + menu as appropriate. Set this to NULL if the menu is about to be + destroyed and command operations may still be performed, or the + command processor may try to access an invalid pointer. """ self._editMenu = menu @@ -3037,10 +3130,20 @@ class CommandProcessor(wx.Object): self._redoAccelerator = accel + def SetEditMenu(self, menu): + """ + Tells the command processor to update the Undo and Redo items on this + menu as appropriate. Set this to NULL if the menu is about to be + destroyed and command operations may still be performed, or the + command processor may try to access an invalid pointer. + """ + self._editMenu = menu + + def SetMenuStrings(self): """ - Sets the menu labels according to the currently set menu and - the current command state. + Sets the menu labels according to the currently set menu and the + current command state. """ if self.GetEditMenu() != None: undoCommand = self._GetCurrentCommand() @@ -3056,15 +3159,15 @@ class CommandProcessor(wx.Object): else: redoAccel = '' if undoCommand and undoItem and undoCommand.CanUndo(): - undoItem.SetText(_("Undo ") + undoCommand.GetName() + undoAccel) + undoItem.SetText(_("&Undo ") + undoCommand.GetName() + undoAccel) #elif undoCommand and not undoCommand.CanUndo(): # undoItem.SetText(_("Can't Undo") + undoAccel) else: - undoItem.SetText(_("Undo" + undoAccel)) + undoItem.SetText(_("&Undo" + undoAccel)) if redoCommand and redoItem: - redoItem.SetText(_("Redo ") + redoCommand.GetName() + redoAccel) + redoItem.SetText(_("&Redo ") + redoCommand.GetName() + redoAccel) else: - redoItem.SetText(_("Redo") + redoAccel) + redoItem.SetText(_("&Redo") + redoAccel) def CanUndo(self): @@ -3085,21 +3188,23 @@ class CommandProcessor(wx.Object): return self._GetCurrentRedoCommand() != None - def Submit(self, command, storeIt = True): + def Submit(self, command, storeIt=True): """ Submits a new command to the command processor. The command processor - calls `Command.Do` to execute the command; if it succeeds, the + calls wxCommand::Do to execute the command; if it succeeds, the command is stored in the history list, and the associated edit menu (if any) updated appropriately. If it fails, the command is deleted - immediately. Once `Submit` has been called, the passed command should + immediately. Once Submit has been called, the passed command should not be deleted directly by the application. storeIt indicates whether the successful command should be stored in the history list. """ done = command.Do() - if done and storeIt: - self._commands.append(command) + if done: + del self._redoCommands[:] + if storeIt: + self._commands.append(command) if self._maxCommands > -1: if len(self._commands) > self._maxCommands: del self._commands[0]