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 void wxDocument::Modify(bool mod
)
238 if (mod
!= m_documentModified
)
240 m_documentModified
= mod
;
242 // Allow views to append asterix to the title
243 wxView
* view
= GetFirstView();
244 if (view
) view
->OnChangeFilename();
248 wxDocManager
*wxDocument::GetDocumentManager() const
250 return m_documentTemplate
? m_documentTemplate
->GetDocumentManager() : NULL
;
253 bool wxDocument::OnNewDocument()
255 // notice that there is no need to neither reset nor even check the
256 // modified flag here as the document itself is a new object (this is only
257 // called from CreateDocument()) and so it shouldn't be saved anyhow even
258 // if it is modified -- this could happen if the user code creates
259 // documents pre-filled with some user-entered (and which hence must not be
262 SetDocumentSaved(false);
264 const wxString name
= GetDocumentManager()->MakeNewDocumentName();
266 SetFilename(name
, true);
271 bool wxDocument::Save()
273 if ( AlreadySaved() )
276 if ( m_documentFile
.empty() || !m_savedYet
)
279 return OnSaveDocument(m_documentFile
);
282 bool wxDocument::SaveAs()
284 wxDocTemplate
*docTemplate
= GetDocumentTemplate();
288 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
289 wxString filter
= docTemplate
->GetDescription() + wxT(" (") +
290 docTemplate
->GetFileFilter() + wxT(")|") +
291 docTemplate
->GetFileFilter();
293 // Now see if there are some other template with identical view and document
294 // classes, whose filters may also be used.
295 if (docTemplate
->GetViewClassInfo() && docTemplate
->GetDocClassInfo())
297 wxList::compatibility_iterator
298 node
= docTemplate
->GetDocumentManager()->GetTemplates().GetFirst();
301 wxDocTemplate
*t
= (wxDocTemplate
*) node
->GetData();
303 if (t
->IsVisible() && t
!= docTemplate
&&
304 t
->GetViewClassInfo() == docTemplate
->GetViewClassInfo() &&
305 t
->GetDocClassInfo() == docTemplate
->GetDocClassInfo())
307 // add a '|' to separate this filter from the previous one
308 if ( !filter
.empty() )
311 filter
<< t
->GetDescription()
312 << wxT(" (") << t
->GetFileFilter() << wxT(") |")
313 << t
->GetFileFilter();
316 node
= node
->GetNext();
320 wxString filter
= docTemplate
->GetFileFilter() ;
323 wxString defaultDir
= docTemplate
->GetDirectory();
324 if ( defaultDir
.empty() )
326 defaultDir
= wxPathOnly(GetFilename());
327 if ( defaultDir
.empty() )
328 defaultDir
= GetDocumentManager()->GetLastDirectory();
331 wxString fileName
= wxFileSelector(_("Save As"),
333 wxFileNameFromPath(GetFilename()),
334 docTemplate
->GetDefaultExtension(),
336 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
337 GetDocumentWindow());
339 if (fileName
.empty())
340 return false; // cancelled by user
343 wxFileName::SplitPath(fileName
, NULL
, NULL
, &ext
);
347 fileName
+= wxT(".");
348 fileName
+= docTemplate
->GetDefaultExtension();
351 // Files that were not saved correctly are not added to the FileHistory.
352 if (!OnSaveDocument(fileName
))
355 SetTitle(wxFileNameFromPath(fileName
));
356 SetFilename(fileName
, true); // will call OnChangeFileName automatically
358 // A file that doesn't use the default extension of its document template
359 // cannot be opened via the FileHistory, so we do not add it.
360 if (docTemplate
->FileMatchesTemplate(fileName
))
362 GetDocumentManager()->AddFileToHistory(fileName
);
364 //else: the user will probably not be able to open the file again, so we
365 // could warn about the wrong file-extension here
370 bool wxDocument::OnSaveDocument(const wxString
& file
)
375 if ( !DoSaveDocument(file
) )
380 SetDocumentSaved(true);
381 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
382 wxFileName
fn(file
) ;
383 fn
.MacSetDefaultTypeAndCreator() ;
388 bool wxDocument::OnOpenDocument(const wxString
& file
)
390 // notice that there is no need to check the modified flag here for the
391 // reasons explained in OnNewDocument()
393 if ( !DoOpenDocument(file
) )
396 SetFilename(file
, true);
398 // stretching the logic a little this does make sense because the document
399 // had been saved into the file we just loaded it from, it just could have
400 // happened during a previous program execution, it's just that the name of
401 // this method is a bit unfortunate, it should probably have been called
402 // HasAssociatedFileName()
403 SetDocumentSaved(true);
410 #if wxUSE_STD_IOSTREAM
411 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
413 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
419 #if wxUSE_STD_IOSTREAM
420 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
422 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
428 bool wxDocument::Revert()
434 // Get title, or filename if no title, else unnamed
435 #if WXWIN_COMPATIBILITY_2_8
436 bool wxDocument::GetPrintableName(wxString
& buf
) const
438 // this function can not only be overridden by the user code but also
439 // called by it so we need to ensure that we return the same thing as
440 // GetUserReadableName() but we can't call it because this would result in
441 // an infinite recursion, hence we use the helper DoGetUserReadableName()
442 buf
= DoGetUserReadableName();
446 #endif // WXWIN_COMPATIBILITY_2_8
448 wxString
wxDocument::GetUserReadableName() const
450 #if WXWIN_COMPATIBILITY_2_8
451 // we need to call the old virtual function to ensure that the overridden
452 // version of it is still called
454 if ( GetPrintableName(name
) )
456 #endif // WXWIN_COMPATIBILITY_2_8
458 return DoGetUserReadableName();
461 wxString
wxDocument::DoGetUserReadableName() const
463 if ( !m_documentTitle
.empty() )
464 return m_documentTitle
;
466 if ( !m_documentFile
.empty() )
467 return wxFileNameFromPath(m_documentFile
);
472 wxWindow
*wxDocument::GetDocumentWindow() const
474 wxView
* const view
= GetFirstView();
476 return view
? view
->GetFrame() : wxTheApp
->GetTopWindow();
479 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
481 return new wxCommandProcessor
;
484 // true if safe to close
485 bool wxDocument::OnSaveModified()
489 switch ( wxMessageBox
493 _("Do you want to save changes to %s?"),
494 GetUserReadableName()
496 wxTheApp
->GetAppDisplayName(),
497 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
515 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
520 bool wxDocument::AddView(wxView
*view
)
522 if ( !m_documentViews
.Member(view
) )
524 m_documentViews
.Append(view
);
530 bool wxDocument::RemoveView(wxView
*view
)
532 (void)m_documentViews
.DeleteObject(view
);
537 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
539 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
542 // Called after a view is added or removed.
543 // The default implementation deletes the document if
544 // there are no more views.
545 void wxDocument::OnChangedViewList()
547 if ( m_documentViews
.empty() && OnSaveModified() )
551 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
553 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
556 wxView
*view
= (wxView
*)node
->GetData();
558 view
->OnUpdate(sender
, hint
);
559 node
= node
->GetNext();
563 void wxDocument::NotifyClosing()
565 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
568 wxView
*view
= (wxView
*)node
->GetData();
569 view
->OnClosingDocument();
570 node
= node
->GetNext();
574 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
576 m_documentFile
= filename
;
577 OnChangeFilename(notifyViews
);
580 void wxDocument::OnChangeFilename(bool notifyViews
)
584 // Notify the views that the filename has changed
585 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
588 wxView
*view
= (wxView
*)node
->GetData();
589 view
->OnChangeFilename();
590 node
= node
->GetNext();
595 bool wxDocument::DoSaveDocument(const wxString
& file
)
597 #if wxUSE_STD_IOSTREAM
598 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
601 wxFileOutputStream
store(file
);
602 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
605 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
609 if (!SaveObject(store
))
611 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
618 bool wxDocument::DoOpenDocument(const wxString
& file
)
620 #if wxUSE_STD_IOSTREAM
621 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
624 wxFileInputStream
store(file
);
625 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
628 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
632 #if wxUSE_STD_IOSTREAM
636 int res
= LoadObject(store
).GetLastError();
637 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
640 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
648 // ----------------------------------------------------------------------------
650 // ----------------------------------------------------------------------------
654 m_viewDocument
= NULL
;
658 m_docChildFrame
= NULL
;
663 GetDocumentManager()->ActivateView(this, false);
665 // reset our frame view first, before removing it from the document as
666 // SetView(NULL) is a simple call while RemoveView() may result in user
667 // code being executed and this user code can, for example, show a message
668 // box which would result in an activation event for m_docChildFrame and so
669 // could reactivate the view being destroyed -- unless we reset it first
670 if ( m_docChildFrame
&& m_docChildFrame
->GetView() == this )
672 // prevent it from doing anything with us
673 m_docChildFrame
->SetView(NULL
);
675 // it doesn't make sense to leave the frame alive if its associated
676 // view doesn't exist any more so unconditionally close it as well
678 // notice that we only get here if m_docChildFrame is non-NULL in the
679 // first place and it will be always NULL if we're deleted because our
680 // frame was closed, so this only catches the case of directly deleting
681 // the view, as it happens if its creation fails in wxDocTemplate::
682 // CreateView() for example
683 m_docChildFrame
->GetWindow()->Destroy();
686 if ( m_viewDocument
)
687 m_viewDocument
->RemoveView(this);
690 void wxView::SetDocChildFrame(wxDocChildFrameAnyBase
*docChildFrame
)
692 SetFrame(docChildFrame
? docChildFrame
->GetWindow() : NULL
);
693 m_docChildFrame
= docChildFrame
;
696 bool wxView::TryBefore(wxEvent
& event
)
698 wxDocument
* const doc
= GetDocument();
699 return doc
&& doc
->ProcessEventHere(event
);
702 void wxView::OnActivateView(bool WXUNUSED(activate
),
703 wxView
*WXUNUSED(activeView
),
704 wxView
*WXUNUSED(deactiveView
))
708 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
713 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
717 void wxView::OnChangeFilename()
719 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
720 // generic MDI implementation so use SetLabel rather than SetTitle.
721 // It should cause SetTitle() for top level windows.
722 wxWindow
*win
= GetFrame();
725 wxDocument
*doc
= GetDocument();
728 wxString label
= doc
->GetUserReadableName();
729 if (doc
->IsModified())
733 win
->SetLabel(label
);
736 void wxView::SetDocument(wxDocument
*doc
)
738 m_viewDocument
= doc
;
743 bool wxView::Close(bool deleteWindow
)
745 return OnClose(deleteWindow
);
748 void wxView::Activate(bool activate
)
750 if (GetDocument() && GetDocumentManager())
752 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
753 GetDocumentManager()->ActivateView(this, activate
);
757 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
759 return GetDocument() ? GetDocument()->Close() : true;
762 #if wxUSE_PRINTING_ARCHITECTURE
763 wxPrintout
*wxView::OnCreatePrintout()
765 return new wxDocPrintout(this);
767 #endif // wxUSE_PRINTING_ARCHITECTURE
769 // ----------------------------------------------------------------------------
771 // ----------------------------------------------------------------------------
773 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
774 const wxString
& descr
,
775 const wxString
& filter
,
778 const wxString
& docTypeName
,
779 const wxString
& viewTypeName
,
780 wxClassInfo
*docClassInfo
,
781 wxClassInfo
*viewClassInfo
,
784 m_documentManager
= manager
;
785 m_description
= descr
;
788 m_fileFilter
= filter
;
790 m_docTypeName
= docTypeName
;
791 m_viewTypeName
= viewTypeName
;
792 m_documentManager
->AssociateTemplate(this);
794 m_docClassInfo
= docClassInfo
;
795 m_viewClassInfo
= viewClassInfo
;
798 wxDocTemplate::~wxDocTemplate()
800 m_documentManager
->DisassociateTemplate(this);
803 // Tries to dynamically construct an object of the right class.
804 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
806 // InitDocument() is supposed to delete the document object if its
807 // initialization fails so don't use wxScopedPtr<> here: this is fragile
808 // but unavoidable because the default implementation uses CreateView()
809 // which may -- or not -- create a wxView and if it does create it and its
810 // initialization fails then the view destructor will delete the document
811 // (via RemoveView()) and as we can't distinguish between the two cases we
812 // just have to assume that it always deletes it in case of failure
813 wxDocument
* const doc
= DoCreateDocument();
815 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
819 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
821 doc
->SetFilename(path
);
822 doc
->SetDocumentTemplate(this);
823 GetDocumentManager()->AddDocument(doc
);
824 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
826 if (doc
->OnCreate(path
, flags
))
829 if (GetDocumentManager()->GetDocuments().Member(doc
))
830 doc
->DeleteAllViews();
834 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
836 wxScopedPtr
<wxView
> view(DoCreateView());
840 view
->SetDocument(doc
);
841 if ( !view
->OnCreate(doc
, flags
) )
844 return view
.release();
847 // The default (very primitive) format detection: check is the extension is
848 // that of the template
849 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
851 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
852 wxString anything
= wxT ("*");
853 while (parser
.HasMoreTokens())
855 wxString filter
= parser
.GetNextToken();
856 wxString filterExt
= FindExtension (filter
);
857 if ( filter
.IsSameAs (anything
) ||
858 filterExt
.IsSameAs (anything
) ||
859 filterExt
.IsSameAs (FindExtension (path
)) )
862 return GetDefaultExtension().IsSameAs(FindExtension(path
));
865 wxDocument
*wxDocTemplate::DoCreateDocument()
870 return static_cast<wxDocument
*>(m_docClassInfo
->CreateObject());
873 wxView
*wxDocTemplate::DoCreateView()
875 if (!m_viewClassInfo
)
878 return static_cast<wxView
*>(m_viewClassInfo
->CreateObject());
881 // ----------------------------------------------------------------------------
883 // ----------------------------------------------------------------------------
885 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
886 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
887 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
888 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
889 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
890 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
891 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
892 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
893 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
894 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
896 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
897 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
898 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
899 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
900 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
901 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
902 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
903 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
904 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
906 #if wxUSE_PRINTING_ARCHITECTURE
907 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
908 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
910 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
911 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
915 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
917 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
919 wxASSERT_MSG( !sm_docManager
, "multiple wxDocManagers not allowed" );
921 sm_docManager
= this;
923 m_defaultDocumentNameCounter
= 1;
924 m_currentView
= NULL
;
925 m_maxDocsOpen
= INT_MAX
;
926 m_fileHistory
= NULL
;
931 wxDocManager::~wxDocManager()
934 delete m_fileHistory
;
935 sm_docManager
= NULL
;
938 // closes the specified document
939 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
941 if ( !doc
->Close() && !force
)
944 // Implicitly deletes the document when
945 // the last view is deleted
946 doc
->DeleteAllViews();
948 // Check we're really deleted
949 if (m_docs
.Member(doc
))
955 bool wxDocManager::CloseDocuments(bool force
)
957 wxList::compatibility_iterator node
= m_docs
.GetFirst();
960 wxDocument
*doc
= (wxDocument
*)node
->GetData();
961 wxList::compatibility_iterator next
= node
->GetNext();
963 if (!CloseDocument(doc
, force
))
966 // This assumes that documents are not connected in
967 // any way, i.e. deleting one document does NOT
974 bool wxDocManager::Clear(bool force
)
976 if (!CloseDocuments(force
))
979 m_currentView
= NULL
;
981 wxList::compatibility_iterator node
= m_templates
.GetFirst();
984 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
985 wxList::compatibility_iterator next
= node
->GetNext();
992 bool wxDocManager::Initialize()
994 m_fileHistory
= OnCreateFileHistory();
998 wxString
wxDocManager::GetLastDirectory() const
1000 // if we haven't determined the last used directory yet, do it now
1001 if ( m_lastDirectory
.empty() )
1003 // we're going to modify m_lastDirectory in this const method, so do it
1004 // via non-const self pointer instead of const this one
1005 wxDocManager
* const self
= const_cast<wxDocManager
*>(this);
1007 // first try to reuse the directory of the most recently opened file:
1008 // this ensures that if the user opens a file, closes the program and
1009 // runs it again the "Open file" dialog will open in the directory of
1010 // the last file he used
1011 if ( m_fileHistory
&& m_fileHistory
->GetCount() )
1013 const wxString lastOpened
= m_fileHistory
->GetHistoryFile(0);
1014 const wxFileName
fn(lastOpened
);
1015 if ( fn
.DirExists() )
1017 self
->m_lastDirectory
= fn
.GetPath();
1019 //else: should we try the next one?
1021 //else: no history yet
1023 // if we don't have any files in the history (yet?), use the
1024 // system-dependent default location for the document files
1025 if ( m_lastDirectory
.empty() )
1027 self
->m_lastDirectory
= wxStandardPaths::Get().GetAppDocumentsDir();
1031 return m_lastDirectory
;
1034 wxFileHistory
*wxDocManager::OnCreateFileHistory()
1036 return new wxFileHistory
;
1039 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
1041 wxDocument
*doc
= GetCurrentDocument();
1046 doc
->DeleteAllViews();
1047 if (m_docs
.Member(doc
))
1052 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
1054 CloseDocuments(false);
1057 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
1059 CreateNewDocument();
1062 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
1064 if ( !CreateDocument("") )
1066 OnOpenFileFailure();
1070 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
1072 wxDocument
*doc
= GetCurrentDocument();
1078 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
1080 wxDocument
*doc
= GetCurrentDocument();
1086 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1088 wxDocument
*doc
= GetCurrentDocument();
1094 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1096 #if wxUSE_PRINTING_ARCHITECTURE
1097 wxView
*view
= GetActiveView();
1101 wxPrintout
*printout
= view
->OnCreatePrintout();
1105 printer
.Print(view
->GetFrame(), printout
, true);
1109 #endif // wxUSE_PRINTING_ARCHITECTURE
1112 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1114 #if wxUSE_PRINTING_ARCHITECTURE
1115 wxView
*view
= GetActiveView();
1119 wxPrintout
*printout
= view
->OnCreatePrintout();
1122 // Pass two printout objects: for preview, and possible printing.
1123 wxPrintPreviewBase
*
1124 preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1125 if ( !preview
->Ok() )
1128 wxLogError(_("Print preview creation failed."));
1133 frame
= new wxPreviewFrame(preview
, wxTheApp
->GetTopWindow(),
1134 _("Print Preview"));
1135 frame
->Centre(wxBOTH
);
1136 frame
->Initialize();
1139 #endif // wxUSE_PRINTING_ARCHITECTURE
1142 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1144 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1154 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1156 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1166 // Handlers for UI update commands
1168 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1170 // CreateDocument() (which is called from OnFileOpen) may succeed
1171 // only when there is at least a template:
1172 event
.Enable( GetTemplates().GetCount()>0 );
1175 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1177 event
.Enable( GetCurrentDocument() != NULL
);
1180 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1182 // CreateDocument() (which is called from OnFileNew) may succeed
1183 // only when there is at least a template:
1184 event
.Enable( GetTemplates().GetCount()>0 );
1187 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1189 wxDocument
* const doc
= GetCurrentDocument();
1190 event
.Enable( doc
&& !doc
->AlreadySaved() );
1193 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1195 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1198 event
.Enable(false);
1202 event
.Enable(cmdproc
->CanUndo());
1203 cmdproc
->SetMenuStrings();
1206 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1208 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1211 event
.Enable(false);
1215 event
.Enable(cmdproc
->CanRedo());
1216 cmdproc
->SetMenuStrings();
1219 wxView
*wxDocManager::GetActiveView() const
1221 wxView
*view
= GetCurrentView();
1223 if ( !view
&& !m_docs
.empty() )
1225 // if we have exactly one document, consider its view to be the current
1228 // VZ: I'm not exactly sure why is this needed but this is how this
1229 // code used to behave before the bug #9518 was fixed and it seems
1230 // safer to preserve the old logic
1231 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1232 if ( !node
->GetNext() )
1234 wxDocument
*doc
= static_cast<wxDocument
*>(node
->GetData());
1235 view
= doc
->GetFirstView();
1237 //else: we have more than one document
1243 bool wxDocManager::TryBefore(wxEvent
& event
)
1245 wxView
* const view
= GetActiveView();
1246 return view
&& view
->ProcessEventHere(event
);
1252 // helper function: return only the visible templates
1253 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1255 // select only the visible templates
1256 const size_t totalNumTemplates
= allTemplates
.GetCount();
1257 wxDocTemplates templates
;
1258 if ( totalNumTemplates
)
1260 templates
.reserve(totalNumTemplates
);
1262 for ( wxList::const_iterator i
= allTemplates
.begin(),
1263 end
= allTemplates
.end();
1267 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1268 if ( temp
->IsVisible() )
1269 templates
.push_back(temp
);
1276 } // anonymous namespace
1278 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1280 // this ought to be const but SelectDocumentType/Path() are not
1281 // const-correct and can't be changed as, being virtual, this risks
1282 // breaking user code overriding them
1283 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1284 const size_t numTemplates
= templates
.size();
1285 if ( !numTemplates
)
1287 // no templates can be used, can't create document
1292 // normally user should select the template to use but wxDOC_SILENT flag we
1293 // choose one ourselves
1294 wxString path
= pathOrig
; // may be modified below
1295 wxDocTemplate
*temp
;
1296 if ( flags
& wxDOC_SILENT
)
1298 wxASSERT_MSG( !path
.empty(),
1299 "using empty path with wxDOC_SILENT doesn't make sense" );
1301 temp
= FindTemplateForPath(path
);
1304 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1308 else // not silent, ask the user
1310 // for the new file we need just the template, for an existing one we
1311 // need the template and the path, unless it's already specified
1312 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1313 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1315 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1321 // check whether the document with this path is already opened
1322 if ( !path
.empty() )
1324 const wxFileName
fn(path
);
1325 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1327 wxDocument
* const doc
= (wxDocument
*)*i
;
1329 if ( fn
== doc
->GetFilename() )
1331 // file already open, just activate it and return
1332 if ( doc
->GetFirstView() )
1334 ActivateView(doc
->GetFirstView());
1335 if ( doc
->GetDocumentWindow() )
1336 doc
->GetDocumentWindow()->SetFocus();
1344 // no, we need to create a new document
1347 // if we've reached the max number of docs, close the first one.
1348 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1350 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1352 // can't open the new document if closing the old one failed
1358 // do create and initialize the new document finally
1359 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1363 docNew
->SetDocumentName(temp
->GetDocumentName());
1364 docNew
->SetDocumentTemplate(temp
);
1368 // call the appropriate function depending on whether we're creating a
1369 // new file or opening an existing one
1370 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1371 : docNew
->OnOpenDocument(path
)) )
1373 docNew
->DeleteAllViews();
1377 wxCATCH_ALL( docNew
->DeleteAllViews(); throw; )
1379 // add the successfully opened file to MRU, but only if we're going to be
1380 // able to reopen it successfully later which requires the template for
1381 // this document to be retrievable from the file extension
1382 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1383 AddFileToHistory(path
);
1388 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1390 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1391 const size_t numTemplates
= templates
.size();
1393 if ( numTemplates
== 0 )
1396 wxDocTemplate
* const
1397 temp
= numTemplates
== 1 ? templates
[0]
1398 : SelectViewType(&templates
[0], numTemplates
);
1403 wxView
*view
= temp
->CreateView(doc
, flags
);
1405 view
->SetViewName(temp
->GetViewName());
1409 // Not yet implemented
1411 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1415 // Not yet implemented
1416 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1421 wxDocument
*wxDocManager::GetCurrentDocument() const
1423 wxView
* const view
= GetActiveView();
1424 return view
? view
->GetDocument() : NULL
;
1427 wxCommandProcessor
*wxDocManager::GetCurrentCommandProcessor() const
1429 wxDocument
* const doc
= GetCurrentDocument();
1430 return doc
? doc
->GetCommandProcessor() : NULL
;
1433 // Make a default name for a new document
1434 #if WXWIN_COMPATIBILITY_2_8
1435 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1437 // we consider that this function can only be overridden by the user code,
1438 // not called by it as it only makes sense to call it internally, so we
1439 // don't bother to return anything from here
1442 #endif // WXWIN_COMPATIBILITY_2_8
1444 wxString
wxDocManager::MakeNewDocumentName()
1448 #if WXWIN_COMPATIBILITY_2_8
1449 if ( !MakeDefaultName(name
) )
1450 #endif // WXWIN_COMPATIBILITY_2_8
1452 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1453 m_defaultDocumentNameCounter
++;
1459 // Make a frame title (override this to do something different)
1460 // If docName is empty, a document is not currently active.
1461 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1463 wxString appName
= wxTheApp
->GetAppDisplayName();
1469 wxString docName
= doc
->GetUserReadableName();
1470 title
= docName
+ wxString(_(" - ")) + appName
;
1476 // Not yet implemented
1477 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1482 // File history management
1483 void wxDocManager::AddFileToHistory(const wxString
& file
)
1486 m_fileHistory
->AddFileToHistory(file
);
1489 void wxDocManager::RemoveFileFromHistory(size_t i
)
1492 m_fileHistory
->RemoveFileFromHistory(i
);
1495 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1500 histFile
= m_fileHistory
->GetHistoryFile(i
);
1505 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1508 m_fileHistory
->UseMenu(menu
);
1511 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1514 m_fileHistory
->RemoveMenu(menu
);
1518 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1521 m_fileHistory
->Load(config
);
1524 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1527 m_fileHistory
->Save(config
);
1531 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1534 m_fileHistory
->AddFilesToMenu(menu
);
1537 void wxDocManager::FileHistoryAddFilesToMenu()
1540 m_fileHistory
->AddFilesToMenu();
1543 size_t wxDocManager::GetHistoryFilesCount() const
1545 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1549 // Find out the document template via matching in the document file format
1550 // against that of the template
1551 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1553 wxDocTemplate
*theTemplate
= NULL
;
1555 // Find the template which this extension corresponds to
1556 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1558 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1559 if ( temp
->FileMatchesTemplate(path
) )
1568 // Prompts user to open a file, using file specs in templates.
1569 // Must extend the file selector dialog or implement own; OR
1570 // match the extension to the template extension.
1572 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1575 long WXUNUSED(flags
),
1576 bool WXUNUSED(save
))
1578 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1581 for (int i
= 0; i
< noTemplates
; i
++)
1583 if (templates
[i
]->IsVisible())
1585 // add a '|' to separate this filter from the previous one
1586 if ( !descrBuf
.empty() )
1587 descrBuf
<< wxT('|');
1589 descrBuf
<< templates
[i
]->GetDescription()
1590 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1591 << templates
[i
]->GetFileFilter();
1595 wxString descrBuf
= wxT("*.*");
1596 wxUnusedVar(noTemplates
);
1599 int FilterIndex
= -1;
1601 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1607 wxDocTemplate
*theTemplate
= NULL
;
1608 if (!pathTmp
.empty())
1610 if (!wxFileExists(pathTmp
))
1613 if (!wxTheApp
->GetAppDisplayName().empty())
1614 msgTitle
= wxTheApp
->GetAppDisplayName();
1616 msgTitle
= wxString(_("File error"));
1618 wxMessageBox(_("Sorry, could not open this file."),
1620 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1622 path
= wxEmptyString
;
1626 SetLastDirectory(wxPathOnly(pathTmp
));
1630 // first choose the template using the extension, if this fails (i.e.
1631 // wxFileSelectorEx() didn't fill it), then use the path
1632 if ( FilterIndex
!= -1 )
1633 theTemplate
= templates
[FilterIndex
];
1635 theTemplate
= FindTemplateForPath(path
);
1638 // Since we do not add files with non-default extensions to the
1639 // file history this can only happen if the application changes the
1640 // allowed templates in runtime.
1641 wxMessageBox(_("Sorry, the format for this file is unknown."),
1643 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1654 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1655 int noTemplates
, bool sort
)
1657 wxArrayString strings
;
1658 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1662 for (i
= 0; i
< noTemplates
; i
++)
1664 if (templates
[i
]->IsVisible())
1668 for (j
= 0; j
< n
; j
++)
1670 //filter out NOT unique documents + view combinations
1671 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1672 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1679 strings
.Add(templates
[i
]->m_description
);
1681 data
[n
] = templates
[i
];
1689 strings
.Sort(); // ascending sort
1690 // Yes, this will be slow, but template lists
1691 // are typically short.
1693 n
= strings
.Count();
1694 for (i
= 0; i
< n
; i
++)
1696 for (j
= 0; j
< noTemplates
; j
++)
1698 if (strings
[i
] == templates
[j
]->m_description
)
1699 data
[i
] = templates
[j
];
1704 wxDocTemplate
*theTemplate
;
1709 // no visible templates, hence nothing to choose from
1714 // don't propose the user to choose if he has no choice
1715 theTemplate
= data
[0];
1719 // propose the user to choose one of several
1720 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1722 _("Select a document template"),
1732 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1733 int noTemplates
, bool sort
)
1735 wxArrayString strings
;
1736 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1740 for (i
= 0; i
< noTemplates
; i
++)
1742 wxDocTemplate
*templ
= templates
[i
];
1743 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1747 for (j
= 0; j
< n
; j
++)
1749 //filter out NOT unique views
1750 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1756 strings
.Add(templ
->m_viewTypeName
);
1765 strings
.Sort(); // ascending sort
1766 // Yes, this will be slow, but template lists
1767 // are typically short.
1769 n
= strings
.Count();
1770 for (i
= 0; i
< n
; i
++)
1772 for (j
= 0; j
< noTemplates
; j
++)
1774 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1775 data
[i
] = templates
[j
];
1780 wxDocTemplate
*theTemplate
;
1782 // the same logic as above
1790 theTemplate
= data
[0];
1794 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1796 _("Select a document view"),
1807 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1809 if (!m_templates
.Member(temp
))
1810 m_templates
.Append(temp
);
1813 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1815 m_templates
.DeleteObject(temp
);
1818 // Add and remove a document from the manager's list
1819 void wxDocManager::AddDocument(wxDocument
*doc
)
1821 if (!m_docs
.Member(doc
))
1825 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1827 m_docs
.DeleteObject(doc
);
1830 // Views or windows should inform the document manager
1831 // when a view is going in or out of focus
1832 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1836 m_currentView
= view
;
1840 if ( m_currentView
== view
)
1842 // don't keep stale pointer
1843 m_currentView
= NULL
;
1848 // ----------------------------------------------------------------------------
1849 // wxDocChildFrameAnyBase
1850 // ----------------------------------------------------------------------------
1852 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent
& event
)
1856 if ( event
.CanVeto() && !m_childView
->Close(false) )
1862 m_childView
->Activate(false);
1864 // it is important to reset m_childView frame pointer to NULL before
1865 // deleting it because while normally it is the frame which deletes the
1866 // view when it's closed, the view also closes the frame if it is
1867 // deleted directly not by us as indicated by its doc child frame
1868 // pointer still being set
1869 m_childView
->SetDocChildFrame(NULL
);
1874 m_childDocument
= NULL
;
1879 // ----------------------------------------------------------------------------
1880 // Default parent frame
1881 // ----------------------------------------------------------------------------
1883 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1884 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1885 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1886 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1889 wxDocParentFrame::wxDocParentFrame()
1891 m_docManager
= NULL
;
1894 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1897 const wxString
& title
,
1901 const wxString
& name
)
1902 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1904 m_docManager
= manager
;
1907 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1910 const wxString
& title
,
1914 const wxString
& name
)
1916 m_docManager
= manager
;
1917 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1920 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1925 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1927 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1928 wxString
filename(m_docManager
->GetHistoryFile(n
));
1929 if ( filename
.empty() )
1932 wxString errMsg
; // must contain exactly one "%s" if non-empty
1933 if ( wxFile::Exists(filename
) )
1936 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1939 errMsg
= _("The file '%s' couldn't be opened.");
1941 else // file doesn't exist
1943 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1947 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1949 // remove the file which we can't open from the MRU list
1950 m_docManager
->RemoveFileFromHistory(n
);
1952 // and tell the user about it
1953 wxLogError(errMsg
+ '\n' +
1954 _("It has been removed from the most recently used files list."),
1958 // Extend event processing to search the view's event table
1959 bool wxDocParentFrame::TryBefore(wxEvent
& event
)
1961 if ( m_docManager
&& m_docManager
->ProcessEventHere(event
) )
1964 return wxFrame::TryBefore(event
);
1967 // Define the behaviour for the frame closing
1968 // - must delete all frames except for the main one.
1969 void wxDocParentFrame::OnCloseWindow(wxCloseEvent
& event
)
1971 if (m_docManager
->Clear(!event
.CanVeto()))
1979 #if wxUSE_PRINTING_ARCHITECTURE
1981 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
1984 m_printoutView
= view
;
1987 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
1991 // Get the logical pixels per inch of screen and printer
1992 int ppiScreenX
, ppiScreenY
;
1993 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
1994 wxUnusedVar(ppiScreenY
);
1995 int ppiPrinterX
, ppiPrinterY
;
1996 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
1997 wxUnusedVar(ppiPrinterY
);
1999 // This scales the DC so that the printout roughly represents the
2000 // the screen scaling. The text point size _should_ be the right size
2001 // but in fact is too small for some reason. This is a detail that will
2002 // need to be addressed at some point but can be fudged for the
2004 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
2006 // Now we have to check in case our real page size is reduced
2007 // (e.g. because we're drawing to a print preview memory DC)
2008 int pageWidth
, pageHeight
;
2010 dc
->GetSize(&w
, &h
);
2011 GetPageSizePixels(&pageWidth
, &pageHeight
);
2012 wxUnusedVar(pageHeight
);
2014 // If printer pageWidth == current DC width, then this doesn't
2015 // change. But w might be the preview bitmap width, so scale down.
2016 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
2017 dc
->SetUserScale(overallScale
, overallScale
);
2021 m_printoutView
->OnDraw(dc
);
2026 bool wxDocPrintout::HasPage(int pageNum
)
2028 return (pageNum
== 1);
2031 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
2033 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
2039 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
,
2040 int *selPageFrom
, int *selPageTo
)
2048 #endif // wxUSE_PRINTING_ARCHITECTURE
2050 // ----------------------------------------------------------------------------
2051 // File history (a.k.a. MRU, most recently used, files list)
2052 // ----------------------------------------------------------------------------
2054 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
2056 m_fileMaxFiles
= maxFiles
;
2060 void wxFileHistory::AddFileToHistory(const wxString
& file
)
2062 // check if we don't already have this file
2063 const wxFileName
fnNew(file
);
2065 numFiles
= m_fileHistory
.size();
2066 for ( i
= 0; i
< numFiles
; i
++ )
2068 if ( fnNew
== m_fileHistory
[i
] )
2070 // we do have it, move it to the top of the history
2071 RemoveFileFromHistory(i
);
2077 // if we already have a full history, delete the one at the end
2078 if ( numFiles
== m_fileMaxFiles
)
2080 RemoveFileFromHistory(--numFiles
);
2083 // add a new menu item to all file menus (they will be updated below)
2084 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2086 node
= node
->GetNext() )
2088 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2090 if ( !numFiles
&& menu
->GetMenuItemCount() )
2091 menu
->AppendSeparator();
2093 // label doesn't matter, it will be set below anyhow, but it can't
2094 // be empty (this is supposed to indicate a stock item)
2095 menu
->Append(m_idBase
+ numFiles
, " ");
2098 // insert the new file in the beginning of the file history
2099 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2102 // update the labels in all menus
2103 for ( i
= 0; i
< numFiles
; i
++ )
2105 // if in same directory just show the filename; otherwise the full path
2106 const wxFileName
fnOld(m_fileHistory
[i
]);
2108 wxString pathInMenu
;
2109 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2111 pathInMenu
= fnOld
.GetFullName();
2113 else // file in different directory
2115 // absolute path; could also set relative path
2116 pathInMenu
= m_fileHistory
[i
];
2119 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2121 node
= node
->GetNext() )
2123 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2125 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2130 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2132 size_t numFiles
= m_fileHistory
.size();
2133 wxCHECK_RET( i
< numFiles
,
2134 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2136 // delete the element from the array
2137 m_fileHistory
.RemoveAt(i
);
2140 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2142 node
= node
->GetNext() )
2144 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2146 // shift filenames up
2147 for ( size_t j
= i
; j
< numFiles
; j
++ )
2149 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2152 // delete the last menu item which is unused now
2153 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2154 if ( menu
->FindItem(lastItemId
) )
2155 menu
->Delete(lastItemId
);
2157 // delete the last separator too if no more files are left
2158 if ( m_fileHistory
.empty() )
2160 const wxMenuItemList::compatibility_iterator
2161 nodeLast
= menu
->GetMenuItems().GetLast();
2164 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2165 if ( lastMenuItem
->IsSeparator() )
2166 menu
->Delete(lastMenuItem
);
2168 //else: menu is empty somehow
2173 void wxFileHistory::UseMenu(wxMenu
*menu
)
2175 if ( !m_fileMenus
.Member(menu
) )
2176 m_fileMenus
.Append(menu
);
2179 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2181 m_fileMenus
.DeleteObject(menu
);
2185 void wxFileHistory::Load(const wxConfigBase
& config
)
2187 m_fileHistory
.Clear();
2190 buf
.Printf(wxT("file%d"), 1);
2192 wxString historyFile
;
2193 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2194 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2196 m_fileHistory
.Add(historyFile
);
2198 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2199 historyFile
= wxEmptyString
;
2205 void wxFileHistory::Save(wxConfigBase
& config
)
2208 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2211 buf
.Printf(wxT("file%d"), (int)i
+1);
2212 if (i
< m_fileHistory
.GetCount())
2213 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2215 config
.Write(buf
, wxEmptyString
);
2218 #endif // wxUSE_CONFIG
2220 void wxFileHistory::AddFilesToMenu()
2222 if ( m_fileHistory
.empty() )
2225 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2227 node
= node
->GetNext() )
2229 AddFilesToMenu((wxMenu
*) node
->GetData());
2233 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2235 if ( m_fileHistory
.empty() )
2238 if ( menu
->GetMenuItemCount() )
2239 menu
->AppendSeparator();
2241 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2243 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2247 // ----------------------------------------------------------------------------
2248 // Permits compatibility with existing file formats and functions that
2249 // manipulate files directly
2250 // ----------------------------------------------------------------------------
2252 #if wxUSE_STD_IOSTREAM
2254 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2257 wxFFile
file(filename
, wxT("rb"));
2259 wxFile
file(filename
, wxFile::read
);
2261 if ( !file
.IsOpened() )
2269 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2273 stream
.write(buf
, nRead
);
2277 while ( !file
.Eof() );
2282 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2285 wxFFile
file(filename
, wxT("wb"));
2287 wxFile
file(filename
, wxFile::write
);
2289 if ( !file
.IsOpened() )
2295 stream
.read(buf
, WXSIZEOF(buf
));
2296 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2298 if ( !file
.Write(buf
, stream
.gcount()) )
2302 while ( !stream
.eof() );
2307 #else // !wxUSE_STD_IOSTREAM
2309 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2312 wxFFile
file(filename
, wxT("rb"));
2314 wxFile
file(filename
, wxFile::read
);
2316 if ( !file
.IsOpened() )
2324 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2328 stream
.Write(buf
, nRead
);
2332 while ( !file
.Eof() );
2337 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2340 wxFFile
file(filename
, wxT("wb"));
2342 wxFile
file(filename
, wxFile::write
);
2344 if ( !file
.IsOpened() )
2350 stream
.Read(buf
, WXSIZEOF(buf
));
2352 const size_t nRead
= stream
.LastRead();
2361 if ( !file
.Write(buf
, nRead
) )
2368 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2370 #endif // wxUSE_DOC_VIEW_ARCHITECTURE