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