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