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