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 fileName
= wxFileSelector(_("Save As"),
315 wxFileNameFromPath(GetFilename()),
316 docTemplate
->GetDefaultExtension(),
318 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
319 GetDocumentWindow());
321 if (fileName
.empty())
325 wxFileName::SplitPath(fileName
, NULL
, NULL
, &ext
);
329 fileName
+= wxT(".");
330 fileName
+= docTemplate
->GetDefaultExtension();
333 // Files that were not saved correctly are not added to the FileHistory.
334 if (!OnSaveDocument(fileName
))
337 SetTitle(wxFileNameFromPath(fileName
));
338 SetFilename(fileName
, true); // will call OnChangeFileName automatically
340 // A file that doesn't use the default extension of its document template cannot be opened
341 // via the FileHistory, so we do not add it.
342 if (docTemplate
->FileMatchesTemplate(fileName
))
344 GetDocumentManager()->AddFileToHistory(fileName
);
348 // The user will probably not be able to open the file again, so
349 // we could warn about the wrong file-extension here.
354 bool wxDocument::OnSaveDocument(const wxString
& file
)
359 if ( !DoSaveDocument(file
) )
364 SetDocumentSaved(true);
365 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
366 wxFileName
fn(file
) ;
367 fn
.MacSetDefaultTypeAndCreator() ;
372 bool wxDocument::OnOpenDocument(const wxString
& file
)
374 if ( !OnSaveModified() )
377 if ( !DoOpenDocument(file
) )
380 SetFilename(file
, true);
389 #if wxUSE_STD_IOSTREAM
390 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
392 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
398 #if wxUSE_STD_IOSTREAM
399 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
401 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
407 bool wxDocument::Revert()
413 // Get title, or filename if no title, else unnamed
414 #if WXWIN_COMPATIBILITY_2_8
415 bool wxDocument::GetPrintableName(wxString
& buf
) const
417 // this function can not only be overridden by the user code but also
418 // called by it so we need to ensure that we return the same thing as
419 // GetUserReadableName() but we can't call it because this would result in
420 // an infinite recursion, hence we use the helper DoGetUserReadableName()
421 buf
= DoGetUserReadableName();
425 #endif // WXWIN_COMPATIBILITY_2_8
427 wxString
wxDocument::GetUserReadableName() const
429 #if WXWIN_COMPATIBILITY_2_8
430 // we need to call the old virtual function to ensure that the overridden
431 // version of it is still called
433 if ( GetPrintableName(name
) )
435 #endif // WXWIN_COMPATIBILITY_2_8
437 return DoGetUserReadableName();
440 wxString
wxDocument::DoGetUserReadableName() const
442 if ( !m_documentTitle
.empty() )
443 return m_documentTitle
;
445 if ( !m_documentFile
.empty() )
446 return wxFileNameFromPath(m_documentFile
);
451 wxWindow
*wxDocument::GetDocumentWindow() const
453 wxView
*view
= GetFirstView();
455 return view
->GetFrame();
457 return wxTheApp
->GetTopWindow();
460 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
462 return new wxCommandProcessor
;
465 // true if safe to close
466 bool wxDocument::OnSaveModified()
470 switch ( wxMessageBox
474 _("Do you want to save changes to document %s?"),
475 GetUserReadableName()
477 wxTheApp
->GetAppDisplayName(),
478 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
,
479 wxFindSuitableParent()
497 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
502 bool wxDocument::AddView(wxView
*view
)
504 if ( !m_documentViews
.Member(view
) )
506 m_documentViews
.Append(view
);
512 bool wxDocument::RemoveView(wxView
*view
)
514 (void)m_documentViews
.DeleteObject(view
);
519 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
521 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
524 // Called after a view is added or removed.
525 // The default implementation deletes the document if
526 // there are no more views.
527 void wxDocument::OnChangedViewList()
529 if ( m_documentViews
.empty() && OnSaveModified() )
533 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
535 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
538 wxView
*view
= (wxView
*)node
->GetData();
540 view
->OnUpdate(sender
, hint
);
541 node
= node
->GetNext();
545 void wxDocument::NotifyClosing()
547 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
550 wxView
*view
= (wxView
*)node
->GetData();
551 view
->OnClosingDocument();
552 node
= node
->GetNext();
556 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
558 m_documentFile
= filename
;
559 OnChangeFilename(notifyViews
);
562 void wxDocument::OnChangeFilename(bool notifyViews
)
566 // Notify the views that the filename has changed
567 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
570 wxView
*view
= (wxView
*)node
->GetData();
571 view
->OnChangeFilename();
572 node
= node
->GetNext();
577 bool wxDocument::DoSaveDocument(const wxString
& file
)
579 #if wxUSE_STD_IOSTREAM
580 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
583 wxFileOutputStream
store(file
);
584 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
587 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
591 if (!SaveObject(store
))
593 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
600 bool wxDocument::DoOpenDocument(const wxString
& file
)
602 #if wxUSE_STD_IOSTREAM
603 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
606 wxFileInputStream
store(file
);
607 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
610 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
614 #if wxUSE_STD_IOSTREAM
618 int res
= LoadObject(store
).GetLastError();
619 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
622 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
630 // ----------------------------------------------------------------------------
632 // ----------------------------------------------------------------------------
636 m_viewDocument
= NULL
;
643 GetDocumentManager()->ActivateView(this, false);
644 m_viewDocument
->RemoveView(this);
647 bool wxView::TryValidator(wxEvent
& event
)
649 wxDocument
* const doc
= GetDocument();
650 return doc
&& doc
->ProcessEventHere(event
);
653 void wxView::OnActivateView(bool WXUNUSED(activate
), wxView
*WXUNUSED(activeView
), wxView
*WXUNUSED(deactiveView
))
657 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
662 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
666 void wxView::OnChangeFilename()
668 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
669 // generic MDI implementation so use SetLabel rather than SetTitle.
670 // It should cause SetTitle() for top level windows.
671 wxWindow
*win
= GetFrame();
674 wxDocument
*doc
= GetDocument();
677 win
->SetLabel(doc
->GetUserReadableName());
680 void wxView::SetDocument(wxDocument
*doc
)
682 m_viewDocument
= doc
;
687 bool wxView::Close(bool deleteWindow
)
689 return OnClose(deleteWindow
);
692 void wxView::Activate(bool activate
)
694 if (GetDocument() && GetDocumentManager())
696 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
697 GetDocumentManager()->ActivateView(this, activate
);
701 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
703 return GetDocument() ? GetDocument()->Close() : true;
706 #if wxUSE_PRINTING_ARCHITECTURE
707 wxPrintout
*wxView::OnCreatePrintout()
709 return new wxDocPrintout(this);
711 #endif // wxUSE_PRINTING_ARCHITECTURE
713 // ----------------------------------------------------------------------------
715 // ----------------------------------------------------------------------------
717 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
718 const wxString
& descr
,
719 const wxString
& filter
,
722 const wxString
& docTypeName
,
723 const wxString
& viewTypeName
,
724 wxClassInfo
*docClassInfo
,
725 wxClassInfo
*viewClassInfo
,
728 m_documentManager
= manager
;
729 m_description
= descr
;
732 m_fileFilter
= filter
;
734 m_docTypeName
= docTypeName
;
735 m_viewTypeName
= viewTypeName
;
736 m_documentManager
->AssociateTemplate(this);
738 m_docClassInfo
= docClassInfo
;
739 m_viewClassInfo
= viewClassInfo
;
742 wxDocTemplate::~wxDocTemplate()
744 m_documentManager
->DisassociateTemplate(this);
747 // Tries to dynamically construct an object of the right class.
748 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
750 wxDocument
* const doc
= DoCreateDocument();
752 // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate())
753 // fails, is this intentional?
755 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
759 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
761 doc
->SetFilename(path
);
762 doc
->SetDocumentTemplate(this);
763 GetDocumentManager()->AddDocument(doc
);
764 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
766 if (doc
->OnCreate(path
, flags
))
770 if (GetDocumentManager()->GetDocuments().Member(doc
))
771 doc
->DeleteAllViews();
776 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
778 wxScopedPtr
<wxView
> view(DoCreateView());
782 view
->SetDocument(doc
);
783 if ( !view
->OnCreate(doc
, flags
) )
786 return view
.release();
789 // The default (very primitive) format detection: check is the extension is
790 // that of the template
791 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
793 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
794 wxString anything
= wxT ("*");
795 while (parser
.HasMoreTokens())
797 wxString filter
= parser
.GetNextToken();
798 wxString filterExt
= FindExtension (filter
);
799 if ( filter
.IsSameAs (anything
) ||
800 filterExt
.IsSameAs (anything
) ||
801 filterExt
.IsSameAs (FindExtension (path
)) )
804 return GetDefaultExtension().IsSameAs(FindExtension(path
));
807 wxDocument
*wxDocTemplate::DoCreateDocument()
812 return (wxDocument
*)m_docClassInfo
->CreateObject();
815 wxView
*wxDocTemplate::DoCreateView()
817 if (!m_viewClassInfo
)
820 return (wxView
*)m_viewClassInfo
->CreateObject();
823 // ----------------------------------------------------------------------------
825 // ----------------------------------------------------------------------------
827 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
828 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
829 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
830 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
831 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
832 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
833 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
834 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
835 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
836 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
838 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
839 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
840 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
841 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
842 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
843 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
844 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
845 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
846 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
848 #if wxUSE_PRINTING_ARCHITECTURE
849 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
850 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
852 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
853 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
857 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
859 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
861 wxASSERT_MSG( !sm_docManager
, "multiple wxDocManagers not allowed" );
863 sm_docManager
= this;
865 m_defaultDocumentNameCounter
= 1;
866 m_currentView
= NULL
;
867 m_maxDocsOpen
= INT_MAX
;
868 m_fileHistory
= NULL
;
873 wxDocManager::~wxDocManager()
876 delete m_fileHistory
;
877 sm_docManager
= NULL
;
880 // closes the specified document
881 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
883 if (doc
->Close() || force
)
885 // Implicitly deletes the document when
886 // the last view is deleted
887 doc
->DeleteAllViews();
889 // Check we're really deleted
890 if (m_docs
.Member(doc
))
898 bool wxDocManager::CloseDocuments(bool force
)
900 wxList::compatibility_iterator node
= m_docs
.GetFirst();
903 wxDocument
*doc
= (wxDocument
*)node
->GetData();
904 wxList::compatibility_iterator next
= node
->GetNext();
906 if (!CloseDocument(doc
, force
))
909 // This assumes that documents are not connected in
910 // any way, i.e. deleting one document does NOT
917 bool wxDocManager::Clear(bool force
)
919 if (!CloseDocuments(force
))
922 m_currentView
= NULL
;
924 wxList::compatibility_iterator node
= m_templates
.GetFirst();
927 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
928 wxList::compatibility_iterator next
= node
->GetNext();
935 bool wxDocManager::Initialize()
937 m_fileHistory
= OnCreateFileHistory();
941 wxFileHistory
*wxDocManager::OnCreateFileHistory()
943 return new wxFileHistory
;
946 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
948 wxDocument
*doc
= GetCurrentDocument();
953 doc
->DeleteAllViews();
954 if (m_docs
.Member(doc
))
959 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
961 CloseDocuments(false);
964 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
969 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
971 if ( !CreateDocument( wxEmptyString
, 0) )
977 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
979 wxDocument
*doc
= GetCurrentDocument();
985 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
987 wxDocument
*doc
= GetCurrentDocument();
993 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
995 wxDocument
*doc
= GetCurrentDocument();
1001 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1003 #if wxUSE_PRINTING_ARCHITECTURE
1004 wxView
*view
= GetCurrentView();
1008 wxPrintout
*printout
= view
->OnCreatePrintout();
1012 printer
.Print(view
->GetFrame(), printout
, true);
1016 #endif // wxUSE_PRINTING_ARCHITECTURE
1019 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1021 #if wxUSE_PRINTING_ARCHITECTURE
1022 wxView
*view
= GetCurrentView();
1026 wxPrintout
*printout
= view
->OnCreatePrintout();
1029 // Pass two printout objects: for preview, and possible printing.
1030 wxPrintPreviewBase
*preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1031 if ( !preview
->Ok() )
1034 wxMessageBox( _("Sorry, print preview needs a printer to be installed.") );
1038 wxPreviewFrame
*frame
= new wxPreviewFrame(preview
, (wxFrame
*)wxTheApp
->GetTopWindow(), _("Print Preview"),
1039 wxPoint(100, 100), wxSize(600, 650));
1040 frame
->Centre(wxBOTH
);
1041 frame
->Initialize();
1044 #endif // wxUSE_PRINTING_ARCHITECTURE
1047 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1049 wxDocument
*doc
= GetCurrentDocument();
1052 if (doc
->GetCommandProcessor())
1053 doc
->GetCommandProcessor()->Undo();
1058 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1060 wxDocument
*doc
= GetCurrentDocument();
1063 if (doc
->GetCommandProcessor())
1064 doc
->GetCommandProcessor()->Redo();
1069 // Handlers for UI update commands
1071 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1073 // CreateDocument() (which is called from OnFileOpen) may succeed
1074 // only when there is at least a template:
1075 event
.Enable( GetTemplates().GetCount()>0 );
1078 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1080 event
.Enable( GetCurrentDocument() != NULL
);
1083 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1085 // CreateDocument() (which is called from OnFileNew) may succeed
1086 // only when there is at least a template:
1087 event
.Enable( GetTemplates().GetCount()>0 );
1090 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1092 wxDocument
* const doc
= GetCurrentDocument();
1093 event
.Enable( doc
&& !doc
->AlreadySaved() );
1096 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1098 wxDocument
*doc
= GetCurrentDocument();
1100 event
.Enable(false);
1101 else if (!doc
->GetCommandProcessor())
1105 event
.Enable( doc
->GetCommandProcessor()->CanUndo() );
1106 doc
->GetCommandProcessor()->SetMenuStrings();
1110 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1112 wxDocument
*doc
= GetCurrentDocument();
1114 event
.Enable(false);
1115 else if (!doc
->GetCommandProcessor())
1119 event
.Enable( doc
->GetCommandProcessor()->CanRedo() );
1120 doc
->GetCommandProcessor()->SetMenuStrings();
1124 wxView
*wxDocManager::GetCurrentView() const
1127 return m_currentView
;
1128 if (m_docs
.GetCount() == 1)
1130 wxDocument
* doc
= (wxDocument
*) m_docs
.GetFirst()->GetData();
1131 return doc
->GetFirstView();
1136 bool wxDocManager::TryValidator(wxEvent
& event
)
1138 wxView
* const view
= GetCurrentView();
1139 return view
&& view
->ProcessEventHere(event
);
1145 // helper function: return only the visible templates
1146 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1148 // select only the visible templates
1149 const size_t totalNumTemplates
= allTemplates
.GetCount();
1150 wxDocTemplates templates
;
1151 if ( totalNumTemplates
)
1153 templates
.reserve(totalNumTemplates
);
1155 for ( wxList::const_iterator i
= allTemplates
.begin(),
1156 end
= allTemplates
.end();
1160 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1161 if ( temp
->IsVisible() )
1162 templates
.push_back(temp
);
1169 } // anonymous namespace
1171 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1173 // this ought to be const but SelectDocumentType/Path() are not
1174 // const-correct and can't be changed as, being virtual, this risks
1175 // breaking user code overriding them
1176 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1177 const size_t numTemplates
= templates
.size();
1178 if ( !numTemplates
)
1180 // no templates can be used, can't create document
1185 // normally user should select the template to use but wxDOC_SILENT flag we
1186 // choose one ourselves
1187 wxString path
= pathOrig
; // may be modified below
1188 wxDocTemplate
*temp
;
1189 if ( flags
& wxDOC_SILENT
)
1191 wxASSERT_MSG( !path
.empty(),
1192 "using empty path with wxDOC_SILENT doesn't make sense" );
1194 temp
= FindTemplateForPath(path
);
1197 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1201 else // not silent, ask the user
1203 // for the new file we need just the template, for an existing one we
1204 // need the template and the path, unless it's already specified
1205 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1206 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1208 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1214 // check whether the document with this path is already opened
1215 if ( !path
.empty() )
1217 const wxFileName
fn(path
);
1218 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1220 wxDocument
* const doc
= (wxDocument
*)*i
;
1222 if ( fn
== doc
->GetFilename() )
1224 // file already open, just activate it and return
1225 if ( doc
->GetFirstView() )
1227 ActivateView(doc
->GetFirstView());
1228 if ( doc
->GetDocumentWindow() )
1229 doc
->GetDocumentWindow()->SetFocus();
1237 // no, we need to create a new document
1240 // if we've reached the max number of docs, close the first one.
1241 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1243 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1245 // can't open the new document if closing the old one failed
1251 // do create and initialize the new document finally
1252 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1256 docNew
->SetDocumentName(temp
->GetDocumentName());
1257 docNew
->SetDocumentTemplate(temp
);
1259 // call the appropriate function depending on whether we're creating a new
1260 // file or opening an existing one
1261 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1262 : docNew
->OnOpenDocument(path
)) )
1264 // Document is implicitly deleted by DeleteAllViews
1265 docNew
->DeleteAllViews();
1269 // add the successfully opened file to MRU, but only if we're going to be
1270 // able to reopen it successfully later which requires the template for
1271 // this document to be retrievable from the file extension
1272 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1273 AddFileToHistory(path
);
1278 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1280 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1281 const size_t numTemplates
= templates
.size();
1283 if ( numTemplates
== 0 )
1286 wxDocTemplate
* const
1287 temp
= numTemplates
== 1 ? templates
[0]
1288 : SelectViewType(&templates
[0], numTemplates
);
1293 wxView
*view
= temp
->CreateView(doc
, flags
);
1295 view
->SetViewName(temp
->GetViewName());
1299 // Not yet implemented
1301 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1305 // Not yet implemented
1306 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1311 wxDocument
*wxDocManager::GetCurrentDocument() const
1313 wxView
*view
= GetCurrentView();
1315 return view
->GetDocument();
1320 // Make a default name for a new document
1321 #if WXWIN_COMPATIBILITY_2_8
1322 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1324 // we consider that this function can only be overridden by the user code,
1325 // not called by it as it only makes sense to call it internally, so we
1326 // don't bother to return anything from here
1329 #endif // WXWIN_COMPATIBILITY_2_8
1331 wxString
wxDocManager::MakeNewDocumentName()
1335 #if WXWIN_COMPATIBILITY_2_8
1336 if ( !MakeDefaultName(name
) )
1337 #endif // WXWIN_COMPATIBILITY_2_8
1339 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1340 m_defaultDocumentNameCounter
++;
1346 // Make a frame title (override this to do something different)
1347 // If docName is empty, a document is not currently active.
1348 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1350 wxString appName
= wxTheApp
->GetAppDisplayName();
1356 wxString docName
= doc
->GetUserReadableName();
1357 title
= docName
+ wxString(_(" - ")) + appName
;
1363 // Not yet implemented
1364 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1369 // File history management
1370 void wxDocManager::AddFileToHistory(const wxString
& file
)
1373 m_fileHistory
->AddFileToHistory(file
);
1376 void wxDocManager::RemoveFileFromHistory(size_t i
)
1379 m_fileHistory
->RemoveFileFromHistory(i
);
1382 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1387 histFile
= m_fileHistory
->GetHistoryFile(i
);
1392 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1395 m_fileHistory
->UseMenu(menu
);
1398 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1401 m_fileHistory
->RemoveMenu(menu
);
1405 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1408 m_fileHistory
->Load(config
);
1411 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1414 m_fileHistory
->Save(config
);
1418 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1421 m_fileHistory
->AddFilesToMenu(menu
);
1424 void wxDocManager::FileHistoryAddFilesToMenu()
1427 m_fileHistory
->AddFilesToMenu();
1430 size_t wxDocManager::GetHistoryFilesCount() const
1432 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1436 // Find out the document template via matching in the document file format
1437 // against that of the template
1438 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1440 wxDocTemplate
*theTemplate
= NULL
;
1442 // Find the template which this extension corresponds to
1443 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1445 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1446 if ( temp
->FileMatchesTemplate(path
) )
1455 // Prompts user to open a file, using file specs in templates.
1456 // Must extend the file selector dialog or implement own; OR
1457 // match the extension to the template extension.
1459 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1462 long WXUNUSED(flags
),
1463 bool WXUNUSED(save
))
1465 // We can only have multiple filters in Windows and GTK
1466 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1470 for (i
= 0; i
< noTemplates
; i
++)
1472 if (templates
[i
]->IsVisible())
1474 // add a '|' to separate this filter from the previous one
1475 if ( !descrBuf
.empty() )
1476 descrBuf
<< wxT('|');
1478 descrBuf
<< templates
[i
]->GetDescription()
1479 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1480 << templates
[i
]->GetFileFilter();
1484 wxString descrBuf
= wxT("*.*");
1485 wxUnusedVar(noTemplates
);
1488 int FilterIndex
= -1;
1490 wxWindow
* parent
= wxFindSuitableParent();
1492 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1500 wxDocTemplate
*theTemplate
= NULL
;
1501 if (!pathTmp
.empty())
1503 if (!wxFileExists(pathTmp
))
1506 if (!wxTheApp
->GetAppDisplayName().empty())
1507 msgTitle
= wxTheApp
->GetAppDisplayName();
1509 msgTitle
= wxString(_("File error"));
1511 (void)wxMessageBox(_("Sorry, could not open this file."), msgTitle
, wxOK
| wxICON_EXCLAMATION
| wxCENTRE
,
1514 path
= wxEmptyString
;
1517 m_lastDirectory
= wxPathOnly(pathTmp
);
1521 // first choose the template using the extension, if this fails (i.e.
1522 // wxFileSelectorEx() didn't fill it), then use the path
1523 if ( FilterIndex
!= -1 )
1524 theTemplate
= templates
[FilterIndex
];
1526 theTemplate
= FindTemplateForPath(path
);
1529 // Since we do not add files with non-default extensions to the FileHistory this
1530 // can only happen if the application changes the allowed templates in runtime.
1531 (void)wxMessageBox(_("Sorry, the format for this file is unknown."),
1533 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
, wxFindSuitableParent());
1538 path
= wxEmptyString
;
1544 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1545 int noTemplates
, bool sort
)
1547 wxArrayString strings
;
1548 wxDocTemplate
**data
= new wxDocTemplate
*[noTemplates
];
1552 for (i
= 0; i
< noTemplates
; i
++)
1554 if (templates
[i
]->IsVisible())
1558 for (j
= 0; j
< n
; j
++)
1560 //filter out NOT unique documents + view combinations
1561 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1562 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1569 strings
.Add(templates
[i
]->m_description
);
1571 data
[n
] = templates
[i
];
1579 strings
.Sort(); // ascending sort
1580 // Yes, this will be slow, but template lists
1581 // are typically short.
1583 n
= strings
.Count();
1584 for (i
= 0; i
< n
; i
++)
1586 for (j
= 0; j
< noTemplates
; j
++)
1588 if (strings
[i
] == templates
[j
]->m_description
)
1589 data
[i
] = templates
[j
];
1594 wxDocTemplate
*theTemplate
;
1599 // no visible templates, hence nothing to choose from
1604 // don't propose the user to choose if he has no choice
1605 theTemplate
= data
[0];
1609 // propose the user to choose one of several
1610 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1612 _("Select a document template"),
1616 wxFindSuitableParent()
1625 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1626 int noTemplates
, bool sort
)
1628 wxArrayString strings
;
1629 wxDocTemplate
**data
= new wxDocTemplate
*[noTemplates
];
1633 for (i
= 0; i
< noTemplates
; i
++)
1635 wxDocTemplate
*templ
= templates
[i
];
1636 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1640 for (j
= 0; j
< n
; j
++)
1642 //filter out NOT unique views
1643 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1649 strings
.Add(templ
->m_viewTypeName
);
1658 strings
.Sort(); // ascending sort
1659 // Yes, this will be slow, but template lists
1660 // are typically short.
1662 n
= strings
.Count();
1663 for (i
= 0; i
< n
; i
++)
1665 for (j
= 0; j
< noTemplates
; j
++)
1667 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1668 data
[i
] = templates
[j
];
1673 wxDocTemplate
*theTemplate
;
1675 // the same logic as above
1683 theTemplate
= data
[0];
1687 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1689 _("Select a document view"),
1693 wxFindSuitableParent()
1702 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1704 if (!m_templates
.Member(temp
))
1705 m_templates
.Append(temp
);
1708 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1710 m_templates
.DeleteObject(temp
);
1713 // Add and remove a document from the manager's list
1714 void wxDocManager::AddDocument(wxDocument
*doc
)
1716 if (!m_docs
.Member(doc
))
1720 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1722 m_docs
.DeleteObject(doc
);
1725 // Views or windows should inform the document manager
1726 // when a view is going in or out of focus
1727 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1731 m_currentView
= view
;
1735 if ( m_currentView
== view
)
1737 // don't keep stale pointer
1738 m_currentView
= NULL
;
1743 // ----------------------------------------------------------------------------
1744 // Default document child frame
1745 // ----------------------------------------------------------------------------
1747 BEGIN_EVENT_TABLE(wxDocChildFrame
, wxFrame
)
1748 EVT_ACTIVATE(wxDocChildFrame::OnActivate
)
1749 EVT_CLOSE(wxDocChildFrame::OnCloseWindow
)
1752 wxDocChildFrame::wxDocChildFrame(wxDocument
*doc
,
1756 const wxString
& title
,
1760 const wxString
& name
)
1761 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1763 m_childDocument
= doc
;
1766 view
->SetFrame(this);
1769 bool wxDocChildFrame::TryValidator(wxEvent
& event
)
1774 // FIXME: why is this needed here?
1775 m_childView
->Activate(true);
1777 return m_childView
->ProcessEventHere(event
);
1780 void wxDocChildFrame::OnActivate(wxActivateEvent
& event
)
1782 wxFrame::OnActivate(event
);
1785 m_childView
->Activate(event
.GetActive());
1788 void wxDocChildFrame::OnCloseWindow(wxCloseEvent
& event
)
1792 bool ans
= event
.CanVeto()
1793 ? m_childView
->Close(false) // false means don't delete associated window
1794 : true; // Must delete.
1798 m_childView
->Activate(false);
1801 m_childDocument
= NULL
;
1812 // ----------------------------------------------------------------------------
1813 // Default parent frame
1814 // ----------------------------------------------------------------------------
1816 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1817 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1818 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1819 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1822 wxDocParentFrame::wxDocParentFrame()
1824 m_docManager
= NULL
;
1827 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1830 const wxString
& title
,
1834 const wxString
& name
)
1835 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1837 m_docManager
= manager
;
1840 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1843 const wxString
& title
,
1847 const wxString
& name
)
1849 m_docManager
= manager
;
1850 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1853 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1858 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1860 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1861 wxString
filename(m_docManager
->GetHistoryFile(n
));
1862 if ( filename
.empty() )
1865 wxString errMsg
; // must contain exactly one "%s" if non-empty
1866 if ( wxFile::Exists(filename
) )
1869 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1872 errMsg
= _("The file '%s' couldn't be opened.");
1874 else // file doesn't exist
1876 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1880 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1882 // remove the file which we can't open from the MRU list
1883 m_docManager
->RemoveFileFromHistory(n
);
1885 // and tell the user about it
1886 wxLogError(errMsg
+ '\n' +
1887 _("It has been removed from the most recently used files list."),
1891 // Extend event processing to search the view's event table
1892 bool wxDocParentFrame::TryValidator(wxEvent
& event
)
1894 return m_docManager
&& m_docManager
->ProcessEventHere(event
);
1897 // Define the behaviour for the frame closing
1898 // - must delete all frames except for the main one.
1899 void wxDocParentFrame::OnCloseWindow(wxCloseEvent
& event
)
1901 if (m_docManager
->Clear(!event
.CanVeto()))
1909 #if wxUSE_PRINTING_ARCHITECTURE
1911 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
1914 m_printoutView
= view
;
1917 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
1921 // Get the logical pixels per inch of screen and printer
1922 int ppiScreenX
, ppiScreenY
;
1923 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
1924 wxUnusedVar(ppiScreenY
);
1925 int ppiPrinterX
, ppiPrinterY
;
1926 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
1927 wxUnusedVar(ppiPrinterY
);
1929 // This scales the DC so that the printout roughly represents the
1930 // the screen scaling. The text point size _should_ be the right size
1931 // but in fact is too small for some reason. This is a detail that will
1932 // need to be addressed at some point but can be fudged for the
1934 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
1936 // Now we have to check in case our real page size is reduced
1937 // (e.g. because we're drawing to a print preview memory DC)
1938 int pageWidth
, pageHeight
;
1940 dc
->GetSize(&w
, &h
);
1941 GetPageSizePixels(&pageWidth
, &pageHeight
);
1942 wxUnusedVar(pageHeight
);
1944 // If printer pageWidth == current DC width, then this doesn't
1945 // change. But w might be the preview bitmap width, so scale down.
1946 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
1947 dc
->SetUserScale(overallScale
, overallScale
);
1951 m_printoutView
->OnDraw(dc
);
1956 bool wxDocPrintout::HasPage(int pageNum
)
1958 return (pageNum
== 1);
1961 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
1963 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
1969 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
, int *selPageFrom
, int *selPageTo
)
1977 #endif // wxUSE_PRINTING_ARCHITECTURE
1979 // ----------------------------------------------------------------------------
1980 // File history (a.k.a. MRU, most recently used, files list)
1981 // ----------------------------------------------------------------------------
1983 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
1985 m_fileMaxFiles
= maxFiles
;
1989 void wxFileHistory::AddFileToHistory(const wxString
& file
)
1991 // check if we don't already have this file
1992 const wxFileName
fnNew(file
);
1994 numFiles
= m_fileHistory
.size();
1995 for ( i
= 0; i
< numFiles
; i
++ )
1997 if ( fnNew
== m_fileHistory
[i
] )
1999 // we do have it, move it to the top of the history
2000 RemoveFileFromHistory(i
);
2006 // if we already have a full history, delete the one at the end
2007 if ( numFiles
== m_fileMaxFiles
)
2009 RemoveFileFromHistory(--numFiles
);
2012 // add a new menu item to all file menus (they will be updated below)
2013 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2015 node
= node
->GetNext() )
2017 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2019 if ( !numFiles
&& menu
->GetMenuItemCount() )
2020 menu
->AppendSeparator();
2022 // label doesn't matter, it will be set below anyhow, but it can't
2023 // be empty (this is supposed to indicate a stock item)
2024 menu
->Append(m_idBase
+ numFiles
, " ");
2027 // insert the new file in the beginning of the file history
2028 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2031 // update the labels in all menus
2032 for ( i
= 0; i
< numFiles
; i
++ )
2034 // if in same directory just show the filename; otherwise the full path
2035 const wxFileName
fnOld(m_fileHistory
[i
]);
2037 wxString pathInMenu
;
2038 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2040 pathInMenu
= fnOld
.GetFullName();
2042 else // file in different directory
2044 // absolute path; could also set relative path
2045 pathInMenu
= m_fileHistory
[i
];
2048 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2050 node
= node
->GetNext() )
2052 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2054 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2059 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2061 size_t numFiles
= m_fileHistory
.size();
2062 wxCHECK_RET( i
< numFiles
,
2063 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2065 // delete the element from the array
2066 m_fileHistory
.RemoveAt(i
);
2069 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2071 node
= node
->GetNext() )
2073 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2075 // shift filenames up
2076 for ( size_t j
= i
; j
< numFiles
; j
++ )
2078 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2081 // delete the last menu item which is unused now
2082 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2083 if ( menu
->FindItem(lastItemId
) )
2084 menu
->Delete(lastItemId
);
2086 // delete the last separator too if no more files are left
2087 if ( m_fileHistory
.empty() )
2089 const wxMenuItemList::compatibility_iterator
2090 nodeLast
= menu
->GetMenuItems().GetLast();
2093 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2094 if ( lastMenuItem
->IsSeparator() )
2095 menu
->Delete(lastMenuItem
);
2097 //else: menu is empty somehow
2102 void wxFileHistory::UseMenu(wxMenu
*menu
)
2104 if ( !m_fileMenus
.Member(menu
) )
2105 m_fileMenus
.Append(menu
);
2108 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2110 m_fileMenus
.DeleteObject(menu
);
2114 void wxFileHistory::Load(const wxConfigBase
& config
)
2116 m_fileHistory
.Clear();
2119 buf
.Printf(wxT("file%d"), 1);
2121 wxString historyFile
;
2122 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2123 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2125 m_fileHistory
.Add(historyFile
);
2127 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2128 historyFile
= wxEmptyString
;
2134 void wxFileHistory::Save(wxConfigBase
& config
)
2137 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2140 buf
.Printf(wxT("file%d"), (int)i
+1);
2141 if (i
< m_fileHistory
.GetCount())
2142 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2144 config
.Write(buf
, wxEmptyString
);
2147 #endif // wxUSE_CONFIG
2149 void wxFileHistory::AddFilesToMenu()
2151 if ( m_fileHistory
.empty() )
2154 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2156 node
= node
->GetNext() )
2158 AddFilesToMenu((wxMenu
*) node
->GetData());
2162 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2164 if ( m_fileHistory
.empty() )
2167 if ( menu
->GetMenuItemCount() )
2168 menu
->AppendSeparator();
2170 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2172 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2176 // ----------------------------------------------------------------------------
2177 // Permits compatibility with existing file formats and functions that
2178 // manipulate files directly
2179 // ----------------------------------------------------------------------------
2181 #if wxUSE_STD_IOSTREAM
2183 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2185 wxFFile
file(filename
, _T("rb"));
2186 if ( !file
.IsOpened() )
2194 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2198 stream
.write(buf
, nRead
);
2202 while ( !file
.Eof() );
2207 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2209 wxFFile
file(filename
, _T("wb"));
2210 if ( !file
.IsOpened() )
2216 stream
.read(buf
, WXSIZEOF(buf
));
2217 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2219 if ( !file
.Write(buf
, stream
.gcount()) )
2223 while ( !stream
.eof() );
2228 #else // !wxUSE_STD_IOSTREAM
2230 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2232 wxFFile
file(filename
, _T("rb"));
2233 if ( !file
.IsOpened() )
2241 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2245 stream
.Write(buf
, nRead
);
2249 while ( !file
.Eof() );
2254 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2256 wxFFile
file(filename
, _T("wb"));
2257 if ( !file
.IsOpened() )
2263 stream
.Read(buf
, WXSIZEOF(buf
));
2265 const size_t nRead
= stream
.LastRead();
2274 if ( !file
.Write(buf
, nRead
) )
2281 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2283 #endif // wxUSE_DOC_VIEW_ARCHITECTURE