1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/docview.cpp
3 // Purpose: Document/view classes
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_DOC_VIEW_ARCHITECTURE
29 #include "wx/docview.h"
33 #include "wx/string.h"
37 #include "wx/dialog.h"
39 #include "wx/filedlg.h"
42 #include "wx/msgdlg.h"
44 #include "wx/choicdlg.h"
47 #if wxUSE_PRINTING_ARCHITECTURE
48 #include "wx/prntbase.h"
49 #include "wx/printdlg.h"
52 #include "wx/confbase.h"
53 #include "wx/filename.h"
56 #include "wx/cmdproc.h"
57 #include "wx/tokenzr.h"
58 #include "wx/filename.h"
59 #include "wx/stdpaths.h"
60 #include "wx/vector.h"
61 #include "wx/scopedarray.h"
62 #include "wx/scopedptr.h"
64 #if wxUSE_STD_IOSTREAM
65 #include "wx/ioswrap.h"
66 #include "wx/beforestd.h"
72 #include "wx/afterstd.h"
74 #include "wx/wfstream.h"
77 typedef wxVector
<wxDocTemplate
*> wxDocTemplates
;
79 // ----------------------------------------------------------------------------
81 // ----------------------------------------------------------------------------
83 IMPLEMENT_ABSTRACT_CLASS(wxDocument
, wxEvtHandler
)
84 IMPLEMENT_ABSTRACT_CLASS(wxView
, wxEvtHandler
)
85 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate
, wxObject
)
86 IMPLEMENT_DYNAMIC_CLASS(wxDocManager
, wxEvtHandler
)
87 IMPLEMENT_CLASS(wxDocChildFrame
, wxFrame
)
88 IMPLEMENT_CLASS(wxDocParentFrame
, wxFrame
)
90 #if wxUSE_PRINTING_ARCHITECTURE
91 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout
, wxPrintout
)
94 IMPLEMENT_DYNAMIC_CLASS(wxFileHistory
, wxObject
)
96 // ============================================================================
98 // ============================================================================
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
107 wxWindow
*wxFindSuitableParent()
109 wxWindow
* const win
= wxGetTopLevelParent(wxWindow::FindFocus());
111 return win
? win
: wxTheApp
->GetTopWindow();
114 wxString
FindExtension(const wxString
& path
)
117 wxFileName::SplitPath(path
, NULL
, NULL
, &ext
);
119 // VZ: extensions are considered not case sensitive - is this really a good
121 return ext
.MakeLower();
124 // return the string used for the MRU list items in the menu
126 // NB: the index n is 0-based, as usual, but the strings start from 1
127 wxString
GetMRUEntryLabel(int n
, const wxString
& path
)
129 // we need to quote '&' characters which are used for mnemonics
130 wxString
pathInMenu(path
);
131 pathInMenu
.Replace("&", "&&");
133 return wxString::Format("&%d %s", n
+ 1, pathInMenu
);
136 } // anonymous namespace
138 // ----------------------------------------------------------------------------
139 // Definition of wxDocument
140 // ----------------------------------------------------------------------------
142 wxDocument::wxDocument(wxDocument
*parent
)
144 m_documentModified
= false;
145 m_documentParent
= parent
;
146 m_documentTemplate
= NULL
;
147 m_commandProcessor
= NULL
;
151 bool wxDocument::DeleteContents()
156 wxDocument::~wxDocument()
160 delete m_commandProcessor
;
162 if (GetDocumentManager())
163 GetDocumentManager()->RemoveDocument(this);
165 // Not safe to do here, since it'll invoke virtual view functions
166 // expecting to see valid derived objects: and by the time we get here,
167 // we've called destructors higher up.
171 bool wxDocument::Close()
173 if ( !OnSaveModified() )
176 return OnCloseDocument();
179 bool wxDocument::OnCloseDocument()
181 // Tell all views that we're about to close
188 // Note that this implicitly deletes the document when the last view is
190 bool wxDocument::DeleteAllViews()
192 wxDocManager
* manager
= GetDocumentManager();
194 // first check if all views agree to be closed
195 const wxList::iterator end
= m_documentViews
.end();
196 for ( wxList::iterator i
= m_documentViews
.begin(); i
!= end
; ++i
)
198 wxView
*view
= (wxView
*)*i
;
199 if ( !view
->Close() )
203 // all views agreed to close, now do close them
204 if ( m_documentViews
.empty() )
206 // normally the document would be implicitly deleted when the last view
207 // is, but if don't have any views, do it here instead
208 if ( manager
&& manager
->GetDocuments().Member(this) )
213 // as we delete elements we iterate over, don't use the usual "from
214 // begin to end" loop
217 wxView
*view
= (wxView
*)*m_documentViews
.begin();
219 bool isLastOne
= m_documentViews
.size() == 1;
221 // this always deletes the node implicitly and if this is the last
222 // view also deletes this object itself (also implicitly, great),
223 // so we can't test for m_documentViews.empty() after calling this!
234 wxView
*wxDocument::GetFirstView() const
236 if ( m_documentViews
.empty() )
239 return static_cast<wxView
*>(m_documentViews
.GetFirst()->GetData());
242 wxDocManager
*wxDocument::GetDocumentManager() const
244 return m_documentTemplate
? m_documentTemplate
->GetDocumentManager() : NULL
;
247 bool wxDocument::OnNewDocument()
249 if ( !OnSaveModified() )
254 SetDocumentSaved(false);
256 const wxString name
= GetDocumentManager()->MakeNewDocumentName();
258 SetFilename(name
, true);
263 bool wxDocument::Save()
265 if ( AlreadySaved() )
268 if ( m_documentFile
.empty() || !m_savedYet
)
271 return OnSaveDocument(m_documentFile
);
274 bool wxDocument::SaveAs()
276 wxDocTemplate
*docTemplate
= GetDocumentTemplate();
280 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
281 wxString filter
= docTemplate
->GetDescription() + wxT(" (") +
282 docTemplate
->GetFileFilter() + wxT(")|") +
283 docTemplate
->GetFileFilter();
285 // Now see if there are some other template with identical view and document
286 // classes, whose filters may also be used.
287 if (docTemplate
->GetViewClassInfo() && docTemplate
->GetDocClassInfo())
289 wxList::compatibility_iterator
290 node
= docTemplate
->GetDocumentManager()->GetTemplates().GetFirst();
293 wxDocTemplate
*t
= (wxDocTemplate
*) node
->GetData();
295 if (t
->IsVisible() && t
!= docTemplate
&&
296 t
->GetViewClassInfo() == docTemplate
->GetViewClassInfo() &&
297 t
->GetDocClassInfo() == docTemplate
->GetDocClassInfo())
299 // add a '|' to separate this filter from the previous one
300 if ( !filter
.empty() )
303 filter
<< t
->GetDescription()
304 << wxT(" (") << t
->GetFileFilter() << wxT(") |")
305 << t
->GetFileFilter();
308 node
= node
->GetNext();
312 wxString filter
= docTemplate
->GetFileFilter() ;
315 wxString defaultDir
= docTemplate
->GetDirectory();
316 if ( defaultDir
.empty() )
318 defaultDir
= wxPathOnly(GetFilename());
319 if ( defaultDir
.empty() )
320 defaultDir
= GetDocumentManager()->GetLastDirectory();
323 wxString fileName
= wxFileSelector(_("Save As"),
325 wxFileNameFromPath(GetFilename()),
326 docTemplate
->GetDefaultExtension(),
328 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
329 GetDocumentWindow());
331 if (fileName
.empty())
332 return false; // cancelled by user
335 wxFileName::SplitPath(fileName
, NULL
, NULL
, &ext
);
339 fileName
+= wxT(".");
340 fileName
+= docTemplate
->GetDefaultExtension();
343 // Files that were not saved correctly are not added to the FileHistory.
344 if (!OnSaveDocument(fileName
))
347 SetTitle(wxFileNameFromPath(fileName
));
348 SetFilename(fileName
, true); // will call OnChangeFileName automatically
350 // A file that doesn't use the default extension of its document template
351 // cannot be opened via the FileHistory, so we do not add it.
352 if (docTemplate
->FileMatchesTemplate(fileName
))
354 GetDocumentManager()->AddFileToHistory(fileName
);
356 //else: the user will probably not be able to open the file again, so we
357 // could warn about the wrong file-extension here
362 bool wxDocument::OnSaveDocument(const wxString
& file
)
367 if ( !DoSaveDocument(file
) )
372 SetDocumentSaved(true);
373 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
374 wxFileName
fn(file
) ;
375 fn
.MacSetDefaultTypeAndCreator() ;
380 bool wxDocument::OnOpenDocument(const wxString
& file
)
382 if ( !OnSaveModified() )
385 if ( !DoOpenDocument(file
) )
388 SetFilename(file
, true);
397 #if wxUSE_STD_IOSTREAM
398 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
400 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
406 #if wxUSE_STD_IOSTREAM
407 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
409 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
415 bool wxDocument::Revert()
421 // Get title, or filename if no title, else unnamed
422 #if WXWIN_COMPATIBILITY_2_8
423 bool wxDocument::GetPrintableName(wxString
& buf
) const
425 // this function can not only be overridden by the user code but also
426 // called by it so we need to ensure that we return the same thing as
427 // GetUserReadableName() but we can't call it because this would result in
428 // an infinite recursion, hence we use the helper DoGetUserReadableName()
429 buf
= DoGetUserReadableName();
433 #endif // WXWIN_COMPATIBILITY_2_8
435 wxString
wxDocument::GetUserReadableName() const
437 #if WXWIN_COMPATIBILITY_2_8
438 // we need to call the old virtual function to ensure that the overridden
439 // version of it is still called
441 if ( GetPrintableName(name
) )
443 #endif // WXWIN_COMPATIBILITY_2_8
445 return DoGetUserReadableName();
448 wxString
wxDocument::DoGetUserReadableName() const
450 if ( !m_documentTitle
.empty() )
451 return m_documentTitle
;
453 if ( !m_documentFile
.empty() )
454 return wxFileNameFromPath(m_documentFile
);
459 wxWindow
*wxDocument::GetDocumentWindow() const
461 wxView
* const view
= GetFirstView();
463 return view
? view
->GetFrame() : wxTheApp
->GetTopWindow();
466 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
468 return new wxCommandProcessor
;
471 // true if safe to close
472 bool wxDocument::OnSaveModified()
476 switch ( wxMessageBox
480 _("Do you want to save changes to %s?"),
481 GetUserReadableName()
483 wxTheApp
->GetAppDisplayName(),
484 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
,
485 wxFindSuitableParent()
503 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
508 bool wxDocument::AddView(wxView
*view
)
510 if ( !m_documentViews
.Member(view
) )
512 m_documentViews
.Append(view
);
518 bool wxDocument::RemoveView(wxView
*view
)
520 (void)m_documentViews
.DeleteObject(view
);
525 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
527 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
530 // Called after a view is added or removed.
531 // The default implementation deletes the document if
532 // there are no more views.
533 void wxDocument::OnChangedViewList()
535 if ( m_documentViews
.empty() && OnSaveModified() )
539 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
541 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
544 wxView
*view
= (wxView
*)node
->GetData();
546 view
->OnUpdate(sender
, hint
);
547 node
= node
->GetNext();
551 void wxDocument::NotifyClosing()
553 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
556 wxView
*view
= (wxView
*)node
->GetData();
557 view
->OnClosingDocument();
558 node
= node
->GetNext();
562 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
564 m_documentFile
= filename
;
565 OnChangeFilename(notifyViews
);
568 void wxDocument::OnChangeFilename(bool notifyViews
)
572 // Notify the views that the filename has changed
573 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
576 wxView
*view
= (wxView
*)node
->GetData();
577 view
->OnChangeFilename();
578 node
= node
->GetNext();
583 bool wxDocument::DoSaveDocument(const wxString
& file
)
585 #if wxUSE_STD_IOSTREAM
586 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
589 wxFileOutputStream
store(file
);
590 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
593 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
597 if (!SaveObject(store
))
599 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
606 bool wxDocument::DoOpenDocument(const wxString
& file
)
608 #if wxUSE_STD_IOSTREAM
609 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
612 wxFileInputStream
store(file
);
613 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
616 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
620 #if wxUSE_STD_IOSTREAM
624 int res
= LoadObject(store
).GetLastError();
625 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
628 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
636 // ----------------------------------------------------------------------------
638 // ----------------------------------------------------------------------------
642 m_viewDocument
= NULL
;
646 m_docChildFrame
= NULL
;
651 GetDocumentManager()->ActivateView(this, false);
653 // reset our frame view first, before removing it from the document as
654 // SetView(NULL) is a simple call while RemoveView() may result in user
655 // code being executed and this user code can, for example, show a message
656 // box which would result in an activation event for m_docChildFrame and so
657 // could reactivate the view being destroyed -- unless we reset it first
658 if ( m_docChildFrame
&& m_docChildFrame
->GetView() == this )
659 m_docChildFrame
->SetView(NULL
);
661 if ( m_viewDocument
)
662 m_viewDocument
->RemoveView(this);
665 bool wxView::TryBefore(wxEvent
& event
)
667 wxDocument
* const doc
= GetDocument();
668 return doc
&& doc
->ProcessEventHere(event
);
671 void wxView::OnActivateView(bool WXUNUSED(activate
),
672 wxView
*WXUNUSED(activeView
),
673 wxView
*WXUNUSED(deactiveView
))
677 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
682 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
686 void wxView::OnChangeFilename()
688 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
689 // generic MDI implementation so use SetLabel rather than SetTitle.
690 // It should cause SetTitle() for top level windows.
691 wxWindow
*win
= GetFrame();
694 wxDocument
*doc
= GetDocument();
697 win
->SetLabel(doc
->GetUserReadableName());
700 void wxView::SetDocument(wxDocument
*doc
)
702 m_viewDocument
= doc
;
707 bool wxView::Close(bool deleteWindow
)
709 return OnClose(deleteWindow
);
712 void wxView::Activate(bool activate
)
714 if (GetDocument() && GetDocumentManager())
716 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
717 GetDocumentManager()->ActivateView(this, activate
);
721 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
723 return GetDocument() ? GetDocument()->Close() : true;
726 #if wxUSE_PRINTING_ARCHITECTURE
727 wxPrintout
*wxView::OnCreatePrintout()
729 return new wxDocPrintout(this);
731 #endif // wxUSE_PRINTING_ARCHITECTURE
733 // ----------------------------------------------------------------------------
735 // ----------------------------------------------------------------------------
737 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
738 const wxString
& descr
,
739 const wxString
& filter
,
742 const wxString
& docTypeName
,
743 const wxString
& viewTypeName
,
744 wxClassInfo
*docClassInfo
,
745 wxClassInfo
*viewClassInfo
,
748 m_documentManager
= manager
;
749 m_description
= descr
;
752 m_fileFilter
= filter
;
754 m_docTypeName
= docTypeName
;
755 m_viewTypeName
= viewTypeName
;
756 m_documentManager
->AssociateTemplate(this);
758 m_docClassInfo
= docClassInfo
;
759 m_viewClassInfo
= viewClassInfo
;
762 wxDocTemplate::~wxDocTemplate()
764 m_documentManager
->DisassociateTemplate(this);
767 // Tries to dynamically construct an object of the right class.
768 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
770 wxDocument
* const doc
= DoCreateDocument();
772 // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate())
773 // fails, is this intentional?
775 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
779 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
781 doc
->SetFilename(path
);
782 doc
->SetDocumentTemplate(this);
783 GetDocumentManager()->AddDocument(doc
);
784 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
786 if (doc
->OnCreate(path
, flags
))
789 if (GetDocumentManager()->GetDocuments().Member(doc
))
790 doc
->DeleteAllViews();
794 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
796 wxScopedPtr
<wxView
> view(DoCreateView());
800 view
->SetDocument(doc
);
801 if ( !view
->OnCreate(doc
, flags
) )
804 return view
.release();
807 // The default (very primitive) format detection: check is the extension is
808 // that of the template
809 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
811 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
812 wxString anything
= wxT ("*");
813 while (parser
.HasMoreTokens())
815 wxString filter
= parser
.GetNextToken();
816 wxString filterExt
= FindExtension (filter
);
817 if ( filter
.IsSameAs (anything
) ||
818 filterExt
.IsSameAs (anything
) ||
819 filterExt
.IsSameAs (FindExtension (path
)) )
822 return GetDefaultExtension().IsSameAs(FindExtension(path
));
825 wxDocument
*wxDocTemplate::DoCreateDocument()
830 return static_cast<wxDocument
*>(m_docClassInfo
->CreateObject());
833 wxView
*wxDocTemplate::DoCreateView()
835 if (!m_viewClassInfo
)
838 return static_cast<wxView
*>(m_viewClassInfo
->CreateObject());
841 // ----------------------------------------------------------------------------
843 // ----------------------------------------------------------------------------
845 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
846 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
847 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
848 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
849 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
850 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
851 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
852 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
853 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
854 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
856 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
857 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
858 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
859 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateDisableIfNoDoc
)
860 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
861 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
862 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateDisableIfNoDoc
)
863 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
864 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
866 #if wxUSE_PRINTING_ARCHITECTURE
867 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
868 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
870 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
871 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
875 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
877 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
879 wxASSERT_MSG( !sm_docManager
, "multiple wxDocManagers not allowed" );
881 sm_docManager
= this;
883 m_defaultDocumentNameCounter
= 1;
884 m_currentView
= NULL
;
885 m_maxDocsOpen
= INT_MAX
;
886 m_fileHistory
= NULL
;
891 wxDocManager::~wxDocManager()
894 delete m_fileHistory
;
895 sm_docManager
= NULL
;
898 // closes the specified document
899 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
901 if ( !doc
->Close() && !force
)
904 // Implicitly deletes the document when
905 // the last view is deleted
906 doc
->DeleteAllViews();
908 // Check we're really deleted
909 if (m_docs
.Member(doc
))
915 bool wxDocManager::CloseDocuments(bool force
)
917 wxList::compatibility_iterator node
= m_docs
.GetFirst();
920 wxDocument
*doc
= (wxDocument
*)node
->GetData();
921 wxList::compatibility_iterator next
= node
->GetNext();
923 if (!CloseDocument(doc
, force
))
926 // This assumes that documents are not connected in
927 // any way, i.e. deleting one document does NOT
934 bool wxDocManager::Clear(bool force
)
936 if (!CloseDocuments(force
))
939 m_currentView
= NULL
;
941 wxList::compatibility_iterator node
= m_templates
.GetFirst();
944 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
945 wxList::compatibility_iterator next
= node
->GetNext();
952 bool wxDocManager::Initialize()
954 m_fileHistory
= OnCreateFileHistory();
958 wxString
wxDocManager::GetLastDirectory() const
960 // use the system-dependent default location for the document files if
961 // we're being opened for the first time
962 if ( m_lastDirectory
.empty() )
964 wxDocManager
* const self
= const_cast<wxDocManager
*>(this);
965 self
->m_lastDirectory
= wxStandardPaths::Get().GetAppDocumentsDir();
968 return m_lastDirectory
;
971 wxFileHistory
*wxDocManager::OnCreateFileHistory()
973 return new wxFileHistory
;
976 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
978 wxDocument
*doc
= GetCurrentDocument();
983 doc
->DeleteAllViews();
984 if (m_docs
.Member(doc
))
989 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
991 CloseDocuments(false);
994 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
999 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
1001 if ( !CreateDocument("") )
1003 OnOpenFileFailure();
1007 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
1009 wxDocument
*doc
= GetCurrentDocument();
1015 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
1017 wxDocument
*doc
= GetCurrentDocument();
1023 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1025 wxDocument
*doc
= GetCurrentDocument();
1031 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1033 #if wxUSE_PRINTING_ARCHITECTURE
1034 wxView
*view
= GetActiveView();
1038 wxPrintout
*printout
= view
->OnCreatePrintout();
1042 printer
.Print(view
->GetFrame(), printout
, true);
1046 #endif // wxUSE_PRINTING_ARCHITECTURE
1049 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1051 #if wxUSE_PRINTING_ARCHITECTURE
1052 wxView
*view
= GetActiveView();
1056 wxPrintout
*printout
= view
->OnCreatePrintout();
1059 // Pass two printout objects: for preview, and possible printing.
1060 wxPrintPreviewBase
*
1061 preview
= new wxPrintPreview(printout
, view
->OnCreatePrintout());
1062 if ( !preview
->Ok() )
1065 wxLogError(_("Print preview creation failed."));
1070 frame
= new wxPreviewFrame(preview
, wxTheApp
->GetTopWindow(),
1071 _("Print Preview"));
1072 frame
->Centre(wxBOTH
);
1073 frame
->Initialize();
1076 #endif // wxUSE_PRINTING_ARCHITECTURE
1079 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1081 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1091 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1093 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1103 // Handlers for UI update commands
1105 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1107 // CreateDocument() (which is called from OnFileOpen) may succeed
1108 // only when there is at least a template:
1109 event
.Enable( GetTemplates().GetCount()>0 );
1112 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1114 event
.Enable( GetCurrentDocument() != NULL
);
1117 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1119 // CreateDocument() (which is called from OnFileNew) may succeed
1120 // only when there is at least a template:
1121 event
.Enable( GetTemplates().GetCount()>0 );
1124 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1126 wxDocument
* const doc
= GetCurrentDocument();
1127 event
.Enable( doc
&& !doc
->AlreadySaved() );
1130 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1132 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1135 event
.Enable(false);
1139 event
.Enable(cmdproc
->CanUndo());
1140 cmdproc
->SetMenuStrings();
1143 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1145 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1148 event
.Enable(false);
1152 event
.Enable(cmdproc
->CanRedo());
1153 cmdproc
->SetMenuStrings();
1156 wxView
*wxDocManager::GetActiveView() const
1158 wxView
*view
= GetCurrentView();
1160 if ( !view
&& !m_docs
.empty() )
1162 // if we have exactly one document, consider its view to be the current
1165 // VZ: I'm not exactly sure why is this needed but this is how this
1166 // code used to behave before the bug #9518 was fixed and it seems
1167 // safer to preserve the old logic
1168 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1169 if ( !node
->GetNext() )
1171 wxDocument
*doc
= static_cast<wxDocument
*>(node
->GetData());
1172 view
= doc
->GetFirstView();
1174 //else: we have more than one document
1180 bool wxDocManager::TryBefore(wxEvent
& event
)
1182 wxView
* const view
= GetActiveView();
1183 return view
&& view
->ProcessEventHere(event
);
1189 // helper function: return only the visible templates
1190 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1192 // select only the visible templates
1193 const size_t totalNumTemplates
= allTemplates
.GetCount();
1194 wxDocTemplates templates
;
1195 if ( totalNumTemplates
)
1197 templates
.reserve(totalNumTemplates
);
1199 for ( wxList::const_iterator i
= allTemplates
.begin(),
1200 end
= allTemplates
.end();
1204 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1205 if ( temp
->IsVisible() )
1206 templates
.push_back(temp
);
1213 } // anonymous namespace
1215 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1217 // this ought to be const but SelectDocumentType/Path() are not
1218 // const-correct and can't be changed as, being virtual, this risks
1219 // breaking user code overriding them
1220 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1221 const size_t numTemplates
= templates
.size();
1222 if ( !numTemplates
)
1224 // no templates can be used, can't create document
1229 // normally user should select the template to use but wxDOC_SILENT flag we
1230 // choose one ourselves
1231 wxString path
= pathOrig
; // may be modified below
1232 wxDocTemplate
*temp
;
1233 if ( flags
& wxDOC_SILENT
)
1235 wxASSERT_MSG( !path
.empty(),
1236 "using empty path with wxDOC_SILENT doesn't make sense" );
1238 temp
= FindTemplateForPath(path
);
1241 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1245 else // not silent, ask the user
1247 // for the new file we need just the template, for an existing one we
1248 // need the template and the path, unless it's already specified
1249 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1250 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1252 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1258 // check whether the document with this path is already opened
1259 if ( !path
.empty() )
1261 const wxFileName
fn(path
);
1262 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1264 wxDocument
* const doc
= (wxDocument
*)*i
;
1266 if ( fn
== doc
->GetFilename() )
1268 // file already open, just activate it and return
1269 if ( doc
->GetFirstView() )
1271 ActivateView(doc
->GetFirstView());
1272 if ( doc
->GetDocumentWindow() )
1273 doc
->GetDocumentWindow()->SetFocus();
1281 // no, we need to create a new document
1284 // if we've reached the max number of docs, close the first one.
1285 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1287 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1289 // can't open the new document if closing the old one failed
1295 // do create and initialize the new document finally
1296 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1300 docNew
->SetDocumentName(temp
->GetDocumentName());
1301 docNew
->SetDocumentTemplate(temp
);
1303 // call the appropriate function depending on whether we're creating a new
1304 // file or opening an existing one
1305 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1306 : docNew
->OnOpenDocument(path
)) )
1308 // Document is implicitly deleted by DeleteAllViews
1309 docNew
->DeleteAllViews();
1313 // add the successfully opened file to MRU, but only if we're going to be
1314 // able to reopen it successfully later which requires the template for
1315 // this document to be retrievable from the file extension
1316 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1317 AddFileToHistory(path
);
1322 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1324 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1325 const size_t numTemplates
= templates
.size();
1327 if ( numTemplates
== 0 )
1330 wxDocTemplate
* const
1331 temp
= numTemplates
== 1 ? templates
[0]
1332 : SelectViewType(&templates
[0], numTemplates
);
1337 wxView
*view
= temp
->CreateView(doc
, flags
);
1339 view
->SetViewName(temp
->GetViewName());
1343 // Not yet implemented
1345 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1349 // Not yet implemented
1350 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1355 wxDocument
*wxDocManager::GetCurrentDocument() const
1357 wxView
* const view
= GetActiveView();
1358 return view
? view
->GetDocument() : NULL
;
1361 wxCommandProcessor
*wxDocManager::GetCurrentCommandProcessor() const
1363 wxDocument
* const doc
= GetCurrentDocument();
1364 return doc
? doc
->GetCommandProcessor() : NULL
;
1367 // Make a default name for a new document
1368 #if WXWIN_COMPATIBILITY_2_8
1369 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1371 // we consider that this function can only be overridden by the user code,
1372 // not called by it as it only makes sense to call it internally, so we
1373 // don't bother to return anything from here
1376 #endif // WXWIN_COMPATIBILITY_2_8
1378 wxString
wxDocManager::MakeNewDocumentName()
1382 #if WXWIN_COMPATIBILITY_2_8
1383 if ( !MakeDefaultName(name
) )
1384 #endif // WXWIN_COMPATIBILITY_2_8
1386 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1387 m_defaultDocumentNameCounter
++;
1393 // Make a frame title (override this to do something different)
1394 // If docName is empty, a document is not currently active.
1395 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1397 wxString appName
= wxTheApp
->GetAppDisplayName();
1403 wxString docName
= doc
->GetUserReadableName();
1404 title
= docName
+ wxString(_(" - ")) + appName
;
1410 // Not yet implemented
1411 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1416 // File history management
1417 void wxDocManager::AddFileToHistory(const wxString
& file
)
1420 m_fileHistory
->AddFileToHistory(file
);
1423 void wxDocManager::RemoveFileFromHistory(size_t i
)
1426 m_fileHistory
->RemoveFileFromHistory(i
);
1429 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1434 histFile
= m_fileHistory
->GetHistoryFile(i
);
1439 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1442 m_fileHistory
->UseMenu(menu
);
1445 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1448 m_fileHistory
->RemoveMenu(menu
);
1452 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1455 m_fileHistory
->Load(config
);
1458 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1461 m_fileHistory
->Save(config
);
1465 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1468 m_fileHistory
->AddFilesToMenu(menu
);
1471 void wxDocManager::FileHistoryAddFilesToMenu()
1474 m_fileHistory
->AddFilesToMenu();
1477 size_t wxDocManager::GetHistoryFilesCount() const
1479 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1483 // Find out the document template via matching in the document file format
1484 // against that of the template
1485 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1487 wxDocTemplate
*theTemplate
= NULL
;
1489 // Find the template which this extension corresponds to
1490 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1492 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1493 if ( temp
->FileMatchesTemplate(path
) )
1502 // Prompts user to open a file, using file specs in templates.
1503 // Must extend the file selector dialog or implement own; OR
1504 // match the extension to the template extension.
1506 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1509 long WXUNUSED(flags
),
1510 bool WXUNUSED(save
))
1512 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1515 for (int i
= 0; i
< noTemplates
; i
++)
1517 if (templates
[i
]->IsVisible())
1519 // add a '|' to separate this filter from the previous one
1520 if ( !descrBuf
.empty() )
1521 descrBuf
<< wxT('|');
1523 descrBuf
<< templates
[i
]->GetDescription()
1524 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1525 << templates
[i
]->GetFileFilter();
1529 wxString descrBuf
= wxT("*.*");
1530 wxUnusedVar(noTemplates
);
1533 int FilterIndex
= -1;
1535 wxWindow
* parent
= wxFindSuitableParent();
1537 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1545 wxDocTemplate
*theTemplate
= NULL
;
1546 if (!pathTmp
.empty())
1548 if (!wxFileExists(pathTmp
))
1551 if (!wxTheApp
->GetAppDisplayName().empty())
1552 msgTitle
= wxTheApp
->GetAppDisplayName();
1554 msgTitle
= wxString(_("File error"));
1556 wxMessageBox(_("Sorry, could not open this file."),
1558 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
,
1561 path
= wxEmptyString
;
1565 SetLastDirectory(wxPathOnly(pathTmp
));
1569 // first choose the template using the extension, if this fails (i.e.
1570 // wxFileSelectorEx() didn't fill it), then use the path
1571 if ( FilterIndex
!= -1 )
1572 theTemplate
= templates
[FilterIndex
];
1574 theTemplate
= FindTemplateForPath(path
);
1577 // Since we do not add files with non-default extensions to the
1578 // file history this can only happen if the application changes the
1579 // allowed templates in runtime.
1580 wxMessageBox(_("Sorry, the format for this file is unknown."),
1582 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
,
1594 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1595 int noTemplates
, bool sort
)
1597 wxArrayString strings
;
1598 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1602 for (i
= 0; i
< noTemplates
; i
++)
1604 if (templates
[i
]->IsVisible())
1608 for (j
= 0; j
< n
; j
++)
1610 //filter out NOT unique documents + view combinations
1611 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1612 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1619 strings
.Add(templates
[i
]->m_description
);
1621 data
[n
] = templates
[i
];
1629 strings
.Sort(); // ascending sort
1630 // Yes, this will be slow, but template lists
1631 // are typically short.
1633 n
= strings
.Count();
1634 for (i
= 0; i
< n
; i
++)
1636 for (j
= 0; j
< noTemplates
; j
++)
1638 if (strings
[i
] == templates
[j
]->m_description
)
1639 data
[i
] = templates
[j
];
1644 wxDocTemplate
*theTemplate
;
1649 // no visible templates, hence nothing to choose from
1654 // don't propose the user to choose if he has no choice
1655 theTemplate
= data
[0];
1659 // propose the user to choose one of several
1660 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1662 _("Select a document template"),
1665 (void **)data
.get(),
1666 wxFindSuitableParent()
1673 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1674 int noTemplates
, bool sort
)
1676 wxArrayString strings
;
1677 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1681 for (i
= 0; i
< noTemplates
; i
++)
1683 wxDocTemplate
*templ
= templates
[i
];
1684 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1688 for (j
= 0; j
< n
; j
++)
1690 //filter out NOT unique views
1691 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1697 strings
.Add(templ
->m_viewTypeName
);
1706 strings
.Sort(); // ascending sort
1707 // Yes, this will be slow, but template lists
1708 // are typically short.
1710 n
= strings
.Count();
1711 for (i
= 0; i
< n
; i
++)
1713 for (j
= 0; j
< noTemplates
; j
++)
1715 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1716 data
[i
] = templates
[j
];
1721 wxDocTemplate
*theTemplate
;
1723 // the same logic as above
1731 theTemplate
= data
[0];
1735 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1737 _("Select a document view"),
1740 (void **)data
.get(),
1741 wxFindSuitableParent()
1749 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1751 if (!m_templates
.Member(temp
))
1752 m_templates
.Append(temp
);
1755 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1757 m_templates
.DeleteObject(temp
);
1760 // Add and remove a document from the manager's list
1761 void wxDocManager::AddDocument(wxDocument
*doc
)
1763 if (!m_docs
.Member(doc
))
1767 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1769 m_docs
.DeleteObject(doc
);
1772 // Views or windows should inform the document manager
1773 // when a view is going in or out of focus
1774 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1778 m_currentView
= view
;
1782 if ( m_currentView
== view
)
1784 // don't keep stale pointer
1785 m_currentView
= NULL
;
1790 // ----------------------------------------------------------------------------
1791 // wxDocChildFrameAnyBase
1792 // ----------------------------------------------------------------------------
1794 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent
& event
)
1798 if ( event
.CanVeto() && !m_childView
->Close(false) )
1804 m_childView
->Activate(false);
1809 m_childDocument
= NULL
;
1814 // ----------------------------------------------------------------------------
1815 // Default parent frame
1816 // ----------------------------------------------------------------------------
1818 BEGIN_EVENT_TABLE(wxDocParentFrame
, wxFrame
)
1819 EVT_MENU(wxID_EXIT
, wxDocParentFrame::OnExit
)
1820 EVT_MENU_RANGE(wxID_FILE1
, wxID_FILE9
, wxDocParentFrame::OnMRUFile
)
1821 EVT_CLOSE(wxDocParentFrame::OnCloseWindow
)
1824 wxDocParentFrame::wxDocParentFrame()
1826 m_docManager
= NULL
;
1829 wxDocParentFrame::wxDocParentFrame(wxDocManager
*manager
,
1832 const wxString
& title
,
1836 const wxString
& name
)
1837 : wxFrame(frame
, id
, title
, pos
, size
, style
, name
)
1839 m_docManager
= manager
;
1842 bool wxDocParentFrame::Create(wxDocManager
*manager
,
1845 const wxString
& title
,
1849 const wxString
& name
)
1851 m_docManager
= manager
;
1852 return base_type::Create(frame
, id
, title
, pos
, size
, style
, name
);
1855 void wxDocParentFrame::OnExit(wxCommandEvent
& WXUNUSED(event
))
1860 void wxDocParentFrame::OnMRUFile(wxCommandEvent
& event
)
1862 int n
= event
.GetId() - wxID_FILE1
; // the index in MRU list
1863 wxString
filename(m_docManager
->GetHistoryFile(n
));
1864 if ( filename
.empty() )
1867 wxString errMsg
; // must contain exactly one "%s" if non-empty
1868 if ( wxFile::Exists(filename
) )
1871 if ( m_docManager
->CreateDocument(filename
, wxDOC_SILENT
) )
1874 errMsg
= _("The file '%s' couldn't be opened.");
1876 else // file doesn't exist
1878 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1882 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1884 // remove the file which we can't open from the MRU list
1885 m_docManager
->RemoveFileFromHistory(n
);
1887 // and tell the user about it
1888 wxLogError(errMsg
+ '\n' +
1889 _("It has been removed from the most recently used files list."),
1893 // Extend event processing to search the view's event table
1894 bool wxDocParentFrame::TryBefore(wxEvent
& event
)
1896 if ( m_docManager
&& m_docManager
->ProcessEventHere(event
) )
1899 return wxFrame::TryBefore(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
,
1975 int *selPageFrom
, int *selPageTo
)
1983 #endif // wxUSE_PRINTING_ARCHITECTURE
1985 // ----------------------------------------------------------------------------
1986 // File history (a.k.a. MRU, most recently used, files list)
1987 // ----------------------------------------------------------------------------
1989 wxFileHistory::wxFileHistory(size_t maxFiles
, wxWindowID idBase
)
1991 m_fileMaxFiles
= maxFiles
;
1995 void wxFileHistory::AddFileToHistory(const wxString
& file
)
1997 // check if we don't already have this file
1998 const wxFileName
fnNew(file
);
2000 numFiles
= m_fileHistory
.size();
2001 for ( i
= 0; i
< numFiles
; i
++ )
2003 if ( fnNew
== m_fileHistory
[i
] )
2005 // we do have it, move it to the top of the history
2006 RemoveFileFromHistory(i
);
2012 // if we already have a full history, delete the one at the end
2013 if ( numFiles
== m_fileMaxFiles
)
2015 RemoveFileFromHistory(--numFiles
);
2018 // add a new menu item to all file menus (they will be updated below)
2019 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2021 node
= node
->GetNext() )
2023 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2025 if ( !numFiles
&& menu
->GetMenuItemCount() )
2026 menu
->AppendSeparator();
2028 // label doesn't matter, it will be set below anyhow, but it can't
2029 // be empty (this is supposed to indicate a stock item)
2030 menu
->Append(m_idBase
+ numFiles
, " ");
2033 // insert the new file in the beginning of the file history
2034 m_fileHistory
.insert(m_fileHistory
.begin(), file
);
2037 // update the labels in all menus
2038 for ( i
= 0; i
< numFiles
; i
++ )
2040 // if in same directory just show the filename; otherwise the full path
2041 const wxFileName
fnOld(m_fileHistory
[i
]);
2043 wxString pathInMenu
;
2044 if ( fnOld
.GetPath() == fnNew
.GetPath() )
2046 pathInMenu
= fnOld
.GetFullName();
2048 else // file in different directory
2050 // absolute path; could also set relative path
2051 pathInMenu
= m_fileHistory
[i
];
2054 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2056 node
= node
->GetNext() )
2058 wxMenu
* const menu
= (wxMenu
*)node
->GetData();
2060 menu
->SetLabel(m_idBase
+ i
, GetMRUEntryLabel(i
, pathInMenu
));
2065 void wxFileHistory::RemoveFileFromHistory(size_t i
)
2067 size_t numFiles
= m_fileHistory
.size();
2068 wxCHECK_RET( i
< numFiles
,
2069 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2071 // delete the element from the array
2072 m_fileHistory
.RemoveAt(i
);
2075 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2077 node
= node
->GetNext() )
2079 wxMenu
* const menu
= (wxMenu
*) node
->GetData();
2081 // shift filenames up
2082 for ( size_t j
= i
; j
< numFiles
; j
++ )
2084 menu
->SetLabel(m_idBase
+ j
, GetMRUEntryLabel(j
, m_fileHistory
[j
]));
2087 // delete the last menu item which is unused now
2088 const wxWindowID lastItemId
= m_idBase
+ numFiles
;
2089 if ( menu
->FindItem(lastItemId
) )
2090 menu
->Delete(lastItemId
);
2092 // delete the last separator too if no more files are left
2093 if ( m_fileHistory
.empty() )
2095 const wxMenuItemList::compatibility_iterator
2096 nodeLast
= menu
->GetMenuItems().GetLast();
2099 wxMenuItem
* const lastMenuItem
= nodeLast
->GetData();
2100 if ( lastMenuItem
->IsSeparator() )
2101 menu
->Delete(lastMenuItem
);
2103 //else: menu is empty somehow
2108 void wxFileHistory::UseMenu(wxMenu
*menu
)
2110 if ( !m_fileMenus
.Member(menu
) )
2111 m_fileMenus
.Append(menu
);
2114 void wxFileHistory::RemoveMenu(wxMenu
*menu
)
2116 m_fileMenus
.DeleteObject(menu
);
2120 void wxFileHistory::Load(const wxConfigBase
& config
)
2122 m_fileHistory
.Clear();
2125 buf
.Printf(wxT("file%d"), 1);
2127 wxString historyFile
;
2128 while ((m_fileHistory
.GetCount() < m_fileMaxFiles
) &&
2129 config
.Read(buf
, &historyFile
) && !historyFile
.empty())
2131 m_fileHistory
.Add(historyFile
);
2133 buf
.Printf(wxT("file%d"), (int)m_fileHistory
.GetCount()+1);
2134 historyFile
= wxEmptyString
;
2140 void wxFileHistory::Save(wxConfigBase
& config
)
2143 for (i
= 0; i
< m_fileMaxFiles
; i
++)
2146 buf
.Printf(wxT("file%d"), (int)i
+1);
2147 if (i
< m_fileHistory
.GetCount())
2148 config
.Write(buf
, wxString(m_fileHistory
[i
]));
2150 config
.Write(buf
, wxEmptyString
);
2153 #endif // wxUSE_CONFIG
2155 void wxFileHistory::AddFilesToMenu()
2157 if ( m_fileHistory
.empty() )
2160 for ( wxList::compatibility_iterator node
= m_fileMenus
.GetFirst();
2162 node
= node
->GetNext() )
2164 AddFilesToMenu((wxMenu
*) node
->GetData());
2168 void wxFileHistory::AddFilesToMenu(wxMenu
* menu
)
2170 if ( m_fileHistory
.empty() )
2173 if ( menu
->GetMenuItemCount() )
2174 menu
->AppendSeparator();
2176 for ( size_t i
= 0; i
< m_fileHistory
.GetCount(); i
++ )
2178 menu
->Append(m_idBase
+ i
, GetMRUEntryLabel(i
, m_fileHistory
[i
]));
2182 // ----------------------------------------------------------------------------
2183 // Permits compatibility with existing file formats and functions that
2184 // manipulate files directly
2185 // ----------------------------------------------------------------------------
2187 #if wxUSE_STD_IOSTREAM
2189 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2191 wxFFile
file(filename
, _T("rb"));
2192 if ( !file
.IsOpened() )
2200 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2204 stream
.write(buf
, nRead
);
2208 while ( !file
.Eof() );
2213 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2215 wxFFile
file(filename
, _T("wb"));
2216 if ( !file
.IsOpened() )
2222 stream
.read(buf
, WXSIZEOF(buf
));
2223 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2225 if ( !file
.Write(buf
, stream
.gcount()) )
2229 while ( !stream
.eof() );
2234 #else // !wxUSE_STD_IOSTREAM
2236 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2238 wxFFile
file(filename
, _T("rb"));
2239 if ( !file
.IsOpened() )
2247 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2251 stream
.Write(buf
, nRead
);
2255 while ( !file
.Eof() );
2260 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2262 wxFFile
file(filename
, _T("wb"));
2263 if ( !file
.IsOpened() )
2269 stream
.Read(buf
, WXSIZEOF(buf
));
2271 const size_t nRead
= stream
.LastRead();
2280 if ( !file
.Write(buf
, nRead
) )
2287 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2289 #endif // wxUSE_DOC_VIEW_ARCHITECTURE