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