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