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