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