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