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
342 // Files that were not saved correctly are not added to the FileHistory.
343 if (!OnSaveDocument(fileName
))
346 SetTitle(wxFileNameFromPath(fileName
));
347 SetFilename(fileName
, true); // will call OnChangeFileName automatically
349 // A file that doesn't use the default extension of its document template
350 // cannot be opened via the FileHistory, so we do not add it.
351 if (docTemplate
->FileMatchesTemplate(fileName
))
353 GetDocumentManager()->AddFileToHistory(fileName
);
355 //else: the user will probably not be able to open the file again, so we
356 // could warn about the wrong file-extension here
361 bool wxDocument::OnSaveDocument(const wxString
& file
)
366 if ( !DoSaveDocument(file
) )
371 SetDocumentSaved(true);
372 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
373 wxFileName
fn(file
) ;
374 fn
.MacSetDefaultTypeAndCreator() ;
379 bool wxDocument::OnOpenDocument(const wxString
& file
)
381 // notice that there is no need to check the modified flag here for the
382 // reasons explained in OnNewDocument()
384 if ( !DoOpenDocument(file
) )
387 SetFilename(file
, true);
389 // stretching the logic a little this does make sense because the document
390 // had been saved into the file we just loaded it from, it just could have
391 // happened during a previous program execution, it's just that the name of
392 // this method is a bit unfortunate, it should probably have been called
393 // HasAssociatedFileName()
394 SetDocumentSaved(true);
401 #if wxUSE_STD_IOSTREAM
402 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
404 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
410 #if wxUSE_STD_IOSTREAM
411 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
413 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
419 bool wxDocument::Revert()
425 // Get title, or filename if no title, else unnamed
426 #if WXWIN_COMPATIBILITY_2_8
427 bool wxDocument::GetPrintableName(wxString
& buf
) const
429 // this function can not only be overridden by the user code but also
430 // called by it so we need to ensure that we return the same thing as
431 // GetUserReadableName() but we can't call it because this would result in
432 // an infinite recursion, hence we use the helper DoGetUserReadableName()
433 buf
= DoGetUserReadableName();
437 #endif // WXWIN_COMPATIBILITY_2_8
439 wxString
wxDocument::GetUserReadableName() const
441 #if WXWIN_COMPATIBILITY_2_8
442 // we need to call the old virtual function to ensure that the overridden
443 // version of it is still called
445 if ( GetPrintableName(name
) )
447 #endif // WXWIN_COMPATIBILITY_2_8
449 return DoGetUserReadableName();
452 wxString
wxDocument::DoGetUserReadableName() const
454 if ( !m_documentTitle
.empty() )
455 return m_documentTitle
;
457 if ( !m_documentFile
.empty() )
458 return wxFileNameFromPath(m_documentFile
);
463 wxWindow
*wxDocument::GetDocumentWindow() const
465 wxView
* const view
= GetFirstView();
467 return view
? view
->GetFrame() : wxTheApp
->GetTopWindow();
470 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
472 return new wxCommandProcessor
;
475 // true if safe to close
476 bool wxDocument::OnSaveModified()
480 switch ( wxMessageBox
484 _("Do you want to save changes to %s?"),
485 GetUserReadableName()
487 wxTheApp
->GetAppDisplayName(),
488 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
506 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
511 bool wxDocument::AddView(wxView
*view
)
513 if ( !m_documentViews
.Member(view
) )
515 m_documentViews
.Append(view
);
521 bool wxDocument::RemoveView(wxView
*view
)
523 (void)m_documentViews
.DeleteObject(view
);
528 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
530 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
533 // Called after a view is added or removed.
534 // The default implementation deletes the document if
535 // there are no more views.
536 void wxDocument::OnChangedViewList()
538 if ( m_documentViews
.empty() && OnSaveModified() )
542 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
544 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
547 wxView
*view
= (wxView
*)node
->GetData();
549 view
->OnUpdate(sender
, hint
);
550 node
= node
->GetNext();
554 void wxDocument::NotifyClosing()
556 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
559 wxView
*view
= (wxView
*)node
->GetData();
560 view
->OnClosingDocument();
561 node
= node
->GetNext();
565 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
567 m_documentFile
= filename
;
568 OnChangeFilename(notifyViews
);
571 void wxDocument::OnChangeFilename(bool notifyViews
)
575 // Notify the views that the filename has changed
576 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
579 wxView
*view
= (wxView
*)node
->GetData();
580 view
->OnChangeFilename();
581 node
= node
->GetNext();
586 bool wxDocument::DoSaveDocument(const wxString
& file
)
588 #if wxUSE_STD_IOSTREAM
589 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
592 wxFileOutputStream
store(file
);
593 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
596 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
600 if (!SaveObject(store
))
602 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
609 bool wxDocument::DoOpenDocument(const wxString
& file
)
611 #if wxUSE_STD_IOSTREAM
612 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
615 wxFileInputStream
store(file
);
616 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
619 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
623 #if wxUSE_STD_IOSTREAM
627 int res
= LoadObject(store
).GetLastError();
628 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
631 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
645 m_viewDocument
= NULL
;
649 m_docChildFrame
= NULL
;
654 GetDocumentManager()->ActivateView(this, false);
656 // reset our frame view first, before removing it from the document as
657 // SetView(NULL) is a simple call while RemoveView() may result in user
658 // code being executed and this user code can, for example, show a message
659 // box which would result in an activation event for m_docChildFrame and so
660 // could reactivate the view being destroyed -- unless we reset it first
661 if ( m_docChildFrame
&& m_docChildFrame
->GetView() == this )
663 // prevent it from doing anything with us
664 m_docChildFrame
->SetView(NULL
);
666 // it doesn't make sense to leave the frame alive if its associated
667 // view doesn't exist any more so unconditionally close it as well
669 // notice that we only get here if m_docChildFrame is non-NULL in the
670 // first place and it will be always NULL if we're deleted because our
671 // frame was closed, so this only catches the case of directly deleting
672 // the view, as it happens if its creation fails in wxDocTemplate::
673 // CreateView() for example
674 m_docChildFrame
->GetWindow()->Destroy();
677 if ( m_viewDocument
)
678 m_viewDocument
->RemoveView(this);
681 void wxView::SetDocChildFrame(wxDocChildFrameAnyBase
*docChildFrame
)
683 SetFrame(docChildFrame
? docChildFrame
->GetWindow() : NULL
);
684 m_docChildFrame
= docChildFrame
;
687 bool wxView::TryBefore(wxEvent
& event
)
689 wxDocument
* const doc
= GetDocument();
690 return doc
&& doc
->ProcessEventHere(event
);
693 void wxView::OnActivateView(bool WXUNUSED(activate
),
694 wxView
*WXUNUSED(activeView
),
695 wxView
*WXUNUSED(deactiveView
))
699 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
704 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
708 void wxView::OnChangeFilename()
710 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
711 // generic MDI implementation so use SetLabel rather than SetTitle.
712 // It should cause SetTitle() for top level windows.
713 wxWindow
*win
= GetFrame();
716 wxDocument
*doc
= GetDocument();
719 wxString label
= doc
->GetUserReadableName();
720 if (doc
->IsModified())
724 win
->SetLabel(label
);
727 void wxView::SetDocument(wxDocument
*doc
)
729 m_viewDocument
= doc
;
734 bool wxView::Close(bool deleteWindow
)
736 return OnClose(deleteWindow
);
739 void wxView::Activate(bool activate
)
741 if (GetDocument() && GetDocumentManager())
743 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
744 GetDocumentManager()->ActivateView(this, activate
);
748 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
750 return GetDocument() ? GetDocument()->Close() : true;
753 #if wxUSE_PRINTING_ARCHITECTURE
754 wxPrintout
*wxView::OnCreatePrintout()
756 return new wxDocPrintout(this);
758 #endif // wxUSE_PRINTING_ARCHITECTURE
760 // ----------------------------------------------------------------------------
762 // ----------------------------------------------------------------------------
764 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
765 const wxString
& descr
,
766 const wxString
& filter
,
769 const wxString
& docTypeName
,
770 const wxString
& viewTypeName
,
771 wxClassInfo
*docClassInfo
,
772 wxClassInfo
*viewClassInfo
,
775 m_documentManager
= manager
;
776 m_description
= descr
;
779 m_fileFilter
= filter
;
781 m_docTypeName
= docTypeName
;
782 m_viewTypeName
= viewTypeName
;
783 m_documentManager
->AssociateTemplate(this);
785 m_docClassInfo
= docClassInfo
;
786 m_viewClassInfo
= viewClassInfo
;
789 wxDocTemplate::~wxDocTemplate()
791 m_documentManager
->DisassociateTemplate(this);
794 // Tries to dynamically construct an object of the right class.
795 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
797 // InitDocument() is supposed to delete the document object if its
798 // initialization fails so don't use wxScopedPtr<> here: this is fragile
799 // but unavoidable because the default implementation uses CreateView()
800 // which may -- or not -- create a wxView and if it does create it and its
801 // initialization fails then the view destructor will delete the document
802 // (via RemoveView()) and as we can't distinguish between the two cases we
803 // just have to assume that it always deletes it in case of failure
804 wxDocument
* const doc
= DoCreateDocument();
806 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
810 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
812 doc
->SetFilename(path
);
813 doc
->SetDocumentTemplate(this);
814 GetDocumentManager()->AddDocument(doc
);
815 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
817 if (doc
->OnCreate(path
, flags
))
820 if (GetDocumentManager()->GetDocuments().Member(doc
))
821 doc
->DeleteAllViews();
825 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
827 wxScopedPtr
<wxView
> view(DoCreateView());
831 view
->SetDocument(doc
);
832 if ( !view
->OnCreate(doc
, flags
) )
835 return view
.release();
838 // The default (very primitive) format detection: check is the extension is
839 // that of the template
840 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
842 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
843 wxString anything
= wxT ("*");
844 while (parser
.HasMoreTokens())
846 wxString filter
= parser
.GetNextToken();
847 wxString filterExt
= FindExtension (filter
);
848 if ( filter
.IsSameAs (anything
) ||
849 filterExt
.IsSameAs (anything
) ||
850 filterExt
.IsSameAs (FindExtension (path
)) )
853 return GetDefaultExtension().IsSameAs(FindExtension(path
));
856 wxDocument
*wxDocTemplate::DoCreateDocument()
861 return static_cast<wxDocument
*>(m_docClassInfo
->CreateObject());
864 wxView
*wxDocTemplate::DoCreateView()
866 if (!m_viewClassInfo
)
869 return static_cast<wxView
*>(m_viewClassInfo
->CreateObject());
872 // ----------------------------------------------------------------------------
874 // ----------------------------------------------------------------------------
876 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
877 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
878 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
879 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
880 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
881 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
882 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
883 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
884 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
885 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
887 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
888 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
889 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
890 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
891 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
892 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
893 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
894 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
895 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
897 #if wxUSE_PRINTING_ARCHITECTURE
898 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
899 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
901 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
902 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
906 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
908 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
910 sm_docManager
= this;
912 m_defaultDocumentNameCounter
= 1;
913 m_currentView
= NULL
;
914 m_maxDocsOpen
= INT_MAX
;
915 m_fileHistory
= NULL
;
920 wxDocManager::~wxDocManager()
923 delete m_fileHistory
;
924 sm_docManager
= NULL
;
927 // closes the specified document
928 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
930 if ( !doc
->Close() && !force
)
933 // Implicitly deletes the document when
934 // the last view is deleted
935 doc
->DeleteAllViews();
937 // Check we're really deleted
938 if (m_docs
.Member(doc
))
944 bool wxDocManager::CloseDocuments(bool force
)
946 wxList::compatibility_iterator node
= m_docs
.GetFirst();
949 wxDocument
*doc
= (wxDocument
*)node
->GetData();
950 wxList::compatibility_iterator next
= node
->GetNext();
952 if (!CloseDocument(doc
, force
))
955 // This assumes that documents are not connected in
956 // any way, i.e. deleting one document does NOT
963 bool wxDocManager::Clear(bool force
)
965 if (!CloseDocuments(force
))
968 m_currentView
= NULL
;
970 wxList::compatibility_iterator node
= m_templates
.GetFirst();
973 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
974 wxList::compatibility_iterator next
= node
->GetNext();
981 bool wxDocManager::Initialize()
983 m_fileHistory
= OnCreateFileHistory();
987 wxString
wxDocManager::GetLastDirectory() const
989 // if we haven't determined the last used directory yet, do it now
990 if ( m_lastDirectory
.empty() )
992 // we're going to modify m_lastDirectory in this const method, so do it
993 // via non-const self pointer instead of const this one
994 wxDocManager
* const self
= const_cast<wxDocManager
*>(this);
996 // first try to reuse the directory of the most recently opened file:
997 // this ensures that if the user opens a file, closes the program and
998 // runs it again the "Open file" dialog will open in the directory of
999 // the last file he used
1000 if ( m_fileHistory
&& m_fileHistory
->GetCount() )
1002 const wxString lastOpened
= m_fileHistory
->GetHistoryFile(0);
1003 const wxFileName
fn(lastOpened
);
1004 if ( fn
.DirExists() )
1006 self
->m_lastDirectory
= fn
.GetPath();
1008 //else: should we try the next one?
1010 //else: no history yet
1012 // if we don't have any files in the history (yet?), use the
1013 // system-dependent default location for the document files
1014 if ( m_lastDirectory
.empty() )
1016 self
->m_lastDirectory
= wxStandardPaths::Get().GetAppDocumentsDir();
1020 return m_lastDirectory
;
1023 wxFileHistory
*wxDocManager::OnCreateFileHistory()
1025 return new wxFileHistory
;
1028 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
1030 wxDocument
*doc
= GetCurrentDocument();
1035 doc
->DeleteAllViews();
1036 if (m_docs
.Member(doc
))
1041 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
1043 CloseDocuments(false);
1046 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
1048 CreateNewDocument();
1051 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
1053 if ( !CreateDocument("") )
1055 OnOpenFileFailure();
1059 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
1061 wxDocument
*doc
= GetCurrentDocument();
1067 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
1069 wxDocument
*doc
= GetCurrentDocument();
1075 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1077 wxDocument
*doc
= GetCurrentDocument();
1083 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1085 #if wxUSE_PRINTING_ARCHITECTURE
1086 wxView
*view
= GetActiveView();
1090 wxPrintout
*printout
= view
->OnCreatePrintout();
1094 printer
.Print(view
->GetFrame(), printout
, true);
1098 #endif // wxUSE_PRINTING_ARCHITECTURE
1101 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1103 #if wxUSE_PRINTING_ARCHITECTURE
1105 wxView
*view
= GetActiveView();
1109 wxPrintout
*printout
= view
->OnCreatePrintout();
1112 // Pass two printout objects: for preview, and possible printing.
1113 wxPrintPreviewBase
*
1114 preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1115 if ( !preview
->Ok() )
1118 wxLogError(_("Print preview creation failed."));
1123 frame
= new wxPreviewFrame(preview
, wxTheApp
->GetTopWindow(),
1124 _("Print Preview"));
1125 frame
->Centre(wxBOTH
);
1126 frame
->Initialize();
1129 #endif // wxUSE_PRINTING_ARCHITECTURE
1132 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1134 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1144 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1146 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1156 // Handlers for UI update commands
1158 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1160 // CreateDocument() (which is called from OnFileOpen) may succeed
1161 // only when there is at least a template:
1162 event
.Enable( GetTemplates().GetCount()>0 );
1165 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1167 event
.Enable( GetCurrentDocument() != NULL
);
1170 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1172 // CreateDocument() (which is called from OnFileNew) may succeed
1173 // only when there is at least a template:
1174 event
.Enable( GetTemplates().GetCount()>0 );
1177 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1179 wxDocument
* const doc
= GetCurrentDocument();
1180 event
.Enable( doc
&& !doc
->AlreadySaved() );
1183 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1185 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1188 event
.Enable(false);
1192 event
.Enable(cmdproc
->CanUndo());
1193 cmdproc
->SetMenuStrings();
1196 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1198 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1201 event
.Enable(false);
1205 event
.Enable(cmdproc
->CanRedo());
1206 cmdproc
->SetMenuStrings();
1209 wxView
*wxDocManager::GetActiveView() const
1211 wxView
*view
= GetCurrentView();
1213 if ( !view
&& !m_docs
.empty() )
1215 // if we have exactly one document, consider its view to be the current
1218 // VZ: I'm not exactly sure why is this needed but this is how this
1219 // code used to behave before the bug #9518 was fixed and it seems
1220 // safer to preserve the old logic
1221 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1222 if ( !node
->GetNext() )
1224 wxDocument
*doc
= static_cast<wxDocument
*>(node
->GetData());
1225 view
= doc
->GetFirstView();
1227 //else: we have more than one document
1233 bool wxDocManager::TryBefore(wxEvent
& event
)
1235 wxView
* const view
= GetActiveView();
1236 return view
&& view
->ProcessEventHere(event
);
1242 // helper function: return only the visible templates
1243 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1245 // select only the visible templates
1246 const size_t totalNumTemplates
= allTemplates
.GetCount();
1247 wxDocTemplates templates
;
1248 if ( totalNumTemplates
)
1250 templates
.reserve(totalNumTemplates
);
1252 for ( wxList::const_iterator i
= allTemplates
.begin(),
1253 end
= allTemplates
.end();
1257 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1258 if ( temp
->IsVisible() )
1259 templates
.push_back(temp
);
1266 } // anonymous namespace
1268 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1270 // this ought to be const but SelectDocumentType/Path() are not
1271 // const-correct and can't be changed as, being virtual, this risks
1272 // breaking user code overriding them
1273 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1274 const size_t numTemplates
= templates
.size();
1275 if ( !numTemplates
)
1277 // no templates can be used, can't create document
1282 // normally user should select the template to use but wxDOC_SILENT flag we
1283 // choose one ourselves
1284 wxString path
= pathOrig
; // may be modified below
1285 wxDocTemplate
*temp
;
1286 if ( flags
& wxDOC_SILENT
)
1288 wxASSERT_MSG( !path
.empty(),
1289 "using empty path with wxDOC_SILENT doesn't make sense" );
1291 temp
= FindTemplateForPath(path
);
1294 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1298 else // not silent, ask the user
1300 // for the new file we need just the template, for an existing one we
1301 // need the template and the path, unless it's already specified
1302 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1303 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1305 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1311 // check whether the document with this path is already opened
1312 if ( !path
.empty() )
1314 const wxFileName
fn(path
);
1315 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1317 wxDocument
* const doc
= (wxDocument
*)*i
;
1319 if ( fn
== doc
->GetFilename() )
1321 // file already open, just activate it and return
1322 if ( doc
->GetFirstView() )
1324 ActivateView(doc
->GetFirstView());
1325 if ( doc
->GetDocumentWindow() )
1326 doc
->GetDocumentWindow()->SetFocus();
1334 // no, we need to create a new document
1337 // if we've reached the max number of docs, close the first one.
1338 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1340 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1342 // can't open the new document if closing the old one failed
1348 // do create and initialize the new document finally
1349 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1353 docNew
->SetDocumentName(temp
->GetDocumentName());
1354 docNew
->SetDocumentTemplate(temp
);
1358 // call the appropriate function depending on whether we're creating a
1359 // new file or opening an existing one
1360 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1361 : docNew
->OnOpenDocument(path
)) )
1363 docNew
->DeleteAllViews();
1367 wxCATCH_ALL( docNew
->DeleteAllViews(); throw; )
1369 // add the successfully opened file to MRU, but only if we're going to be
1370 // able to reopen it successfully later which requires the template for
1371 // this document to be retrievable from the file extension
1372 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1373 AddFileToHistory(path
);
1378 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1380 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1381 const size_t numTemplates
= templates
.size();
1383 if ( numTemplates
== 0 )
1386 wxDocTemplate
* const
1387 temp
= numTemplates
== 1 ? templates
[0]
1388 : SelectViewType(&templates
[0], numTemplates
);
1393 wxView
*view
= temp
->CreateView(doc
, flags
);
1395 view
->SetViewName(temp
->GetViewName());
1399 // Not yet implemented
1401 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1405 // Not yet implemented
1406 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1411 wxDocument
*wxDocManager::GetCurrentDocument() const
1413 wxView
* const view
= GetActiveView();
1414 return view
? view
->GetDocument() : NULL
;
1417 wxCommandProcessor
*wxDocManager::GetCurrentCommandProcessor() const
1419 wxDocument
* const doc
= GetCurrentDocument();
1420 return doc
? doc
->GetCommandProcessor() : NULL
;
1423 // Make a default name for a new document
1424 #if WXWIN_COMPATIBILITY_2_8
1425 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1427 // we consider that this function can only be overridden by the user code,
1428 // not called by it as it only makes sense to call it internally, so we
1429 // don't bother to return anything from here
1432 #endif // WXWIN_COMPATIBILITY_2_8
1434 wxString
wxDocManager::MakeNewDocumentName()
1438 #if WXWIN_COMPATIBILITY_2_8
1439 if ( !MakeDefaultName(name
) )
1440 #endif // WXWIN_COMPATIBILITY_2_8
1442 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1443 m_defaultDocumentNameCounter
++;
1449 // Make a frame title (override this to do something different)
1450 // If docName is empty, a document is not currently active.
1451 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1453 wxString appName
= wxTheApp
->GetAppDisplayName();
1459 wxString docName
= doc
->GetUserReadableName();
1460 title
= docName
+ wxString(_(" - ")) + appName
;
1466 // Not yet implemented
1467 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1472 // File history management
1473 void wxDocManager::AddFileToHistory(const wxString
& file
)
1476 m_fileHistory
->AddFileToHistory(file
);
1479 void wxDocManager::RemoveFileFromHistory(size_t i
)
1482 m_fileHistory
->RemoveFileFromHistory(i
);
1485 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1490 histFile
= m_fileHistory
->GetHistoryFile(i
);
1495 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1498 m_fileHistory
->UseMenu(menu
);
1501 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1504 m_fileHistory
->RemoveMenu(menu
);
1508 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1511 m_fileHistory
->Load(config
);
1514 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1517 m_fileHistory
->Save(config
);
1521 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1524 m_fileHistory
->AddFilesToMenu(menu
);
1527 void wxDocManager::FileHistoryAddFilesToMenu()
1530 m_fileHistory
->AddFilesToMenu();
1533 size_t wxDocManager::GetHistoryFilesCount() const
1535 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1539 // Find out the document template via matching in the document file format
1540 // against that of the template
1541 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1543 wxDocTemplate
*theTemplate
= NULL
;
1545 // Find the template which this extension corresponds to
1546 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1548 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1549 if ( temp
->FileMatchesTemplate(path
) )
1558 // Prompts user to open a file, using file specs in templates.
1559 // Must extend the file selector dialog or implement own; OR
1560 // match the extension to the template extension.
1562 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1565 long WXUNUSED(flags
),
1566 bool WXUNUSED(save
))
1568 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1571 for (int i
= 0; i
< noTemplates
; i
++)
1573 if (templates
[i
]->IsVisible())
1575 // add a '|' to separate this filter from the previous one
1576 if ( !descrBuf
.empty() )
1577 descrBuf
<< wxT('|');
1579 descrBuf
<< templates
[i
]->GetDescription()
1580 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1581 << templates
[i
]->GetFileFilter();
1585 wxString descrBuf
= wxT("*.*");
1586 wxUnusedVar(noTemplates
);
1589 int FilterIndex
= -1;
1591 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1597 wxDocTemplate
*theTemplate
= NULL
;
1598 if (!pathTmp
.empty())
1600 if (!wxFileExists(pathTmp
))
1603 if (!wxTheApp
->GetAppDisplayName().empty())
1604 msgTitle
= wxTheApp
->GetAppDisplayName();
1606 msgTitle
= wxString(_("File error"));
1608 wxMessageBox(_("Sorry, could not open this file."),
1610 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1612 path
= wxEmptyString
;
1616 SetLastDirectory(wxPathOnly(pathTmp
));
1620 // first choose the template using the extension, if this fails (i.e.
1621 // wxFileSelectorEx() didn't fill it), then use the path
1622 if ( FilterIndex
!= -1 )
1623 theTemplate
= templates
[FilterIndex
];
1625 theTemplate
= FindTemplateForPath(path
);
1628 // Since we do not add files with non-default extensions to the
1629 // file history this can only happen if the application changes the
1630 // allowed templates in runtime.
1631 wxMessageBox(_("Sorry, the format for this file is unknown."),
1633 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1644 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1645 int noTemplates
, bool sort
)
1647 wxArrayString strings
;
1648 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1652 for (i
= 0; i
< noTemplates
; i
++)
1654 if (templates
[i
]->IsVisible())
1658 for (j
= 0; j
< n
; j
++)
1660 //filter out NOT unique documents + view combinations
1661 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1662 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1669 strings
.Add(templates
[i
]->m_description
);
1671 data
[n
] = templates
[i
];
1679 strings
.Sort(); // ascending sort
1680 // Yes, this will be slow, but template lists
1681 // are typically short.
1683 n
= strings
.Count();
1684 for (i
= 0; i
< n
; i
++)
1686 for (j
= 0; j
< noTemplates
; j
++)
1688 if (strings
[i
] == templates
[j
]->m_description
)
1689 data
[i
] = templates
[j
];
1694 wxDocTemplate
*theTemplate
;
1699 // no visible templates, hence nothing to choose from
1704 // don't propose the user to choose if he has no choice
1705 theTemplate
= data
[0];
1709 // propose the user to choose one of several
1710 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1712 _("Select a document template"),
1722 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1723 int noTemplates
, bool sort
)
1725 wxArrayString strings
;
1726 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1730 for (i
= 0; i
< noTemplates
; i
++)
1732 wxDocTemplate
*templ
= templates
[i
];
1733 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1737 for (j
= 0; j
< n
; j
++)
1739 //filter out NOT unique views
1740 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1746 strings
.Add(templ
->m_viewTypeName
);
1755 strings
.Sort(); // ascending sort
1756 // Yes, this will be slow, but template lists
1757 // are typically short.
1759 n
= strings
.Count();
1760 for (i
= 0; i
< n
; i
++)
1762 for (j
= 0; j
< noTemplates
; j
++)
1764 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1765 data
[i
] = templates
[j
];
1770 wxDocTemplate
*theTemplate
;
1772 // the same logic as above
1780 theTemplate
= data
[0];
1784 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1786 _("Select a document view"),
1797 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1799 if (!m_templates
.Member(temp
))
1800 m_templates
.Append(temp
);
1803 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1805 m_templates
.DeleteObject(temp
);
1808 // Add and remove a document from the manager's list
1809 void wxDocManager::AddDocument(wxDocument
*doc
)
1811 if (!m_docs
.Member(doc
))
1815 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1817 m_docs
.DeleteObject(doc
);
1820 // Views or windows should inform the document manager
1821 // when a view is going in or out of focus
1822 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1826 m_currentView
= view
;
1830 if ( m_currentView
== view
)
1832 // don't keep stale pointer
1833 m_currentView
= NULL
;
1838 // ----------------------------------------------------------------------------
1839 // wxDocChildFrameAnyBase
1840 // ----------------------------------------------------------------------------
1842 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent
& event
)
1846 if ( event
.CanVeto() && !m_childView
->Close(false) )
1852 m_childView
->Activate(false);
1854 // it is important to reset m_childView frame pointer to NULL before
1855 // deleting it because while normally it is the frame which deletes the
1856 // view when it's closed, the view also closes the frame if it is
1857 // deleted directly not by us as indicated by its doc child frame
1858 // pointer still being set
1859 m_childView
->SetDocChildFrame(NULL
);
1864 m_childDocument
= NULL
;
1869 // ----------------------------------------------------------------------------
1870 // Default parent frame
1871 // ----------------------------------------------------------------------------
1873 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1874 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1875 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1876 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1879 wxDocParentFrame::wxDocParentFrame()
1881 m_docManager
= NULL
;
1884 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1887 const wxString
& title
,
1891 const wxString
& name
)
1892 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1894 m_docManager
= manager
;
1897 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1900 const wxString
& title
,
1904 const wxString
& name
)
1906 m_docManager
= manager
;
1907 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1910 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1915 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1917 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1918 wxString
filename(m_docManager
->GetHistoryFile(n
));
1919 if ( filename
.empty() )
1922 wxString errMsg
; // must contain exactly one "%s" if non-empty
1923 if ( wxFile::Exists(filename
) )
1926 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1929 errMsg
= _("The file '%s' couldn't be opened.");
1931 else // file doesn't exist
1933 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1937 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1939 // remove the file which we can't open from the MRU list
1940 m_docManager
->RemoveFileFromHistory(n
);
1942 // and tell the user about it
1943 wxLogError(errMsg
+ '\n' +
1944 _("It has been removed from the most recently used files list."),
1948 // Extend event processing to search the view's event table
1949 bool wxDocParentFrame::TryBefore(wxEvent
& event
)
1951 if ( m_docManager
&& m_docManager
->ProcessEventHere(event
) )
1954 return wxFrame::TryBefore(event
);
1957 // Define the behaviour for the frame closing
1958 // - must delete all frames except for the main one.
1959 void wxDocParentFrame::OnCloseWindow(wxCloseEvent
& event
)
1961 if (m_docManager
->Clear(!event
.CanVeto()))
1969 #if wxUSE_PRINTING_ARCHITECTURE
1971 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
1974 m_printoutView
= view
;
1977 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
1981 // Get the logical pixels per inch of screen and printer
1982 int ppiScreenX
, ppiScreenY
;
1983 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
1984 wxUnusedVar(ppiScreenY
);
1985 int ppiPrinterX
, ppiPrinterY
;
1986 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
1987 wxUnusedVar(ppiPrinterY
);
1989 // This scales the DC so that the printout roughly represents the
1990 // the screen scaling. The text point size _should_ be the right size
1991 // but in fact is too small for some reason. This is a detail that will
1992 // need to be addressed at some point but can be fudged for the
1994 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
1996 // Now we have to check in case our real page size is reduced
1997 // (e.g. because we're drawing to a print preview memory DC)
1998 int pageWidth
, pageHeight
;
2000 dc
->GetSize(&w
, &h
);
2001 GetPageSizePixels(&pageWidth
, &pageHeight
);
2002 wxUnusedVar(pageHeight
);
2004 // If printer pageWidth == current DC width, then this doesn't
2005 // change. But w might be the preview bitmap width, so scale down.
2006 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
2007 dc
->SetUserScale(overallScale
, overallScale
);
2011 m_printoutView
->OnDraw(dc
);
2016 bool wxDocPrintout::HasPage(int pageNum
)
2018 return (pageNum
== 1);
2021 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
2023 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
2029 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
,
2030 int *selPageFrom
, int *selPageTo
)
2038 #endif // wxUSE_PRINTING_ARCHITECTURE
2040 // ----------------------------------------------------------------------------
2041 // File history (a.k.a. MRU, most recently used, files list)
2042 // ----------------------------------------------------------------------------
2044 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
2046 m_fileMaxFiles
= maxFiles
;
2050 void wxFileHistory::AddFileToHistory(const wxString
& file
)
2052 // check if we don't already have this file
2053 const wxFileName
fnNew(file
);
2055 numFiles
= m_fileHistory
.size();
2056 for ( i
= 0; i
< numFiles
; i
++ )
2058 if ( fnNew
== m_fileHistory
[i
] )
2060 // we do have it, move it to the top of the history
2061 RemoveFileFromHistory(i
);
2067 // if we already have a full history, delete the one at the end
2068 if ( numFiles
== m_fileMaxFiles
)
2070 RemoveFileFromHistory(--numFiles
);
2073 // add a new menu item to all file menus (they will be updated below)
2074 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2076 node
= node
->GetNext() )
2078 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2080 if ( !numFiles
&& menu
->GetMenuItemCount() )
2081 menu
->AppendSeparator();
2083 // label doesn't matter, it will be set below anyhow, but it can't
2084 // be empty (this is supposed to indicate a stock item)
2085 menu
->Append(m_idBase
+ numFiles
, " ");
2088 // insert the new file in the beginning of the file history
2089 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2092 // update the labels in all menus
2093 for ( i
= 0; i
< numFiles
; i
++ )
2095 // if in same directory just show the filename; otherwise the full path
2096 const wxFileName
fnOld(m_fileHistory
[i
]);
2098 wxString pathInMenu
;
2099 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2101 pathInMenu
= fnOld
.GetFullName();
2103 else // file in different directory
2105 // absolute path; could also set relative path
2106 pathInMenu
= m_fileHistory
[i
];
2109 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2111 node
= node
->GetNext() )
2113 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2115 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2120 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2122 size_t numFiles
= m_fileHistory
.size();
2123 wxCHECK_RET( i
< numFiles
,
2124 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2126 // delete the element from the array
2127 m_fileHistory
.RemoveAt(i
);
2130 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2132 node
= node
->GetNext() )
2134 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2136 // shift filenames up
2137 for ( size_t j
= i
; j
< numFiles
; j
++ )
2139 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2142 // delete the last menu item which is unused now
2143 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2144 if ( menu
->FindItem(lastItemId
) )
2145 menu
->Delete(lastItemId
);
2147 // delete the last separator too if no more files are left
2148 if ( m_fileHistory
.empty() )
2150 const wxMenuItemList::compatibility_iterator
2151 nodeLast
= menu
->GetMenuItems().GetLast();
2154 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2155 if ( lastMenuItem
->IsSeparator() )
2156 menu
->Delete(lastMenuItem
);
2158 //else: menu is empty somehow
2163 void wxFileHistory::UseMenu(wxMenu
*menu
)
2165 if ( !m_fileMenus
.Member(menu
) )
2166 m_fileMenus
.Append(menu
);
2169 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2171 m_fileMenus
.DeleteObject(menu
);
2175 void wxFileHistory::Load(const wxConfigBase
& config
)
2177 m_fileHistory
.Clear();
2180 buf
.Printf(wxT("file%d"), 1);
2182 wxString historyFile
;
2183 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2184 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2186 m_fileHistory
.Add(historyFile
);
2188 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2189 historyFile
= wxEmptyString
;
2195 void wxFileHistory::Save(wxConfigBase
& config
)
2198 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2201 buf
.Printf(wxT("file%d"), (int)i
+1);
2202 if (i
< m_fileHistory
.GetCount())
2203 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2205 config
.Write(buf
, wxEmptyString
);
2208 #endif // wxUSE_CONFIG
2210 void wxFileHistory::AddFilesToMenu()
2212 if ( m_fileHistory
.empty() )
2215 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2217 node
= node
->GetNext() )
2219 AddFilesToMenu((wxMenu
*) node
->GetData());
2223 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2225 if ( m_fileHistory
.empty() )
2228 if ( menu
->GetMenuItemCount() )
2229 menu
->AppendSeparator();
2231 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2233 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2237 // ----------------------------------------------------------------------------
2238 // Permits compatibility with existing file formats and functions that
2239 // manipulate files directly
2240 // ----------------------------------------------------------------------------
2242 #if wxUSE_STD_IOSTREAM
2244 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2247 wxFFile
file(filename
, wxT("rb"));
2249 wxFile
file(filename
, wxFile::read
);
2251 if ( !file
.IsOpened() )
2259 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2263 stream
.write(buf
, nRead
);
2267 while ( !file
.Eof() );
2272 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2275 wxFFile
file(filename
, wxT("wb"));
2277 wxFile
file(filename
, wxFile::write
);
2279 if ( !file
.IsOpened() )
2285 stream
.read(buf
, WXSIZEOF(buf
));
2286 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2288 if ( !file
.Write(buf
, stream
.gcount()) )
2292 while ( !stream
.eof() );
2297 #else // !wxUSE_STD_IOSTREAM
2299 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2302 wxFFile
file(filename
, wxT("rb"));
2304 wxFile
file(filename
, wxFile::read
);
2306 if ( !file
.IsOpened() )
2314 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2318 stream
.Write(buf
, nRead
);
2322 while ( !file
.Eof() );
2327 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2330 wxFFile
file(filename
, wxT("wb"));
2332 wxFile
file(filename
, wxFile::write
);
2334 if ( !file
.IsOpened() )
2340 stream
.Read(buf
, WXSIZEOF(buf
));
2342 const size_t nRead
= stream
.LastRead();
2351 if ( !file
.Write(buf
, nRead
) )
2358 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2360 #endif // wxUSE_DOC_VIEW_ARCHITECTURE