X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/664e13143ee51a6b1aa1c30d1401ac04b11bdcca..5c475284a2f878f72449fa1e5517052c4e804758:/src/common/docview.cpp diff --git a/src/common/docview.cpp b/src/common/docview.cpp index dc27049995..fc1c256337 100644 --- a/src/common/docview.cpp +++ b/src/common/docview.cpp @@ -60,6 +60,8 @@ #include "wx/vector.h" #include "wx/scopedarray.h" #include "wx/scopedptr.h" +#include "wx/scopeguard.h" +#include "wx/except.h" #if wxUSE_STD_IOSTREAM #include "wx/ioswrap.h" @@ -74,8 +76,6 @@ #include "wx/wfstream.h" #endif -typedef wxVector wxDocTemplates; - // ---------------------------------------------------------------------------- // wxWidgets macros // ---------------------------------------------------------------------------- @@ -91,8 +91,6 @@ IMPLEMENT_CLASS(wxDocParentFrame, wxFrame) IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout, wxPrintout) #endif -IMPLEMENT_DYNAMIC_CLASS(wxFileHistory, wxObject) - // ============================================================================ // implementation // ============================================================================ @@ -104,13 +102,6 @@ IMPLEMENT_DYNAMIC_CLASS(wxFileHistory, wxObject) namespace { -wxWindow *wxFindSuitableParent() -{ - wxWindow * const win = wxGetTopLevelParent(wxWindow::FindFocus()); - - return win ? win : wxTheApp->GetTopWindow(); -} - wxString FindExtension(const wxString& path) { wxString ext; @@ -121,18 +112,6 @@ wxString FindExtension(const wxString& path) return ext.MakeLower(); } -// return the string used for the MRU list items in the menu -// -// NB: the index n is 0-based, as usual, but the strings start from 1 -wxString GetMRUEntryLabel(int n, const wxString& path) -{ - // we need to quote '&' characters which are used for mnemonics - wxString pathInMenu(path); - pathInMenu.Replace("&", "&&"); - - return wxString::Format("&%d %s", n + 1, pathInMenu); -} - } // anonymous namespace // ---------------------------------------------------------------------------- @@ -142,8 +121,12 @@ wxString GetMRUEntryLabel(int n, const wxString& path) wxDocument::wxDocument(wxDocument *parent) { m_documentModified = false; - m_documentParent = parent; m_documentTemplate = NULL; + + m_documentParent = parent; + if ( parent ) + parent->m_childDocuments.push_back(this); + m_commandProcessor = NULL; m_savedYet = false; } @@ -155,13 +138,14 @@ bool wxDocument::DeleteContents() wxDocument::~wxDocument() { - DeleteContents(); - delete m_commandProcessor; if (GetDocumentManager()) GetDocumentManager()->RemoveDocument(this); + if ( m_documentParent ) + m_documentParent->m_childDocuments.remove(this); + // Not safe to do here, since it'll invoke virtual view functions // expecting to see valid derived objects: and by the time we get here, // we've called destructors higher up. @@ -173,6 +157,40 @@ bool wxDocument::Close() if ( !OnSaveModified() ) return false; + // When the parent document closes, its children must be closed as well as + // they can't exist without the parent. + + // As usual, first check if all children can be closed. + DocsList::const_iterator it = m_childDocuments.begin(); + for ( DocsList::const_iterator end = m_childDocuments.end(); it != end; ++it ) + { + if ( !(*it)->OnSaveModified() ) + { + // Leave the parent document opened if a child can't close. + return false; + } + } + + // Now that they all did, do close them: as m_childDocuments is modified as + // we iterate over it, don't use the usual for-style iteration here. + while ( !m_childDocuments.empty() ) + { + wxDocument * const childDoc = m_childDocuments.front(); + + // This will call OnSaveModified() once again but it shouldn't do + // anything as the document was just saved or marked as not needing to + // be saved by the call to OnSaveModified() that returned true above. + if ( !childDoc->Close() ) + { + wxFAIL_MSG( "Closing the child document unexpectedly failed " + "after its OnSaveModified() returned true" ); + } + + // Delete the child document by deleting all its views. + childDoc->DeleteAllViews(); + } + + return OnCloseDocument(); } @@ -239,18 +257,38 @@ wxView *wxDocument::GetFirstView() const return static_cast(m_documentViews.GetFirst()->GetData()); } +void wxDocument::Modify(bool mod) +{ + if (mod != m_documentModified) + { + m_documentModified = mod; + + // Allow views to append asterix to the title + wxView* view = GetFirstView(); + if (view) view->OnChangeFilename(); + } +} + wxDocManager *wxDocument::GetDocumentManager() const { + // For child documents we use the same document manager as the parent, even + // though we don't have our own template (as children are not opened/saved + // directly). + if ( m_documentParent ) + return m_documentParent->GetDocumentManager(); + return m_documentTemplate ? m_documentTemplate->GetDocumentManager() : NULL; } bool wxDocument::OnNewDocument() { - if ( !OnSaveModified() ) - return false; + // notice that there is no need to neither reset nor even check the + // modified flag here as the document itself is a new object (this is only + // called from CreateDocument()) and so it shouldn't be saved anyhow even + // if it is modified -- this could happen if the user code creates + // documents pre-filled with some user-entered (and which hence must not be + // lost) information - DeleteContents(); - Modify(false); SetDocumentSaved(false); const wxString name = GetDocumentManager()->MakeNewDocumentName(); @@ -331,15 +369,6 @@ bool wxDocument::SaveAs() if (fileName.empty()) return false; // cancelled by user - wxString ext; - wxFileName::SplitPath(fileName, NULL, NULL, &ext); - - if (ext.empty()) - { - fileName += wxT("."); - fileName += docTemplate->GetDefaultExtension(); - } - // Files that were not saved correctly are not added to the FileHistory. if (!OnSaveDocument(fileName)) return false; @@ -347,16 +376,16 @@ bool wxDocument::SaveAs() SetTitle(wxFileNameFromPath(fileName)); SetFilename(fileName, true); // will call OnChangeFileName automatically - // A file that doesn't use the default extension of its document template - // cannot be opened via the FileHistory, so we do not add it. - if (docTemplate->FileMatchesTemplate(fileName)) - { - GetDocumentManager()->AddFileToHistory(fileName); - } - //else: the user will probably not be able to open the file again, so we - // could warn about the wrong file-extension here + // A file that doesn't use the default extension of its document template + // cannot be opened via the FileHistory, so we do not add it. + if (docTemplate->FileMatchesTemplate(fileName)) + { + GetDocumentManager()->AddFileToHistory(fileName); + } + //else: the user will probably not be able to open the file again, so we + // could warn about the wrong file-extension here - return true; + return true; } bool wxDocument::OnSaveDocument(const wxString& file) @@ -367,6 +396,9 @@ bool wxDocument::OnSaveDocument(const wxString& file) if ( !DoSaveDocument(file) ) return false; + if ( m_commandProcessor ) + m_commandProcessor->MarkAsSaved(); + Modify(false); SetFilename(file); SetDocumentSaved(true); @@ -379,15 +411,20 @@ bool wxDocument::OnSaveDocument(const wxString& file) bool wxDocument::OnOpenDocument(const wxString& file) { - if ( !OnSaveModified() ) - return false; + // notice that there is no need to check the modified flag here for the + // reasons explained in OnNewDocument() if ( !DoOpenDocument(file) ) return false; SetFilename(file, true); - Modify(false); - m_savedYet = true; + + // stretching the logic a little this does make sense because the document + // had been saved into the file we just loaded it from, it just could have + // happened during a previous program execution, it's just that the name of + // this method is a bit unfortunate, it should probably have been called + // HasAssociatedFileName() + SetDocumentSaved(true); UpdateAllViews(); @@ -414,7 +451,22 @@ wxOutputStream& wxDocument::SaveObject(wxOutputStream& stream) bool wxDocument::Revert() { - return false; + if ( wxMessageBox + ( + _("Discard changes and reload the last saved version?"), + wxTheApp->GetAppDisplayName(), + wxYES_NO | wxCANCEL | wxICON_QUESTION, + GetDocumentWindow() + ) != wxYES ) + return false; + + if ( !DoOpenDocument(GetFilename()) ) + return false; + + Modify(false); + UpdateAllViews(); + + return true; } @@ -422,7 +474,7 @@ bool wxDocument::Revert() #if WXWIN_COMPATIBILITY_2_8 bool wxDocument::GetPrintableName(wxString& buf) const { - // this function can not only be overridden by the user code but also + // this function cannot only be overridden by the user code but also // called by it so we need to ensure that we return the same thing as // GetUserReadableName() but we can't call it because this would result in // an infinite recursion, hence we use the helper DoGetUserReadableName() @@ -481,8 +533,7 @@ bool wxDocument::OnSaveModified() GetUserReadableName() ), wxTheApp->GetAppDisplayName(), - wxYES_NO | wxCANCEL | wxICON_QUESTION | wxCENTRE, - wxFindSuitableParent() + wxYES_NO | wxCANCEL | wxICON_QUESTION | wxCENTRE ) ) { case wxNO: @@ -642,18 +693,50 @@ wxView::wxView() m_viewDocument = NULL; m_viewFrame = NULL; + + m_docChildFrame = NULL; } wxView::~wxView() { - GetDocumentManager()->ActivateView(this, false); - m_viewDocument->RemoveView(this); + if (m_viewDocument && GetDocumentManager()) + GetDocumentManager()->ActivateView(this, false); + + // reset our frame view first, before removing it from the document as + // SetView(NULL) is a simple call while RemoveView() may result in user + // code being executed and this user code can, for example, show a message + // box which would result in an activation event for m_docChildFrame and so + // could reactivate the view being destroyed -- unless we reset it first + if ( m_docChildFrame && m_docChildFrame->GetView() == this ) + { + // prevent it from doing anything with us + m_docChildFrame->SetView(NULL); + + // it doesn't make sense to leave the frame alive if its associated + // view doesn't exist any more so unconditionally close it as well + // + // notice that we only get here if m_docChildFrame is non-NULL in the + // first place and it will be always NULL if we're deleted because our + // frame was closed, so this only catches the case of directly deleting + // the view, as it happens if its creation fails in wxDocTemplate:: + // CreateView() for example + m_docChildFrame->GetWindow()->Destroy(); + } + + if ( m_viewDocument ) + m_viewDocument->RemoveView(this); } -bool wxView::TryValidator(wxEvent& event) +void wxView::SetDocChildFrame(wxDocChildFrameAnyBase *docChildFrame) +{ + SetFrame(docChildFrame ? docChildFrame->GetWindow() : NULL); + m_docChildFrame = docChildFrame; +} + +bool wxView::TryBefore(wxEvent& event) { wxDocument * const doc = GetDocument(); - return doc && doc->ProcessEventHere(event); + return doc && doc->ProcessEventLocally(event); } void wxView::OnActivateView(bool WXUNUSED(activate), @@ -682,7 +765,12 @@ void wxView::OnChangeFilename() wxDocument *doc = GetDocument(); if (!doc) return; - win->SetLabel(doc->GetUserReadableName()); + wxString label = doc->GetUserReadableName(); + if (doc->IsModified()) + { + label += "*"; + } + win->SetLabel(label); } void wxView::SetDocument(wxDocument *doc) @@ -755,28 +843,34 @@ wxDocTemplate::~wxDocTemplate() // Tries to dynamically construct an object of the right class. wxDocument *wxDocTemplate::CreateDocument(const wxString& path, long flags) { + // InitDocument() is supposed to delete the document object if its + // initialization fails so don't use wxScopedPtr<> here: this is fragile + // but unavoidable because the default implementation uses CreateView() + // which may -- or not -- create a wxView and if it does create it and its + // initialization fails then the view destructor will delete the document + // (via RemoveView()) and as we can't distinguish between the two cases we + // just have to assume that it always deletes it in case of failure wxDocument * const doc = DoCreateDocument(); - // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate()) - // fails, is this intentional? - return doc && InitDocument(doc, path, flags) ? doc : NULL; } bool wxDocTemplate::InitDocument(wxDocument* doc, const wxString& path, long flags) { + wxScopeGuard g = wxMakeObjGuard(*doc, &wxDocument::DeleteAllViews); + doc->SetFilename(path); doc->SetDocumentTemplate(this); GetDocumentManager()->AddDocument(doc); doc->SetCommandProcessor(doc->OnCreateCommandProcessor()); - if (doc->OnCreate(path, flags)) - return true; + if ( !doc->OnCreate(path, flags) ) + return false; - if (GetDocumentManager()->GetDocuments().Member(doc)) - doc->DeleteAllViews(); - return false; + g.Dismiss(); // no need to call DeleteAllViews() anymore + + return true; } wxView *wxDocTemplate::CreateView(wxDocument *doc, long flags) @@ -841,31 +935,37 @@ BEGIN_EVENT_TABLE(wxDocManager, wxEvtHandler) EVT_MENU(wxID_UNDO, wxDocManager::OnUndo) EVT_MENU(wxID_REDO, wxDocManager::OnRedo) + // We don't know in advance how many items can there be in the MRU files + // list so set up OnMRUFile() as a handler for all menu events and do the + // check for the id of the menu item clicked inside it. + EVT_MENU(wxID_ANY, wxDocManager::OnMRUFile) + EVT_UPDATE_UI(wxID_OPEN, wxDocManager::OnUpdateFileOpen) EVT_UPDATE_UI(wxID_CLOSE, wxDocManager::OnUpdateDisableIfNoDoc) EVT_UPDATE_UI(wxID_CLOSE_ALL, wxDocManager::OnUpdateDisableIfNoDoc) - EVT_UPDATE_UI(wxID_REVERT, wxDocManager::OnUpdateDisableIfNoDoc) + EVT_UPDATE_UI(wxID_REVERT, wxDocManager::OnUpdateFileRevert) EVT_UPDATE_UI(wxID_NEW, wxDocManager::OnUpdateFileNew) EVT_UPDATE_UI(wxID_SAVE, wxDocManager::OnUpdateFileSave) - EVT_UPDATE_UI(wxID_SAVEAS, wxDocManager::OnUpdateDisableIfNoDoc) + EVT_UPDATE_UI(wxID_SAVEAS, wxDocManager::OnUpdateFileSaveAs) EVT_UPDATE_UI(wxID_UNDO, wxDocManager::OnUpdateUndo) EVT_UPDATE_UI(wxID_REDO, wxDocManager::OnUpdateRedo) #if wxUSE_PRINTING_ARCHITECTURE EVT_MENU(wxID_PRINT, wxDocManager::OnPrint) EVT_MENU(wxID_PREVIEW, wxDocManager::OnPreview) + EVT_MENU(wxID_PRINT_SETUP, wxDocManager::OnPageSetup) EVT_UPDATE_UI(wxID_PRINT, wxDocManager::OnUpdateDisableIfNoDoc) EVT_UPDATE_UI(wxID_PREVIEW, wxDocManager::OnUpdateDisableIfNoDoc) -#endif + // NB: we keep "Print setup" menu item always enabled as it can be used + // even without an active document +#endif // wxUSE_PRINTING_ARCHITECTURE END_EVENT_TABLE() wxDocManager* wxDocManager::sm_docManager = NULL; wxDocManager::wxDocManager(long WXUNUSED(flags), bool initialize) { - wxASSERT_MSG( !sm_docManager, "multiple wxDocManagers not allowed" ); - sm_docManager = this; m_defaultDocumentNameCounter = 1; @@ -945,12 +1045,35 @@ bool wxDocManager::Initialize() wxString wxDocManager::GetLastDirectory() const { - // use the system-dependent default location for the document files if - // we're being opened for the first time + // if we haven't determined the last used directory yet, do it now if ( m_lastDirectory.empty() ) { + // we're going to modify m_lastDirectory in this const method, so do it + // via non-const self pointer instead of const this one wxDocManager * const self = const_cast(this); - self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir(); + + // first try to reuse the directory of the most recently opened file: + // this ensures that if the user opens a file, closes the program and + // runs it again the "Open file" dialog will open in the directory of + // the last file he used + if ( m_fileHistory && m_fileHistory->GetCount() ) + { + const wxString lastOpened = m_fileHistory->GetHistoryFile(0); + const wxFileName fn(lastOpened); + if ( fn.DirExists() ) + { + self->m_lastDirectory = fn.GetPath(); + } + //else: should we try the next one? + } + //else: no history yet + + // if we don't have any files in the history (yet?), use the + // system-dependent default location for the document files + if ( m_lastDirectory.empty() ) + { + self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir(); + } } return m_lastDirectory; @@ -964,14 +1087,8 @@ wxFileHistory *wxDocManager::OnCreateFileHistory() void wxDocManager::OnFileClose(wxCommandEvent& WXUNUSED(event)) { wxDocument *doc = GetCurrentDocument(); - if (!doc) - return; - if (doc->Close()) - { - doc->DeleteAllViews(); - if (m_docs.Member(doc)) - delete doc; - } + if (doc) + CloseDocument(doc); } void wxDocManager::OnFileCloseAll(wxCommandEvent& WXUNUSED(event)) @@ -1016,53 +1133,124 @@ void wxDocManager::OnFileSaveAs(wxCommandEvent& WXUNUSED(event)) doc->SaveAs(); } -void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event)) +void wxDocManager::OnMRUFile(wxCommandEvent& event) { + // Check if the id is in the range assigned to MRU list entries. + const int id = event.GetId(); + if ( id >= wxID_FILE1 && + id < wxID_FILE1 + static_cast(m_fileHistory->GetCount()) ) + { + DoOpenMRUFile(id - wxID_FILE1); + } + else + { + event.Skip(); + } +} + +void wxDocManager::DoOpenMRUFile(unsigned n) +{ + wxString filename(GetHistoryFile(n)); + if ( filename.empty() ) + return; + + wxString errMsg; // must contain exactly one "%s" if non-empty + if ( wxFile::Exists(filename) ) + { + // Try to open it but don't give an error if it failed: this could be + // normal, e.g. because the user cancelled opening it, and we don't + // have any useful information to put in the error message anyhow, so + // we assume that in case of an error the appropriate message had been + // already logged. + (void)CreateDocument(filename, wxDOC_SILENT); + } + else // file doesn't exist + { + OnMRUFileNotExist(n, filename); + } +} + +void wxDocManager::OnMRUFileNotExist(unsigned n, const wxString& filename) +{ + // remove the file which we can't open from the MRU list + RemoveFileFromHistory(n); + + // and tell the user about it + wxLogError(_("The file '%s' doesn't exist and couldn't be opened.\n" + "It has been removed from the most recently used files list."), + filename); +} + #if wxUSE_PRINTING_ARCHITECTURE - wxView *view = GetActiveView(); + +void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event)) +{ + wxView *view = GetAnyUsableView(); if (!view) return; wxPrintout *printout = view->OnCreatePrintout(); if (printout) { - wxPrinter printer; + wxPrintDialogData printDialogData(m_pageSetupDialogData.GetPrintData()); + wxPrinter printer(&printDialogData); printer.Print(view->GetFrame(), printout, true); delete printout; } -#endif // wxUSE_PRINTING_ARCHITECTURE +} + +void wxDocManager::OnPageSetup(wxCommandEvent& WXUNUSED(event)) +{ + wxPageSetupDialog dlg(wxTheApp->GetTopWindow(), &m_pageSetupDialogData); + if ( dlg.ShowModal() == wxID_OK ) + { + m_pageSetupDialogData = dlg.GetPageSetupData(); + } +} + +wxPreviewFrame* wxDocManager::CreatePreviewFrame(wxPrintPreviewBase* preview, + wxWindow *parent, + const wxString& title) +{ + return new wxPreviewFrame(preview, parent, title); } void wxDocManager::OnPreview(wxCommandEvent& WXUNUSED(event)) { -#if wxUSE_PRINTING_ARCHITECTURE - wxView *view = GetActiveView(); + wxBusyCursor busy; + wxView *view = GetAnyUsableView(); if (!view) return; wxPrintout *printout = view->OnCreatePrintout(); if (printout) { + wxPrintDialogData printDialogData(m_pageSetupDialogData.GetPrintData()); + // Pass two printout objects: for preview, and possible printing. wxPrintPreviewBase * - preview = new wxPrintPreview(printout, view->OnCreatePrintout()); - if ( !preview->Ok() ) + preview = new wxPrintPreview(printout, + view->OnCreatePrintout(), + &printDialogData); + if ( !preview->IsOk() ) { delete preview; wxLogError(_("Print preview creation failed.")); return; } - wxPreviewFrame * - frame = new wxPreviewFrame(preview, wxTheApp->GetTopWindow(), - _("Print Preview")); + wxPreviewFrame* frame = CreatePreviewFrame(preview, + wxTheApp->GetTopWindow(), + _("Print Preview")); + wxCHECK_RET( frame, "should create a print preview frame" ); + frame->Centre(wxBOTH); frame->Initialize(); frame->Show(true); } -#endif // wxUSE_PRINTING_ARCHITECTURE } +#endif // wxUSE_PRINTING_ARCHITECTURE void wxDocManager::OnUndo(wxCommandEvent& event) { @@ -1102,6 +1290,12 @@ void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent& event) event.Enable( GetCurrentDocument() != NULL ); } +void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent& event) +{ + wxDocument* doc = GetCurrentDocument(); + event.Enable(doc && doc->IsModified() && doc->GetDocumentSaved()); +} + void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event) { // CreateDocument() (which is called from OnFileNew) may succeed @@ -1112,7 +1306,13 @@ void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event) void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event) { wxDocument * const doc = GetCurrentDocument(); - event.Enable( doc && !doc->AlreadySaved() ); + event.Enable( doc && !doc->IsChildDocument() && !doc->AlreadySaved() ); +} + +void wxDocManager::OnUpdateFileSaveAs(wxUpdateUIEvent& event) +{ + wxDocument * const doc = GetCurrentDocument(); + event.Enable( doc && !doc->IsChildDocument() ); } void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event) @@ -1120,10 +1320,14 @@ void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event) wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor(); if ( !cmdproc ) { - event.Enable(false); + // If we don't have any document at all, the menu item should really be + // disabled. + if ( !GetCurrentDocument() ) + event.Enable(false); + else // But if we do have it, it might handle wxID_UNDO on its own + event.Skip(); return; } - event.Enable(cmdproc->CanUndo()); cmdproc->SetMenuStrings(); } @@ -1133,15 +1337,18 @@ void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event) wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor(); if ( !cmdproc ) { - event.Enable(false); + // Use same logic as in OnUpdateUndo() above. + if ( !GetCurrentDocument() ) + event.Enable(false); + else + event.Skip(); return; } - event.Enable(cmdproc->CanRedo()); cmdproc->SetMenuStrings(); } -wxView *wxDocManager::GetActiveView() const +wxView *wxDocManager::GetAnyUsableView() const { wxView *view = GetCurrentView(); @@ -1165,21 +1372,21 @@ wxView *wxDocManager::GetActiveView() const return view; } -bool wxDocManager::TryValidator(wxEvent& event) +bool wxDocManager::TryBefore(wxEvent& event) { - wxView * const view = GetActiveView(); - return view && view->ProcessEventHere(event); + wxView * const view = GetAnyUsableView(); + return view && view->ProcessEventLocally(event); } namespace { // helper function: return only the visible templates -wxDocTemplates GetVisibleTemplates(const wxList& allTemplates) +wxDocTemplateVector GetVisibleTemplates(const wxList& allTemplates) { // select only the visible templates const size_t totalNumTemplates = allTemplates.GetCount(); - wxDocTemplates templates; + wxDocTemplateVector templates; if ( totalNumTemplates ) { templates.reserve(totalNumTemplates); @@ -1200,12 +1407,36 @@ wxDocTemplates GetVisibleTemplates(const wxList& allTemplates) } // anonymous namespace +void wxDocument::Activate() +{ + wxView * const view = GetFirstView(); + if ( !view ) + return; + + view->Activate(true); + if ( wxWindow *win = view->GetFrame() ) + win->Raise(); +} + +wxDocument* wxDocManager::FindDocumentByPath(const wxString& path) const +{ + const wxFileName fileName(path); + for ( wxList::const_iterator i = m_docs.begin(); i != m_docs.end(); ++i ) + { + wxDocument * const doc = wxStaticCast(*i, wxDocument); + + if ( fileName == wxFileName(doc->GetFilename()) ) + return doc; + } + return NULL; +} + wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags) { // this ought to be const but SelectDocumentType/Path() are not // const-correct and can't be changed as, being virtual, this risks // breaking user code overriding them - wxDocTemplates templates(GetVisibleTemplates(m_templates)); + wxDocTemplateVector templates(GetVisibleTemplates(m_templates)); const size_t numTemplates = templates.size(); if ( !numTemplates ) { @@ -1246,26 +1477,15 @@ wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags) // check whether the document with this path is already opened if ( !path.empty() ) { - const wxFileName fn(path); - for ( wxList::const_iterator i = m_docs.begin(); i != m_docs.end(); ++i ) + wxDocument * const doc = FindDocumentByPath(path); + if (doc) { - wxDocument * const doc = (wxDocument*)*i; - - if ( fn == doc->GetFilename() ) - { - // file already open, just activate it and return - if ( doc->GetFirstView() ) - { - ActivateView(doc->GetFirstView()); - if ( doc->GetDocumentWindow() ) - doc->GetDocumentWindow()->SetFocus(); - return doc; - } - } + // file already open, just activate it and return + doc->Activate(); + return doc; } } - // no, we need to create a new document @@ -1288,15 +1508,18 @@ wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags) docNew->SetDocumentName(temp->GetDocumentName()); docNew->SetDocumentTemplate(temp); - // call the appropriate function depending on whether we're creating a new - // file or opening an existing one - if ( !(flags & wxDOC_NEW ? docNew->OnNewDocument() - : docNew->OnOpenDocument(path)) ) + wxTRY { - // Document is implicitly deleted by DeleteAllViews - docNew->DeleteAllViews(); - return NULL; + // call the appropriate function depending on whether we're creating a + // new file or opening an existing one + if ( !(flags & wxDOC_NEW ? docNew->OnNewDocument() + : docNew->OnOpenDocument(path)) ) + { + docNew->DeleteAllViews(); + return NULL; + } } + wxCATCH_ALL( docNew->DeleteAllViews(); throw; ) // add the successfully opened file to MRU, but only if we're going to be // able to reopen it successfully later which requires the template for @@ -1304,12 +1527,17 @@ wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags) if ( !(flags & wxDOC_NEW) && temp->FileMatchesTemplate(path) ) AddFileToHistory(path); + // at least under Mac (where views are top level windows) it seems to be + // necessary to manually activate the new document to bring it to the + // forefront -- and it shouldn't hurt doing this under the other platforms + docNew->Activate(); + return docNew; } wxView *wxDocManager::CreateView(wxDocument *doc, long flags) { - wxDocTemplates templates(GetVisibleTemplates(m_templates)); + wxDocTemplateVector templates(GetVisibleTemplates(m_templates)); const size_t numTemplates = templates.size(); if ( numTemplates == 0 ) @@ -1342,7 +1570,7 @@ bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc)) wxDocument *wxDocManager::GetCurrentDocument() const { - wxView * const view = GetActiveView(); + wxView * const view = GetAnyUsableView(); return view ? view->GetDocument() : NULL; } @@ -1520,15 +1748,12 @@ wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates, int FilterIndex = -1; - wxWindow* parent = wxFindSuitableParent(); - wxString pathTmp = wxFileSelectorEx(_("Open File"), GetLastDirectory(), wxEmptyString, &FilterIndex, descrBuf, - 0, - parent); + wxFD_OPEN | wxFD_FILE_MUST_EXIST); wxDocTemplate *theTemplate = NULL; if (!pathTmp.empty()) @@ -1543,8 +1768,7 @@ wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates, wxMessageBox(_("Sorry, could not open this file."), msgTitle, - wxOK | wxICON_EXCLAMATION | wxCENTRE, - parent); + wxOK | wxICON_EXCLAMATION | wxCENTRE); path = wxEmptyString; return NULL; @@ -1567,8 +1791,7 @@ wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates, // allowed templates in runtime. wxMessageBox(_("Sorry, the format for this file is unknown."), _("Open File"), - wxOK | wxICON_EXCLAMATION | wxCENTRE, - parent); + wxOK | wxICON_EXCLAMATION | wxCENTRE); } } else @@ -1650,8 +1873,7 @@ wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates, _("Select a document template"), _("Templates"), strings, - (void **)data.get(), - wxFindSuitableParent() + (void **)data.get() ); } @@ -1725,8 +1947,7 @@ wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates, _("Select a document view"), _("Views"), strings, - (void **)data.get(), - wxFindSuitableParent() + (void **)data.get() ); } @@ -1745,6 +1966,20 @@ void wxDocManager::DisassociateTemplate(wxDocTemplate *temp) m_templates.DeleteObject(temp); } +wxDocTemplate* wxDocManager::FindTemplate(const wxClassInfo* classinfo) +{ + for ( wxList::compatibility_iterator node = m_templates.GetFirst(); + node; + node = node->GetNext() ) + { + wxDocTemplate* t = wxStaticCast(node->GetData(), wxDocTemplate); + if ( t->GetDocClassInfo() == classinfo ) + return t; + } + + return NULL; +} + // Add and remove a document from the manager's list void wxDocManager::AddDocument(wxDocument *doc) { @@ -1776,171 +2011,122 @@ void wxDocManager::ActivateView(wxView *view, bool activate) } // ---------------------------------------------------------------------------- -// Default document child frame +// wxDocChildFrameAnyBase // ---------------------------------------------------------------------------- -BEGIN_EVENT_TABLE(wxDocChildFrame, wxFrame) - EVT_ACTIVATE(wxDocChildFrame::OnActivate) - EVT_CLOSE(wxDocChildFrame::OnCloseWindow) -END_EVENT_TABLE() - -wxDocChildFrame::wxDocChildFrame(wxDocument *doc, - wxView *view, - wxFrame *frame, - wxWindowID id, - const wxString& title, - const wxPoint& pos, - const wxSize& size, - long style, - const wxString& name) - : wxFrame(frame, id, title, pos, size, style, name) -{ - m_childDocument = doc; - m_childView = view; - if (view) - view->SetFrame(this); -} - -bool wxDocChildFrame::TryValidator(wxEvent& event) +bool wxDocChildFrameAnyBase::TryProcessEvent(wxEvent& event) { if ( !m_childView ) + { + // We must be being destroyed, don't forward events anywhere as + // m_childDocument could be invalid by now. return false; + } - // FIXME: why is this needed here? - m_childView->Activate(true); - - return m_childView->ProcessEventHere(event); + // Forward the event to the document manager which will, in turn, forward + // it to its active view which must be our m_childView. + // + // Notice that we do things in this roundabout way to guarantee the correct + // event handlers call order: first the document, then the new and then the + // document manager itself. And if we forwarded the event directly to the + // view, then the document manager would do it once again when we forwarded + // it to it. + return m_childDocument->GetDocumentManager()->ProcessEventLocally(event); } -void wxDocChildFrame::OnActivate(wxActivateEvent& event) +bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent& event) { - wxFrame::OnActivate(event); - - if (m_childView) - m_childView->Activate(event.GetActive()); -} + if ( m_childView ) + { + // notice that we must call wxView::Close() and OnClose() called from + // it in any case, even if we know that we are going to close anyhow + if ( !m_childView->Close(false) && event.CanVeto() ) + { + event.Veto(); + return false; + } -void wxDocChildFrame::OnCloseWindow(wxCloseEvent& event) -{ - if ( !m_childView ) - return; + m_childView->Activate(false); - // passing false to Close() means to not delete associated window - if ( event.CanVeto() && !m_childView->Close(false) ) - { - event.Veto(); - return; + // it is important to reset m_childView frame pointer to NULL before + // deleting it because while normally it is the frame which deletes the + // view when it's closed, the view also closes the frame if it is + // deleted directly not by us as indicated by its doc child frame + // pointer still being set + m_childView->SetDocChildFrame(NULL); + wxDELETE(m_childView); } - m_childView->Activate(false); - delete m_childView; - m_childView = NULL; m_childDocument = NULL; - Destroy(); + return true; } // ---------------------------------------------------------------------------- -// Default parent frame +// wxDocParentFrameAnyBase // ---------------------------------------------------------------------------- -BEGIN_EVENT_TABLE(wxDocParentFrame, wxFrame) - EVT_MENU(wxID_EXIT, wxDocParentFrame::OnExit) - EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocParentFrame::OnMRUFile) - EVT_CLOSE(wxDocParentFrame::OnCloseWindow) -END_EVENT_TABLE() - -wxDocParentFrame::wxDocParentFrame() -{ - m_docManager = NULL; -} - -wxDocParentFrame::wxDocParentFrame(wxDocManager *manager, - wxFrame *frame, - wxWindowID id, - const wxString& title, - const wxPoint& pos, - const wxSize& size, - long style, - const wxString& name) - : wxFrame(frame, id, title, pos, size, style, name) -{ - m_docManager = manager; -} - -bool wxDocParentFrame::Create(wxDocManager *manager, - wxFrame *frame, - wxWindowID id, - const wxString& title, - const wxPoint& pos, - const wxSize& size, - long style, - const wxString& name) +bool wxDocParentFrameAnyBase::TryProcessEvent(wxEvent& event) { - m_docManager = manager; - return base_type::Create(frame, id, title, pos, size, style, name); -} - -void wxDocParentFrame::OnExit(wxCommandEvent& WXUNUSED(event)) -{ - Close(); -} - -void wxDocParentFrame::OnMRUFile(wxCommandEvent& event) -{ - int n = event.GetId() - wxID_FILE1; // the index in MRU list - wxString filename(m_docManager->GetHistoryFile(n)); - if ( filename.empty() ) - return; - - wxString errMsg; // must contain exactly one "%s" if non-empty - if ( wxFile::Exists(filename) ) - { - // try to open it - if ( m_docManager->CreateDocument(filename, wxDOC_SILENT) ) - return; + if ( !m_docManager ) + return false; - errMsg = _("The file '%s' couldn't be opened."); - } - else // file doesn't exist + // If we have an active view, its associated child frame may have + // already forwarded the event to wxDocManager, check for this: + if ( wxView* const view = m_docManager->GetAnyUsableView() ) { - errMsg = _("The file '%s' doesn't exist and couldn't be opened."); + wxWindow* win = view->GetFrame(); + if ( win && win != m_frame ) + { + // Notice that we intentionally don't use wxGetTopLevelParent() + // here because we want to check both for the case of a child + // "frame" (e.g. MDI child frame or notebook page) inside this TLW + // and a separate child TLW frame (as used in the SDI mode) here. + for ( win = win->GetParent(); win; win = win->GetParent() ) + { + if ( win == m_frame ) + return false; + } + } + //else: This view is directly associated with the parent frame (which + // can happen in the so called "single" mode in which only one + // document can be opened and so is managed by the parent frame + // itself), there can be no child frame in play so we must forward + // the event to wxDocManager ourselves. } + // But forward the event to wxDocManager ourselves if there are no views at + // all or if we are the frame's view ourselves. + return m_docManager->ProcessEventLocally(event); +} - wxASSERT_MSG( !errMsg.empty(), "should have an error message" ); - - // remove the file which we can't open from the MRU list - m_docManager->RemoveFileFromHistory(n); +// ---------------------------------------------------------------------------- +// Printing support +// ---------------------------------------------------------------------------- - // and tell the user about it - wxLogError(errMsg + '\n' + - _("It has been removed from the most recently used files list."), - filename); -} +#if wxUSE_PRINTING_ARCHITECTURE -// Extend event processing to search the view's event table -bool wxDocParentFrame::TryValidator(wxEvent& event) +namespace { - return m_docManager && m_docManager->ProcessEventHere(event); -} -// Define the behaviour for the frame closing -// - must delete all frames except for the main one. -void wxDocParentFrame::OnCloseWindow(wxCloseEvent& event) +wxString GetAppropriateTitle(const wxView *view, const wxString& titleGiven) { - if (m_docManager->Clear(!event.CanVeto())) + wxString title(titleGiven); + if ( title.empty() ) { - Destroy(); + if ( view && view->GetDocument() ) + title = view->GetDocument()->GetUserReadableName(); + else + title = _("Printout"); } - else - event.Veto(); + + return title; } -#if wxUSE_PRINTING_ARCHITECTURE +} // anonymous namespace wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title) - : wxPrintout(title) + : wxPrintout(GetAppropriateTitle(view, title)) { m_printoutView = view; } @@ -2008,203 +2194,6 @@ void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage, #endif // wxUSE_PRINTING_ARCHITECTURE -// ---------------------------------------------------------------------------- -// File history (a.k.a. MRU, most recently used, files list) -// ---------------------------------------------------------------------------- - -wxFileHistory::wxFileHistory(size_t maxFiles, wxWindowID idBase) -{ - m_fileMaxFiles = maxFiles; - m_idBase = idBase; -} - -void wxFileHistory::AddFileToHistory(const wxString& file) -{ - // check if we don't already have this file - const wxFileName fnNew(file); - size_t i, - numFiles = m_fileHistory.size(); - for ( i = 0; i < numFiles; i++ ) - { - if ( fnNew == m_fileHistory[i] ) - { - // we do have it, move it to the top of the history - RemoveFileFromHistory(i); - numFiles--; - break; - } - } - - // if we already have a full history, delete the one at the end - if ( numFiles == m_fileMaxFiles ) - { - RemoveFileFromHistory(--numFiles); - } - - // add a new menu item to all file menus (they will be updated below) - for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst(); - node; - node = node->GetNext() ) - { - wxMenu * const menu = (wxMenu *)node->GetData(); - - if ( !numFiles && menu->GetMenuItemCount() ) - menu->AppendSeparator(); - - // label doesn't matter, it will be set below anyhow, but it can't - // be empty (this is supposed to indicate a stock item) - menu->Append(m_idBase + numFiles, " "); - } - - // insert the new file in the beginning of the file history - m_fileHistory.insert(m_fileHistory.begin(), file); - numFiles++; - - // update the labels in all menus - for ( i = 0; i < numFiles; i++ ) - { - // if in same directory just show the filename; otherwise the full path - const wxFileName fnOld(m_fileHistory[i]); - - wxString pathInMenu; - if ( fnOld.GetPath() == fnNew.GetPath() ) - { - pathInMenu = fnOld.GetFullName(); - } - else // file in different directory - { - // absolute path; could also set relative path - pathInMenu = m_fileHistory[i]; - } - - for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst(); - node; - node = node->GetNext() ) - { - wxMenu * const menu = (wxMenu *)node->GetData(); - - menu->SetLabel(m_idBase + i, GetMRUEntryLabel(i, pathInMenu)); - } - } -} - -void wxFileHistory::RemoveFileFromHistory(size_t i) -{ - size_t numFiles = m_fileHistory.size(); - wxCHECK_RET( i < numFiles, - wxT("invalid index in wxFileHistory::RemoveFileFromHistory") ); - - // delete the element from the array - m_fileHistory.RemoveAt(i); - numFiles--; - - for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst(); - node; - node = node->GetNext() ) - { - wxMenu * const menu = (wxMenu *) node->GetData(); - - // shift filenames up - for ( size_t j = i; j < numFiles; j++ ) - { - menu->SetLabel(m_idBase + j, GetMRUEntryLabel(j, m_fileHistory[j])); - } - - // delete the last menu item which is unused now - const wxWindowID lastItemId = m_idBase + numFiles; - if ( menu->FindItem(lastItemId) ) - menu->Delete(lastItemId); - - // delete the last separator too if no more files are left - if ( m_fileHistory.empty() ) - { - const wxMenuItemList::compatibility_iterator - nodeLast = menu->GetMenuItems().GetLast(); - if ( nodeLast ) - { - wxMenuItem * const lastMenuItem = nodeLast->GetData(); - if ( lastMenuItem->IsSeparator() ) - menu->Delete(lastMenuItem); - } - //else: menu is empty somehow - } - } -} - -void wxFileHistory::UseMenu(wxMenu *menu) -{ - if ( !m_fileMenus.Member(menu) ) - m_fileMenus.Append(menu); -} - -void wxFileHistory::RemoveMenu(wxMenu *menu) -{ - m_fileMenus.DeleteObject(menu); -} - -#if wxUSE_CONFIG -void wxFileHistory::Load(const wxConfigBase& config) -{ - m_fileHistory.Clear(); - - wxString buf; - buf.Printf(wxT("file%d"), 1); - - wxString historyFile; - while ((m_fileHistory.GetCount() < m_fileMaxFiles) && - config.Read(buf, &historyFile) && !historyFile.empty()) - { - m_fileHistory.Add(historyFile); - - buf.Printf(wxT("file%d"), (int)m_fileHistory.GetCount()+1); - historyFile = wxEmptyString; - } - - AddFilesToMenu(); -} - -void wxFileHistory::Save(wxConfigBase& config) -{ - size_t i; - for (i = 0; i < m_fileMaxFiles; i++) - { - wxString buf; - buf.Printf(wxT("file%d"), (int)i+1); - if (i < m_fileHistory.GetCount()) - config.Write(buf, wxString(m_fileHistory[i])); - else - config.Write(buf, wxEmptyString); - } -} -#endif // wxUSE_CONFIG - -void wxFileHistory::AddFilesToMenu() -{ - if ( m_fileHistory.empty() ) - return; - - for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst(); - node; - node = node->GetNext() ) - { - AddFilesToMenu((wxMenu *) node->GetData()); - } -} - -void wxFileHistory::AddFilesToMenu(wxMenu* menu) -{ - if ( m_fileHistory.empty() ) - return; - - if ( menu->GetMenuItemCount() ) - menu->AppendSeparator(); - - for ( size_t i = 0; i < m_fileHistory.GetCount(); i++ ) - { - menu->Append(m_idBase + i, GetMRUEntryLabel(i, m_fileHistory[i])); - } -} - // ---------------------------------------------------------------------------- // Permits compatibility with existing file formats and functions that // manipulate files directly @@ -2214,7 +2203,11 @@ void wxFileHistory::AddFilesToMenu(wxMenu* menu) bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream) { - wxFFile file(filename, _T("rb")); +#if wxUSE_FFILE + wxFFile file(filename, wxT("rb")); +#elif wxUSE_FILE + wxFile file(filename, wxFile::read); +#endif if ( !file.IsOpened() ) return false; @@ -2238,7 +2231,11 @@ bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream) bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename) { - wxFFile file(filename, _T("wb")); +#if wxUSE_FFILE + wxFFile file(filename, wxT("wb")); +#elif wxUSE_FILE + wxFile file(filename, wxFile::write); +#endif if ( !file.IsOpened() ) return false; @@ -2261,7 +2258,11 @@ bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename) bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream) { - wxFFile file(filename, _T("rb")); +#if wxUSE_FFILE + wxFFile file(filename, wxT("rb")); +#elif wxUSE_FILE + wxFile file(filename, wxFile::read); +#endif if ( !file.IsOpened() ) return false; @@ -2285,7 +2286,11 @@ bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream) bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename) { - wxFFile file(filename, _T("wb")); +#if wxUSE_FFILE + wxFFile file(filename, wxT("wb")); +#elif wxUSE_FILE + wxFile file(filename, wxFile::write); +#endif if ( !file.IsOpened() ) return false;