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