]> git.saurik.com Git - wxWidgets.git/blob - src/common/docview.cpp
Don't pass NULL to wxDir, rather hop over when trying to find dir with translation
[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 // We don't know in advance how many items can there be in the MRU files
888 // list so set up OnMRUFile() as a handler for all menu events and do the
889 // check for the id of the menu item clicked inside it.
890 EVT_MENU(wxID_ANY, wxDocManager::OnMRUFile)
891
892 EVT_UPDATE_UI(wxID_OPEN, wxDocManager::OnUpdateFileOpen)
893 EVT_UPDATE_UI(wxID_CLOSE, wxDocManager::OnUpdateDisableIfNoDoc)
894 EVT_UPDATE_UI(wxID_CLOSE_ALL, wxDocManager::OnUpdateDisableIfNoDoc)
895 EVT_UPDATE_UI(wxID_REVERT, wxDocManager::OnUpdateFileRevert)
896 EVT_UPDATE_UI(wxID_NEW, wxDocManager::OnUpdateFileNew)
897 EVT_UPDATE_UI(wxID_SAVE, wxDocManager::OnUpdateFileSave)
898 EVT_UPDATE_UI(wxID_SAVEAS, wxDocManager::OnUpdateDisableIfNoDoc)
899 EVT_UPDATE_UI(wxID_UNDO, wxDocManager::OnUpdateUndo)
900 EVT_UPDATE_UI(wxID_REDO, wxDocManager::OnUpdateRedo)
901
902 #if wxUSE_PRINTING_ARCHITECTURE
903 EVT_MENU(wxID_PRINT, wxDocManager::OnPrint)
904 EVT_MENU(wxID_PREVIEW, wxDocManager::OnPreview)
905 EVT_MENU(wxID_PRINT_SETUP, wxDocManager::OnPageSetup)
906
907 EVT_UPDATE_UI(wxID_PRINT, wxDocManager::OnUpdateDisableIfNoDoc)
908 EVT_UPDATE_UI(wxID_PREVIEW, wxDocManager::OnUpdateDisableIfNoDoc)
909 // NB: we keep "Print setup" menu item always enabled as it can be used
910 // even without an active document
911 #endif // wxUSE_PRINTING_ARCHITECTURE
912 END_EVENT_TABLE()
913
914 wxDocManager* wxDocManager::sm_docManager = NULL;
915
916 wxDocManager::wxDocManager(long WXUNUSED(flags), bool initialize)
917 {
918 sm_docManager = this;
919
920 m_defaultDocumentNameCounter = 1;
921 m_currentView = NULL;
922 m_maxDocsOpen = INT_MAX;
923 m_fileHistory = NULL;
924 if ( initialize )
925 Initialize();
926 }
927
928 wxDocManager::~wxDocManager()
929 {
930 Clear();
931 delete m_fileHistory;
932 sm_docManager = NULL;
933 }
934
935 // closes the specified document
936 bool wxDocManager::CloseDocument(wxDocument* doc, bool force)
937 {
938 if ( !doc->Close() && !force )
939 return false;
940
941 // Implicitly deletes the document when
942 // the last view is deleted
943 doc->DeleteAllViews();
944
945 // Check we're really deleted
946 if (m_docs.Member(doc))
947 delete doc;
948
949 return true;
950 }
951
952 bool wxDocManager::CloseDocuments(bool force)
953 {
954 wxList::compatibility_iterator node = m_docs.GetFirst();
955 while (node)
956 {
957 wxDocument *doc = (wxDocument *)node->GetData();
958 wxList::compatibility_iterator next = node->GetNext();
959
960 if (!CloseDocument(doc, force))
961 return false;
962
963 // This assumes that documents are not connected in
964 // any way, i.e. deleting one document does NOT
965 // delete another.
966 node = next;
967 }
968 return true;
969 }
970
971 bool wxDocManager::Clear(bool force)
972 {
973 if (!CloseDocuments(force))
974 return false;
975
976 m_currentView = NULL;
977
978 wxList::compatibility_iterator node = m_templates.GetFirst();
979 while (node)
980 {
981 wxDocTemplate *templ = (wxDocTemplate*) node->GetData();
982 wxList::compatibility_iterator next = node->GetNext();
983 delete templ;
984 node = next;
985 }
986 return true;
987 }
988
989 bool wxDocManager::Initialize()
990 {
991 m_fileHistory = OnCreateFileHistory();
992 return true;
993 }
994
995 wxString wxDocManager::GetLastDirectory() const
996 {
997 // if we haven't determined the last used directory yet, do it now
998 if ( m_lastDirectory.empty() )
999 {
1000 // we're going to modify m_lastDirectory in this const method, so do it
1001 // via non-const self pointer instead of const this one
1002 wxDocManager * const self = const_cast<wxDocManager *>(this);
1003
1004 // first try to reuse the directory of the most recently opened file:
1005 // this ensures that if the user opens a file, closes the program and
1006 // runs it again the "Open file" dialog will open in the directory of
1007 // the last file he used
1008 if ( m_fileHistory && m_fileHistory->GetCount() )
1009 {
1010 const wxString lastOpened = m_fileHistory->GetHistoryFile(0);
1011 const wxFileName fn(lastOpened);
1012 if ( fn.DirExists() )
1013 {
1014 self->m_lastDirectory = fn.GetPath();
1015 }
1016 //else: should we try the next one?
1017 }
1018 //else: no history yet
1019
1020 // if we don't have any files in the history (yet?), use the
1021 // system-dependent default location for the document files
1022 if ( m_lastDirectory.empty() )
1023 {
1024 self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir();
1025 }
1026 }
1027
1028 return m_lastDirectory;
1029 }
1030
1031 wxFileHistory *wxDocManager::OnCreateFileHistory()
1032 {
1033 return new wxFileHistory;
1034 }
1035
1036 void wxDocManager::OnFileClose(wxCommandEvent& WXUNUSED(event))
1037 {
1038 wxDocument *doc = GetCurrentDocument();
1039 if (!doc)
1040 return;
1041 if (doc->Close())
1042 {
1043 doc->DeleteAllViews();
1044 if (m_docs.Member(doc))
1045 delete doc;
1046 }
1047 }
1048
1049 void wxDocManager::OnFileCloseAll(wxCommandEvent& WXUNUSED(event))
1050 {
1051 CloseDocuments(false);
1052 }
1053
1054 void wxDocManager::OnFileNew(wxCommandEvent& WXUNUSED(event))
1055 {
1056 CreateNewDocument();
1057 }
1058
1059 void wxDocManager::OnFileOpen(wxCommandEvent& WXUNUSED(event))
1060 {
1061 if ( !CreateDocument("") )
1062 {
1063 OnOpenFileFailure();
1064 }
1065 }
1066
1067 void wxDocManager::OnFileRevert(wxCommandEvent& WXUNUSED(event))
1068 {
1069 wxDocument *doc = GetCurrentDocument();
1070 if (!doc)
1071 return;
1072 doc->Revert();
1073 }
1074
1075 void wxDocManager::OnFileSave(wxCommandEvent& WXUNUSED(event))
1076 {
1077 wxDocument *doc = GetCurrentDocument();
1078 if (!doc)
1079 return;
1080 doc->Save();
1081 }
1082
1083 void wxDocManager::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))
1084 {
1085 wxDocument *doc = GetCurrentDocument();
1086 if (!doc)
1087 return;
1088 doc->SaveAs();
1089 }
1090
1091 void wxDocManager::OnMRUFile(wxCommandEvent& event)
1092 {
1093 // Check if the id is in the range assigned to MRU list entries.
1094 const int id = event.GetId();
1095 if ( id >= wxID_FILE1 &&
1096 id < wxID_FILE1 + m_fileHistory->GetBaseId() )
1097 {
1098 DoOpenMRUFile(id - wxID_FILE1);
1099 }
1100 else
1101 {
1102 event.Skip();
1103 }
1104 }
1105
1106 void wxDocManager::DoOpenMRUFile(unsigned n)
1107 {
1108 wxString filename(GetHistoryFile(n));
1109 if ( filename.empty() )
1110 return;
1111
1112 wxString errMsg; // must contain exactly one "%s" if non-empty
1113 if ( wxFile::Exists(filename) )
1114 {
1115 // try to open it
1116 if ( CreateDocument(filename, wxDOC_SILENT) )
1117 return;
1118
1119 errMsg = _("The file '%s' couldn't be opened.");
1120 }
1121 else // file doesn't exist
1122 {
1123 errMsg = _("The file '%s' doesn't exist and couldn't be opened.");
1124 }
1125
1126
1127 wxASSERT_MSG( !errMsg.empty(), "should have an error message" );
1128
1129 // remove the file which we can't open from the MRU list
1130 RemoveFileFromHistory(n);
1131
1132 // and tell the user about it
1133 wxLogError(errMsg + '\n' +
1134 _("It has been removed from the most recently used files list."),
1135 filename);
1136 }
1137
1138 #if wxUSE_PRINTING_ARCHITECTURE
1139
1140 void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event))
1141 {
1142 wxView *view = GetActiveView();
1143 if (!view)
1144 return;
1145
1146 wxPrintout *printout = view->OnCreatePrintout();
1147 if (printout)
1148 {
1149 wxPrintDialogData printDialogData(m_pageSetupDialogData.GetPrintData());
1150 wxPrinter printer(&printDialogData);
1151 printer.Print(view->GetFrame(), printout, true);
1152
1153 delete printout;
1154 }
1155 }
1156
1157 void wxDocManager::OnPageSetup(wxCommandEvent& WXUNUSED(event))
1158 {
1159 wxPageSetupDialog dlg(wxTheApp->GetTopWindow(), &m_pageSetupDialogData);
1160 if ( dlg.ShowModal() == wxID_OK )
1161 {
1162 m_pageSetupDialogData = dlg.GetPageSetupData();
1163 }
1164 }
1165
1166 wxPreviewFrame* wxDocManager::CreatePreviewFrame(wxPrintPreviewBase* preview,
1167 wxWindow *parent,
1168 const wxString& title)
1169 {
1170 return new wxPreviewFrame(preview, parent, title);
1171 }
1172
1173 void wxDocManager::OnPreview(wxCommandEvent& WXUNUSED(event))
1174 {
1175 wxBusyCursor busy;
1176 wxView *view = GetActiveView();
1177 if (!view)
1178 return;
1179
1180 wxPrintout *printout = view->OnCreatePrintout();
1181 if (printout)
1182 {
1183 wxPrintDialogData printDialogData(m_pageSetupDialogData.GetPrintData());
1184
1185 // Pass two printout objects: for preview, and possible printing.
1186 wxPrintPreviewBase *
1187 preview = new wxPrintPreview(printout,
1188 view->OnCreatePrintout(),
1189 &printDialogData);
1190 if ( !preview->Ok() )
1191 {
1192 delete preview;
1193 wxLogError(_("Print preview creation failed."));
1194 return;
1195 }
1196
1197 wxPreviewFrame* frame = CreatePreviewFrame(preview,
1198 wxTheApp->GetTopWindow(),
1199 _("Print Preview"));
1200 wxCHECK_RET( frame, "should create a print preview frame" );
1201
1202 frame->Centre(wxBOTH);
1203 frame->Initialize();
1204 frame->Show(true);
1205 }
1206 }
1207 #endif // wxUSE_PRINTING_ARCHITECTURE
1208
1209 void wxDocManager::OnUndo(wxCommandEvent& event)
1210 {
1211 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1212 if ( !cmdproc )
1213 {
1214 event.Skip();
1215 return;
1216 }
1217
1218 cmdproc->Undo();
1219 }
1220
1221 void wxDocManager::OnRedo(wxCommandEvent& event)
1222 {
1223 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1224 if ( !cmdproc )
1225 {
1226 event.Skip();
1227 return;
1228 }
1229
1230 cmdproc->Redo();
1231 }
1232
1233 // Handlers for UI update commands
1234
1235 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent& event)
1236 {
1237 // CreateDocument() (which is called from OnFileOpen) may succeed
1238 // only when there is at least a template:
1239 event.Enable( GetTemplates().GetCount()>0 );
1240 }
1241
1242 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent& event)
1243 {
1244 event.Enable( GetCurrentDocument() != NULL );
1245 }
1246
1247 void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent& event)
1248 {
1249 wxDocument* doc = GetCurrentDocument();
1250 event.Enable(doc && doc->IsModified() && doc->GetDocumentSaved());
1251 }
1252
1253 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event)
1254 {
1255 // CreateDocument() (which is called from OnFileNew) may succeed
1256 // only when there is at least a template:
1257 event.Enable( GetTemplates().GetCount()>0 );
1258 }
1259
1260 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event)
1261 {
1262 wxDocument * const doc = GetCurrentDocument();
1263 event.Enable( doc && !doc->AlreadySaved() );
1264 }
1265
1266 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event)
1267 {
1268 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1269 if ( !cmdproc )
1270 {
1271 event.Enable(false);
1272 return;
1273 }
1274
1275 event.Enable(cmdproc->CanUndo());
1276 cmdproc->SetMenuStrings();
1277 }
1278
1279 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event)
1280 {
1281 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1282 if ( !cmdproc )
1283 {
1284 event.Enable(false);
1285 return;
1286 }
1287
1288 event.Enable(cmdproc->CanRedo());
1289 cmdproc->SetMenuStrings();
1290 }
1291
1292 wxView *wxDocManager::GetActiveView() const
1293 {
1294 wxView *view = GetCurrentView();
1295
1296 if ( !view && !m_docs.empty() )
1297 {
1298 // if we have exactly one document, consider its view to be the current
1299 // one
1300 //
1301 // VZ: I'm not exactly sure why is this needed but this is how this
1302 // code used to behave before the bug #9518 was fixed and it seems
1303 // safer to preserve the old logic
1304 wxList::compatibility_iterator node = m_docs.GetFirst();
1305 if ( !node->GetNext() )
1306 {
1307 wxDocument *doc = static_cast<wxDocument *>(node->GetData());
1308 view = doc->GetFirstView();
1309 }
1310 //else: we have more than one document
1311 }
1312
1313 return view;
1314 }
1315
1316 bool wxDocManager::TryBefore(wxEvent& event)
1317 {
1318 wxView * const view = GetActiveView();
1319 return view && view->ProcessEventLocally(event);
1320 }
1321
1322 namespace
1323 {
1324
1325 // helper function: return only the visible templates
1326 wxDocTemplates GetVisibleTemplates(const wxList& allTemplates)
1327 {
1328 // select only the visible templates
1329 const size_t totalNumTemplates = allTemplates.GetCount();
1330 wxDocTemplates templates;
1331 if ( totalNumTemplates )
1332 {
1333 templates.reserve(totalNumTemplates);
1334
1335 for ( wxList::const_iterator i = allTemplates.begin(),
1336 end = allTemplates.end();
1337 i != end;
1338 ++i )
1339 {
1340 wxDocTemplate * const temp = (wxDocTemplate *)*i;
1341 if ( temp->IsVisible() )
1342 templates.push_back(temp);
1343 }
1344 }
1345
1346 return templates;
1347 }
1348
1349 } // anonymous namespace
1350
1351 void wxDocManager::ActivateDocument(wxDocument *doc)
1352 {
1353 wxView * const view = doc->GetFirstView();
1354 if ( !view )
1355 return;
1356
1357 view->Activate(true);
1358 if ( wxWindow *win = view->GetFrame() )
1359 win->SetFocus();
1360 }
1361
1362 wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags)
1363 {
1364 // this ought to be const but SelectDocumentType/Path() are not
1365 // const-correct and can't be changed as, being virtual, this risks
1366 // breaking user code overriding them
1367 wxDocTemplates templates(GetVisibleTemplates(m_templates));
1368 const size_t numTemplates = templates.size();
1369 if ( !numTemplates )
1370 {
1371 // no templates can be used, can't create document
1372 return NULL;
1373 }
1374
1375
1376 // normally user should select the template to use but wxDOC_SILENT flag we
1377 // choose one ourselves
1378 wxString path = pathOrig; // may be modified below
1379 wxDocTemplate *temp;
1380 if ( flags & wxDOC_SILENT )
1381 {
1382 wxASSERT_MSG( !path.empty(),
1383 "using empty path with wxDOC_SILENT doesn't make sense" );
1384
1385 temp = FindTemplateForPath(path);
1386 if ( !temp )
1387 {
1388 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1389 path);
1390 }
1391 }
1392 else // not silent, ask the user
1393 {
1394 // for the new file we need just the template, for an existing one we
1395 // need the template and the path, unless it's already specified
1396 if ( (flags & wxDOC_NEW) || !path.empty() )
1397 temp = SelectDocumentType(&templates[0], numTemplates);
1398 else
1399 temp = SelectDocumentPath(&templates[0], numTemplates, path, flags);
1400 }
1401
1402 if ( !temp )
1403 return NULL;
1404
1405 // check whether the document with this path is already opened
1406 if ( !path.empty() )
1407 {
1408 const wxFileName fn(path);
1409 for ( wxList::const_iterator i = m_docs.begin(); i != m_docs.end(); ++i )
1410 {
1411 wxDocument * const doc = (wxDocument*)*i;
1412
1413 if ( fn == doc->GetFilename() )
1414 {
1415 // file already open, just activate it and return
1416 ActivateDocument(doc);
1417 }
1418 }
1419 }
1420
1421
1422 // no, we need to create a new document
1423
1424
1425 // if we've reached the max number of docs, close the first one.
1426 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen )
1427 {
1428 if ( !CloseDocument((wxDocument *)GetDocuments().GetFirst()->GetData()) )
1429 {
1430 // can't open the new document if closing the old one failed
1431 return NULL;
1432 }
1433 }
1434
1435
1436 // do create and initialize the new document finally
1437 wxDocument * const docNew = temp->CreateDocument(path, flags);
1438 if ( !docNew )
1439 return NULL;
1440
1441 docNew->SetDocumentName(temp->GetDocumentName());
1442 docNew->SetDocumentTemplate(temp);
1443
1444 wxTRY
1445 {
1446 // call the appropriate function depending on whether we're creating a
1447 // new file or opening an existing one
1448 if ( !(flags & wxDOC_NEW ? docNew->OnNewDocument()
1449 : docNew->OnOpenDocument(path)) )
1450 {
1451 docNew->DeleteAllViews();
1452 return NULL;
1453 }
1454 }
1455 wxCATCH_ALL( docNew->DeleteAllViews(); throw; )
1456
1457 // add the successfully opened file to MRU, but only if we're going to be
1458 // able to reopen it successfully later which requires the template for
1459 // this document to be retrievable from the file extension
1460 if ( !(flags & wxDOC_NEW) && temp->FileMatchesTemplate(path) )
1461 AddFileToHistory(path);
1462
1463 // at least under Mac (where views are top level windows) it seems to be
1464 // necessary to manually activate the new document to bring it to the
1465 // forefront -- and it shouldn't hurt doing this under the other platforms
1466 ActivateDocument(docNew);
1467
1468 return docNew;
1469 }
1470
1471 wxView *wxDocManager::CreateView(wxDocument *doc, long flags)
1472 {
1473 wxDocTemplates templates(GetVisibleTemplates(m_templates));
1474 const size_t numTemplates = templates.size();
1475
1476 if ( numTemplates == 0 )
1477 return NULL;
1478
1479 wxDocTemplate * const
1480 temp = numTemplates == 1 ? templates[0]
1481 : SelectViewType(&templates[0], numTemplates);
1482
1483 if ( !temp )
1484 return NULL;
1485
1486 wxView *view = temp->CreateView(doc, flags);
1487 if ( view )
1488 view->SetViewName(temp->GetViewName());
1489 return view;
1490 }
1491
1492 // Not yet implemented
1493 void
1494 wxDocManager::DeleteTemplate(wxDocTemplate *WXUNUSED(temp), long WXUNUSED(flags))
1495 {
1496 }
1497
1498 // Not yet implemented
1499 bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc))
1500 {
1501 return false;
1502 }
1503
1504 wxDocument *wxDocManager::GetCurrentDocument() const
1505 {
1506 wxView * const view = GetActiveView();
1507 return view ? view->GetDocument() : NULL;
1508 }
1509
1510 wxCommandProcessor *wxDocManager::GetCurrentCommandProcessor() const
1511 {
1512 wxDocument * const doc = GetCurrentDocument();
1513 return doc ? doc->GetCommandProcessor() : NULL;
1514 }
1515
1516 // Make a default name for a new document
1517 #if WXWIN_COMPATIBILITY_2_8
1518 bool wxDocManager::MakeDefaultName(wxString& WXUNUSED(name))
1519 {
1520 // we consider that this function can only be overridden by the user code,
1521 // not called by it as it only makes sense to call it internally, so we
1522 // don't bother to return anything from here
1523 return false;
1524 }
1525 #endif // WXWIN_COMPATIBILITY_2_8
1526
1527 wxString wxDocManager::MakeNewDocumentName()
1528 {
1529 wxString name;
1530
1531 #if WXWIN_COMPATIBILITY_2_8
1532 if ( !MakeDefaultName(name) )
1533 #endif // WXWIN_COMPATIBILITY_2_8
1534 {
1535 name.Printf(_("unnamed%d"), m_defaultDocumentNameCounter);
1536 m_defaultDocumentNameCounter++;
1537 }
1538
1539 return name;
1540 }
1541
1542 // Make a frame title (override this to do something different)
1543 // If docName is empty, a document is not currently active.
1544 wxString wxDocManager::MakeFrameTitle(wxDocument* doc)
1545 {
1546 wxString appName = wxTheApp->GetAppDisplayName();
1547 wxString title;
1548 if (!doc)
1549 title = appName;
1550 else
1551 {
1552 wxString docName = doc->GetUserReadableName();
1553 title = docName + wxString(_(" - ")) + appName;
1554 }
1555 return title;
1556 }
1557
1558
1559 // Not yet implemented
1560 wxDocTemplate *wxDocManager::MatchTemplate(const wxString& WXUNUSED(path))
1561 {
1562 return NULL;
1563 }
1564
1565 // File history management
1566 void wxDocManager::AddFileToHistory(const wxString& file)
1567 {
1568 if (m_fileHistory)
1569 m_fileHistory->AddFileToHistory(file);
1570 }
1571
1572 void wxDocManager::RemoveFileFromHistory(size_t i)
1573 {
1574 if (m_fileHistory)
1575 m_fileHistory->RemoveFileFromHistory(i);
1576 }
1577
1578 wxString wxDocManager::GetHistoryFile(size_t i) const
1579 {
1580 wxString histFile;
1581
1582 if (m_fileHistory)
1583 histFile = m_fileHistory->GetHistoryFile(i);
1584
1585 return histFile;
1586 }
1587
1588 void wxDocManager::FileHistoryUseMenu(wxMenu *menu)
1589 {
1590 if (m_fileHistory)
1591 m_fileHistory->UseMenu(menu);
1592 }
1593
1594 void wxDocManager::FileHistoryRemoveMenu(wxMenu *menu)
1595 {
1596 if (m_fileHistory)
1597 m_fileHistory->RemoveMenu(menu);
1598 }
1599
1600 #if wxUSE_CONFIG
1601 void wxDocManager::FileHistoryLoad(const wxConfigBase& config)
1602 {
1603 if (m_fileHistory)
1604 m_fileHistory->Load(config);
1605 }
1606
1607 void wxDocManager::FileHistorySave(wxConfigBase& config)
1608 {
1609 if (m_fileHistory)
1610 m_fileHistory->Save(config);
1611 }
1612 #endif
1613
1614 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu* menu)
1615 {
1616 if (m_fileHistory)
1617 m_fileHistory->AddFilesToMenu(menu);
1618 }
1619
1620 void wxDocManager::FileHistoryAddFilesToMenu()
1621 {
1622 if (m_fileHistory)
1623 m_fileHistory->AddFilesToMenu();
1624 }
1625
1626 size_t wxDocManager::GetHistoryFilesCount() const
1627 {
1628 return m_fileHistory ? m_fileHistory->GetCount() : 0;
1629 }
1630
1631
1632 // Find out the document template via matching in the document file format
1633 // against that of the template
1634 wxDocTemplate *wxDocManager::FindTemplateForPath(const wxString& path)
1635 {
1636 wxDocTemplate *theTemplate = NULL;
1637
1638 // Find the template which this extension corresponds to
1639 for (size_t i = 0; i < m_templates.GetCount(); i++)
1640 {
1641 wxDocTemplate *temp = (wxDocTemplate *)m_templates.Item(i)->GetData();
1642 if ( temp->FileMatchesTemplate(path) )
1643 {
1644 theTemplate = temp;
1645 break;
1646 }
1647 }
1648 return theTemplate;
1649 }
1650
1651 // Prompts user to open a file, using file specs in templates.
1652 // Must extend the file selector dialog or implement own; OR
1653 // match the extension to the template extension.
1654
1655 wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates,
1656 int noTemplates,
1657 wxString& path,
1658 long WXUNUSED(flags),
1659 bool WXUNUSED(save))
1660 {
1661 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1662 wxString descrBuf;
1663
1664 for (int i = 0; i < noTemplates; i++)
1665 {
1666 if (templates[i]->IsVisible())
1667 {
1668 // add a '|' to separate this filter from the previous one
1669 if ( !descrBuf.empty() )
1670 descrBuf << wxT('|');
1671
1672 descrBuf << templates[i]->GetDescription()
1673 << wxT(" (") << templates[i]->GetFileFilter() << wxT(") |")
1674 << templates[i]->GetFileFilter();
1675 }
1676 }
1677 #else
1678 wxString descrBuf = wxT("*.*");
1679 wxUnusedVar(noTemplates);
1680 #endif
1681
1682 int FilterIndex = -1;
1683
1684 wxString pathTmp = wxFileSelectorEx(_("Open File"),
1685 GetLastDirectory(),
1686 wxEmptyString,
1687 &FilterIndex,
1688 descrBuf,
1689 wxFD_OPEN | wxFD_FILE_MUST_EXIST);
1690
1691 wxDocTemplate *theTemplate = NULL;
1692 if (!pathTmp.empty())
1693 {
1694 if (!wxFileExists(pathTmp))
1695 {
1696 wxString msgTitle;
1697 if (!wxTheApp->GetAppDisplayName().empty())
1698 msgTitle = wxTheApp->GetAppDisplayName();
1699 else
1700 msgTitle = wxString(_("File error"));
1701
1702 wxMessageBox(_("Sorry, could not open this file."),
1703 msgTitle,
1704 wxOK | wxICON_EXCLAMATION | wxCENTRE);
1705
1706 path = wxEmptyString;
1707 return NULL;
1708 }
1709
1710 SetLastDirectory(wxPathOnly(pathTmp));
1711
1712 path = pathTmp;
1713
1714 // first choose the template using the extension, if this fails (i.e.
1715 // wxFileSelectorEx() didn't fill it), then use the path
1716 if ( FilterIndex != -1 )
1717 theTemplate = templates[FilterIndex];
1718 if ( !theTemplate )
1719 theTemplate = FindTemplateForPath(path);
1720 if ( !theTemplate )
1721 {
1722 // Since we do not add files with non-default extensions to the
1723 // file history this can only happen if the application changes the
1724 // allowed templates in runtime.
1725 wxMessageBox(_("Sorry, the format for this file is unknown."),
1726 _("Open File"),
1727 wxOK | wxICON_EXCLAMATION | wxCENTRE);
1728 }
1729 }
1730 else
1731 {
1732 path.clear();
1733 }
1734
1735 return theTemplate;
1736 }
1737
1738 wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1739 int noTemplates, bool sort)
1740 {
1741 wxArrayString strings;
1742 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1743 int i;
1744 int n = 0;
1745
1746 for (i = 0; i < noTemplates; i++)
1747 {
1748 if (templates[i]->IsVisible())
1749 {
1750 int j;
1751 bool want = true;
1752 for (j = 0; j < n; j++)
1753 {
1754 //filter out NOT unique documents + view combinations
1755 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1756 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1757 )
1758 want = false;
1759 }
1760
1761 if ( want )
1762 {
1763 strings.Add(templates[i]->m_description);
1764
1765 data[n] = templates[i];
1766 n ++;
1767 }
1768 }
1769 } // for
1770
1771 if (sort)
1772 {
1773 strings.Sort(); // ascending sort
1774 // Yes, this will be slow, but template lists
1775 // are typically short.
1776 int j;
1777 n = strings.Count();
1778 for (i = 0; i < n; i++)
1779 {
1780 for (j = 0; j < noTemplates; j++)
1781 {
1782 if (strings[i] == templates[j]->m_description)
1783 data[i] = templates[j];
1784 }
1785 }
1786 }
1787
1788 wxDocTemplate *theTemplate;
1789
1790 switch ( n )
1791 {
1792 case 0:
1793 // no visible templates, hence nothing to choose from
1794 theTemplate = NULL;
1795 break;
1796
1797 case 1:
1798 // don't propose the user to choose if he has no choice
1799 theTemplate = data[0];
1800 break;
1801
1802 default:
1803 // propose the user to choose one of several
1804 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1805 (
1806 _("Select a document template"),
1807 _("Templates"),
1808 strings,
1809 (void **)data.get()
1810 );
1811 }
1812
1813 return theTemplate;
1814 }
1815
1816 wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1817 int noTemplates, bool sort)
1818 {
1819 wxArrayString strings;
1820 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1821 int i;
1822 int n = 0;
1823
1824 for (i = 0; i < noTemplates; i++)
1825 {
1826 wxDocTemplate *templ = templates[i];
1827 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1828 {
1829 int j;
1830 bool want = true;
1831 for (j = 0; j < n; j++)
1832 {
1833 //filter out NOT unique views
1834 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1835 want = false;
1836 }
1837
1838 if ( want )
1839 {
1840 strings.Add(templ->m_viewTypeName);
1841 data[n] = templ;
1842 n ++;
1843 }
1844 }
1845 }
1846
1847 if (sort)
1848 {
1849 strings.Sort(); // ascending sort
1850 // Yes, this will be slow, but template lists
1851 // are typically short.
1852 int j;
1853 n = strings.Count();
1854 for (i = 0; i < n; i++)
1855 {
1856 for (j = 0; j < noTemplates; j++)
1857 {
1858 if (strings[i] == templates[j]->m_viewTypeName)
1859 data[i] = templates[j];
1860 }
1861 }
1862 }
1863
1864 wxDocTemplate *theTemplate;
1865
1866 // the same logic as above
1867 switch ( n )
1868 {
1869 case 0:
1870 theTemplate = NULL;
1871 break;
1872
1873 case 1:
1874 theTemplate = data[0];
1875 break;
1876
1877 default:
1878 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1879 (
1880 _("Select a document view"),
1881 _("Views"),
1882 strings,
1883 (void **)data.get()
1884 );
1885
1886 }
1887
1888 return theTemplate;
1889 }
1890
1891 void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1892 {
1893 if (!m_templates.Member(temp))
1894 m_templates.Append(temp);
1895 }
1896
1897 void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1898 {
1899 m_templates.DeleteObject(temp);
1900 }
1901
1902 // Add and remove a document from the manager's list
1903 void wxDocManager::AddDocument(wxDocument *doc)
1904 {
1905 if (!m_docs.Member(doc))
1906 m_docs.Append(doc);
1907 }
1908
1909 void wxDocManager::RemoveDocument(wxDocument *doc)
1910 {
1911 m_docs.DeleteObject(doc);
1912 }
1913
1914 // Views or windows should inform the document manager
1915 // when a view is going in or out of focus
1916 void wxDocManager::ActivateView(wxView *view, bool activate)
1917 {
1918 if ( activate )
1919 {
1920 m_currentView = view;
1921 }
1922 else // deactivate
1923 {
1924 if ( m_currentView == view )
1925 {
1926 // don't keep stale pointer
1927 m_currentView = NULL;
1928 }
1929 }
1930 }
1931
1932 // ----------------------------------------------------------------------------
1933 // wxDocChildFrameAnyBase
1934 // ----------------------------------------------------------------------------
1935
1936 bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent& event)
1937 {
1938 if ( m_childView )
1939 {
1940 // notice that we must call wxView::Close() and OnClose() called from
1941 // it in any case, even if we know that we are going to close anyhow
1942 if ( !m_childView->Close(false) && event.CanVeto() )
1943 {
1944 event.Veto();
1945 return false;
1946 }
1947
1948 m_childView->Activate(false);
1949
1950 // it is important to reset m_childView frame pointer to NULL before
1951 // deleting it because while normally it is the frame which deletes the
1952 // view when it's closed, the view also closes the frame if it is
1953 // deleted directly not by us as indicated by its doc child frame
1954 // pointer still being set
1955 m_childView->SetDocChildFrame(NULL);
1956 wxDELETE(m_childView);
1957 }
1958
1959 m_childDocument = NULL;
1960
1961 return true;
1962 }
1963
1964 // ----------------------------------------------------------------------------
1965 // wxDocParentFrameAnyBase
1966 // ----------------------------------------------------------------------------
1967
1968 #if wxUSE_PRINTING_ARCHITECTURE
1969
1970 wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
1971 : wxPrintout(title)
1972 {
1973 m_printoutView = view;
1974 }
1975
1976 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
1977 {
1978 wxDC *dc = GetDC();
1979
1980 // Get the logical pixels per inch of screen and printer
1981 int ppiScreenX, ppiScreenY;
1982 GetPPIScreen(&ppiScreenX, &ppiScreenY);
1983 wxUnusedVar(ppiScreenY);
1984 int ppiPrinterX, ppiPrinterY;
1985 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
1986 wxUnusedVar(ppiPrinterY);
1987
1988 // This scales the DC so that the printout roughly represents the
1989 // the screen scaling. The text point size _should_ be the right size
1990 // but in fact is too small for some reason. This is a detail that will
1991 // need to be addressed at some point but can be fudged for the
1992 // moment.
1993 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
1994
1995 // Now we have to check in case our real page size is reduced
1996 // (e.g. because we're drawing to a print preview memory DC)
1997 int pageWidth, pageHeight;
1998 int w, h;
1999 dc->GetSize(&w, &h);
2000 GetPageSizePixels(&pageWidth, &pageHeight);
2001 wxUnusedVar(pageHeight);
2002
2003 // If printer pageWidth == current DC width, then this doesn't
2004 // change. But w might be the preview bitmap width, so scale down.
2005 float overallScale = scale * (float)(w/(float)pageWidth);
2006 dc->SetUserScale(overallScale, overallScale);
2007
2008 if (m_printoutView)
2009 {
2010 m_printoutView->OnDraw(dc);
2011 }
2012 return true;
2013 }
2014
2015 bool wxDocPrintout::HasPage(int pageNum)
2016 {
2017 return (pageNum == 1);
2018 }
2019
2020 bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
2021 {
2022 if (!wxPrintout::OnBeginDocument(startPage, endPage))
2023 return false;
2024
2025 return true;
2026 }
2027
2028 void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage,
2029 int *selPageFrom, int *selPageTo)
2030 {
2031 *minPage = 1;
2032 *maxPage = 1;
2033 *selPageFrom = 1;
2034 *selPageTo = 1;
2035 }
2036
2037 #endif // wxUSE_PRINTING_ARCHITECTURE
2038
2039 // ----------------------------------------------------------------------------
2040 // Permits compatibility with existing file formats and functions that
2041 // manipulate files directly
2042 // ----------------------------------------------------------------------------
2043
2044 #if wxUSE_STD_IOSTREAM
2045
2046 bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream)
2047 {
2048 #if wxUSE_FFILE
2049 wxFFile file(filename, wxT("rb"));
2050 #elif wxUSE_FILE
2051 wxFile file(filename, wxFile::read);
2052 #endif
2053 if ( !file.IsOpened() )
2054 return false;
2055
2056 char buf[4096];
2057
2058 size_t nRead;
2059 do
2060 {
2061 nRead = file.Read(buf, WXSIZEOF(buf));
2062 if ( file.Error() )
2063 return false;
2064
2065 stream.write(buf, nRead);
2066 if ( !stream )
2067 return false;
2068 }
2069 while ( !file.Eof() );
2070
2071 return true;
2072 }
2073
2074 bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename)
2075 {
2076 #if wxUSE_FFILE
2077 wxFFile file(filename, wxT("wb"));
2078 #elif wxUSE_FILE
2079 wxFile file(filename, wxFile::write);
2080 #endif
2081 if ( !file.IsOpened() )
2082 return false;
2083
2084 char buf[4096];
2085 do
2086 {
2087 stream.read(buf, WXSIZEOF(buf));
2088 if ( !stream.bad() ) // fail may be set on EOF, don't use operator!()
2089 {
2090 if ( !file.Write(buf, stream.gcount()) )
2091 return false;
2092 }
2093 }
2094 while ( !stream.eof() );
2095
2096 return true;
2097 }
2098
2099 #else // !wxUSE_STD_IOSTREAM
2100
2101 bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream)
2102 {
2103 #if wxUSE_FFILE
2104 wxFFile file(filename, wxT("rb"));
2105 #elif wxUSE_FILE
2106 wxFile file(filename, wxFile::read);
2107 #endif
2108 if ( !file.IsOpened() )
2109 return false;
2110
2111 char buf[4096];
2112
2113 size_t nRead;
2114 do
2115 {
2116 nRead = file.Read(buf, WXSIZEOF(buf));
2117 if ( file.Error() )
2118 return false;
2119
2120 stream.Write(buf, nRead);
2121 if ( !stream )
2122 return false;
2123 }
2124 while ( !file.Eof() );
2125
2126 return true;
2127 }
2128
2129 bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename)
2130 {
2131 #if wxUSE_FFILE
2132 wxFFile file(filename, wxT("wb"));
2133 #elif wxUSE_FILE
2134 wxFile file(filename, wxFile::write);
2135 #endif
2136 if ( !file.IsOpened() )
2137 return false;
2138
2139 char buf[4096];
2140 for ( ;; )
2141 {
2142 stream.Read(buf, WXSIZEOF(buf));
2143
2144 const size_t nRead = stream.LastRead();
2145 if ( !nRead )
2146 {
2147 if ( stream.Eof() )
2148 break;
2149
2150 return false;
2151 }
2152
2153 if ( !file.Write(buf, nRead) )
2154 return false;
2155 }
2156
2157 return true;
2158 }
2159
2160 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2161
2162 #endif // wxUSE_DOC_VIEW_ARCHITECTURE