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