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