1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/docview.cpp
3 // Purpose: Document/view classes
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_DOC_VIEW_ARCHITECTURE
29 #include "wx/docview.h"
33 #include "wx/string.h"
37 #include "wx/dialog.h"
39 #include "wx/filedlg.h"
42 #include "wx/msgdlg.h"
44 #include "wx/choicdlg.h"
47 #if wxUSE_PRINTING_ARCHITECTURE
48 #include "wx/prntbase.h"
49 #include "wx/printdlg.h"
52 #include "wx/confbase.h"
53 #include "wx/filename.h"
56 #include "wx/cmdproc.h"
57 #include "wx/tokenzr.h"
58 #include "wx/filename.h"
59 #include "wx/stdpaths.h"
60 #include "wx/vector.h"
61 #include "wx/scopedarray.h"
62 #include "wx/scopedptr.h"
63 #include "wx/except.h"
65 #if wxUSE_STD_IOSTREAM
66 #include "wx/ioswrap.h"
67 #include "wx/beforestd.h"
73 #include "wx/afterstd.h"
75 #include "wx/wfstream.h"
78 typedef wxVector
<wxDocTemplate
*> wxDocTemplates
;
80 // ----------------------------------------------------------------------------
82 // ----------------------------------------------------------------------------
84 IMPLEMENT_ABSTRACT_CLASS(wxDocument
, wxEvtHandler
)
85 IMPLEMENT_ABSTRACT_CLASS(wxView
, wxEvtHandler
)
86 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate
, wxObject
)
87 IMPLEMENT_DYNAMIC_CLASS(wxDocManager
, wxEvtHandler
)
88 IMPLEMENT_CLASS(wxDocChildFrame
, wxFrame
)
89 IMPLEMENT_CLASS(wxDocParentFrame
, wxFrame
)
91 #if wxUSE_PRINTING_ARCHITECTURE
92 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout
, wxPrintout
)
95 // ============================================================================
97 // ============================================================================
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
106 wxString
FindExtension(const wxString
& path
)
109 wxFileName::SplitPath(path
, NULL
, NULL
, &ext
);
111 // VZ: extensions are considered not case sensitive - is this really a good
113 return ext
.MakeLower();
116 } // anonymous namespace
118 // ----------------------------------------------------------------------------
119 // Definition of wxDocument
120 // ----------------------------------------------------------------------------
122 wxDocument::wxDocument(wxDocument
*parent
)
124 m_documentModified
= false;
125 m_documentTemplate
= NULL
;
127 m_documentParent
= parent
;
129 parent
->m_childDocuments
.push_back(this);
131 m_commandProcessor
= NULL
;
135 bool wxDocument::DeleteContents()
140 wxDocument::~wxDocument()
142 delete m_commandProcessor
;
144 if (GetDocumentManager())
145 GetDocumentManager()->RemoveDocument(this);
147 if ( m_documentParent
)
148 m_documentParent
->m_childDocuments
.remove(this);
150 // Not safe to do here, since it'll invoke virtual view functions
151 // expecting to see valid derived objects: and by the time we get here,
152 // we've called destructors higher up.
156 bool wxDocument::Close()
158 if ( !OnSaveModified() )
161 // When the parent document closes, its children must be closed as well as
162 // they can't exist without the parent.
164 // As usual, first check if all children can be closed.
165 DocsList::const_iterator it
= m_childDocuments
.begin();
166 for ( DocsList::const_iterator end
= m_childDocuments
.end(); it
!= end
; ++it
)
168 if ( !(*it
)->OnSaveModified() )
170 // Leave the parent document opened if a child can't close.
175 // Now that they all did, do close them: as m_childDocuments is modified as
176 // we iterate over it, don't use the usual for-style iteration here.
177 while ( !m_childDocuments
.empty() )
179 wxDocument
* const childDoc
= m_childDocuments
.front();
181 // This will call OnSaveModified() once again but it shouldn't do
182 // anything as the document was just saved or marked as not needing to
183 // be saved by the call to OnSaveModified() that returned true above.
184 if ( !childDoc
->Close() )
186 wxFAIL_MSG( "Closing the child document unexpectedly failed "
187 "after its OnSaveModified() returned true" );
190 // Delete the child document by deleting all its views.
191 childDoc
->DeleteAllViews();
195 return OnCloseDocument();
198 bool wxDocument::OnCloseDocument()
200 // Tell all views that we're about to close
207 // Note that this implicitly deletes the document when the last view is
209 bool wxDocument::DeleteAllViews()
211 wxDocManager
* manager
= GetDocumentManager();
213 // first check if all views agree to be closed
214 const wxList::iterator end
= m_documentViews
.end();
215 for ( wxList::iterator i
= m_documentViews
.begin(); i
!= end
; ++i
)
217 wxView
*view
= (wxView
*)*i
;
218 if ( !view
->Close() )
222 // all views agreed to close, now do close them
223 if ( m_documentViews
.empty() )
225 // normally the document would be implicitly deleted when the last view
226 // is, but if don't have any views, do it here instead
227 if ( manager
&& manager
->GetDocuments().Member(this) )
232 // as we delete elements we iterate over, don't use the usual "from
233 // begin to end" loop
236 wxView
*view
= (wxView
*)*m_documentViews
.begin();
238 bool isLastOne
= m_documentViews
.size() == 1;
240 // this always deletes the node implicitly and if this is the last
241 // view also deletes this object itself (also implicitly, great),
242 // so we can't test for m_documentViews.empty() after calling this!
253 wxView
*wxDocument::GetFirstView() const
255 if ( m_documentViews
.empty() )
258 return static_cast<wxView
*>(m_documentViews
.GetFirst()->GetData());
261 void wxDocument::Modify(bool mod
)
263 if (mod
!= m_documentModified
)
265 m_documentModified
= mod
;
267 // Allow views to append asterix to the title
268 wxView
* view
= GetFirstView();
269 if (view
) view
->OnChangeFilename();
273 wxDocManager
*wxDocument::GetDocumentManager() const
275 // For child documents we use the same document manager as the parent, even
276 // though we don't have our own template (as children are not opened/saved
278 if ( m_documentParent
)
279 return m_documentParent
->GetDocumentManager();
281 return m_documentTemplate
? m_documentTemplate
->GetDocumentManager() : NULL
;
284 bool wxDocument::OnNewDocument()
286 // notice that there is no need to neither reset nor even check the
287 // modified flag here as the document itself is a new object (this is only
288 // called from CreateDocument()) and so it shouldn't be saved anyhow even
289 // if it is modified -- this could happen if the user code creates
290 // documents pre-filled with some user-entered (and which hence must not be
293 SetDocumentSaved(false);
295 const wxString name
= GetDocumentManager()->MakeNewDocumentName();
297 SetFilename(name
, true);
302 bool wxDocument::Save()
304 if ( AlreadySaved() )
307 if ( m_documentFile
.empty() || !m_savedYet
)
310 return OnSaveDocument(m_documentFile
);
313 bool wxDocument::SaveAs()
315 wxDocTemplate
*docTemplate
= GetDocumentTemplate();
319 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
320 wxString filter
= docTemplate
->GetDescription() + wxT(" (") +
321 docTemplate
->GetFileFilter() + wxT(")|") +
322 docTemplate
->GetFileFilter();
324 // Now see if there are some other template with identical view and document
325 // classes, whose filters may also be used.
326 if (docTemplate
->GetViewClassInfo() && docTemplate
->GetDocClassInfo())
328 wxList::compatibility_iterator
329 node
= docTemplate
->GetDocumentManager()->GetTemplates().GetFirst();
332 wxDocTemplate
*t
= (wxDocTemplate
*) node
->GetData();
334 if (t
->IsVisible() && t
!= docTemplate
&&
335 t
->GetViewClassInfo() == docTemplate
->GetViewClassInfo() &&
336 t
->GetDocClassInfo() == docTemplate
->GetDocClassInfo())
338 // add a '|' to separate this filter from the previous one
339 if ( !filter
.empty() )
342 filter
<< t
->GetDescription()
343 << wxT(" (") << t
->GetFileFilter() << wxT(") |")
344 << t
->GetFileFilter();
347 node
= node
->GetNext();
351 wxString filter
= docTemplate
->GetFileFilter() ;
354 wxString defaultDir
= docTemplate
->GetDirectory();
355 if ( defaultDir
.empty() )
357 defaultDir
= wxPathOnly(GetFilename());
358 if ( defaultDir
.empty() )
359 defaultDir
= GetDocumentManager()->GetLastDirectory();
362 wxString fileName
= wxFileSelector(_("Save As"),
364 wxFileNameFromPath(GetFilename()),
365 docTemplate
->GetDefaultExtension(),
367 wxFD_SAVE
| wxFD_OVERWRITE_PROMPT
,
368 GetDocumentWindow());
370 if (fileName
.empty())
371 return false; // cancelled by user
373 // Files that were not saved correctly are not added to the FileHistory.
374 if (!OnSaveDocument(fileName
))
377 SetTitle(wxFileNameFromPath(fileName
));
378 SetFilename(fileName
, true); // will call OnChangeFileName automatically
380 // A file that doesn't use the default extension of its document template
381 // cannot be opened via the FileHistory, so we do not add it.
382 if (docTemplate
->FileMatchesTemplate(fileName
))
384 GetDocumentManager()->AddFileToHistory(fileName
);
386 //else: the user will probably not be able to open the file again, so we
387 // could warn about the wrong file-extension here
392 bool wxDocument::OnSaveDocument(const wxString
& file
)
397 if ( !DoSaveDocument(file
) )
402 SetDocumentSaved(true);
403 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
404 wxFileName
fn(file
) ;
405 fn
.MacSetDefaultTypeAndCreator() ;
410 bool wxDocument::OnOpenDocument(const wxString
& file
)
412 // notice that there is no need to check the modified flag here for the
413 // reasons explained in OnNewDocument()
415 if ( !DoOpenDocument(file
) )
418 SetFilename(file
, true);
420 // stretching the logic a little this does make sense because the document
421 // had been saved into the file we just loaded it from, it just could have
422 // happened during a previous program execution, it's just that the name of
423 // this method is a bit unfortunate, it should probably have been called
424 // HasAssociatedFileName()
425 SetDocumentSaved(true);
432 #if wxUSE_STD_IOSTREAM
433 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
435 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
441 #if wxUSE_STD_IOSTREAM
442 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
444 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
450 bool wxDocument::Revert()
454 _("Discard changes and reload the last saved version?"),
455 wxTheApp
->GetAppDisplayName(),
456 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
,
461 if ( !DoOpenDocument(GetFilename()) )
471 // Get title, or filename if no title, else unnamed
472 #if WXWIN_COMPATIBILITY_2_8
473 bool wxDocument::GetPrintableName(wxString
& buf
) const
475 // this function cannot only be overridden by the user code but also
476 // called by it so we need to ensure that we return the same thing as
477 // GetUserReadableName() but we can't call it because this would result in
478 // an infinite recursion, hence we use the helper DoGetUserReadableName()
479 buf
= DoGetUserReadableName();
483 #endif // WXWIN_COMPATIBILITY_2_8
485 wxString
wxDocument::GetUserReadableName() const
487 #if WXWIN_COMPATIBILITY_2_8
488 // we need to call the old virtual function to ensure that the overridden
489 // version of it is still called
491 if ( GetPrintableName(name
) )
493 #endif // WXWIN_COMPATIBILITY_2_8
495 return DoGetUserReadableName();
498 wxString
wxDocument::DoGetUserReadableName() const
500 if ( !m_documentTitle
.empty() )
501 return m_documentTitle
;
503 if ( !m_documentFile
.empty() )
504 return wxFileNameFromPath(m_documentFile
);
509 wxWindow
*wxDocument::GetDocumentWindow() const
511 wxView
* const view
= GetFirstView();
513 return view
? view
->GetFrame() : wxTheApp
->GetTopWindow();
516 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
518 return new wxCommandProcessor
;
521 // true if safe to close
522 bool wxDocument::OnSaveModified()
526 switch ( wxMessageBox
530 _("Do you want to save changes to %s?"),
531 GetUserReadableName()
533 wxTheApp
->GetAppDisplayName(),
534 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
552 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
557 bool wxDocument::AddView(wxView
*view
)
559 if ( !m_documentViews
.Member(view
) )
561 m_documentViews
.Append(view
);
567 bool wxDocument::RemoveView(wxView
*view
)
569 (void)m_documentViews
.DeleteObject(view
);
574 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
576 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
579 // Called after a view is added or removed.
580 // The default implementation deletes the document if
581 // there are no more views.
582 void wxDocument::OnChangedViewList()
584 if ( m_documentViews
.empty() && OnSaveModified() )
588 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
590 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
593 wxView
*view
= (wxView
*)node
->GetData();
595 view
->OnUpdate(sender
, hint
);
596 node
= node
->GetNext();
600 void wxDocument::NotifyClosing()
602 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
605 wxView
*view
= (wxView
*)node
->GetData();
606 view
->OnClosingDocument();
607 node
= node
->GetNext();
611 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
613 m_documentFile
= filename
;
614 OnChangeFilename(notifyViews
);
617 void wxDocument::OnChangeFilename(bool notifyViews
)
621 // Notify the views that the filename has changed
622 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
625 wxView
*view
= (wxView
*)node
->GetData();
626 view
->OnChangeFilename();
627 node
= node
->GetNext();
632 bool wxDocument::DoSaveDocument(const wxString
& file
)
634 #if wxUSE_STD_IOSTREAM
635 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
638 wxFileOutputStream
store(file
);
639 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
642 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
646 if (!SaveObject(store
))
648 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
655 bool wxDocument::DoOpenDocument(const wxString
& file
)
657 #if wxUSE_STD_IOSTREAM
658 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
661 wxFileInputStream
store(file
);
662 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
665 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
669 #if wxUSE_STD_IOSTREAM
673 int res
= LoadObject(store
).GetLastError();
674 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
677 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
685 // ----------------------------------------------------------------------------
687 // ----------------------------------------------------------------------------
691 m_viewDocument
= NULL
;
695 m_docChildFrame
= NULL
;
700 if (m_viewDocument
&& GetDocumentManager())
701 GetDocumentManager()->ActivateView(this, false);
703 // reset our frame view first, before removing it from the document as
704 // SetView(NULL) is a simple call while RemoveView() may result in user
705 // code being executed and this user code can, for example, show a message
706 // box which would result in an activation event for m_docChildFrame and so
707 // could reactivate the view being destroyed -- unless we reset it first
708 if ( m_docChildFrame
&& m_docChildFrame
->GetView() == this )
710 // prevent it from doing anything with us
711 m_docChildFrame
->SetView(NULL
);
713 // it doesn't make sense to leave the frame alive if its associated
714 // view doesn't exist any more so unconditionally close it as well
716 // notice that we only get here if m_docChildFrame is non-NULL in the
717 // first place and it will be always NULL if we're deleted because our
718 // frame was closed, so this only catches the case of directly deleting
719 // the view, as it happens if its creation fails in wxDocTemplate::
720 // CreateView() for example
721 m_docChildFrame
->GetWindow()->Destroy();
724 if ( m_viewDocument
)
725 m_viewDocument
->RemoveView(this);
728 void wxView::SetDocChildFrame(wxDocChildFrameAnyBase
*docChildFrame
)
730 SetFrame(docChildFrame
? docChildFrame
->GetWindow() : NULL
);
731 m_docChildFrame
= docChildFrame
;
734 bool wxView::TryBefore(wxEvent
& event
)
736 wxDocument
* const doc
= GetDocument();
737 return doc
&& doc
->ProcessEventLocally(event
);
740 void wxView::OnActivateView(bool WXUNUSED(activate
),
741 wxView
*WXUNUSED(activeView
),
742 wxView
*WXUNUSED(deactiveView
))
746 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
751 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
755 void wxView::OnChangeFilename()
757 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
758 // generic MDI implementation so use SetLabel rather than SetTitle.
759 // It should cause SetTitle() for top level windows.
760 wxWindow
*win
= GetFrame();
763 wxDocument
*doc
= GetDocument();
766 wxString label
= doc
->GetUserReadableName();
767 if (doc
->IsModified())
771 win
->SetLabel(label
);
774 void wxView::SetDocument(wxDocument
*doc
)
776 m_viewDocument
= doc
;
781 bool wxView::Close(bool deleteWindow
)
783 return OnClose(deleteWindow
);
786 void wxView::Activate(bool activate
)
788 if (GetDocument() && GetDocumentManager())
790 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
791 GetDocumentManager()->ActivateView(this, activate
);
795 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
797 return GetDocument() ? GetDocument()->Close() : true;
800 #if wxUSE_PRINTING_ARCHITECTURE
801 wxPrintout
*wxView::OnCreatePrintout()
803 return new wxDocPrintout(this);
805 #endif // wxUSE_PRINTING_ARCHITECTURE
807 // ----------------------------------------------------------------------------
809 // ----------------------------------------------------------------------------
811 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
812 const wxString
& descr
,
813 const wxString
& filter
,
816 const wxString
& docTypeName
,
817 const wxString
& viewTypeName
,
818 wxClassInfo
*docClassInfo
,
819 wxClassInfo
*viewClassInfo
,
822 m_documentManager
= manager
;
823 m_description
= descr
;
826 m_fileFilter
= filter
;
828 m_docTypeName
= docTypeName
;
829 m_viewTypeName
= viewTypeName
;
830 m_documentManager
->AssociateTemplate(this);
832 m_docClassInfo
= docClassInfo
;
833 m_viewClassInfo
= viewClassInfo
;
836 wxDocTemplate::~wxDocTemplate()
838 m_documentManager
->DisassociateTemplate(this);
841 // Tries to dynamically construct an object of the right class.
842 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
844 // InitDocument() is supposed to delete the document object if its
845 // initialization fails so don't use wxScopedPtr<> here: this is fragile
846 // but unavoidable because the default implementation uses CreateView()
847 // which may -- or not -- create a wxView and if it does create it and its
848 // initialization fails then the view destructor will delete the document
849 // (via RemoveView()) and as we can't distinguish between the two cases we
850 // just have to assume that it always deletes it in case of failure
851 wxDocument
* const doc
= DoCreateDocument();
853 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
857 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
859 doc
->SetFilename(path
);
860 doc
->SetDocumentTemplate(this);
861 GetDocumentManager()->AddDocument(doc
);
862 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
864 if (doc
->OnCreate(path
, flags
))
867 if (GetDocumentManager()->GetDocuments().Member(doc
))
868 doc
->DeleteAllViews();
872 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
874 wxScopedPtr
<wxView
> view(DoCreateView());
878 view
->SetDocument(doc
);
879 if ( !view
->OnCreate(doc
, flags
) )
882 return view
.release();
885 // The default (very primitive) format detection: check is the extension is
886 // that of the template
887 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
889 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
890 wxString anything
= wxT ("*");
891 while (parser
.HasMoreTokens())
893 wxString filter
= parser
.GetNextToken();
894 wxString filterExt
= FindExtension (filter
);
895 if ( filter
.IsSameAs (anything
) ||
896 filterExt
.IsSameAs (anything
) ||
897 filterExt
.IsSameAs (FindExtension (path
)) )
900 return GetDefaultExtension().IsSameAs(FindExtension(path
));
903 wxDocument
*wxDocTemplate::DoCreateDocument()
908 return static_cast<wxDocument
*>(m_docClassInfo
->CreateObject());
911 wxView
*wxDocTemplate::DoCreateView()
913 if (!m_viewClassInfo
)
916 return static_cast<wxView
*>(m_viewClassInfo
->CreateObject());
919 // ----------------------------------------------------------------------------
921 // ----------------------------------------------------------------------------
923 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
924 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
925 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
926 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
927 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
928 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
929 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
930 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
931 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
932 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
934 // We don't know in advance how many items can there be in the MRU files
935 // list so set up OnMRUFile() as a handler for all menu events and do the
936 // check for the id of the menu item clicked inside it.
937 EVT_MENU(wxID_ANY
, wxDocManager::OnMRUFile
)
939 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
940 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
941 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
942 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateFileRevert
)
943 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
944 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
945 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateFileSaveAs
)
946 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
947 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
949 #if wxUSE_PRINTING_ARCHITECTURE
950 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
951 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
952 EVT_MENU(wxID_PRINT_SETUP
, wxDocManager::OnPageSetup
)
954 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
955 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
956 // NB: we keep "Print setup" menu item always enabled as it can be used
957 // even without an active document
958 #endif // wxUSE_PRINTING_ARCHITECTURE
961 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
963 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
965 sm_docManager
= this;
967 m_defaultDocumentNameCounter
= 1;
968 m_currentView
= NULL
;
969 m_maxDocsOpen
= INT_MAX
;
970 m_fileHistory
= NULL
;
975 wxDocManager::~wxDocManager()
978 delete m_fileHistory
;
979 sm_docManager
= NULL
;
982 // closes the specified document
983 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
985 if ( !doc
->Close() && !force
)
988 // Implicitly deletes the document when
989 // the last view is deleted
990 doc
->DeleteAllViews();
992 // Check we're really deleted
993 if (m_docs
.Member(doc
))
999 bool wxDocManager::CloseDocuments(bool force
)
1001 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1004 wxDocument
*doc
= (wxDocument
*)node
->GetData();
1005 wxList::compatibility_iterator next
= node
->GetNext();
1007 if (!CloseDocument(doc
, force
))
1010 // This assumes that documents are not connected in
1011 // any way, i.e. deleting one document does NOT
1018 bool wxDocManager::Clear(bool force
)
1020 if (!CloseDocuments(force
))
1023 m_currentView
= NULL
;
1025 wxList::compatibility_iterator node
= m_templates
.GetFirst();
1028 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
1029 wxList::compatibility_iterator next
= node
->GetNext();
1036 bool wxDocManager::Initialize()
1038 m_fileHistory
= OnCreateFileHistory();
1042 wxString
wxDocManager::GetLastDirectory() const
1044 // if we haven't determined the last used directory yet, do it now
1045 if ( m_lastDirectory
.empty() )
1047 // we're going to modify m_lastDirectory in this const method, so do it
1048 // via non-const self pointer instead of const this one
1049 wxDocManager
* const self
= const_cast<wxDocManager
*>(this);
1051 // first try to reuse the directory of the most recently opened file:
1052 // this ensures that if the user opens a file, closes the program and
1053 // runs it again the "Open file" dialog will open in the directory of
1054 // the last file he used
1055 if ( m_fileHistory
&& m_fileHistory
->GetCount() )
1057 const wxString lastOpened
= m_fileHistory
->GetHistoryFile(0);
1058 const wxFileName
fn(lastOpened
);
1059 if ( fn
.DirExists() )
1061 self
->m_lastDirectory
= fn
.GetPath();
1063 //else: should we try the next one?
1065 //else: no history yet
1067 // if we don't have any files in the history (yet?), use the
1068 // system-dependent default location for the document files
1069 if ( m_lastDirectory
.empty() )
1071 self
->m_lastDirectory
= wxStandardPaths::Get().GetAppDocumentsDir();
1075 return m_lastDirectory
;
1078 wxFileHistory
*wxDocManager::OnCreateFileHistory()
1080 return new wxFileHistory
;
1083 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
1085 wxDocument
*doc
= GetCurrentDocument();
1090 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
1092 CloseDocuments(false);
1095 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
1097 CreateNewDocument();
1100 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
1102 if ( !CreateDocument("") )
1104 OnOpenFileFailure();
1108 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
1110 wxDocument
*doc
= GetCurrentDocument();
1116 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
1118 wxDocument
*doc
= GetCurrentDocument();
1124 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1126 wxDocument
*doc
= GetCurrentDocument();
1132 void wxDocManager::OnMRUFile(wxCommandEvent
& event
)
1134 // Check if the id is in the range assigned to MRU list entries.
1135 const int id
= event
.GetId();
1136 if ( id
>= wxID_FILE1
&&
1137 id
< wxID_FILE1
+ static_cast<int>(m_fileHistory
->GetCount()) )
1139 DoOpenMRUFile(id
- wxID_FILE1
);
1147 void wxDocManager::DoOpenMRUFile(unsigned n
)
1149 wxString
filename(GetHistoryFile(n
));
1150 if ( filename
.empty() )
1153 wxString errMsg
; // must contain exactly one "%s" if non-empty
1154 if ( wxFile::Exists(filename
) )
1157 if ( CreateDocument(filename
, wxDOC_SILENT
) )
1160 errMsg
= _("The file '%s' couldn't be opened.");
1162 else // file doesn't exist
1164 errMsg
= _("The file '%s' doesn't exist and couldn't be opened.");
1168 wxASSERT_MSG( !errMsg
.empty(), "should have an error message" );
1170 // remove the file which we can't open from the MRU list
1171 RemoveFileFromHistory(n
);
1173 // and tell the user about it
1174 wxLogError(errMsg
+ '\n' +
1175 _("It has been removed from the most recently used files list."),
1179 #if wxUSE_PRINTING_ARCHITECTURE
1181 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1183 wxView
*view
= GetActiveView();
1187 wxPrintout
*printout
= view
->OnCreatePrintout();
1190 wxPrintDialogData
printDialogData(m_pageSetupDialogData
.GetPrintData());
1191 wxPrinter
printer(&printDialogData
);
1192 printer
.Print(view
->GetFrame(), printout
, true);
1198 void wxDocManager::OnPageSetup(wxCommandEvent
& WXUNUSED(event
))
1200 wxPageSetupDialog
dlg(wxTheApp
->GetTopWindow(), &m_pageSetupDialogData
);
1201 if ( dlg
.ShowModal() == wxID_OK
)
1203 m_pageSetupDialogData
= dlg
.GetPageSetupData();
1207 wxPreviewFrame
* wxDocManager::CreatePreviewFrame(wxPrintPreviewBase
* preview
,
1209 const wxString
& title
)
1211 return new wxPreviewFrame(preview
, parent
, title
);
1214 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1217 wxView
*view
= GetActiveView();
1221 wxPrintout
*printout
= view
->OnCreatePrintout();
1224 wxPrintDialogData
printDialogData(m_pageSetupDialogData
.GetPrintData());
1226 // Pass two printout objects: for preview, and possible printing.
1227 wxPrintPreviewBase
*
1228 preview
= new wxPrintPreview(printout
,
1229 view
->OnCreatePrintout(),
1231 if ( !preview
->IsOk() )
1234 wxLogError(_("Print preview creation failed."));
1238 wxPreviewFrame
* frame
= CreatePreviewFrame(preview
,
1239 wxTheApp
->GetTopWindow(),
1240 _("Print Preview"));
1241 wxCHECK_RET( frame
, "should create a print preview frame" );
1243 frame
->Centre(wxBOTH
);
1244 frame
->Initialize();
1248 #endif // wxUSE_PRINTING_ARCHITECTURE
1250 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1252 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1262 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1264 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1274 // Handlers for UI update commands
1276 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1278 // CreateDocument() (which is called from OnFileOpen) may succeed
1279 // only when there is at least a template:
1280 event
.Enable( GetTemplates().GetCount()>0 );
1283 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1285 event
.Enable( GetCurrentDocument() != NULL
);
1288 void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent
& event
)
1290 wxDocument
* doc
= GetCurrentDocument();
1291 event
.Enable(doc
&& doc
->IsModified() && doc
->GetDocumentSaved());
1294 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1296 // CreateDocument() (which is called from OnFileNew) may succeed
1297 // only when there is at least a template:
1298 event
.Enable( GetTemplates().GetCount()>0 );
1301 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1303 wxDocument
* const doc
= GetCurrentDocument();
1304 event
.Enable( doc
&& !doc
->IsChildDocument() && !doc
->AlreadySaved() );
1307 void wxDocManager::OnUpdateFileSaveAs(wxUpdateUIEvent
& event
)
1309 wxDocument
* const doc
= GetCurrentDocument();
1310 event
.Enable( doc
&& !doc
->IsChildDocument() );
1313 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1315 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1318 event
.Enable(false);
1322 event
.Enable(cmdproc
->CanUndo());
1323 cmdproc
->SetMenuStrings();
1326 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1328 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1331 event
.Enable(false);
1335 event
.Enable(cmdproc
->CanRedo());
1336 cmdproc
->SetMenuStrings();
1339 wxView
*wxDocManager::GetActiveView() const
1341 wxView
*view
= GetCurrentView();
1343 if ( !view
&& !m_docs
.empty() )
1345 // if we have exactly one document, consider its view to be the current
1348 // VZ: I'm not exactly sure why is this needed but this is how this
1349 // code used to behave before the bug #9518 was fixed and it seems
1350 // safer to preserve the old logic
1351 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1352 if ( !node
->GetNext() )
1354 wxDocument
*doc
= static_cast<wxDocument
*>(node
->GetData());
1355 view
= doc
->GetFirstView();
1357 //else: we have more than one document
1363 bool wxDocManager::TryBefore(wxEvent
& event
)
1365 wxView
* const view
= GetActiveView();
1366 return view
&& view
->ProcessEventLocally(event
);
1372 // helper function: return only the visible templates
1373 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1375 // select only the visible templates
1376 const size_t totalNumTemplates
= allTemplates
.GetCount();
1377 wxDocTemplates templates
;
1378 if ( totalNumTemplates
)
1380 templates
.reserve(totalNumTemplates
);
1382 for ( wxList::const_iterator i
= allTemplates
.begin(),
1383 end
= allTemplates
.end();
1387 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1388 if ( temp
->IsVisible() )
1389 templates
.push_back(temp
);
1396 } // anonymous namespace
1398 void wxDocManager::ActivateDocument(wxDocument
*doc
)
1400 wxView
* const view
= doc
->GetFirstView();
1404 view
->Activate(true);
1405 if ( wxWindow
*win
= view
->GetFrame() )
1409 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1411 // this ought to be const but SelectDocumentType/Path() are not
1412 // const-correct and can't be changed as, being virtual, this risks
1413 // breaking user code overriding them
1414 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1415 const size_t numTemplates
= templates
.size();
1416 if ( !numTemplates
)
1418 // no templates can be used, can't create document
1423 // normally user should select the template to use but wxDOC_SILENT flag we
1424 // choose one ourselves
1425 wxString path
= pathOrig
; // may be modified below
1426 wxDocTemplate
*temp
;
1427 if ( flags
& wxDOC_SILENT
)
1429 wxASSERT_MSG( !path
.empty(),
1430 "using empty path with wxDOC_SILENT doesn't make sense" );
1432 temp
= FindTemplateForPath(path
);
1435 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1439 else // not silent, ask the user
1441 // for the new file we need just the template, for an existing one we
1442 // need the template and the path, unless it's already specified
1443 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1444 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1446 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1452 // check whether the document with this path is already opened
1453 if ( !path
.empty() )
1455 const wxFileName
fn(path
);
1456 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1458 wxDocument
* const doc
= (wxDocument
*)*i
;
1460 if ( fn
== doc
->GetFilename() )
1462 // file already open, just activate it and return
1463 ActivateDocument(doc
);
1470 // no, we need to create a new document
1473 // if we've reached the max number of docs, close the first one.
1474 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1476 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1478 // can't open the new document if closing the old one failed
1484 // do create and initialize the new document finally
1485 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1489 docNew
->SetDocumentName(temp
->GetDocumentName());
1490 docNew
->SetDocumentTemplate(temp
);
1494 // call the appropriate function depending on whether we're creating a
1495 // new file or opening an existing one
1496 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1497 : docNew
->OnOpenDocument(path
)) )
1499 docNew
->DeleteAllViews();
1503 wxCATCH_ALL( docNew
->DeleteAllViews(); throw; )
1505 // add the successfully opened file to MRU, but only if we're going to be
1506 // able to reopen it successfully later which requires the template for
1507 // this document to be retrievable from the file extension
1508 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1509 AddFileToHistory(path
);
1511 // at least under Mac (where views are top level windows) it seems to be
1512 // necessary to manually activate the new document to bring it to the
1513 // forefront -- and it shouldn't hurt doing this under the other platforms
1514 ActivateDocument(docNew
);
1519 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1521 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1522 const size_t numTemplates
= templates
.size();
1524 if ( numTemplates
== 0 )
1527 wxDocTemplate
* const
1528 temp
= numTemplates
== 1 ? templates
[0]
1529 : SelectViewType(&templates
[0], numTemplates
);
1534 wxView
*view
= temp
->CreateView(doc
, flags
);
1536 view
->SetViewName(temp
->GetViewName());
1540 // Not yet implemented
1542 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1546 // Not yet implemented
1547 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1552 wxDocument
*wxDocManager::GetCurrentDocument() const
1554 wxView
* const view
= GetActiveView();
1555 return view
? view
->GetDocument() : NULL
;
1558 wxCommandProcessor
*wxDocManager::GetCurrentCommandProcessor() const
1560 wxDocument
* const doc
= GetCurrentDocument();
1561 return doc
? doc
->GetCommandProcessor() : NULL
;
1564 // Make a default name for a new document
1565 #if WXWIN_COMPATIBILITY_2_8
1566 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1568 // we consider that this function can only be overridden by the user code,
1569 // not called by it as it only makes sense to call it internally, so we
1570 // don't bother to return anything from here
1573 #endif // WXWIN_COMPATIBILITY_2_8
1575 wxString
wxDocManager::MakeNewDocumentName()
1579 #if WXWIN_COMPATIBILITY_2_8
1580 if ( !MakeDefaultName(name
) )
1581 #endif // WXWIN_COMPATIBILITY_2_8
1583 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1584 m_defaultDocumentNameCounter
++;
1590 // Make a frame title (override this to do something different)
1591 // If docName is empty, a document is not currently active.
1592 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1594 wxString appName
= wxTheApp
->GetAppDisplayName();
1600 wxString docName
= doc
->GetUserReadableName();
1601 title
= docName
+ wxString(_(" - ")) + appName
;
1607 // Not yet implemented
1608 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1613 // File history management
1614 void wxDocManager::AddFileToHistory(const wxString
& file
)
1617 m_fileHistory
->AddFileToHistory(file
);
1620 void wxDocManager::RemoveFileFromHistory(size_t i
)
1623 m_fileHistory
->RemoveFileFromHistory(i
);
1626 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1631 histFile
= m_fileHistory
->GetHistoryFile(i
);
1636 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1639 m_fileHistory
->UseMenu(menu
);
1642 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1645 m_fileHistory
->RemoveMenu(menu
);
1649 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1652 m_fileHistory
->Load(config
);
1655 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1658 m_fileHistory
->Save(config
);
1662 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1665 m_fileHistory
->AddFilesToMenu(menu
);
1668 void wxDocManager::FileHistoryAddFilesToMenu()
1671 m_fileHistory
->AddFilesToMenu();
1674 size_t wxDocManager::GetHistoryFilesCount() const
1676 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1680 // Find out the document template via matching in the document file format
1681 // against that of the template
1682 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1684 wxDocTemplate
*theTemplate
= NULL
;
1686 // Find the template which this extension corresponds to
1687 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1689 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1690 if ( temp
->FileMatchesTemplate(path
) )
1699 // Prompts user to open a file, using file specs in templates.
1700 // Must extend the file selector dialog or implement own; OR
1701 // match the extension to the template extension.
1703 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1706 long WXUNUSED(flags
),
1707 bool WXUNUSED(save
))
1709 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1712 for (int i
= 0; i
< noTemplates
; i
++)
1714 if (templates
[i
]->IsVisible())
1716 // add a '|' to separate this filter from the previous one
1717 if ( !descrBuf
.empty() )
1718 descrBuf
<< wxT('|');
1720 descrBuf
<< templates
[i
]->GetDescription()
1721 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1722 << templates
[i
]->GetFileFilter();
1726 wxString descrBuf
= wxT("*.*");
1727 wxUnusedVar(noTemplates
);
1730 int FilterIndex
= -1;
1732 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1737 wxFD_OPEN
| wxFD_FILE_MUST_EXIST
);
1739 wxDocTemplate
*theTemplate
= NULL
;
1740 if (!pathTmp
.empty())
1742 if (!wxFileExists(pathTmp
))
1745 if (!wxTheApp
->GetAppDisplayName().empty())
1746 msgTitle
= wxTheApp
->GetAppDisplayName();
1748 msgTitle
= wxString(_("File error"));
1750 wxMessageBox(_("Sorry, could not open this file."),
1752 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1754 path
= wxEmptyString
;
1758 SetLastDirectory(wxPathOnly(pathTmp
));
1762 // first choose the template using the extension, if this fails (i.e.
1763 // wxFileSelectorEx() didn't fill it), then use the path
1764 if ( FilterIndex
!= -1 )
1765 theTemplate
= templates
[FilterIndex
];
1767 theTemplate
= FindTemplateForPath(path
);
1770 // Since we do not add files with non-default extensions to the
1771 // file history this can only happen if the application changes the
1772 // allowed templates in runtime.
1773 wxMessageBox(_("Sorry, the format for this file is unknown."),
1775 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1786 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1787 int noTemplates
, bool sort
)
1789 wxArrayString strings
;
1790 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1794 for (i
= 0; i
< noTemplates
; i
++)
1796 if (templates
[i
]->IsVisible())
1800 for (j
= 0; j
< n
; j
++)
1802 //filter out NOT unique documents + view combinations
1803 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1804 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1811 strings
.Add(templates
[i
]->m_description
);
1813 data
[n
] = templates
[i
];
1821 strings
.Sort(); // ascending sort
1822 // Yes, this will be slow, but template lists
1823 // are typically short.
1825 n
= strings
.Count();
1826 for (i
= 0; i
< n
; i
++)
1828 for (j
= 0; j
< noTemplates
; j
++)
1830 if (strings
[i
] == templates
[j
]->m_description
)
1831 data
[i
] = templates
[j
];
1836 wxDocTemplate
*theTemplate
;
1841 // no visible templates, hence nothing to choose from
1846 // don't propose the user to choose if he has no choice
1847 theTemplate
= data
[0];
1851 // propose the user to choose one of several
1852 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1854 _("Select a document template"),
1864 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1865 int noTemplates
, bool sort
)
1867 wxArrayString strings
;
1868 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1872 for (i
= 0; i
< noTemplates
; i
++)
1874 wxDocTemplate
*templ
= templates
[i
];
1875 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1879 for (j
= 0; j
< n
; j
++)
1881 //filter out NOT unique views
1882 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1888 strings
.Add(templ
->m_viewTypeName
);
1897 strings
.Sort(); // ascending sort
1898 // Yes, this will be slow, but template lists
1899 // are typically short.
1901 n
= strings
.Count();
1902 for (i
= 0; i
< n
; i
++)
1904 for (j
= 0; j
< noTemplates
; j
++)
1906 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1907 data
[i
] = templates
[j
];
1912 wxDocTemplate
*theTemplate
;
1914 // the same logic as above
1922 theTemplate
= data
[0];
1926 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1928 _("Select a document view"),
1939 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1941 if (!m_templates
.Member(temp
))
1942 m_templates
.Append(temp
);
1945 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1947 m_templates
.DeleteObject(temp
);
1950 wxDocTemplate
* wxDocManager::FindTemplate(const wxClassInfo
* classinfo
)
1952 for ( wxList::compatibility_iterator node
= m_templates
.GetFirst();
1954 node
= node
->GetNext() )
1956 wxDocTemplate
* t
= wxStaticCast(node
->GetData(), wxDocTemplate
);
1957 if ( t
->GetDocClassInfo() == classinfo
)
1964 // Add and remove a document from the manager's list
1965 void wxDocManager::AddDocument(wxDocument
*doc
)
1967 if (!m_docs
.Member(doc
))
1971 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1973 m_docs
.DeleteObject(doc
);
1976 // Views or windows should inform the document manager
1977 // when a view is going in or out of focus
1978 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1982 m_currentView
= view
;
1986 if ( m_currentView
== view
)
1988 // don't keep stale pointer
1989 m_currentView
= NULL
;
1994 // ----------------------------------------------------------------------------
1995 // wxDocChildFrameAnyBase
1996 // ----------------------------------------------------------------------------
1998 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent
& event
)
2002 // notice that we must call wxView::Close() and OnClose() called from
2003 // it in any case, even if we know that we are going to close anyhow
2004 if ( !m_childView
->Close(false) && event
.CanVeto() )
2010 m_childView
->Activate(false);
2012 // it is important to reset m_childView frame pointer to NULL before
2013 // deleting it because while normally it is the frame which deletes the
2014 // view when it's closed, the view also closes the frame if it is
2015 // deleted directly not by us as indicated by its doc child frame
2016 // pointer still being set
2017 m_childView
->SetDocChildFrame(NULL
);
2018 wxDELETE(m_childView
);
2021 m_childDocument
= NULL
;
2026 // ----------------------------------------------------------------------------
2027 // wxDocParentFrameAnyBase
2028 // ----------------------------------------------------------------------------
2030 #if wxUSE_PRINTING_ARCHITECTURE
2035 wxString
GetAppropriateTitle(const wxView
*view
, const wxString
& titleGiven
)
2037 wxString
title(titleGiven
);
2038 if ( title
.empty() )
2040 if ( view
&& view
->GetDocument() )
2041 title
= view
->GetDocument()->GetUserReadableName();
2043 title
= _("Printout");
2049 } // anonymous namespace
2051 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
2052 : wxPrintout(GetAppropriateTitle(view
, title
))
2054 m_printoutView
= view
;
2057 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
2061 // Get the logical pixels per inch of screen and printer
2062 int ppiScreenX
, ppiScreenY
;
2063 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
2064 wxUnusedVar(ppiScreenY
);
2065 int ppiPrinterX
, ppiPrinterY
;
2066 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
2067 wxUnusedVar(ppiPrinterY
);
2069 // This scales the DC so that the printout roughly represents the
2070 // the screen scaling. The text point size _should_ be the right size
2071 // but in fact is too small for some reason. This is a detail that will
2072 // need to be addressed at some point but can be fudged for the
2074 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
2076 // Now we have to check in case our real page size is reduced
2077 // (e.g. because we're drawing to a print preview memory DC)
2078 int pageWidth
, pageHeight
;
2080 dc
->GetSize(&w
, &h
);
2081 GetPageSizePixels(&pageWidth
, &pageHeight
);
2082 wxUnusedVar(pageHeight
);
2084 // If printer pageWidth == current DC width, then this doesn't
2085 // change. But w might be the preview bitmap width, so scale down.
2086 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
2087 dc
->SetUserScale(overallScale
, overallScale
);
2091 m_printoutView
->OnDraw(dc
);
2096 bool wxDocPrintout::HasPage(int pageNum
)
2098 return (pageNum
== 1);
2101 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
2103 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
2109 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
,
2110 int *selPageFrom
, int *selPageTo
)
2118 #endif // wxUSE_PRINTING_ARCHITECTURE
2120 // ----------------------------------------------------------------------------
2121 // Permits compatibility with existing file formats and functions that
2122 // manipulate files directly
2123 // ----------------------------------------------------------------------------
2125 #if wxUSE_STD_IOSTREAM
2127 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2130 wxFFile
file(filename
, wxT("rb"));
2132 wxFile
file(filename
, wxFile::read
);
2134 if ( !file
.IsOpened() )
2142 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2146 stream
.write(buf
, nRead
);
2150 while ( !file
.Eof() );
2155 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2158 wxFFile
file(filename
, wxT("wb"));
2160 wxFile
file(filename
, wxFile::write
);
2162 if ( !file
.IsOpened() )
2168 stream
.read(buf
, WXSIZEOF(buf
));
2169 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2171 if ( !file
.Write(buf
, stream
.gcount()) )
2175 while ( !stream
.eof() );
2180 #else // !wxUSE_STD_IOSTREAM
2182 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2185 wxFFile
file(filename
, wxT("rb"));
2187 wxFile
file(filename
, wxFile::read
);
2189 if ( !file
.IsOpened() )
2197 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2201 stream
.Write(buf
, nRead
);
2205 while ( !file
.Eof() );
2210 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2213 wxFFile
file(filename
, wxT("wb"));
2215 wxFile
file(filename
, wxFile::write
);
2217 if ( !file
.IsOpened() )
2223 stream
.Read(buf
, WXSIZEOF(buf
));
2225 const size_t nRead
= stream
.LastRead();
2234 if ( !file
.Write(buf
, nRead
) )
2241 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2243 #endif // wxUSE_DOC_VIEW_ARCHITECTURE