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