Add wxDocManager::Get{Views,Documents,Templates}Vector().
[wxWidgets.git] / src / common / docview.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/docview.cpp
3 // Purpose: Document/view classes
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
6 // Created: 01/02/97
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_DOC_VIEW_ARCHITECTURE
28
29 #include "wx/docview.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/list.h"
33 #include "wx/string.h"
34 #include "wx/utils.h"
35 #include "wx/app.h"
36 #include "wx/dc.h"
37 #include "wx/dialog.h"
38 #include "wx/menu.h"
39 #include "wx/filedlg.h"
40 #include "wx/intl.h"
41 #include "wx/log.h"
42 #include "wx/msgdlg.h"
43 #include "wx/mdi.h"
44 #include "wx/choicdlg.h"
45 #endif
46
47 #if wxUSE_PRINTING_ARCHITECTURE
48 #include "wx/prntbase.h"
49 #include "wx/printdlg.h"
50 #endif
51
52 #include "wx/confbase.h"
53 #include "wx/filename.h"
54 #include "wx/file.h"
55 #include "wx/ffile.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/scopeguard.h"
64 #include "wx/except.h"
65
66 #if wxUSE_STD_IOSTREAM
67 #include "wx/ioswrap.h"
68 #include "wx/beforestd.h"
69 #if wxUSE_IOSTREAMH
70 #include <fstream.h>
71 #else
72 #include <fstream>
73 #endif
74 #include "wx/afterstd.h"
75 #else
76 #include "wx/wfstream.h"
77 #endif
78
79 // ----------------------------------------------------------------------------
80 // wxWidgets macros
81 // ----------------------------------------------------------------------------
82
83 IMPLEMENT_ABSTRACT_CLASS(wxDocument, wxEvtHandler)
84 IMPLEMENT_ABSTRACT_CLASS(wxView, wxEvtHandler)
85 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate, wxObject)
86 IMPLEMENT_DYNAMIC_CLASS(wxDocManager, wxEvtHandler)
87 IMPLEMENT_CLASS(wxDocChildFrame, wxFrame)
88 IMPLEMENT_CLASS(wxDocParentFrame, wxFrame)
89
90 #if wxUSE_PRINTING_ARCHITECTURE
91 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout, wxPrintout)
92 #endif
93
94 // ============================================================================
95 // implementation
96 // ============================================================================
97
98 // ----------------------------------------------------------------------------
99 // private helpers
100 // ----------------------------------------------------------------------------
101
102 namespace
103 {
104
105 wxString FindExtension(const wxString& path)
106 {
107 wxString ext;
108 wxFileName::SplitPath(path, NULL, NULL, &ext);
109
110 // VZ: extensions are considered not case sensitive - is this really a good
111 // idea?
112 return ext.MakeLower();
113 }
114
115 } // anonymous namespace
116
117 // ----------------------------------------------------------------------------
118 // Definition of wxDocument
119 // ----------------------------------------------------------------------------
120
121 wxDocument::wxDocument(wxDocument *parent)
122 {
123 m_documentModified = false;
124 m_documentTemplate = NULL;
125
126 m_documentParent = parent;
127 if ( parent )
128 parent->m_childDocuments.push_back(this);
129
130 m_commandProcessor = NULL;
131 m_savedYet = false;
132 }
133
134 bool wxDocument::DeleteContents()
135 {
136 return true;
137 }
138
139 wxDocument::~wxDocument()
140 {
141 delete m_commandProcessor;
142
143 if (GetDocumentManager())
144 GetDocumentManager()->RemoveDocument(this);
145
146 if ( m_documentParent )
147 m_documentParent->m_childDocuments.remove(this);
148
149 // Not safe to do here, since it'll invoke virtual view functions
150 // expecting to see valid derived objects: and by the time we get here,
151 // we've called destructors higher up.
152 //DeleteAllViews();
153 }
154
155 bool wxDocument::Close()
156 {
157 if ( !OnSaveModified() )
158 return false;
159
160 // When the parent document closes, its children must be closed as well as
161 // they can't exist without the parent.
162
163 // As usual, first check if all children can be closed.
164 DocsList::const_iterator it = m_childDocuments.begin();
165 for ( DocsList::const_iterator end = m_childDocuments.end(); it != end; ++it )
166 {
167 if ( !(*it)->OnSaveModified() )
168 {
169 // Leave the parent document opened if a child can't close.
170 return false;
171 }
172 }
173
174 // Now that they all did, do close them: as m_childDocuments is modified as
175 // we iterate over it, don't use the usual for-style iteration here.
176 while ( !m_childDocuments.empty() )
177 {
178 wxDocument * const childDoc = m_childDocuments.front();
179
180 // This will call OnSaveModified() once again but it shouldn't do
181 // anything as the document was just saved or marked as not needing to
182 // be saved by the call to OnSaveModified() that returned true above.
183 if ( !childDoc->Close() )
184 {
185 wxFAIL_MSG( "Closing the child document unexpectedly failed "
186 "after its OnSaveModified() returned true" );
187 }
188
189 // Delete the child document by deleting all its views.
190 childDoc->DeleteAllViews();
191 }
192
193
194 return OnCloseDocument();
195 }
196
197 bool wxDocument::OnCloseDocument()
198 {
199 // Tell all views that we're about to close
200 NotifyClosing();
201 DeleteContents();
202 Modify(false);
203 return true;
204 }
205
206 // Note that this implicitly deletes the document when the last view is
207 // deleted.
208 bool wxDocument::DeleteAllViews()
209 {
210 wxDocManager* manager = GetDocumentManager();
211
212 // first check if all views agree to be closed
213 const wxList::iterator end = m_documentViews.end();
214 for ( wxList::iterator i = m_documentViews.begin(); i != end; ++i )
215 {
216 wxView *view = (wxView *)*i;
217 if ( !view->Close() )
218 return false;
219 }
220
221 // all views agreed to close, now do close them
222 if ( m_documentViews.empty() )
223 {
224 // normally the document would be implicitly deleted when the last view
225 // is, but if don't have any views, do it here instead
226 if ( manager && manager->GetDocuments().Member(this) )
227 delete this;
228 }
229 else // have views
230 {
231 // as we delete elements we iterate over, don't use the usual "from
232 // begin to end" loop
233 for ( ;; )
234 {
235 wxView *view = (wxView *)*m_documentViews.begin();
236
237 bool isLastOne = m_documentViews.size() == 1;
238
239 // this always deletes the node implicitly and if this is the last
240 // view also deletes this object itself (also implicitly, great),
241 // so we can't test for m_documentViews.empty() after calling this!
242 delete view;
243
244 if ( isLastOne )
245 break;
246 }
247 }
248
249 return true;
250 }
251
252 wxView *wxDocument::GetFirstView() const
253 {
254 if ( m_documentViews.empty() )
255 return NULL;
256
257 return static_cast<wxView *>(m_documentViews.GetFirst()->GetData());
258 }
259
260 void wxDocument::Modify(bool mod)
261 {
262 if (mod != m_documentModified)
263 {
264 m_documentModified = mod;
265
266 // Allow views to append asterix to the title
267 wxView* view = GetFirstView();
268 if (view) view->OnChangeFilename();
269 }
270 }
271
272 wxDocManager *wxDocument::GetDocumentManager() const
273 {
274 // For child documents we use the same document manager as the parent, even
275 // though we don't have our own template (as children are not opened/saved
276 // directly).
277 if ( m_documentParent )
278 return m_documentParent->GetDocumentManager();
279
280 return m_documentTemplate ? m_documentTemplate->GetDocumentManager() : NULL;
281 }
282
283 bool wxDocument::OnNewDocument()
284 {
285 // notice that there is no need to neither reset nor even check the
286 // modified flag here as the document itself is a new object (this is only
287 // called from CreateDocument()) and so it shouldn't be saved anyhow even
288 // if it is modified -- this could happen if the user code creates
289 // documents pre-filled with some user-entered (and which hence must not be
290 // lost) information
291
292 SetDocumentSaved(false);
293
294 const wxString name = GetDocumentManager()->MakeNewDocumentName();
295 SetTitle(name);
296 SetFilename(name, true);
297
298 return true;
299 }
300
301 bool wxDocument::Save()
302 {
303 if ( AlreadySaved() )
304 return true;
305
306 if ( m_documentFile.empty() || !m_savedYet )
307 return SaveAs();
308
309 return OnSaveDocument(m_documentFile);
310 }
311
312 bool wxDocument::SaveAs()
313 {
314 wxDocTemplate *docTemplate = GetDocumentTemplate();
315 if (!docTemplate)
316 return false;
317
318 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
319 wxString filter = docTemplate->GetDescription() + wxT(" (") +
320 docTemplate->GetFileFilter() + wxT(")|") +
321 docTemplate->GetFileFilter();
322
323 // Now see if there are some other template with identical view and document
324 // classes, whose filters may also be used.
325 if (docTemplate->GetViewClassInfo() && docTemplate->GetDocClassInfo())
326 {
327 wxList::compatibility_iterator
328 node = docTemplate->GetDocumentManager()->GetTemplates().GetFirst();
329 while (node)
330 {
331 wxDocTemplate *t = (wxDocTemplate*) node->GetData();
332
333 if (t->IsVisible() && t != docTemplate &&
334 t->GetViewClassInfo() == docTemplate->GetViewClassInfo() &&
335 t->GetDocClassInfo() == docTemplate->GetDocClassInfo())
336 {
337 // add a '|' to separate this filter from the previous one
338 if ( !filter.empty() )
339 filter << wxT('|');
340
341 filter << t->GetDescription()
342 << wxT(" (") << t->GetFileFilter() << wxT(") |")
343 << t->GetFileFilter();
344 }
345
346 node = node->GetNext();
347 }
348 }
349 #else
350 wxString filter = docTemplate->GetFileFilter() ;
351 #endif
352
353 wxString defaultDir = docTemplate->GetDirectory();
354 if ( defaultDir.empty() )
355 {
356 defaultDir = wxPathOnly(GetFilename());
357 if ( defaultDir.empty() )
358 defaultDir = GetDocumentManager()->GetLastDirectory();
359 }
360
361 wxString fileName = wxFileSelector(_("Save As"),
362 defaultDir,
363 wxFileNameFromPath(GetFilename()),
364 docTemplate->GetDefaultExtension(),
365 filter,
366 wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
367 GetDocumentWindow());
368
369 if (fileName.empty())
370 return false; // cancelled by user
371
372 // Files that were not saved correctly are not added to the FileHistory.
373 if (!OnSaveDocument(fileName))
374 return false;
375
376 SetTitle(wxFileNameFromPath(fileName));
377 SetFilename(fileName, true); // will call OnChangeFileName automatically
378
379 // A file that doesn't use the default extension of its document template
380 // cannot be opened via the FileHistory, so we do not add it.
381 if (docTemplate->FileMatchesTemplate(fileName))
382 {
383 GetDocumentManager()->AddFileToHistory(fileName);
384 }
385 //else: the user will probably not be able to open the file again, so we
386 // could warn about the wrong file-extension here
387
388 return true;
389 }
390
391 bool wxDocument::OnSaveDocument(const wxString& file)
392 {
393 if ( !file )
394 return false;
395
396 if ( !DoSaveDocument(file) )
397 return false;
398
399 if ( m_commandProcessor )
400 m_commandProcessor->MarkAsSaved();
401
402 Modify(false);
403 SetFilename(file);
404 SetDocumentSaved(true);
405 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
406 wxFileName fn(file) ;
407 fn.MacSetDefaultTypeAndCreator() ;
408 #endif
409 return true;
410 }
411
412 bool wxDocument::OnOpenDocument(const wxString& file)
413 {
414 // notice that there is no need to check the modified flag here for the
415 // reasons explained in OnNewDocument()
416
417 if ( !DoOpenDocument(file) )
418 return false;
419
420 SetFilename(file, true);
421
422 // stretching the logic a little this does make sense because the document
423 // had been saved into the file we just loaded it from, it just could have
424 // happened during a previous program execution, it's just that the name of
425 // this method is a bit unfortunate, it should probably have been called
426 // HasAssociatedFileName()
427 SetDocumentSaved(true);
428
429 UpdateAllViews();
430
431 return true;
432 }
433
434 #if wxUSE_STD_IOSTREAM
435 wxSTD istream& wxDocument::LoadObject(wxSTD istream& stream)
436 #else
437 wxInputStream& wxDocument::LoadObject(wxInputStream& stream)
438 #endif
439 {
440 return stream;
441 }
442
443 #if wxUSE_STD_IOSTREAM
444 wxSTD ostream& wxDocument::SaveObject(wxSTD ostream& stream)
445 #else
446 wxOutputStream& wxDocument::SaveObject(wxOutputStream& stream)
447 #endif
448 {
449 return stream;
450 }
451
452 bool wxDocument::Revert()
453 {
454 if ( wxMessageBox
455 (
456 _("Discard changes and reload the last saved version?"),
457 wxTheApp->GetAppDisplayName(),
458 wxYES_NO | wxCANCEL | wxICON_QUESTION,
459 GetDocumentWindow()
460 ) != wxYES )
461 return false;
462
463 if ( !DoOpenDocument(GetFilename()) )
464 return false;
465
466 Modify(false);
467 UpdateAllViews();
468
469 return true;
470 }
471
472
473 // Get title, or filename if no title, else unnamed
474 #if WXWIN_COMPATIBILITY_2_8
475 bool wxDocument::GetPrintableName(wxString& buf) const
476 {
477 // this function cannot only be overridden by the user code but also
478 // called by it so we need to ensure that we return the same thing as
479 // GetUserReadableName() but we can't call it because this would result in
480 // an infinite recursion, hence we use the helper DoGetUserReadableName()
481 buf = DoGetUserReadableName();
482
483 return true;
484 }
485 #endif // WXWIN_COMPATIBILITY_2_8
486
487 wxString wxDocument::GetUserReadableName() const
488 {
489 #if WXWIN_COMPATIBILITY_2_8
490 // we need to call the old virtual function to ensure that the overridden
491 // version of it is still called
492 wxString name;
493 if ( GetPrintableName(name) )
494 return name;
495 #endif // WXWIN_COMPATIBILITY_2_8
496
497 return DoGetUserReadableName();
498 }
499
500 wxString wxDocument::DoGetUserReadableName() const
501 {
502 if ( !m_documentTitle.empty() )
503 return m_documentTitle;
504
505 if ( !m_documentFile.empty() )
506 return wxFileNameFromPath(m_documentFile);
507
508 return _("unnamed");
509 }
510
511 wxWindow *wxDocument::GetDocumentWindow() const
512 {
513 wxView * const view = GetFirstView();
514
515 return view ? view->GetFrame() : wxTheApp->GetTopWindow();
516 }
517
518 wxCommandProcessor *wxDocument::OnCreateCommandProcessor()
519 {
520 return new wxCommandProcessor;
521 }
522
523 // true if safe to close
524 bool wxDocument::OnSaveModified()
525 {
526 if ( IsModified() )
527 {
528 switch ( wxMessageBox
529 (
530 wxString::Format
531 (
532 _("Do you want to save changes to %s?"),
533 GetUserReadableName()
534 ),
535 wxTheApp->GetAppDisplayName(),
536 wxYES_NO | wxCANCEL | wxICON_QUESTION | wxCENTRE
537 ) )
538 {
539 case wxNO:
540 Modify(false);
541 break;
542
543 case wxYES:
544 return Save();
545
546 case wxCANCEL:
547 return false;
548 }
549 }
550
551 return true;
552 }
553
554 bool wxDocument::Draw(wxDC& WXUNUSED(context))
555 {
556 return true;
557 }
558
559 bool wxDocument::AddView(wxView *view)
560 {
561 if ( !m_documentViews.Member(view) )
562 {
563 m_documentViews.Append(view);
564 OnChangedViewList();
565 }
566 return true;
567 }
568
569 bool wxDocument::RemoveView(wxView *view)
570 {
571 (void)m_documentViews.DeleteObject(view);
572 OnChangedViewList();
573 return true;
574 }
575
576 bool wxDocument::OnCreate(const wxString& WXUNUSED(path), long flags)
577 {
578 return GetDocumentTemplate()->CreateView(this, flags) != NULL;
579 }
580
581 // Called after a view is added or removed.
582 // The default implementation deletes the document if
583 // there are no more views.
584 void wxDocument::OnChangedViewList()
585 {
586 if ( m_documentViews.empty() && OnSaveModified() )
587 delete this;
588 }
589
590 void wxDocument::UpdateAllViews(wxView *sender, wxObject *hint)
591 {
592 wxList::compatibility_iterator node = m_documentViews.GetFirst();
593 while (node)
594 {
595 wxView *view = (wxView *)node->GetData();
596 if (view != sender)
597 view->OnUpdate(sender, hint);
598 node = node->GetNext();
599 }
600 }
601
602 void wxDocument::NotifyClosing()
603 {
604 wxList::compatibility_iterator node = m_documentViews.GetFirst();
605 while (node)
606 {
607 wxView *view = (wxView *)node->GetData();
608 view->OnClosingDocument();
609 node = node->GetNext();
610 }
611 }
612
613 void wxDocument::SetFilename(const wxString& filename, bool notifyViews)
614 {
615 m_documentFile = filename;
616 OnChangeFilename(notifyViews);
617 }
618
619 void wxDocument::OnChangeFilename(bool notifyViews)
620 {
621 if ( notifyViews )
622 {
623 // Notify the views that the filename has changed
624 wxList::compatibility_iterator node = m_documentViews.GetFirst();
625 while (node)
626 {
627 wxView *view = (wxView *)node->GetData();
628 view->OnChangeFilename();
629 node = node->GetNext();
630 }
631 }
632 }
633
634 bool wxDocument::DoSaveDocument(const wxString& file)
635 {
636 #if wxUSE_STD_IOSTREAM
637 wxSTD ofstream store(file.mb_str(), wxSTD ios::binary);
638 if ( !store )
639 #else
640 wxFileOutputStream store(file);
641 if ( store.GetLastError() != wxSTREAM_NO_ERROR )
642 #endif
643 {
644 wxLogError(_("File \"%s\" could not be opened for writing."), file);
645 return false;
646 }
647
648 if (!SaveObject(store))
649 {
650 wxLogError(_("Failed to save document to the file \"%s\"."), file);
651 return false;
652 }
653
654 return true;
655 }
656
657 bool wxDocument::DoOpenDocument(const wxString& file)
658 {
659 #if wxUSE_STD_IOSTREAM
660 wxSTD ifstream store(file.mb_str(), wxSTD ios::binary);
661 if ( !store )
662 #else
663 wxFileInputStream store(file);
664 if (store.GetLastError() != wxSTREAM_NO_ERROR || !store.IsOk())
665 #endif
666 {
667 wxLogError(_("File \"%s\" could not be opened for reading."), file);
668 return false;
669 }
670
671 #if wxUSE_STD_IOSTREAM
672 LoadObject(store);
673 if ( !store )
674 #else
675 int res = LoadObject(store).GetLastError();
676 if ( res != wxSTREAM_NO_ERROR && res != wxSTREAM_EOF )
677 #endif
678 {
679 wxLogError(_("Failed to read document from the file \"%s\"."), file);
680 return false;
681 }
682
683 return true;
684 }
685
686
687 // ----------------------------------------------------------------------------
688 // Document view
689 // ----------------------------------------------------------------------------
690
691 wxView::wxView()
692 {
693 m_viewDocument = NULL;
694
695 m_viewFrame = NULL;
696
697 m_docChildFrame = NULL;
698 }
699
700 wxView::~wxView()
701 {
702 if (m_viewDocument && GetDocumentManager())
703 GetDocumentManager()->ActivateView(this, false);
704
705 // reset our frame view first, before removing it from the document as
706 // SetView(NULL) is a simple call while RemoveView() may result in user
707 // code being executed and this user code can, for example, show a message
708 // box which would result in an activation event for m_docChildFrame and so
709 // could reactivate the view being destroyed -- unless we reset it first
710 if ( m_docChildFrame && m_docChildFrame->GetView() == this )
711 {
712 // prevent it from doing anything with us
713 m_docChildFrame->SetView(NULL);
714
715 // it doesn't make sense to leave the frame alive if its associated
716 // view doesn't exist any more so unconditionally close it as well
717 //
718 // notice that we only get here if m_docChildFrame is non-NULL in the
719 // first place and it will be always NULL if we're deleted because our
720 // frame was closed, so this only catches the case of directly deleting
721 // the view, as it happens if its creation fails in wxDocTemplate::
722 // CreateView() for example
723 m_docChildFrame->GetWindow()->Destroy();
724 }
725
726 if ( m_viewDocument )
727 m_viewDocument->RemoveView(this);
728 }
729
730 void wxView::SetDocChildFrame(wxDocChildFrameAnyBase *docChildFrame)
731 {
732 SetFrame(docChildFrame ? docChildFrame->GetWindow() : NULL);
733 m_docChildFrame = docChildFrame;
734 }
735
736 bool wxView::TryBefore(wxEvent& event)
737 {
738 wxDocument * const doc = GetDocument();
739 return doc && doc->ProcessEventLocally(event);
740 }
741
742 void wxView::OnActivateView(bool WXUNUSED(activate),
743 wxView *WXUNUSED(activeView),
744 wxView *WXUNUSED(deactiveView))
745 {
746 }
747
748 void wxView::OnPrint(wxDC *dc, wxObject *WXUNUSED(info))
749 {
750 OnDraw(dc);
751 }
752
753 void wxView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint))
754 {
755 }
756
757 void wxView::OnChangeFilename()
758 {
759 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
760 // generic MDI implementation so use SetLabel rather than SetTitle.
761 // It should cause SetTitle() for top level windows.
762 wxWindow *win = GetFrame();
763 if (!win) return;
764
765 wxDocument *doc = GetDocument();
766 if (!doc) return;
767
768 wxString label = doc->GetUserReadableName();
769 if (doc->IsModified())
770 {
771 label += "*";
772 }
773 win->SetLabel(label);
774 }
775
776 void wxView::SetDocument(wxDocument *doc)
777 {
778 m_viewDocument = doc;
779 if (doc)
780 doc->AddView(this);
781 }
782
783 bool wxView::Close(bool deleteWindow)
784 {
785 return OnClose(deleteWindow);
786 }
787
788 void wxView::Activate(bool activate)
789 {
790 if (GetDocument() && GetDocumentManager())
791 {
792 OnActivateView(activate, this, GetDocumentManager()->GetCurrentView());
793 GetDocumentManager()->ActivateView(this, activate);
794 }
795 }
796
797 bool wxView::OnClose(bool WXUNUSED(deleteWindow))
798 {
799 return GetDocument() ? GetDocument()->Close() : true;
800 }
801
802 #if wxUSE_PRINTING_ARCHITECTURE
803 wxPrintout *wxView::OnCreatePrintout()
804 {
805 return new wxDocPrintout(this);
806 }
807 #endif // wxUSE_PRINTING_ARCHITECTURE
808
809 // ----------------------------------------------------------------------------
810 // wxDocTemplate
811 // ----------------------------------------------------------------------------
812
813 wxDocTemplate::wxDocTemplate(wxDocManager *manager,
814 const wxString& descr,
815 const wxString& filter,
816 const wxString& dir,
817 const wxString& ext,
818 const wxString& docTypeName,
819 const wxString& viewTypeName,
820 wxClassInfo *docClassInfo,
821 wxClassInfo *viewClassInfo,
822 long flags)
823 {
824 m_documentManager = manager;
825 m_description = descr;
826 m_directory = dir;
827 m_defaultExt = ext;
828 m_fileFilter = filter;
829 m_flags = flags;
830 m_docTypeName = docTypeName;
831 m_viewTypeName = viewTypeName;
832 m_documentManager->AssociateTemplate(this);
833
834 m_docClassInfo = docClassInfo;
835 m_viewClassInfo = viewClassInfo;
836 }
837
838 wxDocTemplate::~wxDocTemplate()
839 {
840 m_documentManager->DisassociateTemplate(this);
841 }
842
843 // Tries to dynamically construct an object of the right class.
844 wxDocument *wxDocTemplate::CreateDocument(const wxString& path, long flags)
845 {
846 // InitDocument() is supposed to delete the document object if its
847 // initialization fails so don't use wxScopedPtr<> here: this is fragile
848 // but unavoidable because the default implementation uses CreateView()
849 // which may -- or not -- create a wxView and if it does create it and its
850 // initialization fails then the view destructor will delete the document
851 // (via RemoveView()) and as we can't distinguish between the two cases we
852 // just have to assume that it always deletes it in case of failure
853 wxDocument * const doc = DoCreateDocument();
854
855 return doc && InitDocument(doc, path, flags) ? doc : NULL;
856 }
857
858 bool
859 wxDocTemplate::InitDocument(wxDocument* doc, const wxString& path, long flags)
860 {
861 wxScopeGuard g = wxMakeObjGuard(*doc, &wxDocument::DeleteAllViews);
862
863 doc->SetFilename(path);
864 doc->SetDocumentTemplate(this);
865 GetDocumentManager()->AddDocument(doc);
866 doc->SetCommandProcessor(doc->OnCreateCommandProcessor());
867
868 if ( !doc->OnCreate(path, flags) )
869 return false;
870
871 g.Dismiss(); // no need to call DeleteAllViews() anymore
872
873 return true;
874 }
875
876 wxView *wxDocTemplate::CreateView(wxDocument *doc, long flags)
877 {
878 wxScopedPtr<wxView> view(DoCreateView());
879 if ( !view )
880 return NULL;
881
882 view->SetDocument(doc);
883 if ( !view->OnCreate(doc, flags) )
884 return NULL;
885
886 return view.release();
887 }
888
889 // The default (very primitive) format detection: check is the extension is
890 // that of the template
891 bool wxDocTemplate::FileMatchesTemplate(const wxString& path)
892 {
893 wxStringTokenizer parser (GetFileFilter(), wxT(";"));
894 wxString anything = wxT ("*");
895 while (parser.HasMoreTokens())
896 {
897 wxString filter = parser.GetNextToken();
898 wxString filterExt = FindExtension (filter);
899 if ( filter.IsSameAs (anything) ||
900 filterExt.IsSameAs (anything) ||
901 filterExt.IsSameAs (FindExtension (path)) )
902 return true;
903 }
904 return GetDefaultExtension().IsSameAs(FindExtension(path));
905 }
906
907 wxDocument *wxDocTemplate::DoCreateDocument()
908 {
909 if (!m_docClassInfo)
910 return NULL;
911
912 return static_cast<wxDocument *>(m_docClassInfo->CreateObject());
913 }
914
915 wxView *wxDocTemplate::DoCreateView()
916 {
917 if (!m_viewClassInfo)
918 return NULL;
919
920 return static_cast<wxView *>(m_viewClassInfo->CreateObject());
921 }
922
923 // ----------------------------------------------------------------------------
924 // wxDocManager
925 // ----------------------------------------------------------------------------
926
927 BEGIN_EVENT_TABLE(wxDocManager, wxEvtHandler)
928 EVT_MENU(wxID_OPEN, wxDocManager::OnFileOpen)
929 EVT_MENU(wxID_CLOSE, wxDocManager::OnFileClose)
930 EVT_MENU(wxID_CLOSE_ALL, wxDocManager::OnFileCloseAll)
931 EVT_MENU(wxID_REVERT, wxDocManager::OnFileRevert)
932 EVT_MENU(wxID_NEW, wxDocManager::OnFileNew)
933 EVT_MENU(wxID_SAVE, wxDocManager::OnFileSave)
934 EVT_MENU(wxID_SAVEAS, wxDocManager::OnFileSaveAs)
935 EVT_MENU(wxID_UNDO, wxDocManager::OnUndo)
936 EVT_MENU(wxID_REDO, wxDocManager::OnRedo)
937
938 // We don't know in advance how many items can there be in the MRU files
939 // list so set up OnMRUFile() as a handler for all menu events and do the
940 // check for the id of the menu item clicked inside it.
941 EVT_MENU(wxID_ANY, wxDocManager::OnMRUFile)
942
943 EVT_UPDATE_UI(wxID_OPEN, wxDocManager::OnUpdateFileOpen)
944 EVT_UPDATE_UI(wxID_CLOSE, wxDocManager::OnUpdateDisableIfNoDoc)
945 EVT_UPDATE_UI(wxID_CLOSE_ALL, wxDocManager::OnUpdateDisableIfNoDoc)
946 EVT_UPDATE_UI(wxID_REVERT, wxDocManager::OnUpdateFileRevert)
947 EVT_UPDATE_UI(wxID_NEW, wxDocManager::OnUpdateFileNew)
948 EVT_UPDATE_UI(wxID_SAVE, wxDocManager::OnUpdateFileSave)
949 EVT_UPDATE_UI(wxID_SAVEAS, wxDocManager::OnUpdateFileSaveAs)
950 EVT_UPDATE_UI(wxID_UNDO, wxDocManager::OnUpdateUndo)
951 EVT_UPDATE_UI(wxID_REDO, wxDocManager::OnUpdateRedo)
952
953 #if wxUSE_PRINTING_ARCHITECTURE
954 EVT_MENU(wxID_PRINT, wxDocManager::OnPrint)
955 EVT_MENU(wxID_PREVIEW, wxDocManager::OnPreview)
956 EVT_MENU(wxID_PRINT_SETUP, wxDocManager::OnPageSetup)
957
958 EVT_UPDATE_UI(wxID_PRINT, wxDocManager::OnUpdateDisableIfNoDoc)
959 EVT_UPDATE_UI(wxID_PREVIEW, wxDocManager::OnUpdateDisableIfNoDoc)
960 // NB: we keep "Print setup" menu item always enabled as it can be used
961 // even without an active document
962 #endif // wxUSE_PRINTING_ARCHITECTURE
963 END_EVENT_TABLE()
964
965 wxDocManager* wxDocManager::sm_docManager = NULL;
966
967 wxDocManager::wxDocManager(long WXUNUSED(flags), bool initialize)
968 {
969 sm_docManager = this;
970
971 m_defaultDocumentNameCounter = 1;
972 m_currentView = NULL;
973 m_maxDocsOpen = INT_MAX;
974 m_fileHistory = NULL;
975 if ( initialize )
976 Initialize();
977 }
978
979 wxDocManager::~wxDocManager()
980 {
981 Clear();
982 delete m_fileHistory;
983 sm_docManager = NULL;
984 }
985
986 // closes the specified document
987 bool wxDocManager::CloseDocument(wxDocument* doc, bool force)
988 {
989 if ( !doc->Close() && !force )
990 return false;
991
992 // Implicitly deletes the document when
993 // the last view is deleted
994 doc->DeleteAllViews();
995
996 // Check we're really deleted
997 if (m_docs.Member(doc))
998 delete doc;
999
1000 return true;
1001 }
1002
1003 bool wxDocManager::CloseDocuments(bool force)
1004 {
1005 wxList::compatibility_iterator node = m_docs.GetFirst();
1006 while (node)
1007 {
1008 wxDocument *doc = (wxDocument *)node->GetData();
1009 wxList::compatibility_iterator next = node->GetNext();
1010
1011 if (!CloseDocument(doc, force))
1012 return false;
1013
1014 // This assumes that documents are not connected in
1015 // any way, i.e. deleting one document does NOT
1016 // delete another.
1017 node = next;
1018 }
1019 return true;
1020 }
1021
1022 bool wxDocManager::Clear(bool force)
1023 {
1024 if (!CloseDocuments(force))
1025 return false;
1026
1027 m_currentView = NULL;
1028
1029 wxList::compatibility_iterator node = m_templates.GetFirst();
1030 while (node)
1031 {
1032 wxDocTemplate *templ = (wxDocTemplate*) node->GetData();
1033 wxList::compatibility_iterator next = node->GetNext();
1034 delete templ;
1035 node = next;
1036 }
1037 return true;
1038 }
1039
1040 bool wxDocManager::Initialize()
1041 {
1042 m_fileHistory = OnCreateFileHistory();
1043 return true;
1044 }
1045
1046 wxString wxDocManager::GetLastDirectory() const
1047 {
1048 // if we haven't determined the last used directory yet, do it now
1049 if ( m_lastDirectory.empty() )
1050 {
1051 // we're going to modify m_lastDirectory in this const method, so do it
1052 // via non-const self pointer instead of const this one
1053 wxDocManager * const self = const_cast<wxDocManager *>(this);
1054
1055 // first try to reuse the directory of the most recently opened file:
1056 // this ensures that if the user opens a file, closes the program and
1057 // runs it again the "Open file" dialog will open in the directory of
1058 // the last file he used
1059 if ( m_fileHistory && m_fileHistory->GetCount() )
1060 {
1061 const wxString lastOpened = m_fileHistory->GetHistoryFile(0);
1062 const wxFileName fn(lastOpened);
1063 if ( fn.DirExists() )
1064 {
1065 self->m_lastDirectory = fn.GetPath();
1066 }
1067 //else: should we try the next one?
1068 }
1069 //else: no history yet
1070
1071 // if we don't have any files in the history (yet?), use the
1072 // system-dependent default location for the document files
1073 if ( m_lastDirectory.empty() )
1074 {
1075 self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir();
1076 }
1077 }
1078
1079 return m_lastDirectory;
1080 }
1081
1082 wxFileHistory *wxDocManager::OnCreateFileHistory()
1083 {
1084 return new wxFileHistory;
1085 }
1086
1087 void wxDocManager::OnFileClose(wxCommandEvent& WXUNUSED(event))
1088 {
1089 wxDocument *doc = GetCurrentDocument();
1090 if (doc)
1091 CloseDocument(doc);
1092 }
1093
1094 void wxDocManager::OnFileCloseAll(wxCommandEvent& WXUNUSED(event))
1095 {
1096 CloseDocuments(false);
1097 }
1098
1099 void wxDocManager::OnFileNew(wxCommandEvent& WXUNUSED(event))
1100 {
1101 CreateNewDocument();
1102 }
1103
1104 void wxDocManager::OnFileOpen(wxCommandEvent& WXUNUSED(event))
1105 {
1106 if ( !CreateDocument("") )
1107 {
1108 OnOpenFileFailure();
1109 }
1110 }
1111
1112 void wxDocManager::OnFileRevert(wxCommandEvent& WXUNUSED(event))
1113 {
1114 wxDocument *doc = GetCurrentDocument();
1115 if (!doc)
1116 return;
1117 doc->Revert();
1118 }
1119
1120 void wxDocManager::OnFileSave(wxCommandEvent& WXUNUSED(event))
1121 {
1122 wxDocument *doc = GetCurrentDocument();
1123 if (!doc)
1124 return;
1125 doc->Save();
1126 }
1127
1128 void wxDocManager::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))
1129 {
1130 wxDocument *doc = GetCurrentDocument();
1131 if (!doc)
1132 return;
1133 doc->SaveAs();
1134 }
1135
1136 void wxDocManager::OnMRUFile(wxCommandEvent& event)
1137 {
1138 // Check if the id is in the range assigned to MRU list entries.
1139 const int id = event.GetId();
1140 if ( id >= wxID_FILE1 &&
1141 id < wxID_FILE1 + static_cast<int>(m_fileHistory->GetCount()) )
1142 {
1143 DoOpenMRUFile(id - wxID_FILE1);
1144 }
1145 else
1146 {
1147 event.Skip();
1148 }
1149 }
1150
1151 void wxDocManager::DoOpenMRUFile(unsigned n)
1152 {
1153 wxString filename(GetHistoryFile(n));
1154 if ( filename.empty() )
1155 return;
1156
1157 wxString errMsg; // must contain exactly one "%s" if non-empty
1158 if ( wxFile::Exists(filename) )
1159 {
1160 // Try to open it but don't give an error if it failed: this could be
1161 // normal, e.g. because the user cancelled opening it, and we don't
1162 // have any useful information to put in the error message anyhow, so
1163 // we assume that in case of an error the appropriate message had been
1164 // already logged.
1165 (void)CreateDocument(filename, wxDOC_SILENT);
1166 }
1167 else // file doesn't exist
1168 {
1169 OnMRUFileNotExist(n, filename);
1170 }
1171 }
1172
1173 void wxDocManager::OnMRUFileNotExist(unsigned n, const wxString& filename)
1174 {
1175 // remove the file which we can't open from the MRU list
1176 RemoveFileFromHistory(n);
1177
1178 // and tell the user about it
1179 wxLogError(_("The file '%s' doesn't exist and couldn't be opened.\n"
1180 "It has been removed from the most recently used files list."),
1181 filename);
1182 }
1183
1184 #if wxUSE_PRINTING_ARCHITECTURE
1185
1186 void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event))
1187 {
1188 wxView *view = GetActiveView();
1189 if (!view)
1190 return;
1191
1192 wxPrintout *printout = view->OnCreatePrintout();
1193 if (printout)
1194 {
1195 wxPrintDialogData printDialogData(m_pageSetupDialogData.GetPrintData());
1196 wxPrinter printer(&printDialogData);
1197 printer.Print(view->GetFrame(), printout, true);
1198
1199 delete printout;
1200 }
1201 }
1202
1203 void wxDocManager::OnPageSetup(wxCommandEvent& WXUNUSED(event))
1204 {
1205 wxPageSetupDialog dlg(wxTheApp->GetTopWindow(), &m_pageSetupDialogData);
1206 if ( dlg.ShowModal() == wxID_OK )
1207 {
1208 m_pageSetupDialogData = dlg.GetPageSetupData();
1209 }
1210 }
1211
1212 wxPreviewFrame* wxDocManager::CreatePreviewFrame(wxPrintPreviewBase* preview,
1213 wxWindow *parent,
1214 const wxString& title)
1215 {
1216 return new wxPreviewFrame(preview, parent, title);
1217 }
1218
1219 void wxDocManager::OnPreview(wxCommandEvent& WXUNUSED(event))
1220 {
1221 wxBusyCursor busy;
1222 wxView *view = GetActiveView();
1223 if (!view)
1224 return;
1225
1226 wxPrintout *printout = view->OnCreatePrintout();
1227 if (printout)
1228 {
1229 wxPrintDialogData printDialogData(m_pageSetupDialogData.GetPrintData());
1230
1231 // Pass two printout objects: for preview, and possible printing.
1232 wxPrintPreviewBase *
1233 preview = new wxPrintPreview(printout,
1234 view->OnCreatePrintout(),
1235 &printDialogData);
1236 if ( !preview->IsOk() )
1237 {
1238 delete preview;
1239 wxLogError(_("Print preview creation failed."));
1240 return;
1241 }
1242
1243 wxPreviewFrame* frame = CreatePreviewFrame(preview,
1244 wxTheApp->GetTopWindow(),
1245 _("Print Preview"));
1246 wxCHECK_RET( frame, "should create a print preview frame" );
1247
1248 frame->Centre(wxBOTH);
1249 frame->Initialize();
1250 frame->Show(true);
1251 }
1252 }
1253 #endif // wxUSE_PRINTING_ARCHITECTURE
1254
1255 void wxDocManager::OnUndo(wxCommandEvent& event)
1256 {
1257 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1258 if ( !cmdproc )
1259 {
1260 event.Skip();
1261 return;
1262 }
1263
1264 cmdproc->Undo();
1265 }
1266
1267 void wxDocManager::OnRedo(wxCommandEvent& event)
1268 {
1269 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1270 if ( !cmdproc )
1271 {
1272 event.Skip();
1273 return;
1274 }
1275
1276 cmdproc->Redo();
1277 }
1278
1279 // Handlers for UI update commands
1280
1281 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent& event)
1282 {
1283 // CreateDocument() (which is called from OnFileOpen) may succeed
1284 // only when there is at least a template:
1285 event.Enable( GetTemplates().GetCount()>0 );
1286 }
1287
1288 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent& event)
1289 {
1290 event.Enable( GetCurrentDocument() != NULL );
1291 }
1292
1293 void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent& event)
1294 {
1295 wxDocument* doc = GetCurrentDocument();
1296 event.Enable(doc && doc->IsModified() && doc->GetDocumentSaved());
1297 }
1298
1299 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event)
1300 {
1301 // CreateDocument() (which is called from OnFileNew) may succeed
1302 // only when there is at least a template:
1303 event.Enable( GetTemplates().GetCount()>0 );
1304 }
1305
1306 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event)
1307 {
1308 wxDocument * const doc = GetCurrentDocument();
1309 event.Enable( doc && !doc->IsChildDocument() && !doc->AlreadySaved() );
1310 }
1311
1312 void wxDocManager::OnUpdateFileSaveAs(wxUpdateUIEvent& event)
1313 {
1314 wxDocument * const doc = GetCurrentDocument();
1315 event.Enable( doc && !doc->IsChildDocument() );
1316 }
1317
1318 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event)
1319 {
1320 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1321 if ( !cmdproc )
1322 {
1323 // If we don't have any document at all, the menu item should really be
1324 // disabled.
1325 if ( !GetCurrentDocument() )
1326 event.Enable(false);
1327 else // But if we do have it, it might handle wxID_UNDO on its own
1328 event.Skip();
1329 return;
1330 }
1331 event.Enable(cmdproc->CanUndo());
1332 cmdproc->SetMenuStrings();
1333 }
1334
1335 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event)
1336 {
1337 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1338 if ( !cmdproc )
1339 {
1340 // Use same logic as in OnUpdateUndo() above.
1341 if ( !GetCurrentDocument() )
1342 event.Enable(false);
1343 else
1344 event.Skip();
1345 return;
1346 }
1347 event.Enable(cmdproc->CanRedo());
1348 cmdproc->SetMenuStrings();
1349 }
1350
1351 wxView *wxDocManager::GetActiveView() const
1352 {
1353 wxView *view = GetCurrentView();
1354
1355 if ( !view && !m_docs.empty() )
1356 {
1357 // if we have exactly one document, consider its view to be the current
1358 // one
1359 //
1360 // VZ: I'm not exactly sure why is this needed but this is how this
1361 // code used to behave before the bug #9518 was fixed and it seems
1362 // safer to preserve the old logic
1363 wxList::compatibility_iterator node = m_docs.GetFirst();
1364 if ( !node->GetNext() )
1365 {
1366 wxDocument *doc = static_cast<wxDocument *>(node->GetData());
1367 view = doc->GetFirstView();
1368 }
1369 //else: we have more than one document
1370 }
1371
1372 return view;
1373 }
1374
1375 bool wxDocManager::TryBefore(wxEvent& event)
1376 {
1377 wxView * const view = GetActiveView();
1378 return view && view->ProcessEventLocally(event);
1379 }
1380
1381 namespace
1382 {
1383
1384 // helper function: return only the visible templates
1385 wxDocTemplateVector GetVisibleTemplates(const wxList& allTemplates)
1386 {
1387 // select only the visible templates
1388 const size_t totalNumTemplates = allTemplates.GetCount();
1389 wxDocTemplateVector templates;
1390 if ( totalNumTemplates )
1391 {
1392 templates.reserve(totalNumTemplates);
1393
1394 for ( wxList::const_iterator i = allTemplates.begin(),
1395 end = allTemplates.end();
1396 i != end;
1397 ++i )
1398 {
1399 wxDocTemplate * const temp = (wxDocTemplate *)*i;
1400 if ( temp->IsVisible() )
1401 templates.push_back(temp);
1402 }
1403 }
1404
1405 return templates;
1406 }
1407
1408 } // anonymous namespace
1409
1410 void wxDocManager::ActivateDocument(wxDocument *doc)
1411 {
1412 wxView * const view = doc->GetFirstView();
1413 if ( !view )
1414 return;
1415
1416 view->Activate(true);
1417 if ( wxWindow *win = view->GetFrame() )
1418 win->Raise();
1419 }
1420
1421 wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags)
1422 {
1423 // this ought to be const but SelectDocumentType/Path() are not
1424 // const-correct and can't be changed as, being virtual, this risks
1425 // breaking user code overriding them
1426 wxDocTemplateVector templates(GetVisibleTemplates(m_templates));
1427 const size_t numTemplates = templates.size();
1428 if ( !numTemplates )
1429 {
1430 // no templates can be used, can't create document
1431 return NULL;
1432 }
1433
1434
1435 // normally user should select the template to use but wxDOC_SILENT flag we
1436 // choose one ourselves
1437 wxString path = pathOrig; // may be modified below
1438 wxDocTemplate *temp;
1439 if ( flags & wxDOC_SILENT )
1440 {
1441 wxASSERT_MSG( !path.empty(),
1442 "using empty path with wxDOC_SILENT doesn't make sense" );
1443
1444 temp = FindTemplateForPath(path);
1445 if ( !temp )
1446 {
1447 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1448 path);
1449 }
1450 }
1451 else // not silent, ask the user
1452 {
1453 // for the new file we need just the template, for an existing one we
1454 // need the template and the path, unless it's already specified
1455 if ( (flags & wxDOC_NEW) || !path.empty() )
1456 temp = SelectDocumentType(&templates[0], numTemplates);
1457 else
1458 temp = SelectDocumentPath(&templates[0], numTemplates, path, flags);
1459 }
1460
1461 if ( !temp )
1462 return NULL;
1463
1464 // check whether the document with this path is already opened
1465 if ( !path.empty() )
1466 {
1467 const wxFileName fn(path);
1468 for ( wxList::const_iterator i = m_docs.begin(); i != m_docs.end(); ++i )
1469 {
1470 wxDocument * const doc = (wxDocument*)*i;
1471
1472 if ( fn == doc->GetFilename() )
1473 {
1474 // file already open, just activate it and return
1475 ActivateDocument(doc);
1476 return doc;
1477 }
1478 }
1479 }
1480
1481
1482 // no, we need to create a new document
1483
1484
1485 // if we've reached the max number of docs, close the first one.
1486 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen )
1487 {
1488 if ( !CloseDocument((wxDocument *)GetDocuments().GetFirst()->GetData()) )
1489 {
1490 // can't open the new document if closing the old one failed
1491 return NULL;
1492 }
1493 }
1494
1495
1496 // do create and initialize the new document finally
1497 wxDocument * const docNew = temp->CreateDocument(path, flags);
1498 if ( !docNew )
1499 return NULL;
1500
1501 docNew->SetDocumentName(temp->GetDocumentName());
1502 docNew->SetDocumentTemplate(temp);
1503
1504 wxTRY
1505 {
1506 // call the appropriate function depending on whether we're creating a
1507 // new file or opening an existing one
1508 if ( !(flags & wxDOC_NEW ? docNew->OnNewDocument()
1509 : docNew->OnOpenDocument(path)) )
1510 {
1511 docNew->DeleteAllViews();
1512 return NULL;
1513 }
1514 }
1515 wxCATCH_ALL( docNew->DeleteAllViews(); throw; )
1516
1517 // add the successfully opened file to MRU, but only if we're going to be
1518 // able to reopen it successfully later which requires the template for
1519 // this document to be retrievable from the file extension
1520 if ( !(flags & wxDOC_NEW) && temp->FileMatchesTemplate(path) )
1521 AddFileToHistory(path);
1522
1523 // at least under Mac (where views are top level windows) it seems to be
1524 // necessary to manually activate the new document to bring it to the
1525 // forefront -- and it shouldn't hurt doing this under the other platforms
1526 ActivateDocument(docNew);
1527
1528 return docNew;
1529 }
1530
1531 wxView *wxDocManager::CreateView(wxDocument *doc, long flags)
1532 {
1533 wxDocTemplateVector templates(GetVisibleTemplates(m_templates));
1534 const size_t numTemplates = templates.size();
1535
1536 if ( numTemplates == 0 )
1537 return NULL;
1538
1539 wxDocTemplate * const
1540 temp = numTemplates == 1 ? templates[0]
1541 : SelectViewType(&templates[0], numTemplates);
1542
1543 if ( !temp )
1544 return NULL;
1545
1546 wxView *view = temp->CreateView(doc, flags);
1547 if ( view )
1548 view->SetViewName(temp->GetViewName());
1549 return view;
1550 }
1551
1552 // Not yet implemented
1553 void
1554 wxDocManager::DeleteTemplate(wxDocTemplate *WXUNUSED(temp), long WXUNUSED(flags))
1555 {
1556 }
1557
1558 // Not yet implemented
1559 bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc))
1560 {
1561 return false;
1562 }
1563
1564 wxDocument *wxDocManager::GetCurrentDocument() const
1565 {
1566 wxView * const view = GetActiveView();
1567 return view ? view->GetDocument() : NULL;
1568 }
1569
1570 wxCommandProcessor *wxDocManager::GetCurrentCommandProcessor() const
1571 {
1572 wxDocument * const doc = GetCurrentDocument();
1573 return doc ? doc->GetCommandProcessor() : NULL;
1574 }
1575
1576 // Make a default name for a new document
1577 #if WXWIN_COMPATIBILITY_2_8
1578 bool wxDocManager::MakeDefaultName(wxString& WXUNUSED(name))
1579 {
1580 // we consider that this function can only be overridden by the user code,
1581 // not called by it as it only makes sense to call it internally, so we
1582 // don't bother to return anything from here
1583 return false;
1584 }
1585 #endif // WXWIN_COMPATIBILITY_2_8
1586
1587 wxString wxDocManager::MakeNewDocumentName()
1588 {
1589 wxString name;
1590
1591 #if WXWIN_COMPATIBILITY_2_8
1592 if ( !MakeDefaultName(name) )
1593 #endif // WXWIN_COMPATIBILITY_2_8
1594 {
1595 name.Printf(_("unnamed%d"), m_defaultDocumentNameCounter);
1596 m_defaultDocumentNameCounter++;
1597 }
1598
1599 return name;
1600 }
1601
1602 // Make a frame title (override this to do something different)
1603 // If docName is empty, a document is not currently active.
1604 wxString wxDocManager::MakeFrameTitle(wxDocument* doc)
1605 {
1606 wxString appName = wxTheApp->GetAppDisplayName();
1607 wxString title;
1608 if (!doc)
1609 title = appName;
1610 else
1611 {
1612 wxString docName = doc->GetUserReadableName();
1613 title = docName + wxString(_(" - ")) + appName;
1614 }
1615 return title;
1616 }
1617
1618
1619 // Not yet implemented
1620 wxDocTemplate *wxDocManager::MatchTemplate(const wxString& WXUNUSED(path))
1621 {
1622 return NULL;
1623 }
1624
1625 // File history management
1626 void wxDocManager::AddFileToHistory(const wxString& file)
1627 {
1628 if (m_fileHistory)
1629 m_fileHistory->AddFileToHistory(file);
1630 }
1631
1632 void wxDocManager::RemoveFileFromHistory(size_t i)
1633 {
1634 if (m_fileHistory)
1635 m_fileHistory->RemoveFileFromHistory(i);
1636 }
1637
1638 wxString wxDocManager::GetHistoryFile(size_t i) const
1639 {
1640 wxString histFile;
1641
1642 if (m_fileHistory)
1643 histFile = m_fileHistory->GetHistoryFile(i);
1644
1645 return histFile;
1646 }
1647
1648 void wxDocManager::FileHistoryUseMenu(wxMenu *menu)
1649 {
1650 if (m_fileHistory)
1651 m_fileHistory->UseMenu(menu);
1652 }
1653
1654 void wxDocManager::FileHistoryRemoveMenu(wxMenu *menu)
1655 {
1656 if (m_fileHistory)
1657 m_fileHistory->RemoveMenu(menu);
1658 }
1659
1660 #if wxUSE_CONFIG
1661 void wxDocManager::FileHistoryLoad(const wxConfigBase& config)
1662 {
1663 if (m_fileHistory)
1664 m_fileHistory->Load(config);
1665 }
1666
1667 void wxDocManager::FileHistorySave(wxConfigBase& config)
1668 {
1669 if (m_fileHistory)
1670 m_fileHistory->Save(config);
1671 }
1672 #endif
1673
1674 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu* menu)
1675 {
1676 if (m_fileHistory)
1677 m_fileHistory->AddFilesToMenu(menu);
1678 }
1679
1680 void wxDocManager::FileHistoryAddFilesToMenu()
1681 {
1682 if (m_fileHistory)
1683 m_fileHistory->AddFilesToMenu();
1684 }
1685
1686 size_t wxDocManager::GetHistoryFilesCount() const
1687 {
1688 return m_fileHistory ? m_fileHistory->GetCount() : 0;
1689 }
1690
1691
1692 // Find out the document template via matching in the document file format
1693 // against that of the template
1694 wxDocTemplate *wxDocManager::FindTemplateForPath(const wxString& path)
1695 {
1696 wxDocTemplate *theTemplate = NULL;
1697
1698 // Find the template which this extension corresponds to
1699 for (size_t i = 0; i < m_templates.GetCount(); i++)
1700 {
1701 wxDocTemplate *temp = (wxDocTemplate *)m_templates.Item(i)->GetData();
1702 if ( temp->FileMatchesTemplate(path) )
1703 {
1704 theTemplate = temp;
1705 break;
1706 }
1707 }
1708 return theTemplate;
1709 }
1710
1711 // Prompts user to open a file, using file specs in templates.
1712 // Must extend the file selector dialog or implement own; OR
1713 // match the extension to the template extension.
1714
1715 wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates,
1716 int noTemplates,
1717 wxString& path,
1718 long WXUNUSED(flags),
1719 bool WXUNUSED(save))
1720 {
1721 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1722 wxString descrBuf;
1723
1724 for (int i = 0; i < noTemplates; i++)
1725 {
1726 if (templates[i]->IsVisible())
1727 {
1728 // add a '|' to separate this filter from the previous one
1729 if ( !descrBuf.empty() )
1730 descrBuf << wxT('|');
1731
1732 descrBuf << templates[i]->GetDescription()
1733 << wxT(" (") << templates[i]->GetFileFilter() << wxT(") |")
1734 << templates[i]->GetFileFilter();
1735 }
1736 }
1737 #else
1738 wxString descrBuf = wxT("*.*");
1739 wxUnusedVar(noTemplates);
1740 #endif
1741
1742 int FilterIndex = -1;
1743
1744 wxString pathTmp = wxFileSelectorEx(_("Open File"),
1745 GetLastDirectory(),
1746 wxEmptyString,
1747 &FilterIndex,
1748 descrBuf,
1749 wxFD_OPEN | wxFD_FILE_MUST_EXIST);
1750
1751 wxDocTemplate *theTemplate = NULL;
1752 if (!pathTmp.empty())
1753 {
1754 if (!wxFileExists(pathTmp))
1755 {
1756 wxString msgTitle;
1757 if (!wxTheApp->GetAppDisplayName().empty())
1758 msgTitle = wxTheApp->GetAppDisplayName();
1759 else
1760 msgTitle = wxString(_("File error"));
1761
1762 wxMessageBox(_("Sorry, could not open this file."),
1763 msgTitle,
1764 wxOK | wxICON_EXCLAMATION | wxCENTRE);
1765
1766 path = wxEmptyString;
1767 return NULL;
1768 }
1769
1770 SetLastDirectory(wxPathOnly(pathTmp));
1771
1772 path = pathTmp;
1773
1774 // first choose the template using the extension, if this fails (i.e.
1775 // wxFileSelectorEx() didn't fill it), then use the path
1776 if ( FilterIndex != -1 )
1777 theTemplate = templates[FilterIndex];
1778 if ( !theTemplate )
1779 theTemplate = FindTemplateForPath(path);
1780 if ( !theTemplate )
1781 {
1782 // Since we do not add files with non-default extensions to the
1783 // file history this can only happen if the application changes the
1784 // allowed templates in runtime.
1785 wxMessageBox(_("Sorry, the format for this file is unknown."),
1786 _("Open File"),
1787 wxOK | wxICON_EXCLAMATION | wxCENTRE);
1788 }
1789 }
1790 else
1791 {
1792 path.clear();
1793 }
1794
1795 return theTemplate;
1796 }
1797
1798 wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1799 int noTemplates, bool sort)
1800 {
1801 wxArrayString strings;
1802 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1803 int i;
1804 int n = 0;
1805
1806 for (i = 0; i < noTemplates; i++)
1807 {
1808 if (templates[i]->IsVisible())
1809 {
1810 int j;
1811 bool want = true;
1812 for (j = 0; j < n; j++)
1813 {
1814 //filter out NOT unique documents + view combinations
1815 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1816 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1817 )
1818 want = false;
1819 }
1820
1821 if ( want )
1822 {
1823 strings.Add(templates[i]->m_description);
1824
1825 data[n] = templates[i];
1826 n ++;
1827 }
1828 }
1829 } // for
1830
1831 if (sort)
1832 {
1833 strings.Sort(); // ascending sort
1834 // Yes, this will be slow, but template lists
1835 // are typically short.
1836 int j;
1837 n = strings.Count();
1838 for (i = 0; i < n; i++)
1839 {
1840 for (j = 0; j < noTemplates; j++)
1841 {
1842 if (strings[i] == templates[j]->m_description)
1843 data[i] = templates[j];
1844 }
1845 }
1846 }
1847
1848 wxDocTemplate *theTemplate;
1849
1850 switch ( n )
1851 {
1852 case 0:
1853 // no visible templates, hence nothing to choose from
1854 theTemplate = NULL;
1855 break;
1856
1857 case 1:
1858 // don't propose the user to choose if he has no choice
1859 theTemplate = data[0];
1860 break;
1861
1862 default:
1863 // propose the user to choose one of several
1864 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1865 (
1866 _("Select a document template"),
1867 _("Templates"),
1868 strings,
1869 (void **)data.get()
1870 );
1871 }
1872
1873 return theTemplate;
1874 }
1875
1876 wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1877 int noTemplates, bool sort)
1878 {
1879 wxArrayString strings;
1880 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1881 int i;
1882 int n = 0;
1883
1884 for (i = 0; i < noTemplates; i++)
1885 {
1886 wxDocTemplate *templ = templates[i];
1887 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1888 {
1889 int j;
1890 bool want = true;
1891 for (j = 0; j < n; j++)
1892 {
1893 //filter out NOT unique views
1894 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1895 want = false;
1896 }
1897
1898 if ( want )
1899 {
1900 strings.Add(templ->m_viewTypeName);
1901 data[n] = templ;
1902 n ++;
1903 }
1904 }
1905 }
1906
1907 if (sort)
1908 {
1909 strings.Sort(); // ascending sort
1910 // Yes, this will be slow, but template lists
1911 // are typically short.
1912 int j;
1913 n = strings.Count();
1914 for (i = 0; i < n; i++)
1915 {
1916 for (j = 0; j < noTemplates; j++)
1917 {
1918 if (strings[i] == templates[j]->m_viewTypeName)
1919 data[i] = templates[j];
1920 }
1921 }
1922 }
1923
1924 wxDocTemplate *theTemplate;
1925
1926 // the same logic as above
1927 switch ( n )
1928 {
1929 case 0:
1930 theTemplate = NULL;
1931 break;
1932
1933 case 1:
1934 theTemplate = data[0];
1935 break;
1936
1937 default:
1938 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1939 (
1940 _("Select a document view"),
1941 _("Views"),
1942 strings,
1943 (void **)data.get()
1944 );
1945
1946 }
1947
1948 return theTemplate;
1949 }
1950
1951 void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1952 {
1953 if (!m_templates.Member(temp))
1954 m_templates.Append(temp);
1955 }
1956
1957 void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1958 {
1959 m_templates.DeleteObject(temp);
1960 }
1961
1962 wxDocTemplate* wxDocManager::FindTemplate(const wxClassInfo* classinfo)
1963 {
1964 for ( wxList::compatibility_iterator node = m_templates.GetFirst();
1965 node;
1966 node = node->GetNext() )
1967 {
1968 wxDocTemplate* t = wxStaticCast(node->GetData(), wxDocTemplate);
1969 if ( t->GetDocClassInfo() == classinfo )
1970 return t;
1971 }
1972
1973 return NULL;
1974 }
1975
1976 // Add and remove a document from the manager's list
1977 void wxDocManager::AddDocument(wxDocument *doc)
1978 {
1979 if (!m_docs.Member(doc))
1980 m_docs.Append(doc);
1981 }
1982
1983 void wxDocManager::RemoveDocument(wxDocument *doc)
1984 {
1985 m_docs.DeleteObject(doc);
1986 }
1987
1988 // Views or windows should inform the document manager
1989 // when a view is going in or out of focus
1990 void wxDocManager::ActivateView(wxView *view, bool activate)
1991 {
1992 if ( activate )
1993 {
1994 m_currentView = view;
1995 }
1996 else // deactivate
1997 {
1998 if ( m_currentView == view )
1999 {
2000 // don't keep stale pointer
2001 m_currentView = NULL;
2002 }
2003 }
2004 }
2005
2006 // ----------------------------------------------------------------------------
2007 // wxDocChildFrameAnyBase
2008 // ----------------------------------------------------------------------------
2009
2010 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent& event)
2011 {
2012 if ( m_childView )
2013 {
2014 // notice that we must call wxView::Close() and OnClose() called from
2015 // it in any case, even if we know that we are going to close anyhow
2016 if ( !m_childView->Close(false) && event.CanVeto() )
2017 {
2018 event.Veto();
2019 return false;
2020 }
2021
2022 m_childView->Activate(false);
2023
2024 // it is important to reset m_childView frame pointer to NULL before
2025 // deleting it because while normally it is the frame which deletes the
2026 // view when it's closed, the view also closes the frame if it is
2027 // deleted directly not by us as indicated by its doc child frame
2028 // pointer still being set
2029 m_childView->SetDocChildFrame(NULL);
2030 wxDELETE(m_childView);
2031 }
2032
2033 m_childDocument = NULL;
2034
2035 return true;
2036 }
2037
2038 // ----------------------------------------------------------------------------
2039 // wxDocParentFrameAnyBase
2040 // ----------------------------------------------------------------------------
2041
2042 #if wxUSE_PRINTING_ARCHITECTURE
2043
2044 namespace
2045 {
2046
2047 wxString GetAppropriateTitle(const wxView *view, const wxString& titleGiven)
2048 {
2049 wxString title(titleGiven);
2050 if ( title.empty() )
2051 {
2052 if ( view && view->GetDocument() )
2053 title = view->GetDocument()->GetUserReadableName();
2054 else
2055 title = _("Printout");
2056 }
2057
2058 return title;
2059 }
2060
2061 } // anonymous namespace
2062
2063 wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
2064 : wxPrintout(GetAppropriateTitle(view, title))
2065 {
2066 m_printoutView = view;
2067 }
2068
2069 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
2070 {
2071 wxDC *dc = GetDC();
2072
2073 // Get the logical pixels per inch of screen and printer
2074 int ppiScreenX, ppiScreenY;
2075 GetPPIScreen(&ppiScreenX, &ppiScreenY);
2076 wxUnusedVar(ppiScreenY);
2077 int ppiPrinterX, ppiPrinterY;
2078 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
2079 wxUnusedVar(ppiPrinterY);
2080
2081 // This scales the DC so that the printout roughly represents the
2082 // the screen scaling. The text point size _should_ be the right size
2083 // but in fact is too small for some reason. This is a detail that will
2084 // need to be addressed at some point but can be fudged for the
2085 // moment.
2086 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
2087
2088 // Now we have to check in case our real page size is reduced
2089 // (e.g. because we're drawing to a print preview memory DC)
2090 int pageWidth, pageHeight;
2091 int w, h;
2092 dc->GetSize(&w, &h);
2093 GetPageSizePixels(&pageWidth, &pageHeight);
2094 wxUnusedVar(pageHeight);
2095
2096 // If printer pageWidth == current DC width, then this doesn't
2097 // change. But w might be the preview bitmap width, so scale down.
2098 float overallScale = scale * (float)(w/(float)pageWidth);
2099 dc->SetUserScale(overallScale, overallScale);
2100
2101 if (m_printoutView)
2102 {
2103 m_printoutView->OnDraw(dc);
2104 }
2105 return true;
2106 }
2107
2108 bool wxDocPrintout::HasPage(int pageNum)
2109 {
2110 return (pageNum == 1);
2111 }
2112
2113 bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
2114 {
2115 if (!wxPrintout::OnBeginDocument(startPage, endPage))
2116 return false;
2117
2118 return true;
2119 }
2120
2121 void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage,
2122 int *selPageFrom, int *selPageTo)
2123 {
2124 *minPage = 1;
2125 *maxPage = 1;
2126 *selPageFrom = 1;
2127 *selPageTo = 1;
2128 }
2129
2130 #endif // wxUSE_PRINTING_ARCHITECTURE
2131
2132 // ----------------------------------------------------------------------------
2133 // Permits compatibility with existing file formats and functions that
2134 // manipulate files directly
2135 // ----------------------------------------------------------------------------
2136
2137 #if wxUSE_STD_IOSTREAM
2138
2139 bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream)
2140 {
2141 #if wxUSE_FFILE
2142 wxFFile file(filename, wxT("rb"));
2143 #elif wxUSE_FILE
2144 wxFile file(filename, wxFile::read);
2145 #endif
2146 if ( !file.IsOpened() )
2147 return false;
2148
2149 char buf[4096];
2150
2151 size_t nRead;
2152 do
2153 {
2154 nRead = file.Read(buf, WXSIZEOF(buf));
2155 if ( file.Error() )
2156 return false;
2157
2158 stream.write(buf, nRead);
2159 if ( !stream )
2160 return false;
2161 }
2162 while ( !file.Eof() );
2163
2164 return true;
2165 }
2166
2167 bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename)
2168 {
2169 #if wxUSE_FFILE
2170 wxFFile file(filename, wxT("wb"));
2171 #elif wxUSE_FILE
2172 wxFile file(filename, wxFile::write);
2173 #endif
2174 if ( !file.IsOpened() )
2175 return false;
2176
2177 char buf[4096];
2178 do
2179 {
2180 stream.read(buf, WXSIZEOF(buf));
2181 if ( !stream.bad() ) // fail may be set on EOF, don't use operator!()
2182 {
2183 if ( !file.Write(buf, stream.gcount()) )
2184 return false;
2185 }
2186 }
2187 while ( !stream.eof() );
2188
2189 return true;
2190 }
2191
2192 #else // !wxUSE_STD_IOSTREAM
2193
2194 bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream)
2195 {
2196 #if wxUSE_FFILE
2197 wxFFile file(filename, wxT("rb"));
2198 #elif wxUSE_FILE
2199 wxFile file(filename, wxFile::read);
2200 #endif
2201 if ( !file.IsOpened() )
2202 return false;
2203
2204 char buf[4096];
2205
2206 size_t nRead;
2207 do
2208 {
2209 nRead = file.Read(buf, WXSIZEOF(buf));
2210 if ( file.Error() )
2211 return false;
2212
2213 stream.Write(buf, nRead);
2214 if ( !stream )
2215 return false;
2216 }
2217 while ( !file.Eof() );
2218
2219 return true;
2220 }
2221
2222 bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename)
2223 {
2224 #if wxUSE_FFILE
2225 wxFFile file(filename, wxT("wb"));
2226 #elif wxUSE_FILE
2227 wxFile file(filename, wxFile::write);
2228 #endif
2229 if ( !file.IsOpened() )
2230 return false;
2231
2232 char buf[4096];
2233 for ( ;; )
2234 {
2235 stream.Read(buf, WXSIZEOF(buf));
2236
2237 const size_t nRead = stream.LastRead();
2238 if ( !nRead )
2239 {
2240 if ( stream.Eof() )
2241 break;
2242
2243 return false;
2244 }
2245
2246 if ( !file.Write(buf, nRead) )
2247 return false;
2248 }
2249
2250 return true;
2251 }
2252
2253 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2254
2255 #endif // wxUSE_DOC_VIEW_ARCHITECTURE