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