1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/docview.cpp
3 // Purpose: Document/view classes
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_DOC_VIEW_ARCHITECTURE
29 #include "wx/docview.h"
33 #include "wx/string.h"
37 #include "wx/dialog.h"
39 #include "wx/filedlg.h"
42 #include "wx/msgdlg.h"
44 #include "wx/choicdlg.h"
47 #if wxUSE_PRINTING_ARCHITECTURE
48 #include "wx/prntbase.h"
49 #include "wx/printdlg.h"
52 #include "wx/confbase.h"
53 #include "wx/filename.h"
56 #include "wx/cmdproc.h"
57 #include "wx/tokenzr.h"
58 #include "wx/filename.h"
59 #include "wx/stdpaths.h"
60 #include "wx/vector.h"
61 #include "wx/scopedarray.h"
62 #include "wx/scopedptr.h"
63 #include "wx/except.h"
65 #if wxUSE_STD_IOSTREAM
66 #include "wx/ioswrap.h"
67 #include "wx/beforestd.h"
73 #include "wx/afterstd.h"
75 #include "wx/wfstream.h"
78 typedef wxVector
<wxDocTemplate
*> wxDocTemplates
;
80 // ----------------------------------------------------------------------------
82 // ----------------------------------------------------------------------------
84 IMPLEMENT_ABSTRACT_CLASS(wxDocument
, wxEvtHandler
)
85 IMPLEMENT_ABSTRACT_CLASS(wxView
, wxEvtHandler
)
86 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate
, wxObject
)
87 IMPLEMENT_DYNAMIC_CLASS(wxDocManager
, wxEvtHandler
)
88 IMPLEMENT_CLASS(wxDocChildFrame
, wxFrame
)
89 IMPLEMENT_CLASS(wxDocParentFrame
, wxFrame
)
91 #if wxUSE_PRINTING_ARCHITECTURE
92 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout
, wxPrintout
)
95 IMPLEMENT_DYNAMIC_CLASS(wxFileHistory
, wxObject
)
97 // ============================================================================
99 // ============================================================================
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
108 wxString
FindExtension(const wxString
& path
)
111 wxFileName::SplitPath(path
, NULL
, NULL
, &ext
);
113 // VZ: extensions are considered not case sensitive - is this really a good
115 return ext
.MakeLower();
118 // return the string used for the MRU list items in the menu
120 // NB: the index n is 0-based, as usual, but the strings start from 1
121 wxString
GetMRUEntryLabel(int n
, const wxString
& path
)
123 // we need to quote '&' characters which are used for mnemonics
124 wxString
pathInMenu(path
);
125 pathInMenu
.Replace("&", "&&");
127 return wxString::Format("&%d %s", n
+ 1, pathInMenu
);
130 } // anonymous namespace
132 // ----------------------------------------------------------------------------
133 // Definition of wxDocument
134 // ----------------------------------------------------------------------------
136 wxDocument::wxDocument(wxDocument
*parent
)
138 m_documentModified
= false;
139 m_documentParent
= parent
;
140 m_documentTemplate
= NULL
;
141 m_commandProcessor
= NULL
;
145 bool wxDocument::DeleteContents()
150 wxDocument::~wxDocument()
154 delete m_commandProcessor
;
156 if (GetDocumentManager())
157 GetDocumentManager()->RemoveDocument(this);
159 // Not safe to do here, since it'll invoke virtual view functions
160 // expecting to see valid derived objects: and by the time we get here,
161 // we've called destructors higher up.
165 bool wxDocument::Close()
167 if ( !OnSaveModified() )
170 return OnCloseDocument();
173 bool wxDocument::OnCloseDocument()
175 // Tell all views that we're about to close
182 // Note that this implicitly deletes the document when the last view is
184 bool wxDocument::DeleteAllViews()
186 wxDocManager
* manager
= GetDocumentManager();
188 // first check if all views agree to be closed
189 const wxList::iterator end
= m_documentViews
.end();
190 for ( wxList::iterator i
= m_documentViews
.begin(); i
!= end
; ++i
)
192 wxView
*view
= (wxView
*)*i
;
193 if ( !view
->Close() )
197 // all views agreed to close, now do close them
198 if ( m_documentViews
.empty() )
200 // normally the document would be implicitly deleted when the last view
201 // is, but if don't have any views, do it here instead
202 if ( manager
&& manager
->GetDocuments().Member(this) )
207 // as we delete elements we iterate over, don't use the usual "from
208 // begin to end" loop
211 wxView
*view
= (wxView
*)*m_documentViews
.begin();
213 bool isLastOne
= m_documentViews
.size() == 1;
215 // this always deletes the node implicitly and if this is the last
216 // view also deletes this object itself (also implicitly, great),
217 // so we can't test for m_documentViews.empty() after calling this!
228 wxView
*wxDocument::GetFirstView() const
230 if ( m_documentViews
.empty() )
233 return static_cast<wxView
*>(m_documentViews
.GetFirst()->GetData());
236 wxDocManager
*wxDocument::GetDocumentManager() const
238 return m_documentTemplate
? m_documentTemplate
->GetDocumentManager() : NULL
;
241 bool wxDocument::OnNewDocument()
243 // notice that there is no need to neither reset nor even check the
244 // modified flag here as the document itself is a new object (this is only
245 // called from CreateDocument()) and so it shouldn't be saved anyhow even
246 // if it is modified -- this could happen if the user code creates
247 // documents pre-filled with some user-entered (and which hence must not be
250 SetDocumentSaved(false);
252 const wxString name
= GetDocumentManager()->MakeNewDocumentName();
254 SetFilename(name
, true);
259 bool wxDocument::Save()
261 if ( AlreadySaved() )
264 if ( m_documentFile
.empty() || !m_savedYet
)
267 return OnSaveDocument(m_documentFile
);
270 bool wxDocument::SaveAs()
272 wxDocTemplate
*docTemplate
= GetDocumentTemplate();
276 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
277 wxString filter
= docTemplate
->GetDescription() + wxT(" (") +
278 docTemplate
->GetFileFilter() + wxT(")|") +
279 docTemplate
->GetFileFilter();
281 // Now see if there are some other template with identical view and document
282 // classes, whose filters may also be used.
283 if (docTemplate
->GetViewClassInfo() && docTemplate
->GetDocClassInfo())
285 wxList::compatibility_iterator
286 node
= docTemplate
->GetDocumentManager()->GetTemplates().GetFirst();
289 wxDocTemplate
*t
= (wxDocTemplate
*) node
->GetData();
291 if (t
->IsVisible() && t
!= docTemplate
&&
292 t
->GetViewClassInfo() == docTemplate
->GetViewClassInfo() &&
293 t
->GetDocClassInfo() == docTemplate
->GetDocClassInfo())
295 // add a '|' to separate this filter from the previous one
296 if ( !filter
.empty() )
299 filter
<< t
->GetDescription()
300 << wxT(" (") << t
->GetFileFilter() << wxT(") |")
301 << t
->GetFileFilter();
304 node
= node
->GetNext();
308 wxString filter
= docTemplate
->GetFileFilter() ;
311 wxString defaultDir
= docTemplate
->GetDirectory();
312 if ( defaultDir
.empty() )
314 defaultDir
= wxPathOnly(GetFilename());
315 if ( defaultDir
.empty() )
316 defaultDir
= GetDocumentManager()->GetLastDirectory();
319 wxString fileName
= wxFileSelector(_("Save As"),
321 wxFileNameFromPath(GetFilename()),
322 docTemplate
->GetDefaultExtension(),
324 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
325 GetDocumentWindow());
327 if (fileName
.empty())
328 return false; // cancelled by user
331 wxFileName::SplitPath(fileName
, NULL
, NULL
, &ext
);
335 fileName
+= wxT(".");
336 fileName
+= docTemplate
->GetDefaultExtension();
339 // Files that were not saved correctly are not added to the FileHistory.
340 if (!OnSaveDocument(fileName
))
343 SetTitle(wxFileNameFromPath(fileName
));
344 SetFilename(fileName
, true); // will call OnChangeFileName automatically
346 // A file that doesn't use the default extension of its document template
347 // cannot be opened via the FileHistory, so we do not add it.
348 if (docTemplate
->FileMatchesTemplate(fileName
))
350 GetDocumentManager()->AddFileToHistory(fileName
);
352 //else: the user will probably not be able to open the file again, so we
353 // could warn about the wrong file-extension here
358 bool wxDocument::OnSaveDocument(const wxString
& file
)
363 if ( !DoSaveDocument(file
) )
368 SetDocumentSaved(true);
369 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
370 wxFileName
fn(file
) ;
371 fn
.MacSetDefaultTypeAndCreator() ;
376 bool wxDocument::OnOpenDocument(const wxString
& file
)
378 // notice that there is no need to check the modified flag here for the
379 // reasons explained in OnNewDocument()
381 if ( !DoOpenDocument(file
) )
384 SetFilename(file
, true);
386 // stretching the logic a little this does make sense because the document
387 // had been saved into the file we just loaded it from, it just could have
388 // happened during a previous program execution, it's just that the name of
389 // this method is a bit unfortunate, it should probably have been called
390 // HasAssociatedFileName()
391 SetDocumentSaved(true);
398 #if wxUSE_STD_IOSTREAM
399 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
401 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
407 #if wxUSE_STD_IOSTREAM
408 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
410 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
416 bool wxDocument::Revert()
422 // Get title, or filename if no title, else unnamed
423 #if WXWIN_COMPATIBILITY_2_8
424 bool wxDocument::GetPrintableName(wxString
& buf
) const
426 // this function can not only be overridden by the user code but also
427 // called by it so we need to ensure that we return the same thing as
428 // GetUserReadableName() but we can't call it because this would result in
429 // an infinite recursion, hence we use the helper DoGetUserReadableName()
430 buf
= DoGetUserReadableName();
434 #endif // WXWIN_COMPATIBILITY_2_8
436 wxString
wxDocument::GetUserReadableName() const
438 #if WXWIN_COMPATIBILITY_2_8
439 // we need to call the old virtual function to ensure that the overridden
440 // version of it is still called
442 if ( GetPrintableName(name
) )
444 #endif // WXWIN_COMPATIBILITY_2_8
446 return DoGetUserReadableName();
449 wxString
wxDocument::DoGetUserReadableName() const
451 if ( !m_documentTitle
.empty() )
452 return m_documentTitle
;
454 if ( !m_documentFile
.empty() )
455 return wxFileNameFromPath(m_documentFile
);
460 wxWindow
*wxDocument::GetDocumentWindow() const
462 wxView
* const view
= GetFirstView();
464 return view
? view
->GetFrame() : wxTheApp
->GetTopWindow();
467 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
469 return new wxCommandProcessor
;
472 // true if safe to close
473 bool wxDocument::OnSaveModified()
477 switch ( wxMessageBox
481 _("Do you want to save changes to %s?"),
482 GetUserReadableName()
484 wxTheApp
->GetAppDisplayName(),
485 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
503 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
508 bool wxDocument::AddView(wxView
*view
)
510 if ( !m_documentViews
.Member(view
) )
512 m_documentViews
.Append(view
);
518 bool wxDocument::RemoveView(wxView
*view
)
520 (void)m_documentViews
.DeleteObject(view
);
525 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
527 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
530 // Called after a view is added or removed.
531 // The default implementation deletes the document if
532 // there are no more views.
533 void wxDocument::OnChangedViewList()
535 if ( m_documentViews
.empty() && OnSaveModified() )
539 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
541 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
544 wxView
*view
= (wxView
*)node
->GetData();
546 view
->OnUpdate(sender
, hint
);
547 node
= node
->GetNext();
551 void wxDocument::NotifyClosing()
553 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
556 wxView
*view
= (wxView
*)node
->GetData();
557 view
->OnClosingDocument();
558 node
= node
->GetNext();
562 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
564 m_documentFile
= filename
;
565 OnChangeFilename(notifyViews
);
568 void wxDocument::OnChangeFilename(bool notifyViews
)
572 // Notify the views that the filename has changed
573 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
576 wxView
*view
= (wxView
*)node
->GetData();
577 view
->OnChangeFilename();
578 node
= node
->GetNext();
583 bool wxDocument::DoSaveDocument(const wxString
& file
)
585 #if wxUSE_STD_IOSTREAM
586 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
589 wxFileOutputStream
store(file
);
590 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
593 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
597 if (!SaveObject(store
))
599 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
606 bool wxDocument::DoOpenDocument(const wxString
& file
)
608 #if wxUSE_STD_IOSTREAM
609 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
612 wxFileInputStream
store(file
);
613 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
616 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
620 #if wxUSE_STD_IOSTREAM
624 int res
= LoadObject(store
).GetLastError();
625 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
628 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
636 // ----------------------------------------------------------------------------
638 // ----------------------------------------------------------------------------
642 m_viewDocument
= NULL
;
646 m_docChildFrame
= NULL
;
651 GetDocumentManager()->ActivateView(this, false);
653 // reset our frame view first, before removing it from the document as
654 // SetView(NULL) is a simple call while RemoveView() may result in user
655 // code being executed and this user code can, for example, show a message
656 // box which would result in an activation event for m_docChildFrame and so
657 // could reactivate the view being destroyed -- unless we reset it first
658 if ( m_docChildFrame
&& m_docChildFrame
->GetView() == this )
660 // prevent it from doing anything with us
661 m_docChildFrame
->SetView(NULL
);
663 // it doesn't make sense to leave the frame alive if its associated
664 // view doesn't exist any more so unconditionally close it as well
666 // notice that we only get here if m_docChildFrame is non-NULL in the
667 // first place and it will be always NULL if we're deleted because our
668 // frame was closed, so this only catches the case of directly deleting
669 // the view, as it happens if its creation fails in wxDocTemplate::
670 // CreateView() for example
671 m_docChildFrame
->GetWindow()->Destroy();
674 if ( m_viewDocument
)
675 m_viewDocument
->RemoveView(this);
678 void wxView::SetDocChildFrame(wxDocChildFrameAnyBase
*docChildFrame
)
680 SetFrame(docChildFrame
? docChildFrame
->GetWindow() : NULL
);
681 m_docChildFrame
= docChildFrame
;
684 bool wxView::TryBefore(wxEvent
& event
)
686 wxDocument
* const doc
= GetDocument();
687 return doc
&& doc
->ProcessEventHere(event
);
690 void wxView::OnActivateView(bool WXUNUSED(activate
),
691 wxView
*WXUNUSED(activeView
),
692 wxView
*WXUNUSED(deactiveView
))
696 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
701 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
705 void wxView::OnChangeFilename()
707 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
708 // generic MDI implementation so use SetLabel rather than SetTitle.
709 // It should cause SetTitle() for top level windows.
710 wxWindow
*win
= GetFrame();
713 wxDocument
*doc
= GetDocument();
716 win
->SetLabel(doc
->GetUserReadableName());
719 void wxView::SetDocument(wxDocument
*doc
)
721 m_viewDocument
= doc
;
726 bool wxView::Close(bool deleteWindow
)
728 return OnClose(deleteWindow
);
731 void wxView::Activate(bool activate
)
733 if (GetDocument() && GetDocumentManager())
735 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
736 GetDocumentManager()->ActivateView(this, activate
);
740 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
742 return GetDocument() ? GetDocument()->Close() : true;
745 #if wxUSE_PRINTING_ARCHITECTURE
746 wxPrintout
*wxView::OnCreatePrintout()
748 return new wxDocPrintout(this);
750 #endif // wxUSE_PRINTING_ARCHITECTURE
752 // ----------------------------------------------------------------------------
754 // ----------------------------------------------------------------------------
756 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
757 const wxString
& descr
,
758 const wxString
& filter
,
761 const wxString
& docTypeName
,
762 const wxString
& viewTypeName
,
763 wxClassInfo
*docClassInfo
,
764 wxClassInfo
*viewClassInfo
,
767 m_documentManager
= manager
;
768 m_description
= descr
;
771 m_fileFilter
= filter
;
773 m_docTypeName
= docTypeName
;
774 m_viewTypeName
= viewTypeName
;
775 m_documentManager
->AssociateTemplate(this);
777 m_docClassInfo
= docClassInfo
;
778 m_viewClassInfo
= viewClassInfo
;
781 wxDocTemplate::~wxDocTemplate()
783 m_documentManager
->DisassociateTemplate(this);
786 // Tries to dynamically construct an object of the right class.
787 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
789 // InitDocument() is supposed to delete the document object if its
790 // initialization fails so don't use wxScopedPtr<> here: this is fragile
791 // but unavoidable because the default implementation uses CreateView()
792 // which may -- or not -- create a wxView and if it does create it and its
793 // initialization fails then the view destructor will delete the document
794 // (via RemoveView()) and as we can't distinguish between the two cases we
795 // just have to assume that it always deletes it in case of failure
796 wxDocument
* const doc
= DoCreateDocument();
798 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
802 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
804 doc
->SetFilename(path
);
805 doc
->SetDocumentTemplate(this);
806 GetDocumentManager()->AddDocument(doc
);
807 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
809 if (doc
->OnCreate(path
, flags
))
812 if (GetDocumentManager()->GetDocuments().Member(doc
))
813 doc
->DeleteAllViews();
817 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
819 wxScopedPtr
<wxView
> view(DoCreateView());
823 view
->SetDocument(doc
);
824 if ( !view
->OnCreate(doc
, flags
) )
827 return view
.release();
830 // The default (very primitive) format detection: check is the extension is
831 // that of the template
832 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
834 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
835 wxString anything
= wxT ("*");
836 while (parser
.HasMoreTokens())
838 wxString filter
= parser
.GetNextToken();
839 wxString filterExt
= FindExtension (filter
);
840 if ( filter
.IsSameAs (anything
) ||
841 filterExt
.IsSameAs (anything
) ||
842 filterExt
.IsSameAs (FindExtension (path
)) )
845 return GetDefaultExtension().IsSameAs(FindExtension(path
));
848 wxDocument
*wxDocTemplate::DoCreateDocument()
853 return static_cast<wxDocument
*>(m_docClassInfo
->CreateObject());
856 wxView
*wxDocTemplate::DoCreateView()
858 if (!m_viewClassInfo
)
861 return static_cast<wxView
*>(m_viewClassInfo
->CreateObject());
864 // ----------------------------------------------------------------------------
866 // ----------------------------------------------------------------------------
868 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
869 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
870 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
871 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
872 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
873 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
874 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
875 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
876 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
877 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
879 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
880 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
881 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
882 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
883 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
884 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
885 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
886 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
887 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
889 #if wxUSE_PRINTING_ARCHITECTURE
890 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
891 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
893 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
894 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
898 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
900 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
902 wxASSERT_MSG( !sm_docManager
, "multiple wxDocManagers not allowed" );
904 sm_docManager
= this;
906 m_defaultDocumentNameCounter
= 1;
907 m_currentView
= NULL
;
908 m_maxDocsOpen
= INT_MAX
;
909 m_fileHistory
= NULL
;
914 wxDocManager::~wxDocManager()
917 delete m_fileHistory
;
918 sm_docManager
= NULL
;
921 // closes the specified document
922 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
924 if ( !doc
->Close() && !force
)
927 // Implicitly deletes the document when
928 // the last view is deleted
929 doc
->DeleteAllViews();
931 // Check we're really deleted
932 if (m_docs
.Member(doc
))
938 bool wxDocManager::CloseDocuments(bool force
)
940 wxList::compatibility_iterator node
= m_docs
.GetFirst();
943 wxDocument
*doc
= (wxDocument
*)node
->GetData();
944 wxList::compatibility_iterator next
= node
->GetNext();
946 if (!CloseDocument(doc
, force
))
949 // This assumes that documents are not connected in
950 // any way, i.e. deleting one document does NOT
957 bool wxDocManager::Clear(bool force
)
959 if (!CloseDocuments(force
))
962 m_currentView
= NULL
;
964 wxList::compatibility_iterator node
= m_templates
.GetFirst();
967 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
968 wxList::compatibility_iterator next
= node
->GetNext();
975 bool wxDocManager::Initialize()
977 m_fileHistory
= OnCreateFileHistory();
981 wxString
wxDocManager::GetLastDirectory() const
983 // if we haven't determined the last used directory yet, do it now
984 if ( m_lastDirectory
.empty() )
986 // we're going to modify m_lastDirectory in this const method, so do it
987 // via non-const self pointer instead of const this one
988 wxDocManager
* const self
= const_cast<wxDocManager
*>(this);
990 // first try to reuse the directory of the most recently opened file:
991 // this ensures that if the user opens a file, closes the program and
992 // runs it again the "Open file" dialog will open in the directory of
993 // the last file he used
994 if ( m_fileHistory
&& m_fileHistory
->GetCount() )
996 const wxString lastOpened
= m_fileHistory
->GetHistoryFile(0);
997 const wxFileName
fn(lastOpened
);
998 if ( fn
.DirExists() )
1000 self
->m_lastDirectory
= fn
.GetPath();
1002 //else: should we try the next one?
1004 //else: no history yet
1006 // if we don't have any files in the history (yet?), use the
1007 // system-dependent default location for the document files
1008 if ( m_lastDirectory
.empty() )
1010 self
->m_lastDirectory
= wxStandardPaths::Get().GetAppDocumentsDir();
1014 return m_lastDirectory
;
1017 wxFileHistory
*wxDocManager::OnCreateFileHistory()
1019 return new wxFileHistory
;
1022 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
1024 wxDocument
*doc
= GetCurrentDocument();
1029 doc
->DeleteAllViews();
1030 if (m_docs
.Member(doc
))
1035 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
1037 CloseDocuments(false);
1040 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
1042 CreateNewDocument();
1045 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
1047 if ( !CreateDocument("") )
1049 OnOpenFileFailure();
1053 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
1055 wxDocument
*doc
= GetCurrentDocument();
1061 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
1063 wxDocument
*doc
= GetCurrentDocument();
1069 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1071 wxDocument
*doc
= GetCurrentDocument();
1077 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1079 #if wxUSE_PRINTING_ARCHITECTURE
1080 wxView
*view
= GetActiveView();
1084 wxPrintout
*printout
= view
->OnCreatePrintout();
1088 printer
.Print(view
->GetFrame(), printout
, true);
1092 #endif // wxUSE_PRINTING_ARCHITECTURE
1095 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1097 #if wxUSE_PRINTING_ARCHITECTURE
1098 wxView
*view
= GetActiveView();
1102 wxPrintout
*printout
= view
->OnCreatePrintout();
1105 // Pass two printout objects: for preview, and possible printing.
1106 wxPrintPreviewBase
*
1107 preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1108 if ( !preview
->Ok() )
1111 wxLogError(_("Print preview creation failed."));
1116 frame
= new wxPreviewFrame(preview
, wxTheApp
->GetTopWindow(),
1117 _("Print Preview"));
1118 frame
->Centre(wxBOTH
);
1119 frame
->Initialize();
1122 #endif // wxUSE_PRINTING_ARCHITECTURE
1125 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1127 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1137 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1139 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1149 // Handlers for UI update commands
1151 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1153 // CreateDocument() (which is called from OnFileOpen) may succeed
1154 // only when there is at least a template:
1155 event
.Enable( GetTemplates().GetCount()>0 );
1158 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1160 event
.Enable( GetCurrentDocument() != NULL
);
1163 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1165 // CreateDocument() (which is called from OnFileNew) may succeed
1166 // only when there is at least a template:
1167 event
.Enable( GetTemplates().GetCount()>0 );
1170 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1172 wxDocument
* const doc
= GetCurrentDocument();
1173 event
.Enable( doc
&& !doc
->AlreadySaved() );
1176 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1178 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1181 event
.Enable(false);
1185 event
.Enable(cmdproc
->CanUndo());
1186 cmdproc
->SetMenuStrings();
1189 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1191 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1194 event
.Enable(false);
1198 event
.Enable(cmdproc
->CanRedo());
1199 cmdproc
->SetMenuStrings();
1202 wxView
*wxDocManager::GetActiveView() const
1204 wxView
*view
= GetCurrentView();
1206 if ( !view
&& !m_docs
.empty() )
1208 // if we have exactly one document, consider its view to be the current
1211 // VZ: I'm not exactly sure why is this needed but this is how this
1212 // code used to behave before the bug #9518 was fixed and it seems
1213 // safer to preserve the old logic
1214 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1215 if ( !node
->GetNext() )
1217 wxDocument
*doc
= static_cast<wxDocument
*>(node
->GetData());
1218 view
= doc
->GetFirstView();
1220 //else: we have more than one document
1226 bool wxDocManager::TryBefore(wxEvent
& event
)
1228 wxView
* const view
= GetActiveView();
1229 return view
&& view
->ProcessEventHere(event
);
1235 // helper function: return only the visible templates
1236 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1238 // select only the visible templates
1239 const size_t totalNumTemplates
= allTemplates
.GetCount();
1240 wxDocTemplates templates
;
1241 if ( totalNumTemplates
)
1243 templates
.reserve(totalNumTemplates
);
1245 for ( wxList::const_iterator i
= allTemplates
.begin(),
1246 end
= allTemplates
.end();
1250 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1251 if ( temp
->IsVisible() )
1252 templates
.push_back(temp
);
1259 } // anonymous namespace
1261 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1263 // this ought to be const but SelectDocumentType/Path() are not
1264 // const-correct and can't be changed as, being virtual, this risks
1265 // breaking user code overriding them
1266 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1267 const size_t numTemplates
= templates
.size();
1268 if ( !numTemplates
)
1270 // no templates can be used, can't create document
1275 // normally user should select the template to use but wxDOC_SILENT flag we
1276 // choose one ourselves
1277 wxString path
= pathOrig
; // may be modified below
1278 wxDocTemplate
*temp
;
1279 if ( flags
& wxDOC_SILENT
)
1281 wxASSERT_MSG( !path
.empty(),
1282 "using empty path with wxDOC_SILENT doesn't make sense" );
1284 temp
= FindTemplateForPath(path
);
1287 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1291 else // not silent, ask the user
1293 // for the new file we need just the template, for an existing one we
1294 // need the template and the path, unless it's already specified
1295 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1296 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1298 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1304 // check whether the document with this path is already opened
1305 if ( !path
.empty() )
1307 const wxFileName
fn(path
);
1308 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1310 wxDocument
* const doc
= (wxDocument
*)*i
;
1312 if ( fn
== doc
->GetFilename() )
1314 // file already open, just activate it and return
1315 if ( doc
->GetFirstView() )
1317 ActivateView(doc
->GetFirstView());
1318 if ( doc
->GetDocumentWindow() )
1319 doc
->GetDocumentWindow()->SetFocus();
1327 // no, we need to create a new document
1330 // if we've reached the max number of docs, close the first one.
1331 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1333 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1335 // can't open the new document if closing the old one failed
1341 // do create and initialize the new document finally
1342 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1346 docNew
->SetDocumentName(temp
->GetDocumentName());
1347 docNew
->SetDocumentTemplate(temp
);
1351 // call the appropriate function depending on whether we're creating a
1352 // new file or opening an existing one
1353 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1354 : docNew
->OnOpenDocument(path
)) )
1356 docNew
->DeleteAllViews();
1360 wxCATCH_ALL( docNew
->DeleteAllViews(); throw; )
1362 // add the successfully opened file to MRU, but only if we're going to be
1363 // able to reopen it successfully later which requires the template for
1364 // this document to be retrievable from the file extension
1365 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1366 AddFileToHistory(path
);
1371 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1373 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1374 const size_t numTemplates
= templates
.size();
1376 if ( numTemplates
== 0 )
1379 wxDocTemplate
* const
1380 temp
= numTemplates
== 1 ? templates
[0]
1381 : SelectViewType(&templates
[0], numTemplates
);
1386 wxView
*view
= temp
->CreateView(doc
, flags
);
1388 view
->SetViewName(temp
->GetViewName());
1392 // Not yet implemented
1394 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1398 // Not yet implemented
1399 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1404 wxDocument
*wxDocManager::GetCurrentDocument() const
1406 wxView
* const view
= GetActiveView();
1407 return view
? view
->GetDocument() : NULL
;
1410 wxCommandProcessor
*wxDocManager::GetCurrentCommandProcessor() const
1412 wxDocument
* const doc
= GetCurrentDocument();
1413 return doc
? doc
->GetCommandProcessor() : NULL
;
1416 // Make a default name for a new document
1417 #if WXWIN_COMPATIBILITY_2_8
1418 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1420 // we consider that this function can only be overridden by the user code,
1421 // not called by it as it only makes sense to call it internally, so we
1422 // don't bother to return anything from here
1425 #endif // WXWIN_COMPATIBILITY_2_8
1427 wxString
wxDocManager::MakeNewDocumentName()
1431 #if WXWIN_COMPATIBILITY_2_8
1432 if ( !MakeDefaultName(name
) )
1433 #endif // WXWIN_COMPATIBILITY_2_8
1435 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1436 m_defaultDocumentNameCounter
++;
1442 // Make a frame title (override this to do something different)
1443 // If docName is empty, a document is not currently active.
1444 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1446 wxString appName
= wxTheApp
->GetAppDisplayName();
1452 wxString docName
= doc
->GetUserReadableName();
1453 title
= docName
+ wxString(_(" - ")) + appName
;
1459 // Not yet implemented
1460 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1465 // File history management
1466 void wxDocManager::AddFileToHistory(const wxString
& file
)
1469 m_fileHistory
->AddFileToHistory(file
);
1472 void wxDocManager::RemoveFileFromHistory(size_t i
)
1475 m_fileHistory
->RemoveFileFromHistory(i
);
1478 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1483 histFile
= m_fileHistory
->GetHistoryFile(i
);
1488 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1491 m_fileHistory
->UseMenu(menu
);
1494 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1497 m_fileHistory
->RemoveMenu(menu
);
1501 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1504 m_fileHistory
->Load(config
);
1507 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1510 m_fileHistory
->Save(config
);
1514 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1517 m_fileHistory
->AddFilesToMenu(menu
);
1520 void wxDocManager::FileHistoryAddFilesToMenu()
1523 m_fileHistory
->AddFilesToMenu();
1526 size_t wxDocManager::GetHistoryFilesCount() const
1528 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1532 // Find out the document template via matching in the document file format
1533 // against that of the template
1534 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1536 wxDocTemplate
*theTemplate
= NULL
;
1538 // Find the template which this extension corresponds to
1539 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1541 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1542 if ( temp
->FileMatchesTemplate(path
) )
1551 // Prompts user to open a file, using file specs in templates.
1552 // Must extend the file selector dialog or implement own; OR
1553 // match the extension to the template extension.
1555 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1558 long WXUNUSED(flags
),
1559 bool WXUNUSED(save
))
1561 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1564 for (int i
= 0; i
< noTemplates
; i
++)
1566 if (templates
[i
]->IsVisible())
1568 // add a '|' to separate this filter from the previous one
1569 if ( !descrBuf
.empty() )
1570 descrBuf
<< wxT('|');
1572 descrBuf
<< templates
[i
]->GetDescription()
1573 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1574 << templates
[i
]->GetFileFilter();
1578 wxString descrBuf
= wxT("*.*");
1579 wxUnusedVar(noTemplates
);
1582 int FilterIndex
= -1;
1584 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1590 wxDocTemplate
*theTemplate
= NULL
;
1591 if (!pathTmp
.empty())
1593 if (!wxFileExists(pathTmp
))
1596 if (!wxTheApp
->GetAppDisplayName().empty())
1597 msgTitle
= wxTheApp
->GetAppDisplayName();
1599 msgTitle
= wxString(_("File error"));
1601 wxMessageBox(_("Sorry, could not open this file."),
1603 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1605 path
= wxEmptyString
;
1609 SetLastDirectory(wxPathOnly(pathTmp
));
1613 // first choose the template using the extension, if this fails (i.e.
1614 // wxFileSelectorEx() didn't fill it), then use the path
1615 if ( FilterIndex
!= -1 )
1616 theTemplate
= templates
[FilterIndex
];
1618 theTemplate
= FindTemplateForPath(path
);
1621 // Since we do not add files with non-default extensions to the
1622 // file history this can only happen if the application changes the
1623 // allowed templates in runtime.
1624 wxMessageBox(_("Sorry, the format for this file is unknown."),
1626 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1637 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1638 int noTemplates
, bool sort
)
1640 wxArrayString strings
;
1641 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1645 for (i
= 0; i
< noTemplates
; i
++)
1647 if (templates
[i
]->IsVisible())
1651 for (j
= 0; j
< n
; j
++)
1653 //filter out NOT unique documents + view combinations
1654 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1655 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1662 strings
.Add(templates
[i
]->m_description
);
1664 data
[n
] = templates
[i
];
1672 strings
.Sort(); // ascending sort
1673 // Yes, this will be slow, but template lists
1674 // are typically short.
1676 n
= strings
.Count();
1677 for (i
= 0; i
< n
; i
++)
1679 for (j
= 0; j
< noTemplates
; j
++)
1681 if (strings
[i
] == templates
[j
]->m_description
)
1682 data
[i
] = templates
[j
];
1687 wxDocTemplate
*theTemplate
;
1692 // no visible templates, hence nothing to choose from
1697 // don't propose the user to choose if he has no choice
1698 theTemplate
= data
[0];
1702 // propose the user to choose one of several
1703 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1705 _("Select a document template"),
1715 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1716 int noTemplates
, bool sort
)
1718 wxArrayString strings
;
1719 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1723 for (i
= 0; i
< noTemplates
; i
++)
1725 wxDocTemplate
*templ
= templates
[i
];
1726 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1730 for (j
= 0; j
< n
; j
++)
1732 //filter out NOT unique views
1733 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1739 strings
.Add(templ
->m_viewTypeName
);
1748 strings
.Sort(); // ascending sort
1749 // Yes, this will be slow, but template lists
1750 // are typically short.
1752 n
= strings
.Count();
1753 for (i
= 0; i
< n
; i
++)
1755 for (j
= 0; j
< noTemplates
; j
++)
1757 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1758 data
[i
] = templates
[j
];
1763 wxDocTemplate
*theTemplate
;
1765 // the same logic as above
1773 theTemplate
= data
[0];
1777 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1779 _("Select a document view"),
1790 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1792 if (!m_templates
.Member(temp
))
1793 m_templates
.Append(temp
);
1796 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1798 m_templates
.DeleteObject(temp
);
1801 // Add and remove a document from the manager's list
1802 void wxDocManager::AddDocument(wxDocument
*doc
)
1804 if (!m_docs
.Member(doc
))
1808 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1810 m_docs
.DeleteObject(doc
);
1813 // Views or windows should inform the document manager
1814 // when a view is going in or out of focus
1815 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1819 m_currentView
= view
;
1823 if ( m_currentView
== view
)
1825 // don't keep stale pointer
1826 m_currentView
= NULL
;
1831 // ----------------------------------------------------------------------------
1832 // wxDocChildFrameAnyBase
1833 // ----------------------------------------------------------------------------
1835 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent
& event
)
1839 if ( event
.CanVeto() && !m_childView
->Close(false) )
1845 m_childView
->Activate(false);
1847 // it is important to reset m_childView frame pointer to NULL before
1848 // deleting it because while normally it is the frame which deletes the
1849 // view when it's closed, the view also closes the frame if it is
1850 // deleted directly not by us as indicated by its doc child frame
1851 // pointer still being set
1852 m_childView
->SetDocChildFrame(NULL
);
1857 m_childDocument
= NULL
;
1862 // ----------------------------------------------------------------------------
1863 // Default parent frame
1864 // ----------------------------------------------------------------------------
1866 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1867 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1868 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1869 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1872 wxDocParentFrame::wxDocParentFrame()
1874 m_docManager
= NULL
;
1877 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1880 const wxString
& title
,
1884 const wxString
& name
)
1885 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1887 m_docManager
= manager
;
1890 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1893 const wxString
& title
,
1897 const wxString
& name
)
1899 m_docManager
= manager
;
1900 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1903 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1908 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1910 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1911 wxString
filename(m_docManager
->GetHistoryFile(n
));
1912 if ( filename
.empty() )
1915 wxString errMsg
; // must contain exactly one "%s" if non-empty
1916 if ( wxFile::Exists(filename
) )
1919 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1922 errMsg
= _("The file '%s' couldn't be opened.");
1924 else // file doesn't exist
1926 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1930 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1932 // remove the file which we can't open from the MRU list
1933 m_docManager
->RemoveFileFromHistory(n
);
1935 // and tell the user about it
1936 wxLogError(errMsg
+ '\n' +
1937 _("It has been removed from the most recently used files list."),
1941 // Extend event processing to search the view's event table
1942 bool wxDocParentFrame::TryBefore(wxEvent
& event
)
1944 if ( m_docManager
&& m_docManager
->ProcessEventHere(event
) )
1947 return wxFrame::TryBefore(event
);
1950 // Define the behaviour for the frame closing
1951 // - must delete all frames except for the main one.
1952 void wxDocParentFrame::OnCloseWindow(wxCloseEvent
& event
)
1954 if (m_docManager
->Clear(!event
.CanVeto()))
1962 #if wxUSE_PRINTING_ARCHITECTURE
1964 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
1967 m_printoutView
= view
;
1970 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
1974 // Get the logical pixels per inch of screen and printer
1975 int ppiScreenX
, ppiScreenY
;
1976 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
1977 wxUnusedVar(ppiScreenY
);
1978 int ppiPrinterX
, ppiPrinterY
;
1979 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
1980 wxUnusedVar(ppiPrinterY
);
1982 // This scales the DC so that the printout roughly represents the
1983 // the screen scaling. The text point size _should_ be the right size
1984 // but in fact is too small for some reason. This is a detail that will
1985 // need to be addressed at some point but can be fudged for the
1987 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
1989 // Now we have to check in case our real page size is reduced
1990 // (e.g. because we're drawing to a print preview memory DC)
1991 int pageWidth
, pageHeight
;
1993 dc
->GetSize(&w
, &h
);
1994 GetPageSizePixels(&pageWidth
, &pageHeight
);
1995 wxUnusedVar(pageHeight
);
1997 // If printer pageWidth == current DC width, then this doesn't
1998 // change. But w might be the preview bitmap width, so scale down.
1999 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
2000 dc
->SetUserScale(overallScale
, overallScale
);
2004 m_printoutView
->OnDraw(dc
);
2009 bool wxDocPrintout::HasPage(int pageNum
)
2011 return (pageNum
== 1);
2014 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
2016 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
2022 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
,
2023 int *selPageFrom
, int *selPageTo
)
2031 #endif // wxUSE_PRINTING_ARCHITECTURE
2033 // ----------------------------------------------------------------------------
2034 // File history (a.k.a. MRU, most recently used, files list)
2035 // ----------------------------------------------------------------------------
2037 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
2039 m_fileMaxFiles
= maxFiles
;
2043 void wxFileHistory::AddFileToHistory(const wxString
& file
)
2045 // check if we don't already have this file
2046 const wxFileName
fnNew(file
);
2048 numFiles
= m_fileHistory
.size();
2049 for ( i
= 0; i
< numFiles
; i
++ )
2051 if ( fnNew
== m_fileHistory
[i
] )
2053 // we do have it, move it to the top of the history
2054 RemoveFileFromHistory(i
);
2060 // if we already have a full history, delete the one at the end
2061 if ( numFiles
== m_fileMaxFiles
)
2063 RemoveFileFromHistory(--numFiles
);
2066 // add a new menu item to all file menus (they will be updated below)
2067 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2069 node
= node
->GetNext() )
2071 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2073 if ( !numFiles
&& menu
->GetMenuItemCount() )
2074 menu
->AppendSeparator();
2076 // label doesn't matter, it will be set below anyhow, but it can't
2077 // be empty (this is supposed to indicate a stock item)
2078 menu
->Append(m_idBase
+ numFiles
, " ");
2081 // insert the new file in the beginning of the file history
2082 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2085 // update the labels in all menus
2086 for ( i
= 0; i
< numFiles
; i
++ )
2088 // if in same directory just show the filename; otherwise the full path
2089 const wxFileName
fnOld(m_fileHistory
[i
]);
2091 wxString pathInMenu
;
2092 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2094 pathInMenu
= fnOld
.GetFullName();
2096 else // file in different directory
2098 // absolute path; could also set relative path
2099 pathInMenu
= m_fileHistory
[i
];
2102 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2104 node
= node
->GetNext() )
2106 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2108 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2113 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2115 size_t numFiles
= m_fileHistory
.size();
2116 wxCHECK_RET( i
< numFiles
,
2117 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2119 // delete the element from the array
2120 m_fileHistory
.RemoveAt(i
);
2123 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2125 node
= node
->GetNext() )
2127 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2129 // shift filenames up
2130 for ( size_t j
= i
; j
< numFiles
; j
++ )
2132 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2135 // delete the last menu item which is unused now
2136 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2137 if ( menu
->FindItem(lastItemId
) )
2138 menu
->Delete(lastItemId
);
2140 // delete the last separator too if no more files are left
2141 if ( m_fileHistory
.empty() )
2143 const wxMenuItemList::compatibility_iterator
2144 nodeLast
= menu
->GetMenuItems().GetLast();
2147 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2148 if ( lastMenuItem
->IsSeparator() )
2149 menu
->Delete(lastMenuItem
);
2151 //else: menu is empty somehow
2156 void wxFileHistory::UseMenu(wxMenu
*menu
)
2158 if ( !m_fileMenus
.Member(menu
) )
2159 m_fileMenus
.Append(menu
);
2162 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2164 m_fileMenus
.DeleteObject(menu
);
2168 void wxFileHistory::Load(const wxConfigBase
& config
)
2170 m_fileHistory
.Clear();
2173 buf
.Printf(wxT("file%d"), 1);
2175 wxString historyFile
;
2176 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2177 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2179 m_fileHistory
.Add(historyFile
);
2181 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2182 historyFile
= wxEmptyString
;
2188 void wxFileHistory::Save(wxConfigBase
& config
)
2191 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2194 buf
.Printf(wxT("file%d"), (int)i
+1);
2195 if (i
< m_fileHistory
.GetCount())
2196 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2198 config
.Write(buf
, wxEmptyString
);
2201 #endif // wxUSE_CONFIG
2203 void wxFileHistory::AddFilesToMenu()
2205 if ( m_fileHistory
.empty() )
2208 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2210 node
= node
->GetNext() )
2212 AddFilesToMenu((wxMenu
*) node
->GetData());
2216 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2218 if ( m_fileHistory
.empty() )
2221 if ( menu
->GetMenuItemCount() )
2222 menu
->AppendSeparator();
2224 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2226 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2230 // ----------------------------------------------------------------------------
2231 // Permits compatibility with existing file formats and functions that
2232 // manipulate files directly
2233 // ----------------------------------------------------------------------------
2235 #if wxUSE_STD_IOSTREAM
2237 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2240 wxFFile
file(filename
, wxT("rb"));
2242 wxFile
file(filename
, wxFile::read
);
2244 if ( !file
.IsOpened() )
2252 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2256 stream
.write(buf
, nRead
);
2260 while ( !file
.Eof() );
2265 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2268 wxFFile
file(filename
, wxT("wb"));
2270 wxFile
file(filename
, wxFile::write
);
2272 if ( !file
.IsOpened() )
2278 stream
.read(buf
, WXSIZEOF(buf
));
2279 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2281 if ( !file
.Write(buf
, stream
.gcount()) )
2285 while ( !stream
.eof() );
2290 #else // !wxUSE_STD_IOSTREAM
2292 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2295 wxFFile
file(filename
, wxT("rb"));
2297 wxFile
file(filename
, wxFile::read
);
2299 if ( !file
.IsOpened() )
2307 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2311 stream
.Write(buf
, nRead
);
2315 while ( !file
.Eof() );
2320 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2323 wxFFile
file(filename
, wxT("wb"));
2325 wxFile
file(filename
, wxFile::write
);
2327 if ( !file
.IsOpened() )
2333 stream
.Read(buf
, WXSIZEOF(buf
));
2335 const size_t nRead
= stream
.LastRead();
2344 if ( !file
.Write(buf
, nRead
) )
2351 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2353 #endif // wxUSE_DOC_VIEW_ARCHITECTURE