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/vector.h"
60 #include "wx/ptr_scpd.h"
62 #if wxUSE_STD_IOSTREAM
63 #include "wx/ioswrap.h"
64 #include "wx/beforestd.h"
70 #include "wx/afterstd.h"
72 #include "wx/wfstream.h"
75 typedef wxVector
<wxDocTemplate
*> wxDocTemplates
;
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 IMPLEMENT_ABSTRACT_CLASS(wxDocument
, wxEvtHandler
)
82 IMPLEMENT_ABSTRACT_CLASS(wxView
, wxEvtHandler
)
83 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate
, wxObject
)
84 IMPLEMENT_DYNAMIC_CLASS(wxDocManager
, wxEvtHandler
)
85 IMPLEMENT_CLASS(wxDocChildFrame
, wxFrame
)
86 IMPLEMENT_CLASS(wxDocParentFrame
, wxFrame
)
88 #if wxUSE_PRINTING_ARCHITECTURE
89 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout
, wxPrintout
)
92 IMPLEMENT_DYNAMIC_CLASS(wxFileHistory
, wxObject
)
94 // ============================================================================
96 // ============================================================================
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
105 wxWindow
*wxFindSuitableParent()
107 wxWindow
* const win
= wxGetTopLevelParent(wxWindow::FindFocus());
109 return win
? win
: wxTheApp
->GetTopWindow();
112 wxString
FindExtension(const wxString
& path
)
115 wxFileName::SplitPath(path
, NULL
, NULL
, &ext
);
117 // VZ: extensions are considered not case sensitive - is this really a good
119 return ext
.MakeLower();
122 // return the string used for the MRU list items in the menu
124 // NB: the index n is 0-based, as usual, but the strings start from 1
125 wxString
GetMRUEntryLabel(int n
, const wxString
& path
)
127 // we need to quote '&' characters which are used for mnemonics
128 wxString
pathInMenu(path
);
129 pathInMenu
.Replace("&", "&&");
131 return wxString::Format("&%d %s", n
+ 1, pathInMenu
);
134 } // anonymous namespace
136 // ----------------------------------------------------------------------------
137 // Definition of wxDocument
138 // ----------------------------------------------------------------------------
140 wxDocument::wxDocument(wxDocument
*parent
)
142 m_documentModified
= false;
143 m_documentParent
= parent
;
144 m_documentTemplate
= NULL
;
145 m_commandProcessor
= NULL
;
149 bool wxDocument::DeleteContents()
154 wxDocument::~wxDocument()
158 if (m_commandProcessor
)
159 delete m_commandProcessor
;
161 if (GetDocumentManager())
162 GetDocumentManager()->RemoveDocument(this);
164 // Not safe to do here, since it'll invoke virtual view functions
165 // expecting to see valid derived objects: and by the time we get here,
166 // we've called destructors higher up.
170 bool wxDocument::Close()
172 if (OnSaveModified())
173 return OnCloseDocument();
178 bool wxDocument::OnCloseDocument()
180 // Tell all views that we're about to close
187 // Note that this implicitly deletes the document when the last view is
189 bool wxDocument::DeleteAllViews()
191 wxDocManager
* manager
= GetDocumentManager();
193 // first check if all views agree to be closed
194 const wxList::iterator end
= m_documentViews
.end();
195 for ( wxList::iterator i
= m_documentViews
.begin(); i
!= end
; ++i
)
197 wxView
*view
= (wxView
*)*i
;
198 if ( !view
->Close() )
202 // all views agreed to close, now do close them
203 if ( m_documentViews
.empty() )
205 // normally the document would be implicitly deleted when the last view
206 // is, but if don't have any views, do it here instead
207 if ( manager
&& manager
->GetDocuments().Member(this) )
212 // as we delete elements we iterate over, don't use the usual "from
213 // begin to end" loop
216 wxView
*view
= (wxView
*)*m_documentViews
.begin();
218 bool isLastOne
= m_documentViews
.size() == 1;
220 // this always deletes the node implicitly and if this is the last
221 // view also deletes this object itself (also implicitly, great),
222 // so we can't test for m_documentViews.empty() after calling this!
233 wxView
*wxDocument::GetFirstView() const
235 if (m_documentViews
.GetCount() == 0)
237 return (wxView
*)m_documentViews
.GetFirst()->GetData();
240 wxDocManager
*wxDocument::GetDocumentManager() const
242 return m_documentTemplate
? m_documentTemplate
->GetDocumentManager() : NULL
;
245 bool wxDocument::OnNewDocument()
247 if ( !OnSaveModified() )
252 SetDocumentSaved(false);
254 const wxString name
= GetDocumentManager()->MakeNewDocumentName();
256 SetFilename(name
, true);
261 bool wxDocument::Save()
263 if ( AlreadySaved() )
266 if ( m_documentFile
.empty() || !m_savedYet
)
269 return OnSaveDocument(m_documentFile
);
272 bool wxDocument::SaveAs()
274 wxDocTemplate
*docTemplate
= GetDocumentTemplate();
278 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
279 wxString filter
= docTemplate
->GetDescription() + wxT(" (") + docTemplate
->GetFileFilter() + wxT(")|") + docTemplate
->GetFileFilter();
281 // Now see if there are some other template with identical view and document
282 // classes, whose filters may also be used.
284 if (docTemplate
->GetViewClassInfo() && docTemplate
->GetDocClassInfo())
286 wxList::compatibility_iterator node
= docTemplate
->GetDocumentManager()->GetTemplates().GetFirst();
289 wxDocTemplate
*t
= (wxDocTemplate
*) node
->GetData();
291 if (t
->IsVisible() && t
!= docTemplate
&&
292 t
->GetViewClassInfo() == docTemplate
->GetViewClassInfo() &&
293 t
->GetDocClassInfo() == docTemplate
->GetDocClassInfo())
295 // add a '|' to separate this filter from the previous one
296 if ( !filter
.empty() )
299 filter
<< t
->GetDescription() << wxT(" (") << t
->GetFileFilter() << wxT(") |")
300 << t
->GetFileFilter();
303 node
= node
->GetNext();
307 wxString filter
= docTemplate
->GetFileFilter() ;
309 wxString defaultDir
= docTemplate
->GetDirectory();
310 if (defaultDir
.IsEmpty())
311 defaultDir
= wxPathOnly(GetFilename());
313 wxString tmp
= wxFileSelector(_("Save As"),
315 wxFileNameFromPath(GetFilename()),
316 docTemplate
->GetDefaultExtension(),
318 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
319 GetDocumentWindow());
324 wxString
fileName(tmp
);
325 wxString path
, name
, ext
;
326 wxFileName::SplitPath(fileName
, & path
, & name
, & ext
);
330 fileName
+= wxT(".");
331 fileName
+= docTemplate
->GetDefaultExtension();
334 SetFilename(fileName
);
335 SetTitle(wxFileNameFromPath(fileName
));
337 // Notify the views that the filename has changed
338 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
341 wxView
*view
= (wxView
*)node
->GetData();
342 view
->OnChangeFilename();
343 node
= node
->GetNext();
346 // Files that were not saved correctly are not added to the FileHistory.
347 if (!OnSaveDocument(m_documentFile
))
350 // A file that doesn't use the default extension of its document template cannot be opened
351 // via the FileHistory, so we do not add it.
352 if (docTemplate
->FileMatchesTemplate(fileName
))
354 GetDocumentManager()->AddFileToHistory(fileName
);
358 // The user will probably not be able to open the file again, so
359 // we could warn about the wrong file-extension here.
364 bool wxDocument::OnSaveDocument(const wxString
& file
)
369 if ( !DoSaveDocument(file
) )
374 SetDocumentSaved(true);
375 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
376 wxFileName
fn(file
) ;
377 fn
.MacSetDefaultTypeAndCreator() ;
382 bool wxDocument::OnOpenDocument(const wxString
& file
)
384 if ( !OnSaveModified() )
387 if ( !DoOpenDocument(file
) )
390 SetFilename(file
, true);
399 #if wxUSE_STD_IOSTREAM
400 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
402 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
408 #if wxUSE_STD_IOSTREAM
409 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
411 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
417 bool wxDocument::Revert()
423 // Get title, or filename if no title, else unnamed
424 #if WXWIN_COMPATIBILITY_2_8
425 bool wxDocument::GetPrintableName(wxString
& buf
) const
427 // this function can not only be overridden by the user code but also
428 // called by it so we need to ensure that we return the same thing as
429 // GetUserReadableName() but we can't call it because this would result in
430 // an infinite recursion, hence we use the helper DoGetUserReadableName()
431 buf
= DoGetUserReadableName();
435 #endif // WXWIN_COMPATIBILITY_2_8
437 wxString
wxDocument::GetUserReadableName() const
439 #if WXWIN_COMPATIBILITY_2_8
440 // we need to call the old virtual function to ensure that the overridden
441 // version of it is still called
443 if ( GetPrintableName(name
) )
445 #endif // WXWIN_COMPATIBILITY_2_8
447 return DoGetUserReadableName();
450 wxString
wxDocument::DoGetUserReadableName() const
452 if ( !m_documentTitle
.empty() )
453 return m_documentTitle
;
455 if ( !m_documentFile
.empty() )
456 return wxFileNameFromPath(m_documentFile
);
461 wxWindow
*wxDocument::GetDocumentWindow() const
463 wxView
*view
= GetFirstView();
465 return view
->GetFrame();
467 return 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 document %s?"),
485 GetUserReadableName()
487 wxTheApp
->GetAppDisplayName(),
488 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
,
507 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
512 bool wxDocument::AddView(wxView
*view
)
514 if ( !m_documentViews
.Member(view
) )
516 m_documentViews
.Append(view
);
522 bool wxDocument::RemoveView(wxView
*view
)
524 (void)m_documentViews
.DeleteObject(view
);
529 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
531 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
534 // Called after a view is added or removed.
535 // The default implementation deletes the document if
536 // there are no more views.
537 void wxDocument::OnChangedViewList()
539 if ( m_documentViews
.empty() && OnSaveModified() )
543 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
545 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
548 wxView
*view
= (wxView
*)node
->GetData();
550 view
->OnUpdate(sender
, hint
);
551 node
= node
->GetNext();
555 void wxDocument::NotifyClosing()
557 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
560 wxView
*view
= (wxView
*)node
->GetData();
561 view
->OnClosingDocument();
562 node
= node
->GetNext();
566 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
568 m_documentFile
= filename
;
571 // Notify the views that the filename has changed
572 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
575 wxView
*view
= (wxView
*)node
->GetData();
576 view
->OnChangeFilename();
577 node
= node
->GetNext();
582 bool wxDocument::DoSaveDocument(const wxString
& file
)
584 #if wxUSE_STD_IOSTREAM
585 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
588 wxFileOutputStream
store(file
);
589 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
592 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
596 if (!SaveObject(store
))
598 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
605 bool wxDocument::DoOpenDocument(const wxString
& file
)
607 #if wxUSE_STD_IOSTREAM
608 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
611 wxFileInputStream
store(file
);
612 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
615 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
619 #if wxUSE_STD_IOSTREAM
623 int res
= LoadObject(store
).GetLastError();
624 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
627 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
635 // ----------------------------------------------------------------------------
637 // ----------------------------------------------------------------------------
641 m_viewDocument
= NULL
;
648 GetDocumentManager()->ActivateView(this, false);
649 m_viewDocument
->RemoveView(this);
652 bool wxView::TryValidator(wxEvent
& event
)
654 wxDocument
* const doc
= GetDocument();
655 return doc
&& doc
->ProcessEventHere(event
);
658 void wxView::OnActivateView(bool WXUNUSED(activate
), wxView
*WXUNUSED(activeView
), wxView
*WXUNUSED(deactiveView
))
662 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
667 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
671 void wxView::OnChangeFilename()
673 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
674 // generic MDI implementation so use SetLabel rather than SetTitle.
675 // It should cause SetTitle() for top level windows.
676 wxWindow
*win
= GetFrame();
679 wxDocument
*doc
= GetDocument();
682 win
->SetLabel(doc
->GetUserReadableName());
685 void wxView::SetDocument(wxDocument
*doc
)
687 m_viewDocument
= doc
;
692 bool wxView::Close(bool deleteWindow
)
694 return OnClose(deleteWindow
);
697 void wxView::Activate(bool activate
)
699 if (GetDocument() && GetDocumentManager())
701 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
702 GetDocumentManager()->ActivateView(this, activate
);
706 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
708 return GetDocument() ? GetDocument()->Close() : true;
711 #if wxUSE_PRINTING_ARCHITECTURE
712 wxPrintout
*wxView::OnCreatePrintout()
714 return new wxDocPrintout(this);
716 #endif // wxUSE_PRINTING_ARCHITECTURE
718 // ----------------------------------------------------------------------------
720 // ----------------------------------------------------------------------------
722 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
723 const wxString
& descr
,
724 const wxString
& filter
,
727 const wxString
& docTypeName
,
728 const wxString
& viewTypeName
,
729 wxClassInfo
*docClassInfo
,
730 wxClassInfo
*viewClassInfo
,
733 m_documentManager
= manager
;
734 m_description
= descr
;
737 m_fileFilter
= filter
;
739 m_docTypeName
= docTypeName
;
740 m_viewTypeName
= viewTypeName
;
741 m_documentManager
->AssociateTemplate(this);
743 m_docClassInfo
= docClassInfo
;
744 m_viewClassInfo
= viewClassInfo
;
747 wxDocTemplate::~wxDocTemplate()
749 m_documentManager
->DisassociateTemplate(this);
752 // Tries to dynamically construct an object of the right class.
753 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
755 wxDocument
* const doc
= DoCreateDocument();
757 // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate())
758 // fails, is this intentional?
760 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
764 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
766 doc
->SetFilename(path
);
767 doc
->SetDocumentTemplate(this);
768 GetDocumentManager()->AddDocument(doc
);
769 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
771 if (doc
->OnCreate(path
, flags
))
775 if (GetDocumentManager()->GetDocuments().Member(doc
))
776 doc
->DeleteAllViews();
781 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
783 wxScopedPtr
<wxView
> view(DoCreateView());
787 view
->SetDocument(doc
);
788 if ( !view
->OnCreate(doc
, flags
) )
791 return view
.release();
794 // The default (very primitive) format detection: check is the extension is
795 // that of the template
796 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
798 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
799 wxString anything
= wxT ("*");
800 while (parser
.HasMoreTokens())
802 wxString filter
= parser
.GetNextToken();
803 wxString filterExt
= FindExtension (filter
);
804 if ( filter
.IsSameAs (anything
) ||
805 filterExt
.IsSameAs (anything
) ||
806 filterExt
.IsSameAs (FindExtension (path
)) )
809 return GetDefaultExtension().IsSameAs(FindExtension(path
));
812 wxDocument
*wxDocTemplate::DoCreateDocument()
817 return (wxDocument
*)m_docClassInfo
->CreateObject();
820 wxView
*wxDocTemplate::DoCreateView()
822 if (!m_viewClassInfo
)
825 return (wxView
*)m_viewClassInfo
->CreateObject();
828 // ----------------------------------------------------------------------------
830 // ----------------------------------------------------------------------------
832 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
833 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
834 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
835 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
836 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
837 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
838 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
839 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
840 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
841 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
843 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
844 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
845 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
846 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
847 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
848 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
849 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
850 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
851 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
853 #if wxUSE_PRINTING_ARCHITECTURE
854 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
855 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
857 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
858 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
862 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
864 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
866 wxASSERT_MSG( !sm_docManager
, "multiple wxDocManagers not allowed" );
868 sm_docManager
= this;
870 m_defaultDocumentNameCounter
= 1;
871 m_currentView
= NULL
;
872 m_maxDocsOpen
= INT_MAX
;
873 m_fileHistory
= NULL
;
878 wxDocManager::~wxDocManager()
881 delete m_fileHistory
;
882 sm_docManager
= NULL
;
885 // closes the specified document
886 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
888 if (doc
->Close() || force
)
890 // Implicitly deletes the document when
891 // the last view is deleted
892 doc
->DeleteAllViews();
894 // Check we're really deleted
895 if (m_docs
.Member(doc
))
903 bool wxDocManager::CloseDocuments(bool force
)
905 wxList::compatibility_iterator node
= m_docs
.GetFirst();
908 wxDocument
*doc
= (wxDocument
*)node
->GetData();
909 wxList::compatibility_iterator next
= node
->GetNext();
911 if (!CloseDocument(doc
, force
))
914 // This assumes that documents are not connected in
915 // any way, i.e. deleting one document does NOT
922 bool wxDocManager::Clear(bool force
)
924 if (!CloseDocuments(force
))
927 m_currentView
= NULL
;
929 wxList::compatibility_iterator node
= m_templates
.GetFirst();
932 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
933 wxList::compatibility_iterator next
= node
->GetNext();
940 bool wxDocManager::Initialize()
942 m_fileHistory
= OnCreateFileHistory();
946 wxFileHistory
*wxDocManager::OnCreateFileHistory()
948 return new wxFileHistory
;
951 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
953 wxDocument
*doc
= GetCurrentDocument();
958 doc
->DeleteAllViews();
959 if (m_docs
.Member(doc
))
964 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
966 CloseDocuments(false);
969 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
974 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
976 if ( !CreateDocument( wxEmptyString
, 0) )
982 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
984 wxDocument
*doc
= GetCurrentDocument();
990 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
992 wxDocument
*doc
= GetCurrentDocument();
998 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1000 wxDocument
*doc
= GetCurrentDocument();
1006 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1008 #if wxUSE_PRINTING_ARCHITECTURE
1009 wxView
*view
= GetCurrentView();
1013 wxPrintout
*printout
= view
->OnCreatePrintout();
1017 printer
.Print(view
->GetFrame(), printout
, true);
1021 #endif // wxUSE_PRINTING_ARCHITECTURE
1024 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1026 #if wxUSE_PRINTING_ARCHITECTURE
1027 wxView
*view
= GetCurrentView();
1031 wxPrintout
*printout
= view
->OnCreatePrintout();
1034 // Pass two printout objects: for preview, and possible printing.
1035 wxPrintPreviewBase
*preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1036 if ( !preview
->Ok() )
1039 wxMessageBox( _("Sorry, print preview needs a printer to be installed.") );
1043 wxPreviewFrame
*frame
= new wxPreviewFrame(preview
, (wxFrame
*)wxTheApp
->GetTopWindow(), _("Print Preview"),
1044 wxPoint(100, 100), wxSize(600, 650));
1045 frame
->Centre(wxBOTH
);
1046 frame
->Initialize();
1049 #endif // wxUSE_PRINTING_ARCHITECTURE
1052 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1054 wxDocument
*doc
= GetCurrentDocument();
1057 if (doc
->GetCommandProcessor())
1058 doc
->GetCommandProcessor()->Undo();
1063 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1065 wxDocument
*doc
= GetCurrentDocument();
1068 if (doc
->GetCommandProcessor())
1069 doc
->GetCommandProcessor()->Redo();
1074 // Handlers for UI update commands
1076 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1078 event
.Enable( true );
1081 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1083 event
.Enable( GetCurrentDocument() != NULL
);
1086 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1088 event
.Enable( true );
1091 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1093 wxDocument
* const doc
= GetCurrentDocument();
1094 event
.Enable( doc
&& !doc
->AlreadySaved() );
1097 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1099 wxDocument
*doc
= GetCurrentDocument();
1101 event
.Enable(false);
1102 else if (!doc
->GetCommandProcessor())
1106 event
.Enable( doc
->GetCommandProcessor()->CanUndo() );
1107 doc
->GetCommandProcessor()->SetMenuStrings();
1111 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1113 wxDocument
*doc
= GetCurrentDocument();
1115 event
.Enable(false);
1116 else if (!doc
->GetCommandProcessor())
1120 event
.Enable( doc
->GetCommandProcessor()->CanRedo() );
1121 doc
->GetCommandProcessor()->SetMenuStrings();
1125 wxView
*wxDocManager::GetCurrentView() const
1128 return m_currentView
;
1129 if (m_docs
.GetCount() == 1)
1131 wxDocument
* doc
= (wxDocument
*) m_docs
.GetFirst()->GetData();
1132 return doc
->GetFirstView();
1137 bool wxDocManager::TryValidator(wxEvent
& event
)
1139 wxView
* const view
= GetCurrentView();
1140 return view
&& view
->ProcessEventHere(event
);
1146 // helper function: return only the visible templates
1147 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1149 // select only the visible templates
1150 const size_t totalNumTemplates
= allTemplates
.GetCount();
1151 wxDocTemplates templates
;
1152 if ( totalNumTemplates
)
1154 templates
.reserve(totalNumTemplates
);
1156 for ( wxList::const_iterator i
= allTemplates
.begin(),
1157 end
= allTemplates
.end();
1161 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1162 if ( temp
->IsVisible() )
1163 templates
.push_back(temp
);
1170 } // anonymous namespace
1172 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1174 // this ought to be const but SelectDocumentType/Path() are not
1175 // const-correct and can't be changed as, being virtual, this risks
1176 // breaking user code overriding them
1177 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1178 const size_t numTemplates
= templates
.size();
1179 if ( !numTemplates
)
1181 // no templates can be used, can't create document
1186 // normally user should select the template to use but wxDOC_SILENT flag we
1187 // choose one ourselves
1188 wxString path
= pathOrig
; // may be modified below
1189 wxDocTemplate
*temp
;
1190 if ( flags
& wxDOC_SILENT
)
1192 wxASSERT_MSG( !path
.empty(),
1193 "using empty path with wxDOC_SILENT doesn't make sense" );
1195 temp
= FindTemplateForPath(path
);
1198 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1202 else // not silent, ask the user
1204 // for the new file we need just the template, for an existing one we
1205 // need the template and the path, unless it's already specified
1206 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1207 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1209 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1215 // check whether the document with this path is already opened
1216 if ( !path
.empty() )
1218 const wxFileName
fn(path
);
1219 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1221 wxDocument
* const doc
= (wxDocument
*)*i
;
1223 if ( fn
== doc
->GetFilename() )
1225 // file already open, just activate it and return
1226 if ( doc
->GetFirstView() )
1228 ActivateView(doc
->GetFirstView());
1229 if ( doc
->GetDocumentWindow() )
1230 doc
->GetDocumentWindow()->SetFocus();
1238 // no, we need to create a new document
1241 // if we've reached the max number of docs, close the first one.
1242 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1244 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1246 // can't open the new document if closing the old one failed
1252 // do create and initialize the new document finally
1253 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1257 docNew
->SetDocumentName(temp
->GetDocumentName());
1258 docNew
->SetDocumentTemplate(temp
);
1260 // call the appropriate function depending on whether we're creating a new
1261 // file or opening an existing one
1262 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1263 : docNew
->OnOpenDocument(path
)) )
1265 // Document is implicitly deleted by DeleteAllViews
1266 docNew
->DeleteAllViews();
1270 // add the successfully opened file to MRU, but only if we're going to be
1271 // able to reopen it successfully later which requires the template for
1272 // this document to be retrievable from the file extension
1273 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1274 AddFileToHistory(path
);
1279 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1281 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1282 const size_t numTemplates
= templates
.size();
1284 if ( numTemplates
== 0 )
1287 wxDocTemplate
* const
1288 temp
= numTemplates
== 1 ? templates
[0]
1289 : SelectViewType(&templates
[0], numTemplates
);
1294 wxView
*view
= temp
->CreateView(doc
, flags
);
1296 view
->SetViewName(temp
->GetViewName());
1300 // Not yet implemented
1302 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1306 // Not yet implemented
1307 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1312 wxDocument
*wxDocManager::GetCurrentDocument() const
1314 wxView
*view
= GetCurrentView();
1316 return view
->GetDocument();
1321 // Make a default name for a new document
1322 #if WXWIN_COMPATIBILITY_2_8
1323 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1325 // we consider that this function can only be overridden by the user code,
1326 // not called by it as it only makes sense to call it internally, so we
1327 // don't bother to return anything from here
1330 #endif // WXWIN_COMPATIBILITY_2_8
1332 wxString
wxDocManager::MakeNewDocumentName()
1336 #if WXWIN_COMPATIBILITY_2_8
1337 if ( !MakeDefaultName(name
) )
1338 #endif // WXWIN_COMPATIBILITY_2_8
1340 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1341 m_defaultDocumentNameCounter
++;
1347 // Make a frame title (override this to do something different)
1348 // If docName is empty, a document is not currently active.
1349 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1351 wxString appName
= wxTheApp
->GetAppDisplayName();
1357 wxString docName
= doc
->GetUserReadableName();
1358 title
= docName
+ wxString(_(" - ")) + appName
;
1364 // Not yet implemented
1365 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1370 // File history management
1371 void wxDocManager::AddFileToHistory(const wxString
& file
)
1374 m_fileHistory
->AddFileToHistory(file
);
1377 void wxDocManager::RemoveFileFromHistory(size_t i
)
1380 m_fileHistory
->RemoveFileFromHistory(i
);
1383 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1388 histFile
= m_fileHistory
->GetHistoryFile(i
);
1393 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1396 m_fileHistory
->UseMenu(menu
);
1399 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1402 m_fileHistory
->RemoveMenu(menu
);
1406 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1409 m_fileHistory
->Load(config
);
1412 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1415 m_fileHistory
->Save(config
);
1419 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1422 m_fileHistory
->AddFilesToMenu(menu
);
1425 void wxDocManager::FileHistoryAddFilesToMenu()
1428 m_fileHistory
->AddFilesToMenu();
1431 size_t wxDocManager::GetHistoryFilesCount() const
1433 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1437 // Find out the document template via matching in the document file format
1438 // against that of the template
1439 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1441 wxDocTemplate
*theTemplate
= NULL
;
1443 // Find the template which this extension corresponds to
1444 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1446 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1447 if ( temp
->FileMatchesTemplate(path
) )
1456 // Prompts user to open a file, using file specs in templates.
1457 // Must extend the file selector dialog or implement own; OR
1458 // match the extension to the template extension.
1460 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1463 long WXUNUSED(flags
),
1464 bool WXUNUSED(save
))
1466 // We can only have multiple filters in Windows and GTK
1467 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1471 for (i
= 0; i
< noTemplates
; i
++)
1473 if (templates
[i
]->IsVisible())
1475 // add a '|' to separate this filter from the previous one
1476 if ( !descrBuf
.empty() )
1477 descrBuf
<< wxT('|');
1479 descrBuf
<< templates
[i
]->GetDescription()
1480 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1481 << templates
[i
]->GetFileFilter();
1485 wxString descrBuf
= wxT("*.*");
1486 wxUnusedVar(noTemplates
);
1489 int FilterIndex
= -1;
1491 wxWindow
* parent
= wxFindSuitableParent();
1493 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1501 wxDocTemplate
*theTemplate
= NULL
;
1502 if (!pathTmp
.empty())
1504 if (!wxFileExists(pathTmp
))
1507 if (!wxTheApp
->GetAppDisplayName().empty())
1508 msgTitle
= wxTheApp
->GetAppDisplayName();
1510 msgTitle
= wxString(_("File error"));
1512 (void)wxMessageBox(_("Sorry, could not open this file."), msgTitle
, wxOK
| wxICON_EXCLAMATION
,
1515 path
= wxEmptyString
;
1518 m_lastDirectory
= wxPathOnly(pathTmp
);
1522 // first choose the template using the extension, if this fails (i.e.
1523 // wxFileSelectorEx() didn't fill it), then use the path
1524 if ( FilterIndex
!= -1 )
1525 theTemplate
= templates
[FilterIndex
];
1527 theTemplate
= FindTemplateForPath(path
);
1530 // Since we do not add files with non-default extensions to the FileHistory this
1531 // can only happen if the application changes the allowed templates in runtime.
1532 (void)wxMessageBox(_("Sorry, the format for this file is unknown."),
1534 wxOK
| wxICON_EXCLAMATION
, wxFindSuitableParent());
1539 path
= wxEmptyString
;
1545 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1546 int noTemplates
, bool sort
)
1548 wxArrayString strings
;
1549 wxDocTemplate
**data
= new wxDocTemplate
*[noTemplates
];
1553 for (i
= 0; i
< noTemplates
; i
++)
1555 if (templates
[i
]->IsVisible())
1559 for (j
= 0; j
< n
; j
++)
1561 //filter out NOT unique documents + view combinations
1562 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1563 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1570 strings
.Add(templates
[i
]->m_description
);
1572 data
[n
] = templates
[i
];
1580 strings
.Sort(); // ascending sort
1581 // Yes, this will be slow, but template lists
1582 // are typically short.
1584 n
= strings
.Count();
1585 for (i
= 0; i
< n
; i
++)
1587 for (j
= 0; j
< noTemplates
; j
++)
1589 if (strings
[i
] == templates
[j
]->m_description
)
1590 data
[i
] = templates
[j
];
1595 wxDocTemplate
*theTemplate
;
1600 // no visible templates, hence nothing to choose from
1605 // don't propose the user to choose if he has no choice
1606 theTemplate
= data
[0];
1610 // propose the user to choose one of several
1611 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1613 _("Select a document template"),
1617 wxFindSuitableParent()
1626 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1627 int noTemplates
, bool sort
)
1629 wxArrayString strings
;
1630 wxDocTemplate
**data
= new wxDocTemplate
*[noTemplates
];
1634 for (i
= 0; i
< noTemplates
; i
++)
1636 wxDocTemplate
*templ
= templates
[i
];
1637 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1641 for (j
= 0; j
< n
; j
++)
1643 //filter out NOT unique views
1644 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1650 strings
.Add(templ
->m_viewTypeName
);
1659 strings
.Sort(); // ascending sort
1660 // Yes, this will be slow, but template lists
1661 // are typically short.
1663 n
= strings
.Count();
1664 for (i
= 0; i
< n
; i
++)
1666 for (j
= 0; j
< noTemplates
; j
++)
1668 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1669 data
[i
] = templates
[j
];
1674 wxDocTemplate
*theTemplate
;
1676 // the same logic as above
1684 theTemplate
= data
[0];
1688 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1690 _("Select a document view"),
1694 wxFindSuitableParent()
1703 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1705 if (!m_templates
.Member(temp
))
1706 m_templates
.Append(temp
);
1709 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1711 m_templates
.DeleteObject(temp
);
1714 // Add and remove a document from the manager's list
1715 void wxDocManager::AddDocument(wxDocument
*doc
)
1717 if (!m_docs
.Member(doc
))
1721 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1723 m_docs
.DeleteObject(doc
);
1726 // Views or windows should inform the document manager
1727 // when a view is going in or out of focus
1728 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1732 m_currentView
= view
;
1736 if ( m_currentView
== view
)
1738 // don't keep stale pointer
1739 m_currentView
= NULL
;
1744 // ----------------------------------------------------------------------------
1745 // Default document child frame
1746 // ----------------------------------------------------------------------------
1748 BEGIN_EVENT_TABLE(wxDocChildFrame
, wxFrame
)
1749 EVT_ACTIVATE(wxDocChildFrame::OnActivate
)
1750 EVT_CLOSE(wxDocChildFrame::OnCloseWindow
)
1753 wxDocChildFrame::wxDocChildFrame(wxDocument
*doc
,
1757 const wxString
& title
,
1761 const wxString
& name
)
1762 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1764 m_childDocument
= doc
;
1767 view
->SetFrame(this);
1770 bool wxDocChildFrame::TryValidator(wxEvent
& event
)
1775 // FIXME: why is this needed here?
1776 m_childView
->Activate(true);
1778 return m_childView
->ProcessEventHere(event
);
1781 void wxDocChildFrame::OnActivate(wxActivateEvent
& event
)
1783 wxFrame::OnActivate(event
);
1786 m_childView
->Activate(event
.GetActive());
1789 void wxDocChildFrame::OnCloseWindow(wxCloseEvent
& event
)
1793 bool ans
= event
.CanVeto()
1794 ? m_childView
->Close(false) // false means don't delete associated window
1795 : true; // Must delete.
1799 m_childView
->Activate(false);
1802 m_childDocument
= NULL
;
1813 // ----------------------------------------------------------------------------
1814 // Default parent frame
1815 // ----------------------------------------------------------------------------
1817 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1818 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1819 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1820 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1823 wxDocParentFrame::wxDocParentFrame()
1825 m_docManager
= NULL
;
1828 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1831 const wxString
& title
,
1835 const wxString
& name
)
1836 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1838 m_docManager
= manager
;
1841 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1844 const wxString
& title
,
1848 const wxString
& name
)
1850 m_docManager
= manager
;
1851 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1854 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1859 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1861 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1862 wxString
filename(m_docManager
->GetHistoryFile(n
));
1863 if ( filename
.empty() )
1866 wxString errMsg
; // must contain exactly one "%s" if non-empty
1867 if ( wxFile::Exists(filename
) )
1870 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1873 errMsg
= _("The file '%s' couldn't be opened.");
1875 else // file doesn't exist
1877 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1881 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1883 // remove the file which we can't open from the MRU list
1884 m_docManager
->RemoveFileFromHistory(n
);
1886 // and tell the user about it
1887 wxLogError(errMsg
+ '\n' +
1888 _("It has been removed from the most recently used files list."),
1892 // Extend event processing to search the view's event table
1893 bool wxDocParentFrame::TryValidator(wxEvent
& event
)
1895 return m_docManager
&& m_docManager
->ProcessEventHere(event
);
1898 // Define the behaviour for the frame closing
1899 // - must delete all frames except for the main one.
1900 void wxDocParentFrame::OnCloseWindow(wxCloseEvent
& event
)
1902 if (m_docManager
->Clear(!event
.CanVeto()))
1910 #if wxUSE_PRINTING_ARCHITECTURE
1912 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
1915 m_printoutView
= view
;
1918 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
1922 // Get the logical pixels per inch of screen and printer
1923 int ppiScreenX
, ppiScreenY
;
1924 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
1925 wxUnusedVar(ppiScreenY
);
1926 int ppiPrinterX
, ppiPrinterY
;
1927 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
1928 wxUnusedVar(ppiPrinterY
);
1930 // This scales the DC so that the printout roughly represents the
1931 // the screen scaling. The text point size _should_ be the right size
1932 // but in fact is too small for some reason. This is a detail that will
1933 // need to be addressed at some point but can be fudged for the
1935 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
1937 // Now we have to check in case our real page size is reduced
1938 // (e.g. because we're drawing to a print preview memory DC)
1939 int pageWidth
, pageHeight
;
1941 dc
->GetSize(&w
, &h
);
1942 GetPageSizePixels(&pageWidth
, &pageHeight
);
1943 wxUnusedVar(pageHeight
);
1945 // If printer pageWidth == current DC width, then this doesn't
1946 // change. But w might be the preview bitmap width, so scale down.
1947 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
1948 dc
->SetUserScale(overallScale
, overallScale
);
1952 m_printoutView
->OnDraw(dc
);
1957 bool wxDocPrintout::HasPage(int pageNum
)
1959 return (pageNum
== 1);
1962 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
1964 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
1970 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
, int *selPageFrom
, int *selPageTo
)
1978 #endif // wxUSE_PRINTING_ARCHITECTURE
1980 // ----------------------------------------------------------------------------
1981 // File history (a.k.a. MRU, most recently used, files list)
1982 // ----------------------------------------------------------------------------
1984 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
1986 m_fileMaxFiles
= maxFiles
;
1990 void wxFileHistory::AddFileToHistory(const wxString
& file
)
1992 // check if we don't already have this file
1993 const wxFileName
fnNew(file
);
1995 numFiles
= m_fileHistory
.size();
1996 for ( i
= 0; i
< numFiles
; i
++ )
1998 if ( fnNew
== m_fileHistory
[i
] )
2000 // we do have it, move it to the top of the history
2001 RemoveFileFromHistory(i
);
2007 // if we already have a full history, delete the one at the end
2008 if ( numFiles
== m_fileMaxFiles
)
2010 RemoveFileFromHistory(--numFiles
);
2013 // add a new menu item to all file menus (they will be updated below)
2014 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2016 node
= node
->GetNext() )
2018 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2020 if ( !numFiles
&& menu
->GetMenuItemCount() )
2021 menu
->AppendSeparator();
2023 // label doesn't matter, it will be set below anyhow, but it can't
2024 // be empty (this is supposed to indicate a stock item)
2025 menu
->Append(m_idBase
+ numFiles
, " ");
2028 // insert the new file in the beginning of the file history
2029 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2032 // update the labels in all menus
2033 for ( i
= 0; i
< numFiles
; i
++ )
2035 // if in same directory just show the filename; otherwise the full path
2036 const wxFileName
fnOld(m_fileHistory
[i
]);
2038 wxString pathInMenu
;
2039 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2041 pathInMenu
= fnOld
.GetFullName();
2043 else // file in different directory
2045 // absolute path; could also set relative path
2046 pathInMenu
= m_fileHistory
[i
];
2049 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2051 node
= node
->GetNext() )
2053 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2055 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2060 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2062 size_t numFiles
= m_fileHistory
.size();
2063 wxCHECK_RET( i
< numFiles
,
2064 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2066 // delete the element from the array
2067 m_fileHistory
.RemoveAt(i
);
2070 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2072 node
= node
->GetNext() )
2074 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2076 // shift filenames up
2077 for ( size_t j
= i
; j
< numFiles
; j
++ )
2079 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2082 // delete the last menu item which is unused now
2083 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2084 if ( menu
->FindItem(lastItemId
) )
2085 menu
->Delete(lastItemId
);
2087 // delete the last separator too if no more files are left
2088 if ( m_fileHistory
.empty() )
2090 const wxMenuItemList::compatibility_iterator
2091 nodeLast
= menu
->GetMenuItems().GetLast();
2094 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2095 if ( lastMenuItem
->IsSeparator() )
2096 menu
->Delete(lastMenuItem
);
2098 //else: menu is empty somehow
2103 void wxFileHistory::UseMenu(wxMenu
*menu
)
2105 if ( !m_fileMenus
.Member(menu
) )
2106 m_fileMenus
.Append(menu
);
2109 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2111 m_fileMenus
.DeleteObject(menu
);
2115 void wxFileHistory::Load(const wxConfigBase
& config
)
2117 m_fileHistory
.Clear();
2120 buf
.Printf(wxT("file%d"), 1);
2122 wxString historyFile
;
2123 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2124 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2126 m_fileHistory
.Add(historyFile
);
2128 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2129 historyFile
= wxEmptyString
;
2135 void wxFileHistory::Save(wxConfigBase
& config
)
2138 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2141 buf
.Printf(wxT("file%d"), (int)i
+1);
2142 if (i
< m_fileHistory
.GetCount())
2143 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2145 config
.Write(buf
, wxEmptyString
);
2148 #endif // wxUSE_CONFIG
2150 void wxFileHistory::AddFilesToMenu()
2152 if ( m_fileHistory
.empty() )
2155 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2157 node
= node
->GetNext() )
2159 AddFilesToMenu((wxMenu
*) node
->GetData());
2163 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2165 if ( m_fileHistory
.empty() )
2168 if ( menu
->GetMenuItemCount() )
2169 menu
->AppendSeparator();
2171 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2173 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2177 // ----------------------------------------------------------------------------
2178 // Permits compatibility with existing file formats and functions that
2179 // manipulate files directly
2180 // ----------------------------------------------------------------------------
2182 #if wxUSE_STD_IOSTREAM
2184 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2186 wxFFile
file(filename
, _T("rb"));
2187 if ( !file
.IsOpened() )
2195 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2199 stream
.write(buf
, nRead
);
2203 while ( !file
.Eof() );
2208 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2210 wxFFile
file(filename
, _T("wb"));
2211 if ( !file
.IsOpened() )
2217 stream
.read(buf
, WXSIZEOF(buf
));
2218 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2220 if ( !file
.Write(buf
, stream
.gcount()) )
2224 while ( !stream
.eof() );
2229 #else // !wxUSE_STD_IOSTREAM
2231 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2233 wxFFile
file(filename
, _T("rb"));
2234 if ( !file
.IsOpened() )
2242 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2246 stream
.Write(buf
, nRead
);
2250 while ( !file
.Eof() );
2255 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2257 wxFFile
file(filename
, _T("wb"));
2258 if ( !file
.IsOpened() )
2264 stream
.Read(buf
, WXSIZEOF(buf
));
2266 const size_t nRead
= stream
.LastRead();
2275 if ( !file
.Write(buf
, nRead
) )
2282 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2284 #endif // wxUSE_DOC_VIEW_ARCHITECTURE