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