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