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
) )
400 if ( m_commandProcessor
)
401 m_commandProcessor
->MarkAsSaved();
405 SetDocumentSaved(true);
406 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
407 wxFileName
fn(file
) ;
408 fn
.MacSetDefaultTypeAndCreator() ;
413 bool wxDocument::OnOpenDocument(const wxString
& file
)
415 // notice that there is no need to check the modified flag here for the
416 // reasons explained in OnNewDocument()
418 if ( !DoOpenDocument(file
) )
421 SetFilename(file
, true);
423 // stretching the logic a little this does make sense because the document
424 // had been saved into the file we just loaded it from, it just could have
425 // happened during a previous program execution, it's just that the name of
426 // this method is a bit unfortunate, it should probably have been called
427 // HasAssociatedFileName()
428 SetDocumentSaved(true);
435 #if wxUSE_STD_IOSTREAM
436 wxSTD istream
& wxDocument::LoadObject(wxSTD istream
& stream
)
438 wxInputStream
& wxDocument::LoadObject(wxInputStream
& stream
)
444 #if wxUSE_STD_IOSTREAM
445 wxSTD ostream
& wxDocument::SaveObject(wxSTD ostream
& stream
)
447 wxOutputStream
& wxDocument::SaveObject(wxOutputStream
& stream
)
453 bool wxDocument::Revert()
457 _("Discard changes and reload the last saved version?"),
458 wxTheApp
->GetAppDisplayName(),
459 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
,
464 if ( !DoOpenDocument(GetFilename()) )
474 // Get title, or filename if no title, else unnamed
475 #if WXWIN_COMPATIBILITY_2_8
476 bool wxDocument::GetPrintableName(wxString
& buf
) const
478 // this function cannot only be overridden by the user code but also
479 // called by it so we need to ensure that we return the same thing as
480 // GetUserReadableName() but we can't call it because this would result in
481 // an infinite recursion, hence we use the helper DoGetUserReadableName()
482 buf
= DoGetUserReadableName();
486 #endif // WXWIN_COMPATIBILITY_2_8
488 wxString
wxDocument::GetUserReadableName() const
490 #if WXWIN_COMPATIBILITY_2_8
491 // we need to call the old virtual function to ensure that the overridden
492 // version of it is still called
494 if ( GetPrintableName(name
) )
496 #endif // WXWIN_COMPATIBILITY_2_8
498 return DoGetUserReadableName();
501 wxString
wxDocument::DoGetUserReadableName() const
503 if ( !m_documentTitle
.empty() )
504 return m_documentTitle
;
506 if ( !m_documentFile
.empty() )
507 return wxFileNameFromPath(m_documentFile
);
512 wxWindow
*wxDocument::GetDocumentWindow() const
514 wxView
* const view
= GetFirstView();
516 return view
? view
->GetFrame() : wxTheApp
->GetTopWindow();
519 wxCommandProcessor
*wxDocument::OnCreateCommandProcessor()
521 return new wxCommandProcessor
;
524 // true if safe to close
525 bool wxDocument::OnSaveModified()
529 switch ( wxMessageBox
533 _("Do you want to save changes to %s?"),
534 GetUserReadableName()
536 wxTheApp
->GetAppDisplayName(),
537 wxYES_NO
| wxCANCEL
| wxICON_QUESTION
| wxCENTRE
555 bool wxDocument::Draw(wxDC
& WXUNUSED(context
))
560 bool wxDocument::AddView(wxView
*view
)
562 if ( !m_documentViews
.Member(view
) )
564 m_documentViews
.Append(view
);
570 bool wxDocument::RemoveView(wxView
*view
)
572 (void)m_documentViews
.DeleteObject(view
);
577 bool wxDocument::OnCreate(const wxString
& WXUNUSED(path
), long flags
)
579 return GetDocumentTemplate()->CreateView(this, flags
) != NULL
;
582 // Called after a view is added or removed.
583 // The default implementation deletes the document if
584 // there are no more views.
585 void wxDocument::OnChangedViewList()
587 if ( m_documentViews
.empty() && OnSaveModified() )
591 void wxDocument::UpdateAllViews(wxView
*sender
, wxObject
*hint
)
593 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
596 wxView
*view
= (wxView
*)node
->GetData();
598 view
->OnUpdate(sender
, hint
);
599 node
= node
->GetNext();
603 void wxDocument::NotifyClosing()
605 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
608 wxView
*view
= (wxView
*)node
->GetData();
609 view
->OnClosingDocument();
610 node
= node
->GetNext();
614 void wxDocument::SetFilename(const wxString
& filename
, bool notifyViews
)
616 m_documentFile
= filename
;
617 OnChangeFilename(notifyViews
);
620 void wxDocument::OnChangeFilename(bool notifyViews
)
624 // Notify the views that the filename has changed
625 wxList::compatibility_iterator node
= m_documentViews
.GetFirst();
628 wxView
*view
= (wxView
*)node
->GetData();
629 view
->OnChangeFilename();
630 node
= node
->GetNext();
635 bool wxDocument::DoSaveDocument(const wxString
& file
)
637 #if wxUSE_STD_IOSTREAM
638 wxSTD ofstream
store(file
.mb_str(), wxSTD
ios::binary
);
641 wxFileOutputStream
store(file
);
642 if ( store
.GetLastError() != wxSTREAM_NO_ERROR
)
645 wxLogError(_("File \"%s\" could not be opened for writing."), file
);
649 if (!SaveObject(store
))
651 wxLogError(_("Failed to save document to the file \"%s\"."), file
);
658 bool wxDocument::DoOpenDocument(const wxString
& file
)
660 #if wxUSE_STD_IOSTREAM
661 wxSTD ifstream
store(file
.mb_str(), wxSTD
ios::binary
);
664 wxFileInputStream
store(file
);
665 if (store
.GetLastError() != wxSTREAM_NO_ERROR
|| !store
.IsOk())
668 wxLogError(_("File \"%s\" could not be opened for reading."), file
);
672 #if wxUSE_STD_IOSTREAM
676 int res
= LoadObject(store
).GetLastError();
677 if ( res
!= wxSTREAM_NO_ERROR
&& res
!= wxSTREAM_EOF
)
680 wxLogError(_("Failed to read document from the file \"%s\"."), file
);
688 // ----------------------------------------------------------------------------
690 // ----------------------------------------------------------------------------
694 m_viewDocument
= NULL
;
698 m_docChildFrame
= NULL
;
703 if (m_viewDocument
&& GetDocumentManager())
704 GetDocumentManager()->ActivateView(this, false);
706 // reset our frame view first, before removing it from the document as
707 // SetView(NULL) is a simple call while RemoveView() may result in user
708 // code being executed and this user code can, for example, show a message
709 // box which would result in an activation event for m_docChildFrame and so
710 // could reactivate the view being destroyed -- unless we reset it first
711 if ( m_docChildFrame
&& m_docChildFrame
->GetView() == this )
713 // prevent it from doing anything with us
714 m_docChildFrame
->SetView(NULL
);
716 // it doesn't make sense to leave the frame alive if its associated
717 // view doesn't exist any more so unconditionally close it as well
719 // notice that we only get here if m_docChildFrame is non-NULL in the
720 // first place and it will be always NULL if we're deleted because our
721 // frame was closed, so this only catches the case of directly deleting
722 // the view, as it happens if its creation fails in wxDocTemplate::
723 // CreateView() for example
724 m_docChildFrame
->GetWindow()->Destroy();
727 if ( m_viewDocument
)
728 m_viewDocument
->RemoveView(this);
731 void wxView::SetDocChildFrame(wxDocChildFrameAnyBase
*docChildFrame
)
733 SetFrame(docChildFrame
? docChildFrame
->GetWindow() : NULL
);
734 m_docChildFrame
= docChildFrame
;
737 bool wxView::TryBefore(wxEvent
& event
)
739 wxDocument
* const doc
= GetDocument();
740 return doc
&& doc
->ProcessEventLocally(event
);
743 void wxView::OnActivateView(bool WXUNUSED(activate
),
744 wxView
*WXUNUSED(activeView
),
745 wxView
*WXUNUSED(deactiveView
))
749 void wxView::OnPrint(wxDC
*dc
, wxObject
*WXUNUSED(info
))
754 void wxView::OnUpdate(wxView
*WXUNUSED(sender
), wxObject
*WXUNUSED(hint
))
758 void wxView::OnChangeFilename()
760 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
761 // generic MDI implementation so use SetLabel rather than SetTitle.
762 // It should cause SetTitle() for top level windows.
763 wxWindow
*win
= GetFrame();
766 wxDocument
*doc
= GetDocument();
769 wxString label
= doc
->GetUserReadableName();
770 if (doc
->IsModified())
774 win
->SetLabel(label
);
777 void wxView::SetDocument(wxDocument
*doc
)
779 m_viewDocument
= doc
;
784 bool wxView::Close(bool deleteWindow
)
786 return OnClose(deleteWindow
);
789 void wxView::Activate(bool activate
)
791 if (GetDocument() && GetDocumentManager())
793 OnActivateView(activate
, this, GetDocumentManager()->GetCurrentView());
794 GetDocumentManager()->ActivateView(this, activate
);
798 bool wxView::OnClose(bool WXUNUSED(deleteWindow
))
800 return GetDocument() ? GetDocument()->Close() : true;
803 #if wxUSE_PRINTING_ARCHITECTURE
804 wxPrintout
*wxView::OnCreatePrintout()
806 return new wxDocPrintout(this);
808 #endif // wxUSE_PRINTING_ARCHITECTURE
810 // ----------------------------------------------------------------------------
812 // ----------------------------------------------------------------------------
814 wxDocTemplate::wxDocTemplate(wxDocManager
*manager
,
815 const wxString
& descr
,
816 const wxString
& filter
,
819 const wxString
& docTypeName
,
820 const wxString
& viewTypeName
,
821 wxClassInfo
*docClassInfo
,
822 wxClassInfo
*viewClassInfo
,
825 m_documentManager
= manager
;
826 m_description
= descr
;
829 m_fileFilter
= filter
;
831 m_docTypeName
= docTypeName
;
832 m_viewTypeName
= viewTypeName
;
833 m_documentManager
->AssociateTemplate(this);
835 m_docClassInfo
= docClassInfo
;
836 m_viewClassInfo
= viewClassInfo
;
839 wxDocTemplate::~wxDocTemplate()
841 m_documentManager
->DisassociateTemplate(this);
844 // Tries to dynamically construct an object of the right class.
845 wxDocument
*wxDocTemplate::CreateDocument(const wxString
& path
, long flags
)
847 // InitDocument() is supposed to delete the document object if its
848 // initialization fails so don't use wxScopedPtr<> here: this is fragile
849 // but unavoidable because the default implementation uses CreateView()
850 // which may -- or not -- create a wxView and if it does create it and its
851 // initialization fails then the view destructor will delete the document
852 // (via RemoveView()) and as we can't distinguish between the two cases we
853 // just have to assume that it always deletes it in case of failure
854 wxDocument
* const doc
= DoCreateDocument();
856 return doc
&& InitDocument(doc
, path
, flags
) ? doc
: NULL
;
860 wxDocTemplate::InitDocument(wxDocument
* doc
, const wxString
& path
, long flags
)
862 doc
->SetFilename(path
);
863 doc
->SetDocumentTemplate(this);
864 GetDocumentManager()->AddDocument(doc
);
865 doc
->SetCommandProcessor(doc
->OnCreateCommandProcessor());
867 if (doc
->OnCreate(path
, flags
))
870 if (GetDocumentManager()->GetDocuments().Member(doc
))
871 doc
->DeleteAllViews();
875 wxView
*wxDocTemplate::CreateView(wxDocument
*doc
, long flags
)
877 wxScopedPtr
<wxView
> view(DoCreateView());
881 view
->SetDocument(doc
);
882 if ( !view
->OnCreate(doc
, flags
) )
885 return view
.release();
888 // The default (very primitive) format detection: check is the extension is
889 // that of the template
890 bool wxDocTemplate::FileMatchesTemplate(const wxString
& path
)
892 wxStringTokenizer
parser (GetFileFilter(), wxT(";"));
893 wxString anything
= wxT ("*");
894 while (parser
.HasMoreTokens())
896 wxString filter
= parser
.GetNextToken();
897 wxString filterExt
= FindExtension (filter
);
898 if ( filter
.IsSameAs (anything
) ||
899 filterExt
.IsSameAs (anything
) ||
900 filterExt
.IsSameAs (FindExtension (path
)) )
903 return GetDefaultExtension().IsSameAs(FindExtension(path
));
906 wxDocument
*wxDocTemplate::DoCreateDocument()
911 return static_cast<wxDocument
*>(m_docClassInfo
->CreateObject());
914 wxView
*wxDocTemplate::DoCreateView()
916 if (!m_viewClassInfo
)
919 return static_cast<wxView
*>(m_viewClassInfo
->CreateObject());
922 // ----------------------------------------------------------------------------
924 // ----------------------------------------------------------------------------
926 BEGIN_EVENT_TABLE(wxDocManager
, wxEvtHandler
)
927 EVT_MENU(wxID_OPEN
, wxDocManager::OnFileOpen
)
928 EVT_MENU(wxID_CLOSE
, wxDocManager::OnFileClose
)
929 EVT_MENU(wxID_CLOSE_ALL
, wxDocManager::OnFileCloseAll
)
930 EVT_MENU(wxID_REVERT
, wxDocManager::OnFileRevert
)
931 EVT_MENU(wxID_NEW
, wxDocManager::OnFileNew
)
932 EVT_MENU(wxID_SAVE
, wxDocManager::OnFileSave
)
933 EVT_MENU(wxID_SAVEAS
, wxDocManager::OnFileSaveAs
)
934 EVT_MENU(wxID_UNDO
, wxDocManager::OnUndo
)
935 EVT_MENU(wxID_REDO
, wxDocManager::OnRedo
)
937 // We don't know in advance how many items can there be in the MRU files
938 // list so set up OnMRUFile() as a handler for all menu events and do the
939 // check for the id of the menu item clicked inside it.
940 EVT_MENU(wxID_ANY
, wxDocManager::OnMRUFile
)
942 EVT_UPDATE_UI(wxID_OPEN
, wxDocManager::OnUpdateFileOpen
)
943 EVT_UPDATE_UI(wxID_CLOSE
, wxDocManager::OnUpdateDisableIfNoDoc
)
944 EVT_UPDATE_UI(wxID_CLOSE_ALL
, wxDocManager::OnUpdateDisableIfNoDoc
)
945 EVT_UPDATE_UI(wxID_REVERT
, wxDocManager::OnUpdateFileRevert
)
946 EVT_UPDATE_UI(wxID_NEW
, wxDocManager::OnUpdateFileNew
)
947 EVT_UPDATE_UI(wxID_SAVE
, wxDocManager::OnUpdateFileSave
)
948 EVT_UPDATE_UI(wxID_SAVEAS
, wxDocManager::OnUpdateFileSaveAs
)
949 EVT_UPDATE_UI(wxID_UNDO
, wxDocManager::OnUpdateUndo
)
950 EVT_UPDATE_UI(wxID_REDO
, wxDocManager::OnUpdateRedo
)
952 #if wxUSE_PRINTING_ARCHITECTURE
953 EVT_MENU(wxID_PRINT
, wxDocManager::OnPrint
)
954 EVT_MENU(wxID_PREVIEW
, wxDocManager::OnPreview
)
955 EVT_MENU(wxID_PRINT_SETUP
, wxDocManager::OnPageSetup
)
957 EVT_UPDATE_UI(wxID_PRINT
, wxDocManager::OnUpdateDisableIfNoDoc
)
958 EVT_UPDATE_UI(wxID_PREVIEW
, wxDocManager::OnUpdateDisableIfNoDoc
)
959 // NB: we keep "Print setup" menu item always enabled as it can be used
960 // even without an active document
961 #endif // wxUSE_PRINTING_ARCHITECTURE
964 wxDocManager
* wxDocManager::sm_docManager
= NULL
;
966 wxDocManager::wxDocManager(long WXUNUSED(flags
), bool initialize
)
968 sm_docManager
= this;
970 m_defaultDocumentNameCounter
= 1;
971 m_currentView
= NULL
;
972 m_maxDocsOpen
= INT_MAX
;
973 m_fileHistory
= NULL
;
978 wxDocManager::~wxDocManager()
981 delete m_fileHistory
;
982 sm_docManager
= NULL
;
985 // closes the specified document
986 bool wxDocManager::CloseDocument(wxDocument
* doc
, bool force
)
988 if ( !doc
->Close() && !force
)
991 // Implicitly deletes the document when
992 // the last view is deleted
993 doc
->DeleteAllViews();
995 // Check we're really deleted
996 if (m_docs
.Member(doc
))
1002 bool wxDocManager::CloseDocuments(bool force
)
1004 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1007 wxDocument
*doc
= (wxDocument
*)node
->GetData();
1008 wxList::compatibility_iterator next
= node
->GetNext();
1010 if (!CloseDocument(doc
, force
))
1013 // This assumes that documents are not connected in
1014 // any way, i.e. deleting one document does NOT
1021 bool wxDocManager::Clear(bool force
)
1023 if (!CloseDocuments(force
))
1026 m_currentView
= NULL
;
1028 wxList::compatibility_iterator node
= m_templates
.GetFirst();
1031 wxDocTemplate
*templ
= (wxDocTemplate
*) node
->GetData();
1032 wxList::compatibility_iterator next
= node
->GetNext();
1039 bool wxDocManager::Initialize()
1041 m_fileHistory
= OnCreateFileHistory();
1045 wxString
wxDocManager::GetLastDirectory() const
1047 // if we haven't determined the last used directory yet, do it now
1048 if ( m_lastDirectory
.empty() )
1050 // we're going to modify m_lastDirectory in this const method, so do it
1051 // via non-const self pointer instead of const this one
1052 wxDocManager
* const self
= const_cast<wxDocManager
*>(this);
1054 // first try to reuse the directory of the most recently opened file:
1055 // this ensures that if the user opens a file, closes the program and
1056 // runs it again the "Open file" dialog will open in the directory of
1057 // the last file he used
1058 if ( m_fileHistory
&& m_fileHistory
->GetCount() )
1060 const wxString lastOpened
= m_fileHistory
->GetHistoryFile(0);
1061 const wxFileName
fn(lastOpened
);
1062 if ( fn
.DirExists() )
1064 self
->m_lastDirectory
= fn
.GetPath();
1066 //else: should we try the next one?
1068 //else: no history yet
1070 // if we don't have any files in the history (yet?), use the
1071 // system-dependent default location for the document files
1072 if ( m_lastDirectory
.empty() )
1074 self
->m_lastDirectory
= wxStandardPaths::Get().GetAppDocumentsDir();
1078 return m_lastDirectory
;
1081 wxFileHistory
*wxDocManager::OnCreateFileHistory()
1083 return new wxFileHistory
;
1086 void wxDocManager::OnFileClose(wxCommandEvent
& WXUNUSED(event
))
1088 wxDocument
*doc
= GetCurrentDocument();
1093 void wxDocManager::OnFileCloseAll(wxCommandEvent
& WXUNUSED(event
))
1095 CloseDocuments(false);
1098 void wxDocManager::OnFileNew(wxCommandEvent
& WXUNUSED(event
))
1100 CreateNewDocument();
1103 void wxDocManager::OnFileOpen(wxCommandEvent
& WXUNUSED(event
))
1105 if ( !CreateDocument("") )
1107 OnOpenFileFailure();
1111 void wxDocManager::OnFileRevert(wxCommandEvent
& WXUNUSED(event
))
1113 wxDocument
*doc
= GetCurrentDocument();
1119 void wxDocManager::OnFileSave(wxCommandEvent
& WXUNUSED(event
))
1121 wxDocument
*doc
= GetCurrentDocument();
1127 void wxDocManager::OnFileSaveAs(wxCommandEvent
& WXUNUSED(event
))
1129 wxDocument
*doc
= GetCurrentDocument();
1135 void wxDocManager::OnMRUFile(wxCommandEvent
& event
)
1137 // Check if the id is in the range assigned to MRU list entries.
1138 const int id
= event
.GetId();
1139 if ( id
>= wxID_FILE1
&&
1140 id
< wxID_FILE1
+ static_cast<int>(m_fileHistory
->GetCount()) )
1142 DoOpenMRUFile(id
- wxID_FILE1
);
1150 void wxDocManager::DoOpenMRUFile(unsigned n
)
1152 wxString
filename(GetHistoryFile(n
));
1153 if ( filename
.empty() )
1156 wxString errMsg
; // must contain exactly one "%s" if non-empty
1157 if ( wxFile::Exists(filename
) )
1159 // Try to open it but don't give an error if it failed: this could be
1160 // normal, e.g. because the user cancelled opening it, and we don't
1161 // have any useful information to put in the error message anyhow, so
1162 // we assume that in case of an error the appropriate message had been
1164 (void)CreateDocument(filename
, wxDOC_SILENT
);
1166 else // file doesn't exist
1168 OnMRUFileNotExist(n
, filename
);
1172 void wxDocManager::OnMRUFileNotExist(unsigned n
, const wxString
& filename
)
1174 // remove the file which we can't open from the MRU list
1175 RemoveFileFromHistory(n
);
1177 // and tell the user about it
1178 wxLogError(_("The file '%s' doesn't exist and couldn't be opened.\n"
1179 "It has been removed from the most recently used files list."),
1183 #if wxUSE_PRINTING_ARCHITECTURE
1185 void wxDocManager::OnPrint(wxCommandEvent
& WXUNUSED(event
))
1187 wxView
*view
= GetActiveView();
1191 wxPrintout
*printout
= view
->OnCreatePrintout();
1194 wxPrintDialogData
printDialogData(m_pageSetupDialogData
.GetPrintData());
1195 wxPrinter
printer(&printDialogData
);
1196 printer
.Print(view
->GetFrame(), printout
, true);
1202 void wxDocManager::OnPageSetup(wxCommandEvent
& WXUNUSED(event
))
1204 wxPageSetupDialog
dlg(wxTheApp
->GetTopWindow(), &m_pageSetupDialogData
);
1205 if ( dlg
.ShowModal() == wxID_OK
)
1207 m_pageSetupDialogData
= dlg
.GetPageSetupData();
1211 wxPreviewFrame
* wxDocManager::CreatePreviewFrame(wxPrintPreviewBase
* preview
,
1213 const wxString
& title
)
1215 return new wxPreviewFrame(preview
, parent
, title
);
1218 void wxDocManager::OnPreview(wxCommandEvent
& WXUNUSED(event
))
1221 wxView
*view
= GetActiveView();
1225 wxPrintout
*printout
= view
->OnCreatePrintout();
1228 wxPrintDialogData
printDialogData(m_pageSetupDialogData
.GetPrintData());
1230 // Pass two printout objects: for preview, and possible printing.
1231 wxPrintPreviewBase
*
1232 preview
= new wxPrintPreview(printout
,
1233 view
->OnCreatePrintout(),
1235 if ( !preview
->IsOk() )
1238 wxLogError(_("Print preview creation failed."));
1242 wxPreviewFrame
* frame
= CreatePreviewFrame(preview
,
1243 wxTheApp
->GetTopWindow(),
1244 _("Print Preview"));
1245 wxCHECK_RET( frame
, "should create a print preview frame" );
1247 frame
->Centre(wxBOTH
);
1248 frame
->Initialize();
1252 #endif // wxUSE_PRINTING_ARCHITECTURE
1254 void wxDocManager::OnUndo(wxCommandEvent
& event
)
1256 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1266 void wxDocManager::OnRedo(wxCommandEvent
& event
)
1268 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1278 // Handlers for UI update commands
1280 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent
& event
)
1282 // CreateDocument() (which is called from OnFileOpen) may succeed
1283 // only when there is at least a template:
1284 event
.Enable( GetTemplates().GetCount()>0 );
1287 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent
& event
)
1289 event
.Enable( GetCurrentDocument() != NULL
);
1292 void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent
& event
)
1294 wxDocument
* doc
= GetCurrentDocument();
1295 event
.Enable(doc
&& doc
->IsModified() && doc
->GetDocumentSaved());
1298 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent
& event
)
1300 // CreateDocument() (which is called from OnFileNew) may succeed
1301 // only when there is at least a template:
1302 event
.Enable( GetTemplates().GetCount()>0 );
1305 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent
& event
)
1307 wxDocument
* const doc
= GetCurrentDocument();
1308 event
.Enable( doc
&& !doc
->IsChildDocument() && !doc
->AlreadySaved() );
1311 void wxDocManager::OnUpdateFileSaveAs(wxUpdateUIEvent
& event
)
1313 wxDocument
* const doc
= GetCurrentDocument();
1314 event
.Enable( doc
&& !doc
->IsChildDocument() );
1317 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent
& event
)
1319 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1322 // If we don't have any document at all, the menu item should really be
1324 if ( !GetCurrentDocument() )
1325 event
.Enable(false);
1326 else // But if we do have it, it might handle wxID_UNDO on its own
1330 event
.Enable(cmdproc
->CanUndo());
1331 cmdproc
->SetMenuStrings();
1334 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent
& event
)
1336 wxCommandProcessor
* const cmdproc
= GetCurrentCommandProcessor();
1339 // Use same logic as in OnUpdateUndo() above.
1340 if ( !GetCurrentDocument() )
1341 event
.Enable(false);
1346 event
.Enable(cmdproc
->CanRedo());
1347 cmdproc
->SetMenuStrings();
1350 wxView
*wxDocManager::GetActiveView() const
1352 wxView
*view
= GetCurrentView();
1354 if ( !view
&& !m_docs
.empty() )
1356 // if we have exactly one document, consider its view to be the current
1359 // VZ: I'm not exactly sure why is this needed but this is how this
1360 // code used to behave before the bug #9518 was fixed and it seems
1361 // safer to preserve the old logic
1362 wxList::compatibility_iterator node
= m_docs
.GetFirst();
1363 if ( !node
->GetNext() )
1365 wxDocument
*doc
= static_cast<wxDocument
*>(node
->GetData());
1366 view
= doc
->GetFirstView();
1368 //else: we have more than one document
1374 bool wxDocManager::TryBefore(wxEvent
& event
)
1376 wxView
* const view
= GetActiveView();
1377 return view
&& view
->ProcessEventLocally(event
);
1383 // helper function: return only the visible templates
1384 wxDocTemplates
GetVisibleTemplates(const wxList
& allTemplates
)
1386 // select only the visible templates
1387 const size_t totalNumTemplates
= allTemplates
.GetCount();
1388 wxDocTemplates templates
;
1389 if ( totalNumTemplates
)
1391 templates
.reserve(totalNumTemplates
);
1393 for ( wxList::const_iterator i
= allTemplates
.begin(),
1394 end
= allTemplates
.end();
1398 wxDocTemplate
* const temp
= (wxDocTemplate
*)*i
;
1399 if ( temp
->IsVisible() )
1400 templates
.push_back(temp
);
1407 } // anonymous namespace
1409 void wxDocManager::ActivateDocument(wxDocument
*doc
)
1411 wxView
* const view
= doc
->GetFirstView();
1415 view
->Activate(true);
1416 if ( wxWindow
*win
= view
->GetFrame() )
1420 wxDocument
*wxDocManager::CreateDocument(const wxString
& pathOrig
, long flags
)
1422 // this ought to be const but SelectDocumentType/Path() are not
1423 // const-correct and can't be changed as, being virtual, this risks
1424 // breaking user code overriding them
1425 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1426 const size_t numTemplates
= templates
.size();
1427 if ( !numTemplates
)
1429 // no templates can be used, can't create document
1434 // normally user should select the template to use but wxDOC_SILENT flag we
1435 // choose one ourselves
1436 wxString path
= pathOrig
; // may be modified below
1437 wxDocTemplate
*temp
;
1438 if ( flags
& wxDOC_SILENT
)
1440 wxASSERT_MSG( !path
.empty(),
1441 "using empty path with wxDOC_SILENT doesn't make sense" );
1443 temp
= FindTemplateForPath(path
);
1446 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1450 else // not silent, ask the user
1452 // for the new file we need just the template, for an existing one we
1453 // need the template and the path, unless it's already specified
1454 if ( (flags
& wxDOC_NEW
) || !path
.empty() )
1455 temp
= SelectDocumentType(&templates
[0], numTemplates
);
1457 temp
= SelectDocumentPath(&templates
[0], numTemplates
, path
, flags
);
1463 // check whether the document with this path is already opened
1464 if ( !path
.empty() )
1466 const wxFileName
fn(path
);
1467 for ( wxList::const_iterator i
= m_docs
.begin(); i
!= m_docs
.end(); ++i
)
1469 wxDocument
* const doc
= (wxDocument
*)*i
;
1471 if ( fn
== doc
->GetFilename() )
1473 // file already open, just activate it and return
1474 ActivateDocument(doc
);
1481 // no, we need to create a new document
1484 // if we've reached the max number of docs, close the first one.
1485 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen
)
1487 if ( !CloseDocument((wxDocument
*)GetDocuments().GetFirst()->GetData()) )
1489 // can't open the new document if closing the old one failed
1495 // do create and initialize the new document finally
1496 wxDocument
* const docNew
= temp
->CreateDocument(path
, flags
);
1500 docNew
->SetDocumentName(temp
->GetDocumentName());
1501 docNew
->SetDocumentTemplate(temp
);
1505 // call the appropriate function depending on whether we're creating a
1506 // new file or opening an existing one
1507 if ( !(flags
& wxDOC_NEW
? docNew
->OnNewDocument()
1508 : docNew
->OnOpenDocument(path
)) )
1510 docNew
->DeleteAllViews();
1514 wxCATCH_ALL( docNew
->DeleteAllViews(); throw; )
1516 // add the successfully opened file to MRU, but only if we're going to be
1517 // able to reopen it successfully later which requires the template for
1518 // this document to be retrievable from the file extension
1519 if ( !(flags
& wxDOC_NEW
) && temp
->FileMatchesTemplate(path
) )
1520 AddFileToHistory(path
);
1522 // at least under Mac (where views are top level windows) it seems to be
1523 // necessary to manually activate the new document to bring it to the
1524 // forefront -- and it shouldn't hurt doing this under the other platforms
1525 ActivateDocument(docNew
);
1530 wxView
*wxDocManager::CreateView(wxDocument
*doc
, long flags
)
1532 wxDocTemplates
templates(GetVisibleTemplates(m_templates
));
1533 const size_t numTemplates
= templates
.size();
1535 if ( numTemplates
== 0 )
1538 wxDocTemplate
* const
1539 temp
= numTemplates
== 1 ? templates
[0]
1540 : SelectViewType(&templates
[0], numTemplates
);
1545 wxView
*view
= temp
->CreateView(doc
, flags
);
1547 view
->SetViewName(temp
->GetViewName());
1551 // Not yet implemented
1553 wxDocManager::DeleteTemplate(wxDocTemplate
*WXUNUSED(temp
), long WXUNUSED(flags
))
1557 // Not yet implemented
1558 bool wxDocManager::FlushDoc(wxDocument
*WXUNUSED(doc
))
1563 wxDocument
*wxDocManager::GetCurrentDocument() const
1565 wxView
* const view
= GetActiveView();
1566 return view
? view
->GetDocument() : NULL
;
1569 wxCommandProcessor
*wxDocManager::GetCurrentCommandProcessor() const
1571 wxDocument
* const doc
= GetCurrentDocument();
1572 return doc
? doc
->GetCommandProcessor() : NULL
;
1575 // Make a default name for a new document
1576 #if WXWIN_COMPATIBILITY_2_8
1577 bool wxDocManager::MakeDefaultName(wxString
& WXUNUSED(name
))
1579 // we consider that this function can only be overridden by the user code,
1580 // not called by it as it only makes sense to call it internally, so we
1581 // don't bother to return anything from here
1584 #endif // WXWIN_COMPATIBILITY_2_8
1586 wxString
wxDocManager::MakeNewDocumentName()
1590 #if WXWIN_COMPATIBILITY_2_8
1591 if ( !MakeDefaultName(name
) )
1592 #endif // WXWIN_COMPATIBILITY_2_8
1594 name
.Printf(_("unnamed%d"), m_defaultDocumentNameCounter
);
1595 m_defaultDocumentNameCounter
++;
1601 // Make a frame title (override this to do something different)
1602 // If docName is empty, a document is not currently active.
1603 wxString
wxDocManager::MakeFrameTitle(wxDocument
* doc
)
1605 wxString appName
= wxTheApp
->GetAppDisplayName();
1611 wxString docName
= doc
->GetUserReadableName();
1612 title
= docName
+ wxString(_(" - ")) + appName
;
1618 // Not yet implemented
1619 wxDocTemplate
*wxDocManager::MatchTemplate(const wxString
& WXUNUSED(path
))
1624 // File history management
1625 void wxDocManager::AddFileToHistory(const wxString
& file
)
1628 m_fileHistory
->AddFileToHistory(file
);
1631 void wxDocManager::RemoveFileFromHistory(size_t i
)
1634 m_fileHistory
->RemoveFileFromHistory(i
);
1637 wxString
wxDocManager::GetHistoryFile(size_t i
) const
1642 histFile
= m_fileHistory
->GetHistoryFile(i
);
1647 void wxDocManager::FileHistoryUseMenu(wxMenu
*menu
)
1650 m_fileHistory
->UseMenu(menu
);
1653 void wxDocManager::FileHistoryRemoveMenu(wxMenu
*menu
)
1656 m_fileHistory
->RemoveMenu(menu
);
1660 void wxDocManager::FileHistoryLoad(const wxConfigBase
& config
)
1663 m_fileHistory
->Load(config
);
1666 void wxDocManager::FileHistorySave(wxConfigBase
& config
)
1669 m_fileHistory
->Save(config
);
1673 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu
* menu
)
1676 m_fileHistory
->AddFilesToMenu(menu
);
1679 void wxDocManager::FileHistoryAddFilesToMenu()
1682 m_fileHistory
->AddFilesToMenu();
1685 size_t wxDocManager::GetHistoryFilesCount() const
1687 return m_fileHistory
? m_fileHistory
->GetCount() : 0;
1691 // Find out the document template via matching in the document file format
1692 // against that of the template
1693 wxDocTemplate
*wxDocManager::FindTemplateForPath(const wxString
& path
)
1695 wxDocTemplate
*theTemplate
= NULL
;
1697 // Find the template which this extension corresponds to
1698 for (size_t i
= 0; i
< m_templates
.GetCount(); i
++)
1700 wxDocTemplate
*temp
= (wxDocTemplate
*)m_templates
.Item(i
)->GetData();
1701 if ( temp
->FileMatchesTemplate(path
) )
1710 // Prompts user to open a file, using file specs in templates.
1711 // Must extend the file selector dialog or implement own; OR
1712 // match the extension to the template extension.
1714 wxDocTemplate
*wxDocManager::SelectDocumentPath(wxDocTemplate
**templates
,
1717 long WXUNUSED(flags
),
1718 bool WXUNUSED(save
))
1720 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1723 for (int i
= 0; i
< noTemplates
; i
++)
1725 if (templates
[i
]->IsVisible())
1727 // add a '|' to separate this filter from the previous one
1728 if ( !descrBuf
.empty() )
1729 descrBuf
<< wxT('|');
1731 descrBuf
<< templates
[i
]->GetDescription()
1732 << wxT(" (") << templates
[i
]->GetFileFilter() << wxT(") |")
1733 << templates
[i
]->GetFileFilter();
1737 wxString descrBuf
= wxT("*.*");
1738 wxUnusedVar(noTemplates
);
1741 int FilterIndex
= -1;
1743 wxString pathTmp
= wxFileSelectorEx(_("Open File"),
1748 wxFD_OPEN
| wxFD_FILE_MUST_EXIST
);
1750 wxDocTemplate
*theTemplate
= NULL
;
1751 if (!pathTmp
.empty())
1753 if (!wxFileExists(pathTmp
))
1756 if (!wxTheApp
->GetAppDisplayName().empty())
1757 msgTitle
= wxTheApp
->GetAppDisplayName();
1759 msgTitle
= wxString(_("File error"));
1761 wxMessageBox(_("Sorry, could not open this file."),
1763 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1765 path
= wxEmptyString
;
1769 SetLastDirectory(wxPathOnly(pathTmp
));
1773 // first choose the template using the extension, if this fails (i.e.
1774 // wxFileSelectorEx() didn't fill it), then use the path
1775 if ( FilterIndex
!= -1 )
1776 theTemplate
= templates
[FilterIndex
];
1778 theTemplate
= FindTemplateForPath(path
);
1781 // Since we do not add files with non-default extensions to the
1782 // file history this can only happen if the application changes the
1783 // allowed templates in runtime.
1784 wxMessageBox(_("Sorry, the format for this file is unknown."),
1786 wxOK
| wxICON_EXCLAMATION
| wxCENTRE
);
1797 wxDocTemplate
*wxDocManager::SelectDocumentType(wxDocTemplate
**templates
,
1798 int noTemplates
, bool sort
)
1800 wxArrayString strings
;
1801 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1805 for (i
= 0; i
< noTemplates
; i
++)
1807 if (templates
[i
]->IsVisible())
1811 for (j
= 0; j
< n
; j
++)
1813 //filter out NOT unique documents + view combinations
1814 if ( templates
[i
]->m_docTypeName
== data
[j
]->m_docTypeName
&&
1815 templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
1822 strings
.Add(templates
[i
]->m_description
);
1824 data
[n
] = templates
[i
];
1832 strings
.Sort(); // ascending sort
1833 // Yes, this will be slow, but template lists
1834 // are typically short.
1836 n
= strings
.Count();
1837 for (i
= 0; i
< n
; i
++)
1839 for (j
= 0; j
< noTemplates
; j
++)
1841 if (strings
[i
] == templates
[j
]->m_description
)
1842 data
[i
] = templates
[j
];
1847 wxDocTemplate
*theTemplate
;
1852 // no visible templates, hence nothing to choose from
1857 // don't propose the user to choose if he has no choice
1858 theTemplate
= data
[0];
1862 // propose the user to choose one of several
1863 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1865 _("Select a document template"),
1875 wxDocTemplate
*wxDocManager::SelectViewType(wxDocTemplate
**templates
,
1876 int noTemplates
, bool sort
)
1878 wxArrayString strings
;
1879 wxScopedArray
<wxDocTemplate
*> data(new wxDocTemplate
*[noTemplates
]);
1883 for (i
= 0; i
< noTemplates
; i
++)
1885 wxDocTemplate
*templ
= templates
[i
];
1886 if ( templ
->IsVisible() && !templ
->GetViewName().empty() )
1890 for (j
= 0; j
< n
; j
++)
1892 //filter out NOT unique views
1893 if ( templates
[i
]->m_viewTypeName
== data
[j
]->m_viewTypeName
)
1899 strings
.Add(templ
->m_viewTypeName
);
1908 strings
.Sort(); // ascending sort
1909 // Yes, this will be slow, but template lists
1910 // are typically short.
1912 n
= strings
.Count();
1913 for (i
= 0; i
< n
; i
++)
1915 for (j
= 0; j
< noTemplates
; j
++)
1917 if (strings
[i
] == templates
[j
]->m_viewTypeName
)
1918 data
[i
] = templates
[j
];
1923 wxDocTemplate
*theTemplate
;
1925 // the same logic as above
1933 theTemplate
= data
[0];
1937 theTemplate
= (wxDocTemplate
*)wxGetSingleChoiceData
1939 _("Select a document view"),
1950 void wxDocManager::AssociateTemplate(wxDocTemplate
*temp
)
1952 if (!m_templates
.Member(temp
))
1953 m_templates
.Append(temp
);
1956 void wxDocManager::DisassociateTemplate(wxDocTemplate
*temp
)
1958 m_templates
.DeleteObject(temp
);
1961 wxDocTemplate
* wxDocManager::FindTemplate(const wxClassInfo
* classinfo
)
1963 for ( wxList::compatibility_iterator node
= m_templates
.GetFirst();
1965 node
= node
->GetNext() )
1967 wxDocTemplate
* t
= wxStaticCast(node
->GetData(), wxDocTemplate
);
1968 if ( t
->GetDocClassInfo() == classinfo
)
1975 // Add and remove a document from the manager's list
1976 void wxDocManager::AddDocument(wxDocument
*doc
)
1978 if (!m_docs
.Member(doc
))
1982 void wxDocManager::RemoveDocument(wxDocument
*doc
)
1984 m_docs
.DeleteObject(doc
);
1987 // Views or windows should inform the document manager
1988 // when a view is going in or out of focus
1989 void wxDocManager::ActivateView(wxView
*view
, bool activate
)
1993 m_currentView
= view
;
1997 if ( m_currentView
== view
)
1999 // don't keep stale pointer
2000 m_currentView
= NULL
;
2005 // ----------------------------------------------------------------------------
2006 // wxDocChildFrameAnyBase
2007 // ----------------------------------------------------------------------------
2009 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent
& event
)
2013 // notice that we must call wxView::Close() and OnClose() called from
2014 // it in any case, even if we know that we are going to close anyhow
2015 if ( !m_childView
->Close(false) && event
.CanVeto() )
2021 m_childView
->Activate(false);
2023 // it is important to reset m_childView frame pointer to NULL before
2024 // deleting it because while normally it is the frame which deletes the
2025 // view when it's closed, the view also closes the frame if it is
2026 // deleted directly not by us as indicated by its doc child frame
2027 // pointer still being set
2028 m_childView
->SetDocChildFrame(NULL
);
2029 wxDELETE(m_childView
);
2032 m_childDocument
= NULL
;
2037 // ----------------------------------------------------------------------------
2038 // wxDocParentFrameAnyBase
2039 // ----------------------------------------------------------------------------
2041 #if wxUSE_PRINTING_ARCHITECTURE
2046 wxString
GetAppropriateTitle(const wxView
*view
, const wxString
& titleGiven
)
2048 wxString
title(titleGiven
);
2049 if ( title
.empty() )
2051 if ( view
&& view
->GetDocument() )
2052 title
= view
->GetDocument()->GetUserReadableName();
2054 title
= _("Printout");
2060 } // anonymous namespace
2062 wxDocPrintout::wxDocPrintout(wxView
*view
, const wxString
& title
)
2063 : wxPrintout(GetAppropriateTitle(view
, title
))
2065 m_printoutView
= view
;
2068 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page
))
2072 // Get the logical pixels per inch of screen and printer
2073 int ppiScreenX
, ppiScreenY
;
2074 GetPPIScreen(&ppiScreenX
, &ppiScreenY
);
2075 wxUnusedVar(ppiScreenY
);
2076 int ppiPrinterX
, ppiPrinterY
;
2077 GetPPIPrinter(&ppiPrinterX
, &ppiPrinterY
);
2078 wxUnusedVar(ppiPrinterY
);
2080 // This scales the DC so that the printout roughly represents the
2081 // the screen scaling. The text point size _should_ be the right size
2082 // but in fact is too small for some reason. This is a detail that will
2083 // need to be addressed at some point but can be fudged for the
2085 float scale
= (float)((float)ppiPrinterX
/(float)ppiScreenX
);
2087 // Now we have to check in case our real page size is reduced
2088 // (e.g. because we're drawing to a print preview memory DC)
2089 int pageWidth
, pageHeight
;
2091 dc
->GetSize(&w
, &h
);
2092 GetPageSizePixels(&pageWidth
, &pageHeight
);
2093 wxUnusedVar(pageHeight
);
2095 // If printer pageWidth == current DC width, then this doesn't
2096 // change. But w might be the preview bitmap width, so scale down.
2097 float overallScale
= scale
* (float)(w
/(float)pageWidth
);
2098 dc
->SetUserScale(overallScale
, overallScale
);
2102 m_printoutView
->OnDraw(dc
);
2107 bool wxDocPrintout::HasPage(int pageNum
)
2109 return (pageNum
== 1);
2112 bool wxDocPrintout::OnBeginDocument(int startPage
, int endPage
)
2114 if (!wxPrintout::OnBeginDocument(startPage
, endPage
))
2120 void wxDocPrintout::GetPageInfo(int *minPage
, int *maxPage
,
2121 int *selPageFrom
, int *selPageTo
)
2129 #endif // wxUSE_PRINTING_ARCHITECTURE
2131 // ----------------------------------------------------------------------------
2132 // Permits compatibility with existing file formats and functions that
2133 // manipulate files directly
2134 // ----------------------------------------------------------------------------
2136 #if wxUSE_STD_IOSTREAM
2138 bool wxTransferFileToStream(const wxString
& filename
, wxSTD ostream
& stream
)
2141 wxFFile
file(filename
, wxT("rb"));
2143 wxFile
file(filename
, wxFile::read
);
2145 if ( !file
.IsOpened() )
2153 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2157 stream
.write(buf
, nRead
);
2161 while ( !file
.Eof() );
2166 bool wxTransferStreamToFile(wxSTD istream
& stream
, const wxString
& filename
)
2169 wxFFile
file(filename
, wxT("wb"));
2171 wxFile
file(filename
, wxFile::write
);
2173 if ( !file
.IsOpened() )
2179 stream
.read(buf
, WXSIZEOF(buf
));
2180 if ( !stream
.bad() ) // fail may be set on EOF, don't use operator!()
2182 if ( !file
.Write(buf
, stream
.gcount()) )
2186 while ( !stream
.eof() );
2191 #else // !wxUSE_STD_IOSTREAM
2193 bool wxTransferFileToStream(const wxString
& filename
, wxOutputStream
& stream
)
2196 wxFFile
file(filename
, wxT("rb"));
2198 wxFile
file(filename
, wxFile::read
);
2200 if ( !file
.IsOpened() )
2208 nRead
= file
.Read(buf
, WXSIZEOF(buf
));
2212 stream
.Write(buf
, nRead
);
2216 while ( !file
.Eof() );
2221 bool wxTransferStreamToFile(wxInputStream
& stream
, const wxString
& filename
)
2224 wxFFile
file(filename
, wxT("wb"));
2226 wxFile
file(filename
, wxFile::write
);
2228 if ( !file
.IsOpened() )
2234 stream
.Read(buf
, WXSIZEOF(buf
));
2236 const size_t nRead
= stream
.LastRead();
2245 if ( !file
.Write(buf
, nRead
) )
2252 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2254 #endif // wxUSE_DOC_VIEW_ARCHITECTURE