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