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