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"
61 #if wxUSE_STD_IOSTREAM
62 #include "wx/ioswrap.h"
63 #include "wx/beforestd.h"
69 #include "wx/afterstd.h"
71 #include "wx/wfstream.h"
74 typedef wxVector
<wxDocTemplate
*> wxDocTemplates
;
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 IMPLEMENT_ABSTRACT_CLASS(wxDocument
, wxEvtHandler
)
81 IMPLEMENT_ABSTRACT_CLASS(wxView
, wxEvtHandler
)
82 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate
, wxObject
)
83 IMPLEMENT_DYNAMIC_CLASS(wxDocManager
, wxEvtHandler
)
84 IMPLEMENT_CLASS(wxDocChildFrame
, wxFrame
)
85 IMPLEMENT_CLASS(wxDocParentFrame
, wxFrame
)
87 #if wxUSE_PRINTING_ARCHITECTURE
88 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout
, wxPrintout
)
91 IMPLEMENT_DYNAMIC_CLASS(wxFileHistory
, wxObject
)
93 // ============================================================================
95 // ============================================================================
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
104 wxWindow
*wxFindSuitableParent()
106 wxWindow
* const win
= wxGetTopLevelParent(wxWindow::FindFocus());
108 return win
? win
: wxTheApp
->GetTopWindow();
111 wxString
FindExtension(const wxString
& path
)
114 wxSplitPath(path
, NULL
, NULL
, &ext
);
116 // VZ: extensions are considered not case sensitive - is this really a good
118 return ext
.MakeLower();
121 // return the string used for the MRU list items in the menu
123 // NB: the index n is 0-based, as usual, but the strings start from 1
124 wxString
GetMRUEntryLabel(int n
, const wxString
& path
)
126 // we need to quote '&' characters which are used for mnemonics
127 wxString
pathInMenu(path
);
128 pathInMenu
.Replace("&", "&&");
130 return wxString::Format("&%d %s", n
+ 1, pathInMenu
);
133 } // anonymous namespace
135 // ----------------------------------------------------------------------------
136 // Definition of wxDocument
137 // ----------------------------------------------------------------------------
139 wxDocument::wxDocument(wxDocument
*parent
)
141 m_documentModified
= false;
142 m_documentParent
= parent
;
143 m_documentTemplate
= NULL
;
144 m_commandProcessor
= NULL
;
148 bool wxDocument::DeleteContents()
153 wxDocument::~wxDocument()
157 if (m_commandProcessor
)
158 delete m_commandProcessor
;
160 if (GetDocumentManager())
161 GetDocumentManager()->RemoveDocument(this);
163 // Not safe to do here, since it'll invoke virtual view functions
164 // expecting to see valid derived objects: and by the time we get here,
165 // we've called destructors higher up.
169 bool wxDocument::Close()
171 if (OnSaveModified())
172 return OnCloseDocument();
177 bool wxDocument::OnCloseDocument()
179 // Tell all views that we're about to close
186 // Note that this implicitly deletes the document when the last view is
188 bool wxDocument::DeleteAllViews()
190 wxDocManager
* manager
= GetDocumentManager();
192 // first check if all views agree to be closed
193 const wxList::iterator end
= m_documentViews
.end();
194 for ( wxList::iterator i
= m_documentViews
.begin(); i
!= end
; ++i
)
196 wxView
*view
= (wxView
*)*i
;
197 if ( !view
->Close() )
201 // all views agreed to close, now do close them
202 if ( m_documentViews
.empty() )
204 // normally the document would be implicitly deleted when the last view
205 // is, but if don't have any views, do it here instead
206 if ( manager
&& manager
->GetDocuments().Member(this) )
211 // as we delete elements we iterate over, don't use the usual "from
212 // begin to end" loop
215 wxView
*view
= (wxView
*)*m_documentViews
.begin();
217 bool isLastOne
= m_documentViews
.size() == 1;
219 // this always deletes the node implicitly and if this is the last
220 // view also deletes this object itself (also implicitly, great),
221 // so we can't test for m_documentViews.empty() after calling this!
232 wxView
*wxDocument::GetFirstView() const
234 if (m_documentViews
.GetCount() == 0)
236 return (wxView
*)m_documentViews
.GetFirst()->GetData();
239 wxDocManager
*wxDocument::GetDocumentManager() const
241 return m_documentTemplate
? m_documentTemplate
->GetDocumentManager() : NULL
;
244 bool wxDocument::OnNewDocument()
246 if ( !OnSaveModified() )
251 SetDocumentSaved(false);
253 const wxString name
= GetDocumentManager()->MakeNewDocumentName();
255 SetFilename(name
, true);
260 bool wxDocument::Save()
262 if (!IsModified() && m_savedYet
)
265 if ( m_documentFile
.empty() || !m_savedYet
)
268 return OnSaveDocument(m_documentFile
);
271 bool wxDocument::SaveAs()
273 wxDocTemplate
*docTemplate
= GetDocumentTemplate();
277 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
278 wxString filter
= docTemplate
->GetDescription() + wxT(" (") + docTemplate
->GetFileFilter() + wxT(")|") + docTemplate
->GetFileFilter();
280 // Now see if there are some other template with identical view and document
281 // classes, whose filters may also be used.
283 if (docTemplate
->GetViewClassInfo() && docTemplate
->GetDocClassInfo())
285 wxList::compatibility_iterator node
= docTemplate
->GetDocumentManager()->GetTemplates().GetFirst();
288 wxDocTemplate
*t
= (wxDocTemplate
*) node
->GetData();
290 if (t
->IsVisible() && t
!= docTemplate
&&
291 t
->GetViewClassInfo() == docTemplate
->GetViewClassInfo() &&
292 t
->GetDocClassInfo() == docTemplate
->GetDocClassInfo())
294 // add a '|' to separate this filter from the previous one
295 if ( !filter
.empty() )
298 filter
<< t
->GetDescription() << wxT(" (") << t
->GetFileFilter() << wxT(") |")
299 << t
->GetFileFilter();
302 node
= node
->GetNext();
306 wxString filter
= docTemplate
->GetFileFilter() ;
308 wxString defaultDir
= docTemplate
->GetDirectory();
309 if (defaultDir
.IsEmpty())
310 defaultDir
= wxPathOnly(GetFilename());
312 wxString tmp
= wxFileSelector(_("Save As"),
314 wxFileNameFromPath(GetFilename()),
315 docTemplate
->GetDefaultExtension(),
317 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
318 GetDocumentWindow());
323 wxString
fileName(tmp
);
324 wxString path
, name
, ext
;
325 wxSplitPath(fileName
, & path
, & name
, & ext
);
329 fileName
+= wxT(".");
330 fileName
+= docTemplate
->GetDefaultExtension();
333 SetFilename(fileName
);
334 SetTitle(wxFileNameFromPath(fileName
));
336 // Notify the views that the filename has changed
337 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
340 wxView
*view
= (wxView
*)node
->GetData();
341 view
->OnChangeFilename();
342 node
= node
->GetNext();
345 // Files that were not saved correctly are not added to the FileHistory.
346 if (!OnSaveDocument(m_documentFile
))
349 // A file that doesn't use the default extension of its document template cannot be opened
350 // via the FileHistory, so we do not add it.
351 if (docTemplate
->FileMatchesTemplate(fileName
))
353 GetDocumentManager()->AddFileToHistory(fileName
);
357 // The user will probably not be able to open the file again, so
358 // we could warn about the wrong file-extension here.
363 bool wxDocument::OnSaveDocument(const wxString
& file
)
368 if ( !DoSaveDocument(file
) )
373 SetDocumentSaved(true);
374 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
375 wxFileName
fn(file
) ;
376 fn
.MacSetDefaultTypeAndCreator() ;
381 bool wxDocument::OnOpenDocument(const wxString
& file
)
383 if ( !OnSaveModified() )
386 if ( !DoOpenDocument(file
) )
389 SetFilename(file
, true);
398 #if wxUSE_STD_IOSTREAM
399 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
401 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
407 #if wxUSE_STD_IOSTREAM
408 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
410 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
416 bool wxDocument::Revert()
422 // Get title, or filename if no title, else unnamed
423 #if WXWIN_COMPATIBILITY_2_8
424 bool wxDocument::GetPrintableName(wxString
& buf
) const
426 // this function can not only be overridden by the user code but also
427 // called by it so we need to ensure that we return the same thing as
428 // GetUserReadableName() but we can't call it because this would result in
429 // an infinite recursion, hence we use the helper DoGetUserReadableName()
430 buf
= DoGetUserReadableName();
434 #endif // WXWIN_COMPATIBILITY_2_8
436 wxString
wxDocument::GetUserReadableName() const
438 #if WXWIN_COMPATIBILITY_2_8
439 // we need to call the old virtual function to ensure that the overridden
440 // version of it is still called
442 if ( GetPrintableName(name
) )
444 #endif // WXWIN_COMPATIBILITY_2_8
446 return DoGetUserReadableName();
449 wxString
wxDocument::DoGetUserReadableName() const
451 if ( !m_documentTitle
.empty() )
452 return m_documentTitle
;
454 if ( !m_documentFile
.empty() )
455 return wxFileNameFromPath(m_documentFile
);
460 wxWindow
*wxDocument::GetDocumentWindow() const
462 wxView
*view
= GetFirstView();
464 return view
->GetFrame();
466 return wxTheApp
->GetTopWindow();
469 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
471 return new wxCommandProcessor
;
474 // true if safe to close
475 bool wxDocument::OnSaveModified()
479 switch ( wxMessageBox
483 _("Do you want to save changes to document %s?"),
484 GetUserReadableName()
486 wxTheApp
->GetAppDisplayName(),
487 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
,
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
;
570 // Notify the views that the filename has changed
571 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
574 wxView
*view
= (wxView
*)node
->GetData();
575 view
->OnChangeFilename();
576 node
= node
->GetNext();
581 bool wxDocument::DoSaveDocument(const wxString
& file
)
583 #if wxUSE_STD_IOSTREAM
584 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
587 wxFileOutputStream
store(file
);
588 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
591 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
595 if (!SaveObject(store
))
597 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
604 bool wxDocument::DoOpenDocument(const wxString
& file
)
606 #if wxUSE_STD_IOSTREAM
607 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
610 wxFileInputStream
store(file
);
611 if (store
.GetLastError() != wxSTREAM_NO_ERROR
)
614 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
618 #if wxUSE_STD_IOSTREAM
622 int res
= LoadObject(store
).GetLastError();
623 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
626 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
634 // ----------------------------------------------------------------------------
636 // ----------------------------------------------------------------------------
640 m_viewDocument
= NULL
;
647 GetDocumentManager()->ActivateView(this, false);
648 m_viewDocument
->RemoveView(this);
651 bool wxView::TryValidator(wxEvent
& event
)
653 wxDocument
* const doc
= GetDocument();
654 return doc
&& doc
->ProcessEventHere(event
);
657 void wxView::OnActivateView(bool WXUNUSED(activate
), wxView
*WXUNUSED(activeView
), wxView
*WXUNUSED(deactiveView
))
661 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
666 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
670 void wxView::OnChangeFilename()
672 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
673 // generic MDI implementation so use SetLabel rather than SetTitle.
674 // It should cause SetTitle() for top level windows.
675 wxWindow
*win
= GetFrame();
678 wxDocument
*doc
= GetDocument();
681 win
->SetLabel(doc
->GetUserReadableName());
684 void wxView::SetDocument(wxDocument
*doc
)
686 m_viewDocument
= doc
;
691 bool wxView::Close(bool deleteWindow
)
693 return OnClose(deleteWindow
);
696 void wxView::Activate(bool activate
)
698 if (GetDocument() && GetDocumentManager())
700 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
701 GetDocumentManager()->ActivateView(this, activate
);
705 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
707 return GetDocument() ? GetDocument()->Close() : true;
710 #if wxUSE_PRINTING_ARCHITECTURE
711 wxPrintout
*wxView::OnCreatePrintout()
713 return new wxDocPrintout(this);
715 #endif // wxUSE_PRINTING_ARCHITECTURE
717 // ----------------------------------------------------------------------------
719 // ----------------------------------------------------------------------------
721 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
722 const wxString
& descr
,
723 const wxString
& filter
,
726 const wxString
& docTypeName
,
727 const wxString
& viewTypeName
,
728 wxClassInfo
*docClassInfo
,
729 wxClassInfo
*viewClassInfo
,
732 m_documentManager
= manager
;
733 m_description
= descr
;
736 m_fileFilter
= filter
;
738 m_docTypeName
= docTypeName
;
739 m_viewTypeName
= viewTypeName
;
740 m_documentManager
->AssociateTemplate(this);
742 m_docClassInfo
= docClassInfo
;
743 m_viewClassInfo
= viewClassInfo
;
746 wxDocTemplate::~wxDocTemplate()
748 m_documentManager
->DisassociateTemplate(this);
751 // Tries to dynamically construct an object of the right class.
752 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
754 wxDocument
* const doc
= DoCreateDocument();
756 // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate())
757 // fails, is this intentional?
759 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
763 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
765 doc
->SetFilename(path
);
766 doc
->SetDocumentTemplate(this);
767 GetDocumentManager()->AddDocument(doc
);
768 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
770 if (doc
->OnCreate(path
, flags
))
774 if (GetDocumentManager()->GetDocuments().Member(doc
))
775 doc
->DeleteAllViews();
780 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
782 wxView
*view
= DoCreateView();
786 view
->SetDocument(doc
);
787 if (view
->OnCreate(doc
, flags
))
798 // The default (very primitive) format detection: check is the extension is
799 // that of the template
800 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
802 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
803 wxString anything
= wxT ("*");
804 while (parser
.HasMoreTokens())
806 wxString filter
= parser
.GetNextToken();
807 wxString filterExt
= FindExtension (filter
);
808 if ( filter
.IsSameAs (anything
) ||
809 filterExt
.IsSameAs (anything
) ||
810 filterExt
.IsSameAs (FindExtension (path
)) )
813 return GetDefaultExtension().IsSameAs(FindExtension(path
));
816 wxDocument
*wxDocTemplate::DoCreateDocument()
821 return (wxDocument
*)m_docClassInfo
->CreateObject();
824 wxView
*wxDocTemplate::DoCreateView()
826 if (!m_viewClassInfo
)
829 return (wxView
*)m_viewClassInfo
->CreateObject();
832 // ----------------------------------------------------------------------------
834 // ----------------------------------------------------------------------------
836 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
837 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
838 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
839 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
840 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
841 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
842 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
843 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
844 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
845 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
847 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
848 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
849 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
850 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
851 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
852 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
853 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
854 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
855 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
857 #if wxUSE_PRINTING_ARCHITECTURE
858 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
859 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
861 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
862 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
866 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
868 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
870 wxASSERT_MSG( !sm_docManager
, "multiple wxDocManagers not allowed" );
872 sm_docManager
= this;
874 m_defaultDocumentNameCounter
= 1;
875 m_currentView
= NULL
;
876 m_maxDocsOpen
= INT_MAX
;
877 m_fileHistory
= NULL
;
882 wxDocManager::~wxDocManager()
885 delete m_fileHistory
;
886 sm_docManager
= NULL
;
889 // closes the specified document
890 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
892 if (doc
->Close() || force
)
894 // Implicitly deletes the document when
895 // the last view is deleted
896 doc
->DeleteAllViews();
898 // Check we're really deleted
899 if (m_docs
.Member(doc
))
907 bool wxDocManager::CloseDocuments(bool force
)
909 wxList::compatibility_iterator node
= m_docs
.GetFirst();
912 wxDocument
*doc
= (wxDocument
*)node
->GetData();
913 wxList::compatibility_iterator next
= node
->GetNext();
915 if (!CloseDocument(doc
, force
))
918 // This assumes that documents are not connected in
919 // any way, i.e. deleting one document does NOT
926 bool wxDocManager::Clear(bool force
)
928 if (!CloseDocuments(force
))
931 m_currentView
= NULL
;
933 wxList::compatibility_iterator node
= m_templates
.GetFirst();
936 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
937 wxList::compatibility_iterator next
= node
->GetNext();
944 bool wxDocManager::Initialize()
946 m_fileHistory
= OnCreateFileHistory();
950 wxFileHistory
*wxDocManager::OnCreateFileHistory()
952 return new wxFileHistory
;
955 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
957 wxDocument
*doc
= GetCurrentDocument();
962 doc
->DeleteAllViews();
963 if (m_docs
.Member(doc
))
968 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
970 CloseDocuments(false);
973 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
978 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
980 if ( !CreateDocument( wxEmptyString
, 0) )
986 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
988 wxDocument
*doc
= GetCurrentDocument();
994 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
996 wxDocument
*doc
= GetCurrentDocument();
1002 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1004 wxDocument
*doc
= GetCurrentDocument();
1010 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1012 #if wxUSE_PRINTING_ARCHITECTURE
1013 wxView
*view
= GetCurrentView();
1017 wxPrintout
*printout
= view
->OnCreatePrintout();
1021 printer
.Print(view
->GetFrame(), printout
, true);
1025 #endif // wxUSE_PRINTING_ARCHITECTURE
1028 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1030 #if wxUSE_PRINTING_ARCHITECTURE
1031 wxView
*view
= GetCurrentView();
1035 wxPrintout
*printout
= view
->OnCreatePrintout();
1038 // Pass two printout objects: for preview, and possible printing.
1039 wxPrintPreviewBase
*preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1040 if ( !preview
->Ok() )
1043 wxMessageBox( _("Sorry, print preview needs a printer to be installed.") );
1047 wxPreviewFrame
*frame
= new wxPreviewFrame(preview
, (wxFrame
*)wxTheApp
->GetTopWindow(), _("Print Preview"),
1048 wxPoint(100, 100), wxSize(600, 650));
1049 frame
->Centre(wxBOTH
);
1050 frame
->Initialize();
1053 #endif // wxUSE_PRINTING_ARCHITECTURE
1056 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1058 wxDocument
*doc
= GetCurrentDocument();
1061 if (doc
->GetCommandProcessor())
1062 doc
->GetCommandProcessor()->Undo();
1067 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1069 wxDocument
*doc
= GetCurrentDocument();
1072 if (doc
->GetCommandProcessor())
1073 doc
->GetCommandProcessor()->Redo();
1078 // Handlers for UI update commands
1080 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1082 event
.Enable( true );
1085 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1087 event
.Enable( GetCurrentDocument() != NULL
);
1090 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1092 event
.Enable( true );
1095 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1097 wxDocument
*doc
= GetCurrentDocument();
1098 event
.Enable( doc
&& doc
->IsModified() );
1101 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1103 wxDocument
*doc
= GetCurrentDocument();
1105 event
.Enable(false);
1106 else if (!doc
->GetCommandProcessor())
1110 event
.Enable( doc
->GetCommandProcessor()->CanUndo() );
1111 doc
->GetCommandProcessor()->SetMenuStrings();
1115 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1117 wxDocument
*doc
= GetCurrentDocument();
1119 event
.Enable(false);
1120 else if (!doc
->GetCommandProcessor())
1124 event
.Enable( doc
->GetCommandProcessor()->CanRedo() );
1125 doc
->GetCommandProcessor()->SetMenuStrings();
1129 wxView
*wxDocManager::GetCurrentView() const
1132 return m_currentView
;
1133 if (m_docs
.GetCount() == 1)
1135 wxDocument
* doc
= (wxDocument
*) m_docs
.GetFirst()->GetData();
1136 return doc
->GetFirstView();
1141 bool wxDocManager::TryValidator(wxEvent
& event
)
1143 wxView
* const view
= GetCurrentView();
1144 return view
&& view
->ProcessEventHere(event
);
1150 // helper function: return only the visible templates
1151 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1153 // select only the visible templates
1154 const size_t totalNumTemplates
= allTemplates
.GetCount();
1155 wxDocTemplates templates
;
1156 if ( totalNumTemplates
)
1158 templates
.reserve(totalNumTemplates
);
1160 for ( wxList::const_iterator i
= allTemplates
.begin(),
1161 end
= allTemplates
.end();
1165 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1166 if ( temp
->IsVisible() )
1167 templates
.push_back(temp
);
1174 } // anonymous namespace
1176 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1178 // this ought to be const but SelectDocumentType/Path() are not
1179 // const-correct and can't be changed as, being virtual, this risks
1180 // breaking user code overriding them
1181 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1182 const size_t numTemplates
= templates
.size();
1183 if ( !numTemplates
)
1185 // no templates can be used, can't create document
1190 // normally user should select the template to use but wxDOC_SILENT flag we
1191 // choose one ourselves
1192 wxString path
= pathOrig
; // may be modified below
1193 wxDocTemplate
*temp
;
1194 if ( flags
& wxDOC_SILENT
)
1196 wxASSERT_MSG( !path
.empty(),
1197 "using empty path with wxDOC_SILENT doesn't make sense" );
1199 temp
= FindTemplateForPath(path
);
1202 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1206 else // not silent, ask the user
1208 // for the new file we need just the template, for an existing one we
1209 // need the template and the path, unless it's already specified
1210 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1211 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1213 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1219 // check whether the document with this path is already opened
1220 if ( !path
.empty() )
1222 const wxFileName
fn(path
);
1223 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1225 wxDocument
* const doc
= (wxDocument
*)*i
;
1227 if ( fn
== doc
->GetFilename() )
1229 // file already open, just activate it and return
1230 if ( doc
->GetFirstView() )
1232 ActivateView(doc
->GetFirstView());
1233 if ( doc
->GetDocumentWindow() )
1234 doc
->GetDocumentWindow()->SetFocus();
1242 // no, we need to create a new document
1245 // if we've reached the max number of docs, close the first one.
1246 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1248 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1250 // can't open the new document if closing the old one failed
1256 // do create and initialize the new document finally
1257 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1261 docNew
->SetDocumentName(temp
->GetDocumentName());
1262 docNew
->SetDocumentTemplate(temp
);
1264 // call the appropriate function depending on whether we're creating a new
1265 // file or opening an existing one
1266 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1267 : docNew
->OnOpenDocument(path
)) )
1269 // Document is implicitly deleted by DeleteAllViews
1270 docNew
->DeleteAllViews();
1274 // add the successfully opened file to MRU, but only if we're going to be
1275 // able to reopen it successfully later which requires the template for
1276 // this document to be retrievable from the file extension
1277 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1278 AddFileToHistory(path
);
1283 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1285 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1286 const size_t numTemplates
= templates
.size();
1288 if ( numTemplates
== 0 )
1291 wxDocTemplate
* const
1292 temp
= numTemplates
== 1 ? templates
[0]
1293 : SelectViewType(&templates
[0], numTemplates
);
1298 wxView
*view
= temp
->CreateView(doc
, flags
);
1300 view
->SetViewName(temp
->GetViewName());
1304 // Not yet implemented
1306 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1310 // Not yet implemented
1311 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1316 wxDocument
*wxDocManager::GetCurrentDocument() const
1318 wxView
*view
= GetCurrentView();
1320 return view
->GetDocument();
1325 // Make a default name for a new document
1326 #if WXWIN_COMPATIBILITY_2_8
1327 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1329 // we consider that this function can only be overridden by the user code,
1330 // not called by it as it only makes sense to call it internally, so we
1331 // don't bother to return anything from here
1334 #endif // WXWIN_COMPATIBILITY_2_8
1336 wxString
wxDocManager::MakeNewDocumentName()
1340 #if WXWIN_COMPATIBILITY_2_8
1341 if ( !MakeDefaultName(name
) )
1342 #endif // WXWIN_COMPATIBILITY_2_8
1344 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1345 m_defaultDocumentNameCounter
++;
1351 // Make a frame title (override this to do something different)
1352 // If docName is empty, a document is not currently active.
1353 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1355 wxString appName
= wxTheApp
->GetAppDisplayName();
1361 wxString docName
= doc
->GetUserReadableName();
1362 title
= docName
+ wxString(_(" - ")) + appName
;
1368 // Not yet implemented
1369 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1374 // File history management
1375 void wxDocManager::AddFileToHistory(const wxString
& file
)
1378 m_fileHistory
->AddFileToHistory(file
);
1381 void wxDocManager::RemoveFileFromHistory(size_t i
)
1384 m_fileHistory
->RemoveFileFromHistory(i
);
1387 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1392 histFile
= m_fileHistory
->GetHistoryFile(i
);
1397 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1400 m_fileHistory
->UseMenu(menu
);
1403 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1406 m_fileHistory
->RemoveMenu(menu
);
1410 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1413 m_fileHistory
->Load(config
);
1416 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1419 m_fileHistory
->Save(config
);
1423 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1426 m_fileHistory
->AddFilesToMenu(menu
);
1429 void wxDocManager::FileHistoryAddFilesToMenu()
1432 m_fileHistory
->AddFilesToMenu();
1435 size_t wxDocManager::GetHistoryFilesCount() const
1437 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1441 // Find out the document template via matching in the document file format
1442 // against that of the template
1443 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1445 wxDocTemplate
*theTemplate
= NULL
;
1447 // Find the template which this extension corresponds to
1448 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1450 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1451 if ( temp
->FileMatchesTemplate(path
) )
1460 // Prompts user to open a file, using file specs in templates.
1461 // Must extend the file selector dialog or implement own; OR
1462 // match the extension to the template extension.
1464 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1467 long WXUNUSED(flags
),
1468 bool WXUNUSED(save
))
1470 // We can only have multiple filters in Windows and GTK
1471 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1475 for (i
= 0; i
< noTemplates
; i
++)
1477 if (templates
[i
]->IsVisible())
1479 // add a '|' to separate this filter from the previous one
1480 if ( !descrBuf
.empty() )
1481 descrBuf
<< wxT('|');
1483 descrBuf
<< templates
[i
]->GetDescription()
1484 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1485 << templates
[i
]->GetFileFilter();
1489 wxString descrBuf
= wxT("*.*");
1490 wxUnusedVar(noTemplates
);
1493 int FilterIndex
= -1;
1495 wxWindow
* parent
= wxFindSuitableParent();
1497 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1505 wxDocTemplate
*theTemplate
= NULL
;
1506 if (!pathTmp
.empty())
1508 if (!wxFileExists(pathTmp
))
1511 if (!wxTheApp
->GetAppDisplayName().empty())
1512 msgTitle
= wxTheApp
->GetAppDisplayName();
1514 msgTitle
= wxString(_("File error"));
1516 (void)wxMessageBox(_("Sorry, could not open this file."), msgTitle
, wxOK
| wxICON_EXCLAMATION
,
1519 path
= wxEmptyString
;
1522 m_lastDirectory
= wxPathOnly(pathTmp
);
1526 // first choose the template using the extension, if this fails (i.e.
1527 // wxFileSelectorEx() didn't fill it), then use the path
1528 if ( FilterIndex
!= -1 )
1529 theTemplate
= templates
[FilterIndex
];
1531 theTemplate
= FindTemplateForPath(path
);
1534 // Since we do not add files with non-default extensions to the FileHistory this
1535 // can only happen if the application changes the allowed templates in runtime.
1536 (void)wxMessageBox(_("Sorry, the format for this file is unknown."),
1538 wxOK
| wxICON_EXCLAMATION
, wxFindSuitableParent());
1543 path
= wxEmptyString
;
1549 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1550 int noTemplates
, bool sort
)
1552 wxArrayString strings
;
1553 wxDocTemplate
**data
= new wxDocTemplate
*[noTemplates
];
1557 for (i
= 0; i
< noTemplates
; i
++)
1559 if (templates
[i
]->IsVisible())
1563 for (j
= 0; j
< n
; j
++)
1565 //filter out NOT unique documents + view combinations
1566 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1567 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1574 strings
.Add(templates
[i
]->m_description
);
1576 data
[n
] = templates
[i
];
1584 strings
.Sort(); // ascending sort
1585 // Yes, this will be slow, but template lists
1586 // are typically short.
1588 n
= strings
.Count();
1589 for (i
= 0; i
< n
; i
++)
1591 for (j
= 0; j
< noTemplates
; j
++)
1593 if (strings
[i
] == templates
[j
]->m_description
)
1594 data
[i
] = templates
[j
];
1599 wxDocTemplate
*theTemplate
;
1604 // no visible templates, hence nothing to choose from
1609 // don't propose the user to choose if he has no choice
1610 theTemplate
= data
[0];
1614 // propose the user to choose one of several
1615 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1617 _("Select a document template"),
1621 wxFindSuitableParent()
1630 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1631 int noTemplates
, bool sort
)
1633 wxArrayString strings
;
1634 wxDocTemplate
**data
= new wxDocTemplate
*[noTemplates
];
1638 for (i
= 0; i
< noTemplates
; i
++)
1640 wxDocTemplate
*templ
= templates
[i
];
1641 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1645 for (j
= 0; j
< n
; j
++)
1647 //filter out NOT unique views
1648 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1654 strings
.Add(templ
->m_viewTypeName
);
1663 strings
.Sort(); // ascending sort
1664 // Yes, this will be slow, but template lists
1665 // are typically short.
1667 n
= strings
.Count();
1668 for (i
= 0; i
< n
; i
++)
1670 for (j
= 0; j
< noTemplates
; j
++)
1672 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1673 data
[i
] = templates
[j
];
1678 wxDocTemplate
*theTemplate
;
1680 // the same logic as above
1688 theTemplate
= data
[0];
1692 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1694 _("Select a document view"),
1698 wxFindSuitableParent()
1707 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1709 if (!m_templates
.Member(temp
))
1710 m_templates
.Append(temp
);
1713 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1715 m_templates
.DeleteObject(temp
);
1718 // Add and remove a document from the manager's list
1719 void wxDocManager::AddDocument(wxDocument
*doc
)
1721 if (!m_docs
.Member(doc
))
1725 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1727 m_docs
.DeleteObject(doc
);
1730 // Views or windows should inform the document manager
1731 // when a view is going in or out of focus
1732 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1736 m_currentView
= view
;
1740 if ( m_currentView
== view
)
1742 // don't keep stale pointer
1743 m_currentView
= NULL
;
1748 // ----------------------------------------------------------------------------
1749 // Default document child frame
1750 // ----------------------------------------------------------------------------
1752 BEGIN_EVENT_TABLE(wxDocChildFrame
, wxFrame
)
1753 EVT_ACTIVATE(wxDocChildFrame::OnActivate
)
1754 EVT_CLOSE(wxDocChildFrame::OnCloseWindow
)
1757 wxDocChildFrame::wxDocChildFrame(wxDocument
*doc
,
1761 const wxString
& title
,
1765 const wxString
& name
)
1766 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1768 m_childDocument
= doc
;
1771 view
->SetFrame(this);
1774 bool wxDocChildFrame::TryValidator(wxEvent
& event
)
1779 // FIXME: why is this needed here?
1780 m_childView
->Activate(true);
1782 return m_childView
->ProcessEventHere(event
);
1785 void wxDocChildFrame::OnActivate(wxActivateEvent
& event
)
1787 wxFrame::OnActivate(event
);
1790 m_childView
->Activate(event
.GetActive());
1793 void wxDocChildFrame::OnCloseWindow(wxCloseEvent
& event
)
1797 bool ans
= event
.CanVeto()
1798 ? m_childView
->Close(false) // false means don't delete associated window
1799 : true; // Must delete.
1803 m_childView
->Activate(false);
1806 m_childDocument
= NULL
;
1817 // ----------------------------------------------------------------------------
1818 // Default parent frame
1819 // ----------------------------------------------------------------------------
1821 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1822 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1823 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1824 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1827 wxDocParentFrame::wxDocParentFrame()
1829 m_docManager
= NULL
;
1832 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1835 const wxString
& title
,
1839 const wxString
& name
)
1840 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1842 m_docManager
= manager
;
1845 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1848 const wxString
& title
,
1852 const wxString
& name
)
1854 m_docManager
= manager
;
1855 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1858 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1863 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1865 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1866 wxString
filename(m_docManager
->GetHistoryFile(n
));
1867 if ( filename
.empty() )
1870 wxString errMsg
; // must contain exactly one "%s" if non-empty
1871 if ( wxFile::Exists(filename
) )
1874 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1877 errMsg
= _("The file '%s' couldn't be opened.");
1879 else // file doesn't exist
1881 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1885 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1887 // remove the file which we can't open from the MRU list
1888 m_docManager
->RemoveFileFromHistory(n
);
1890 // and tell the user about it
1891 wxLogError(errMsg
+ '\n' +
1892 _("It has been removed from the most recently used files list."),
1896 // Extend event processing to search the view's event table
1897 bool wxDocParentFrame::TryValidator(wxEvent
& event
)
1899 return m_docManager
&& m_docManager
->ProcessEventHere(event
);
1902 // Define the behaviour for the frame closing
1903 // - must delete all frames except for the main one.
1904 void wxDocParentFrame::OnCloseWindow(wxCloseEvent
& event
)
1906 if (m_docManager
->Clear(!event
.CanVeto()))
1914 #if wxUSE_PRINTING_ARCHITECTURE
1916 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
1919 m_printoutView
= view
;
1922 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
1926 // Get the logical pixels per inch of screen and printer
1927 int ppiScreenX
, ppiScreenY
;
1928 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
1929 wxUnusedVar(ppiScreenY
);
1930 int ppiPrinterX
, ppiPrinterY
;
1931 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
1932 wxUnusedVar(ppiPrinterY
);
1934 // This scales the DC so that the printout roughly represents the
1935 // the screen scaling. The text point size _should_ be the right size
1936 // but in fact is too small for some reason. This is a detail that will
1937 // need to be addressed at some point but can be fudged for the
1939 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
1941 // Now we have to check in case our real page size is reduced
1942 // (e.g. because we're drawing to a print preview memory DC)
1943 int pageWidth
, pageHeight
;
1945 dc
->GetSize(&w
, &h
);
1946 GetPageSizePixels(&pageWidth
, &pageHeight
);
1947 wxUnusedVar(pageHeight
);
1949 // If printer pageWidth == current DC width, then this doesn't
1950 // change. But w might be the preview bitmap width, so scale down.
1951 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
1952 dc
->SetUserScale(overallScale
, overallScale
);
1956 m_printoutView
->OnDraw(dc
);
1961 bool wxDocPrintout::HasPage(int pageNum
)
1963 return (pageNum
== 1);
1966 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
1968 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
1974 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
, int *selPageFrom
, int *selPageTo
)
1982 #endif // wxUSE_PRINTING_ARCHITECTURE
1984 // ----------------------------------------------------------------------------
1985 // File history (a.k.a. MRU, most recently used, files list)
1986 // ----------------------------------------------------------------------------
1988 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
1990 m_fileMaxFiles
= maxFiles
;
1994 void wxFileHistory::AddFileToHistory(const wxString
& file
)
1996 // check if we don't already have this file
1997 const wxFileName
fnNew(file
);
1999 numFiles
= m_fileHistory
.size();
2000 for ( i
= 0; i
< numFiles
; i
++ )
2002 if ( fnNew
== m_fileHistory
[i
] )
2004 // we do have it, move it to the top of the history
2005 RemoveFileFromHistory(i
);
2011 // if we already have a full history, delete the one at the end
2012 if ( numFiles
== m_fileMaxFiles
)
2014 RemoveFileFromHistory(--numFiles
);
2016 else // add a new menu item to all file menus (will be updated below)
2018 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2020 node
= node
->GetNext() )
2022 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2024 if ( !numFiles
&& menu
->GetMenuItemCount() )
2025 menu
->AppendSeparator();
2027 // label doesn't matter, it will be set below anyhow, but it can't
2028 // be empty (this is supposed to indicate a stock item)
2029 menu
->Append(m_idBase
+ numFiles
, " ");
2034 // insert the new file in the beginning of the file history
2035 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2038 // update the labels in all menus
2039 for ( i
= 0; i
< numFiles
; i
++ )
2041 // if in same directory just show the filename; otherwise the full path
2042 const wxFileName
fnOld(m_fileHistory
[i
]);
2044 wxString pathInMenu
;
2045 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2047 pathInMenu
= fnOld
.GetFullName();
2049 else // file in different directory
2051 // absolute path; could also set relative path
2052 pathInMenu
= m_fileHistory
[i
];
2055 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2057 node
= node
->GetNext() )
2059 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2061 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2066 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2068 size_t numFiles
= m_fileHistory
.size();
2069 wxCHECK_RET( i
< numFiles
,
2070 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2072 // delete the element from the array
2073 m_fileHistory
.RemoveAt(i
);
2076 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2078 node
= node
->GetNext() )
2080 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2082 // shift filenames up
2083 for ( size_t j
= i
; j
< numFiles
; j
++ )
2085 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2088 // delete the last menu item which is unused now
2089 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2090 if ( menu
->FindItem(lastItemId
) )
2091 menu
->Delete(lastItemId
);
2093 // delete the last separator too if no more files are left
2094 if ( m_fileHistory
.empty() )
2096 const wxMenuItemList::compatibility_iterator
2097 nodeLast
= menu
->GetMenuItems().GetLast();
2100 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2101 if ( lastMenuItem
->IsSeparator() )
2102 menu
->Delete(lastMenuItem
);
2104 //else: menu is empty somehow
2109 void wxFileHistory::UseMenu(wxMenu
*menu
)
2111 if ( !m_fileMenus
.Member(menu
) )
2112 m_fileMenus
.Append(menu
);
2115 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2117 m_fileMenus
.DeleteObject(menu
);
2121 void wxFileHistory::Load(const wxConfigBase
& config
)
2123 m_fileHistory
.Clear();
2126 buf
.Printf(wxT("file%d"), 1);
2128 wxString historyFile
;
2129 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2130 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2132 m_fileHistory
.Add(historyFile
);
2134 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2135 historyFile
= wxEmptyString
;
2141 void wxFileHistory::Save(wxConfigBase
& config
)
2144 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2147 buf
.Printf(wxT("file%d"), (int)i
+1);
2148 if (i
< m_fileHistory
.GetCount())
2149 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2151 config
.Write(buf
, wxEmptyString
);
2154 #endif // wxUSE_CONFIG
2156 void wxFileHistory::AddFilesToMenu()
2158 if ( m_fileHistory
.empty() )
2161 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2163 node
= node
->GetNext() )
2165 AddFilesToMenu((wxMenu
*) node
->GetData());
2169 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2171 if ( m_fileHistory
.empty() )
2174 if ( menu
->GetMenuItemCount() )
2175 menu
->AppendSeparator();
2177 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2179 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2183 // ----------------------------------------------------------------------------
2184 // Permits compatibility with existing file formats and functions that
2185 // manipulate files directly
2186 // ----------------------------------------------------------------------------
2188 #if wxUSE_STD_IOSTREAM
2190 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2192 wxFFile
file(filename
, _T("rb"));
2193 if ( !file
.IsOpened() )
2201 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2205 stream
.write(buf
, nRead
);
2209 while ( !file
.Eof() );
2214 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2216 wxFFile
file(filename
, _T("wb"));
2217 if ( !file
.IsOpened() )
2223 stream
.read(buf
, WXSIZEOF(buf
));
2224 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2226 if ( !file
.Write(buf
, stream
.gcount()) )
2230 while ( !stream
.eof() );
2235 #else // !wxUSE_STD_IOSTREAM
2237 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2239 wxFFile
file(filename
, _T("rb"));
2240 if ( !file
.IsOpened() )
2248 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2252 stream
.Write(buf
, nRead
);
2256 while ( !file
.Eof() );
2261 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2263 wxFFile
file(filename
, _T("wb"));
2264 if ( !file
.IsOpened() )
2270 stream
.Read(buf
, WXSIZEOF(buf
));
2272 const size_t nRead
= stream
.LastRead();
2281 if ( !file
.Write(buf
, nRead
) )
2288 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2290 #endif // wxUSE_DOC_VIEW_ARCHITECTURE