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