]> git.saurik.com Git - wxWidgets.git/blob - src/common/docview.cpp
459ce5585ccc8fe77119f9203ce74cdc7b51c20c
[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 if (m_commandProcessor)
160 delete m_commandProcessor;
161
162 if (GetDocumentManager())
163 GetDocumentManager()->RemoveDocument(this);
164
165 // Not safe to do here, since it'll invoke virtual view functions
166 // expecting to see valid derived objects: and by the time we get here,
167 // we've called destructors higher up.
168 //DeleteAllViews();
169 }
170
171 bool wxDocument::Close()
172 {
173 if (OnSaveModified())
174 return OnCloseDocument();
175 else
176 return false;
177 }
178
179 bool wxDocument::OnCloseDocument()
180 {
181 // Tell all views that we're about to close
182 NotifyClosing();
183 DeleteContents();
184 Modify(false);
185 return true;
186 }
187
188 // Note that this implicitly deletes the document when the last view is
189 // deleted.
190 bool wxDocument::DeleteAllViews()
191 {
192 wxDocManager* manager = GetDocumentManager();
193
194 // first check if all views agree to be closed
195 const wxList::iterator end = m_documentViews.end();
196 for ( wxList::iterator i = m_documentViews.begin(); i != end; ++i )
197 {
198 wxView *view = (wxView *)*i;
199 if ( !view->Close() )
200 return false;
201 }
202
203 // all views agreed to close, now do close them
204 if ( m_documentViews.empty() )
205 {
206 // normally the document would be implicitly deleted when the last view
207 // is, but if don't have any views, do it here instead
208 if ( manager && manager->GetDocuments().Member(this) )
209 delete this;
210 }
211 else // have views
212 {
213 // as we delete elements we iterate over, don't use the usual "from
214 // begin to end" loop
215 for ( ;; )
216 {
217 wxView *view = (wxView *)*m_documentViews.begin();
218
219 bool isLastOne = m_documentViews.size() == 1;
220
221 // this always deletes the node implicitly and if this is the last
222 // view also deletes this object itself (also implicitly, great),
223 // so we can't test for m_documentViews.empty() after calling this!
224 delete view;
225
226 if ( isLastOne )
227 break;
228 }
229 }
230
231 return true;
232 }
233
234 wxView *wxDocument::GetFirstView() const
235 {
236 if (m_documentViews.GetCount() == 0)
237 return NULL;
238 return (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 #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.empty() )
312 {
313 defaultDir = wxPathOnly(GetFilename());
314 if ( defaultDir.empty() )
315 defaultDir = GetDocumentManager()->GetLastDirectory();
316 }
317
318 wxString fileName = wxFileSelector(_("Save As"),
319 defaultDir,
320 wxFileNameFromPath(GetFilename()),
321 docTemplate->GetDefaultExtension(),
322 filter,
323 wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
324 GetDocumentWindow());
325
326 if (fileName.empty())
327 return false;
328
329 wxString ext;
330 wxFileName::SplitPath(fileName, NULL, NULL, &ext);
331
332 if (ext.empty())
333 {
334 fileName += wxT(".");
335 fileName += docTemplate->GetDefaultExtension();
336 }
337
338 // Files that were not saved correctly are not added to the FileHistory.
339 if (!OnSaveDocument(fileName))
340 return false;
341
342 SetTitle(wxFileNameFromPath(fileName));
343 SetFilename(fileName, true); // will call OnChangeFileName automatically
344
345 // A file that doesn't use the default extension of its document template cannot be opened
346 // via the FileHistory, so we do not add it.
347 if (docTemplate->FileMatchesTemplate(fileName))
348 {
349 GetDocumentManager()->AddFileToHistory(fileName);
350 }
351 else
352 {
353 // The user will probably not be able to open the file again, so
354 // we could warn about the wrong file-extension here.
355 }
356 return true;
357 }
358
359 bool wxDocument::OnSaveDocument(const wxString& file)
360 {
361 if ( !file )
362 return false;
363
364 if ( !DoSaveDocument(file) )
365 return false;
366
367 Modify(false);
368 SetFilename(file);
369 SetDocumentSaved(true);
370 #if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
371 wxFileName fn(file) ;
372 fn.MacSetDefaultTypeAndCreator() ;
373 #endif
374 return true;
375 }
376
377 bool wxDocument::OnOpenDocument(const wxString& file)
378 {
379 if ( !OnSaveModified() )
380 return false;
381
382 if ( !DoOpenDocument(file) )
383 return false;
384
385 SetFilename(file, true);
386 Modify(false);
387 m_savedYet = true;
388
389 UpdateAllViews();
390
391 return true;
392 }
393
394 #if wxUSE_STD_IOSTREAM
395 wxSTD istream& wxDocument::LoadObject(wxSTD istream& stream)
396 #else
397 wxInputStream& wxDocument::LoadObject(wxInputStream& stream)
398 #endif
399 {
400 return stream;
401 }
402
403 #if wxUSE_STD_IOSTREAM
404 wxSTD ostream& wxDocument::SaveObject(wxSTD ostream& stream)
405 #else
406 wxOutputStream& wxDocument::SaveObject(wxOutputStream& stream)
407 #endif
408 {
409 return stream;
410 }
411
412 bool wxDocument::Revert()
413 {
414 return false;
415 }
416
417
418 // Get title, or filename if no title, else unnamed
419 #if WXWIN_COMPATIBILITY_2_8
420 bool wxDocument::GetPrintableName(wxString& buf) const
421 {
422 // this function can not only be overridden by the user code but also
423 // called by it so we need to ensure that we return the same thing as
424 // GetUserReadableName() but we can't call it because this would result in
425 // an infinite recursion, hence we use the helper DoGetUserReadableName()
426 buf = DoGetUserReadableName();
427
428 return true;
429 }
430 #endif // WXWIN_COMPATIBILITY_2_8
431
432 wxString wxDocument::GetUserReadableName() const
433 {
434 #if WXWIN_COMPATIBILITY_2_8
435 // we need to call the old virtual function to ensure that the overridden
436 // version of it is still called
437 wxString name;
438 if ( GetPrintableName(name) )
439 return name;
440 #endif // WXWIN_COMPATIBILITY_2_8
441
442 return DoGetUserReadableName();
443 }
444
445 wxString wxDocument::DoGetUserReadableName() const
446 {
447 if ( !m_documentTitle.empty() )
448 return m_documentTitle;
449
450 if ( !m_documentFile.empty() )
451 return wxFileNameFromPath(m_documentFile);
452
453 return _("unnamed");
454 }
455
456 wxWindow *wxDocument::GetDocumentWindow() const
457 {
458 wxView *view = GetFirstView();
459 if (view)
460 return view->GetFrame();
461 else
462 return 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), wxView *WXUNUSED(activeView), wxView *WXUNUSED(deactiveView))
659 {
660 }
661
662 void wxView::OnPrint(wxDC *dc, wxObject *WXUNUSED(info))
663 {
664 OnDraw(dc);
665 }
666
667 void wxView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint))
668 {
669 }
670
671 void wxView::OnChangeFilename()
672 {
673 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
674 // generic MDI implementation so use SetLabel rather than SetTitle.
675 // It should cause SetTitle() for top level windows.
676 wxWindow *win = GetFrame();
677 if (!win) return;
678
679 wxDocument *doc = GetDocument();
680 if (!doc) return;
681
682 win->SetLabel(doc->GetUserReadableName());
683 }
684
685 void wxView::SetDocument(wxDocument *doc)
686 {
687 m_viewDocument = doc;
688 if (doc)
689 doc->AddView(this);
690 }
691
692 bool wxView::Close(bool deleteWindow)
693 {
694 return OnClose(deleteWindow);
695 }
696
697 void wxView::Activate(bool activate)
698 {
699 if (GetDocument() && GetDocumentManager())
700 {
701 OnActivateView(activate, this, GetDocumentManager()->GetCurrentView());
702 GetDocumentManager()->ActivateView(this, activate);
703 }
704 }
705
706 bool wxView::OnClose(bool WXUNUSED(deleteWindow))
707 {
708 return GetDocument() ? GetDocument()->Close() : true;
709 }
710
711 #if wxUSE_PRINTING_ARCHITECTURE
712 wxPrintout *wxView::OnCreatePrintout()
713 {
714 return new wxDocPrintout(this);
715 }
716 #endif // wxUSE_PRINTING_ARCHITECTURE
717
718 // ----------------------------------------------------------------------------
719 // wxDocTemplate
720 // ----------------------------------------------------------------------------
721
722 wxDocTemplate::wxDocTemplate(wxDocManager *manager,
723 const wxString& descr,
724 const wxString& filter,
725 const wxString& dir,
726 const wxString& ext,
727 const wxString& docTypeName,
728 const wxString& viewTypeName,
729 wxClassInfo *docClassInfo,
730 wxClassInfo *viewClassInfo,
731 long flags)
732 {
733 m_documentManager = manager;
734 m_description = descr;
735 m_directory = dir;
736 m_defaultExt = ext;
737 m_fileFilter = filter;
738 m_flags = flags;
739 m_docTypeName = docTypeName;
740 m_viewTypeName = viewTypeName;
741 m_documentManager->AssociateTemplate(this);
742
743 m_docClassInfo = docClassInfo;
744 m_viewClassInfo = viewClassInfo;
745 }
746
747 wxDocTemplate::~wxDocTemplate()
748 {
749 m_documentManager->DisassociateTemplate(this);
750 }
751
752 // Tries to dynamically construct an object of the right class.
753 wxDocument *wxDocTemplate::CreateDocument(const wxString& path, long flags)
754 {
755 wxDocument * const doc = DoCreateDocument();
756
757 // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate())
758 // fails, is this intentional?
759
760 return doc && InitDocument(doc, path, flags) ? doc : NULL;
761 }
762
763 bool
764 wxDocTemplate::InitDocument(wxDocument* doc, const wxString& path, long flags)
765 {
766 doc->SetFilename(path);
767 doc->SetDocumentTemplate(this);
768 GetDocumentManager()->AddDocument(doc);
769 doc->SetCommandProcessor(doc->OnCreateCommandProcessor());
770
771 if (doc->OnCreate(path, flags))
772 return true;
773 else
774 {
775 if (GetDocumentManager()->GetDocuments().Member(doc))
776 doc->DeleteAllViews();
777 return false;
778 }
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 (wxDocument *)m_docClassInfo->CreateObject();
818 }
819
820 wxView *wxDocTemplate::DoCreateView()
821 {
822 if (!m_viewClassInfo)
823 return NULL;
824
825 return (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 {
890 // Implicitly deletes the document when
891 // the last view is deleted
892 doc->DeleteAllViews();
893
894 // Check we're really deleted
895 if (m_docs.Member(doc))
896 delete doc;
897
898 return true;
899 }
900 return false;
901 }
902
903 bool wxDocManager::CloseDocuments(bool force)
904 {
905 wxList::compatibility_iterator node = m_docs.GetFirst();
906 while (node)
907 {
908 wxDocument *doc = (wxDocument *)node->GetData();
909 wxList::compatibility_iterator next = node->GetNext();
910
911 if (!CloseDocument(doc, force))
912 return false;
913
914 // This assumes that documents are not connected in
915 // any way, i.e. deleting one document does NOT
916 // delete another.
917 node = next;
918 }
919 return true;
920 }
921
922 bool wxDocManager::Clear(bool force)
923 {
924 if (!CloseDocuments(force))
925 return false;
926
927 m_currentView = NULL;
928
929 wxList::compatibility_iterator node = m_templates.GetFirst();
930 while (node)
931 {
932 wxDocTemplate *templ = (wxDocTemplate*) node->GetData();
933 wxList::compatibility_iterator next = node->GetNext();
934 delete templ;
935 node = next;
936 }
937 return true;
938 }
939
940 bool wxDocManager::Initialize()
941 {
942 m_fileHistory = OnCreateFileHistory();
943 return true;
944 }
945
946 wxString wxDocManager::GetLastDirectory() const
947 {
948 // use the system-dependent default location for the document files if
949 // we're being opened for the first time
950 if ( m_lastDirectory.empty() )
951 {
952 wxDocManager * const self = const_cast<wxDocManager *>(this);
953 self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir();
954 }
955
956 return m_lastDirectory;
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 CreateNewDocument();
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 // CreateDocument() (which is called from OnFileOpen) may succeed
1092 // only when there is at least a template:
1093 event.Enable( GetTemplates().GetCount()>0 );
1094 }
1095
1096 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent& event)
1097 {
1098 event.Enable( GetCurrentDocument() != NULL );
1099 }
1100
1101 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event)
1102 {
1103 // CreateDocument() (which is called from OnFileNew) may succeed
1104 // only when there is at least a template:
1105 event.Enable( GetTemplates().GetCount()>0 );
1106 }
1107
1108 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event)
1109 {
1110 wxDocument * const doc = GetCurrentDocument();
1111 event.Enable( doc && !doc->AlreadySaved() );
1112 }
1113
1114 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event)
1115 {
1116 wxDocument *doc = GetCurrentDocument();
1117 if (!doc)
1118 event.Enable(false);
1119 else if (!doc->GetCommandProcessor())
1120 event.Skip();
1121 else
1122 {
1123 event.Enable( doc->GetCommandProcessor()->CanUndo() );
1124 doc->GetCommandProcessor()->SetMenuStrings();
1125 }
1126 }
1127
1128 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event)
1129 {
1130 wxDocument *doc = GetCurrentDocument();
1131 if (!doc)
1132 event.Enable(false);
1133 else if (!doc->GetCommandProcessor())
1134 event.Skip();
1135 else
1136 {
1137 event.Enable( doc->GetCommandProcessor()->CanRedo() );
1138 doc->GetCommandProcessor()->SetMenuStrings();
1139 }
1140 }
1141
1142 wxView *wxDocManager::GetCurrentView() const
1143 {
1144 if (m_currentView)
1145 return m_currentView;
1146 if (m_docs.GetCount() == 1)
1147 {
1148 wxDocument* doc = (wxDocument*) m_docs.GetFirst()->GetData();
1149 return doc->GetFirstView();
1150 }
1151 return NULL;
1152 }
1153
1154 bool wxDocManager::TryValidator(wxEvent& event)
1155 {
1156 wxView * const view = GetCurrentView();
1157 return view && view->ProcessEventHere(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 GetLastDirectory(),
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 | wxCENTRE,
1530 parent);
1531
1532 path = wxEmptyString;
1533 return NULL;
1534 }
1535
1536 SetLastDirectory(wxPathOnly(pathTmp));
1537
1538 path = pathTmp;
1539
1540 // first choose the template using the extension, if this fails (i.e.
1541 // wxFileSelectorEx() didn't fill it), then use the path
1542 if ( FilterIndex != -1 )
1543 theTemplate = templates[FilterIndex];
1544 if ( !theTemplate )
1545 theTemplate = FindTemplateForPath(path);
1546 if ( !theTemplate )
1547 {
1548 // Since we do not add files with non-default extensions to the FileHistory this
1549 // can only happen if the application changes the allowed templates in runtime.
1550 (void)wxMessageBox(_("Sorry, the format for this file is unknown."),
1551 _("Open File"),
1552 wxOK | wxICON_EXCLAMATION | wxCENTRE, wxFindSuitableParent());
1553 }
1554 }
1555 else
1556 {
1557 path = wxEmptyString;
1558 }
1559
1560 return theTemplate;
1561 }
1562
1563 wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1564 int noTemplates, bool sort)
1565 {
1566 wxArrayString strings;
1567 wxDocTemplate **data = new wxDocTemplate *[noTemplates];
1568 int i;
1569 int n = 0;
1570
1571 for (i = 0; i < noTemplates; i++)
1572 {
1573 if (templates[i]->IsVisible())
1574 {
1575 int j;
1576 bool want = true;
1577 for (j = 0; j < n; j++)
1578 {
1579 //filter out NOT unique documents + view combinations
1580 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1581 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1582 )
1583 want = false;
1584 }
1585
1586 if ( want )
1587 {
1588 strings.Add(templates[i]->m_description);
1589
1590 data[n] = templates[i];
1591 n ++;
1592 }
1593 }
1594 } // for
1595
1596 if (sort)
1597 {
1598 strings.Sort(); // ascending sort
1599 // Yes, this will be slow, but template lists
1600 // are typically short.
1601 int j;
1602 n = strings.Count();
1603 for (i = 0; i < n; i++)
1604 {
1605 for (j = 0; j < noTemplates; j++)
1606 {
1607 if (strings[i] == templates[j]->m_description)
1608 data[i] = templates[j];
1609 }
1610 }
1611 }
1612
1613 wxDocTemplate *theTemplate;
1614
1615 switch ( n )
1616 {
1617 case 0:
1618 // no visible templates, hence nothing to choose from
1619 theTemplate = NULL;
1620 break;
1621
1622 case 1:
1623 // don't propose the user to choose if he has no choice
1624 theTemplate = data[0];
1625 break;
1626
1627 default:
1628 // propose the user to choose one of several
1629 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1630 (
1631 _("Select a document template"),
1632 _("Templates"),
1633 strings,
1634 (void **)data,
1635 wxFindSuitableParent()
1636 );
1637 }
1638
1639 delete[] data;
1640
1641 return theTemplate;
1642 }
1643
1644 wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1645 int noTemplates, bool sort)
1646 {
1647 wxArrayString strings;
1648 wxDocTemplate **data = new wxDocTemplate *[noTemplates];
1649 int i;
1650 int n = 0;
1651
1652 for (i = 0; i < noTemplates; i++)
1653 {
1654 wxDocTemplate *templ = templates[i];
1655 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1656 {
1657 int j;
1658 bool want = true;
1659 for (j = 0; j < n; j++)
1660 {
1661 //filter out NOT unique views
1662 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1663 want = false;
1664 }
1665
1666 if ( want )
1667 {
1668 strings.Add(templ->m_viewTypeName);
1669 data[n] = templ;
1670 n ++;
1671 }
1672 }
1673 }
1674
1675 if (sort)
1676 {
1677 strings.Sort(); // ascending sort
1678 // Yes, this will be slow, but template lists
1679 // are typically short.
1680 int j;
1681 n = strings.Count();
1682 for (i = 0; i < n; i++)
1683 {
1684 for (j = 0; j < noTemplates; j++)
1685 {
1686 if (strings[i] == templates[j]->m_viewTypeName)
1687 data[i] = templates[j];
1688 }
1689 }
1690 }
1691
1692 wxDocTemplate *theTemplate;
1693
1694 // the same logic as above
1695 switch ( n )
1696 {
1697 case 0:
1698 theTemplate = NULL;
1699 break;
1700
1701 case 1:
1702 theTemplate = data[0];
1703 break;
1704
1705 default:
1706 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1707 (
1708 _("Select a document view"),
1709 _("Views"),
1710 strings,
1711 (void **)data,
1712 wxFindSuitableParent()
1713 );
1714
1715 }
1716
1717 delete[] data;
1718 return theTemplate;
1719 }
1720
1721 void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1722 {
1723 if (!m_templates.Member(temp))
1724 m_templates.Append(temp);
1725 }
1726
1727 void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1728 {
1729 m_templates.DeleteObject(temp);
1730 }
1731
1732 // Add and remove a document from the manager's list
1733 void wxDocManager::AddDocument(wxDocument *doc)
1734 {
1735 if (!m_docs.Member(doc))
1736 m_docs.Append(doc);
1737 }
1738
1739 void wxDocManager::RemoveDocument(wxDocument *doc)
1740 {
1741 m_docs.DeleteObject(doc);
1742 }
1743
1744 // Views or windows should inform the document manager
1745 // when a view is going in or out of focus
1746 void wxDocManager::ActivateView(wxView *view, bool activate)
1747 {
1748 if ( activate )
1749 {
1750 m_currentView = view;
1751 }
1752 else // deactivate
1753 {
1754 if ( m_currentView == view )
1755 {
1756 // don't keep stale pointer
1757 m_currentView = NULL;
1758 }
1759 }
1760 }
1761
1762 // ----------------------------------------------------------------------------
1763 // Default document child frame
1764 // ----------------------------------------------------------------------------
1765
1766 BEGIN_EVENT_TABLE(wxDocChildFrame, wxFrame)
1767 EVT_ACTIVATE(wxDocChildFrame::OnActivate)
1768 EVT_CLOSE(wxDocChildFrame::OnCloseWindow)
1769 END_EVENT_TABLE()
1770
1771 wxDocChildFrame::wxDocChildFrame(wxDocument *doc,
1772 wxView *view,
1773 wxFrame *frame,
1774 wxWindowID id,
1775 const wxString& title,
1776 const wxPoint& pos,
1777 const wxSize& size,
1778 long style,
1779 const wxString& name)
1780 : wxFrame(frame, id, title, pos, size, style, name)
1781 {
1782 m_childDocument = doc;
1783 m_childView = view;
1784 if (view)
1785 view->SetFrame(this);
1786 }
1787
1788 bool wxDocChildFrame::TryValidator(wxEvent& event)
1789 {
1790 if ( !m_childView )
1791 return false;
1792
1793 // FIXME: why is this needed here?
1794 m_childView->Activate(true);
1795
1796 return m_childView->ProcessEventHere(event);
1797 }
1798
1799 void wxDocChildFrame::OnActivate(wxActivateEvent& event)
1800 {
1801 wxFrame::OnActivate(event);
1802
1803 if (m_childView)
1804 m_childView->Activate(event.GetActive());
1805 }
1806
1807 void wxDocChildFrame::OnCloseWindow(wxCloseEvent& event)
1808 {
1809 if (m_childView)
1810 {
1811 bool ans = event.CanVeto()
1812 ? m_childView->Close(false) // false means don't delete associated window
1813 : true; // Must delete.
1814
1815 if (ans)
1816 {
1817 m_childView->Activate(false);
1818 delete m_childView;
1819 m_childView = NULL;
1820 m_childDocument = NULL;
1821
1822 this->Destroy();
1823 }
1824 else
1825 event.Veto();
1826 }
1827 else
1828 event.Veto();
1829 }
1830
1831 // ----------------------------------------------------------------------------
1832 // Default parent frame
1833 // ----------------------------------------------------------------------------
1834
1835 BEGIN_EVENT_TABLE(wxDocParentFrame, wxFrame)
1836 EVT_MENU(wxID_EXIT, wxDocParentFrame::OnExit)
1837 EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocParentFrame::OnMRUFile)
1838 EVT_CLOSE(wxDocParentFrame::OnCloseWindow)
1839 END_EVENT_TABLE()
1840
1841 wxDocParentFrame::wxDocParentFrame()
1842 {
1843 m_docManager = NULL;
1844 }
1845
1846 wxDocParentFrame::wxDocParentFrame(wxDocManager *manager,
1847 wxFrame *frame,
1848 wxWindowID id,
1849 const wxString& title,
1850 const wxPoint& pos,
1851 const wxSize& size,
1852 long style,
1853 const wxString& name)
1854 : wxFrame(frame, id, title, pos, size, style, name)
1855 {
1856 m_docManager = manager;
1857 }
1858
1859 bool wxDocParentFrame::Create(wxDocManager *manager,
1860 wxFrame *frame,
1861 wxWindowID id,
1862 const wxString& title,
1863 const wxPoint& pos,
1864 const wxSize& size,
1865 long style,
1866 const wxString& name)
1867 {
1868 m_docManager = manager;
1869 return base_type::Create(frame, id, title, pos, size, style, name);
1870 }
1871
1872 void wxDocParentFrame::OnExit(wxCommandEvent& WXUNUSED(event))
1873 {
1874 Close();
1875 }
1876
1877 void wxDocParentFrame::OnMRUFile(wxCommandEvent& event)
1878 {
1879 int n = event.GetId() - wxID_FILE1; // the index in MRU list
1880 wxString filename(m_docManager->GetHistoryFile(n));
1881 if ( filename.empty() )
1882 return;
1883
1884 wxString errMsg; // must contain exactly one "%s" if non-empty
1885 if ( wxFile::Exists(filename) )
1886 {
1887 // try to open it
1888 if ( m_docManager->CreateDocument(filename, wxDOC_SILENT) )
1889 return;
1890
1891 errMsg = _("The file '%s' couldn't be opened.");
1892 }
1893 else // file doesn't exist
1894 {
1895 errMsg = _("The file '%s' doesn't exist and couldn't be opened.");
1896 }
1897
1898
1899 wxASSERT_MSG( !errMsg.empty(), "should have an error message" );
1900
1901 // remove the file which we can't open from the MRU list
1902 m_docManager->RemoveFileFromHistory(n);
1903
1904 // and tell the user about it
1905 wxLogError(errMsg + '\n' +
1906 _("It has been removed from the most recently used files list."),
1907 filename);
1908 }
1909
1910 // Extend event processing to search the view's event table
1911 bool wxDocParentFrame::TryValidator(wxEvent& event)
1912 {
1913 return m_docManager && m_docManager->ProcessEventHere(event);
1914 }
1915
1916 // Define the behaviour for the frame closing
1917 // - must delete all frames except for the main one.
1918 void wxDocParentFrame::OnCloseWindow(wxCloseEvent& event)
1919 {
1920 if (m_docManager->Clear(!event.CanVeto()))
1921 {
1922 this->Destroy();
1923 }
1924 else
1925 event.Veto();
1926 }
1927
1928 #if wxUSE_PRINTING_ARCHITECTURE
1929
1930 wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
1931 : wxPrintout(title)
1932 {
1933 m_printoutView = view;
1934 }
1935
1936 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
1937 {
1938 wxDC *dc = GetDC();
1939
1940 // Get the logical pixels per inch of screen and printer
1941 int ppiScreenX, ppiScreenY;
1942 GetPPIScreen(&ppiScreenX, &ppiScreenY);
1943 wxUnusedVar(ppiScreenY);
1944 int ppiPrinterX, ppiPrinterY;
1945 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
1946 wxUnusedVar(ppiPrinterY);
1947
1948 // This scales the DC so that the printout roughly represents the
1949 // the screen scaling. The text point size _should_ be the right size
1950 // but in fact is too small for some reason. This is a detail that will
1951 // need to be addressed at some point but can be fudged for the
1952 // moment.
1953 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
1954
1955 // Now we have to check in case our real page size is reduced
1956 // (e.g. because we're drawing to a print preview memory DC)
1957 int pageWidth, pageHeight;
1958 int w, h;
1959 dc->GetSize(&w, &h);
1960 GetPageSizePixels(&pageWidth, &pageHeight);
1961 wxUnusedVar(pageHeight);
1962
1963 // If printer pageWidth == current DC width, then this doesn't
1964 // change. But w might be the preview bitmap width, so scale down.
1965 float overallScale = scale * (float)(w/(float)pageWidth);
1966 dc->SetUserScale(overallScale, overallScale);
1967
1968 if (m_printoutView)
1969 {
1970 m_printoutView->OnDraw(dc);
1971 }
1972 return true;
1973 }
1974
1975 bool wxDocPrintout::HasPage(int pageNum)
1976 {
1977 return (pageNum == 1);
1978 }
1979
1980 bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
1981 {
1982 if (!wxPrintout::OnBeginDocument(startPage, endPage))
1983 return false;
1984
1985 return true;
1986 }
1987
1988 void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage, 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