]> git.saurik.com Git - wxWidgets.git/blob - src/common/docview.cpp
fixed wxXmlResource::Load's detection of filenames to be done as early as possible
[wxWidgets.git] / src / common / docview.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/docview.cpp
3 // Purpose: Document/view classes
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
6 // Created: 01/02/97
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_DOC_VIEW_ARCHITECTURE
28
29 #include "wx/docview.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/list.h"
33 #include "wx/string.h"
34 #include "wx/utils.h"
35 #include "wx/app.h"
36 #include "wx/dc.h"
37 #include "wx/dialog.h"
38 #include "wx/menu.h"
39 #include "wx/filedlg.h"
40 #include "wx/intl.h"
41 #include "wx/log.h"
42 #include "wx/msgdlg.h"
43 #include "wx/mdi.h"
44 #include "wx/choicdlg.h"
45 #endif
46
47 #if wxUSE_PRINTING_ARCHITECTURE
48 #include "wx/prntbase.h"
49 #include "wx/printdlg.h"
50 #endif
51
52 #include "wx/confbase.h"
53 #include "wx/filename.h"
54 #include "wx/file.h"
55 #include "wx/ffile.h"
56 #include "wx/cmdproc.h"
57 #include "wx/tokenzr.h"
58 #include "wx/filename.h"
59 #include "wx/stdpaths.h"
60 #include "wx/vector.h"
61 #include "wx/scopedarray.h"
62 #include "wx/scopedptr.h"
63
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
77 typedef wxVector<wxDocTemplate *> wxDocTemplates;
78
79 // ----------------------------------------------------------------------------
80 // wxWidgets macros
81 // ----------------------------------------------------------------------------
82
83 IMPLEMENT_ABSTRACT_CLASS(wxDocument, wxEvtHandler)
84 IMPLEMENT_ABSTRACT_CLASS(wxView, wxEvtHandler)
85 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate, wxObject)
86 IMPLEMENT_DYNAMIC_CLASS(wxDocManager, wxEvtHandler)
87 IMPLEMENT_CLASS(wxDocChildFrame, wxFrame)
88 IMPLEMENT_CLASS(wxDocParentFrame, wxFrame)
89
90 #if wxUSE_PRINTING_ARCHITECTURE
91 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout, wxPrintout)
92 #endif
93
94 IMPLEMENT_DYNAMIC_CLASS(wxFileHistory, wxObject)
95
96 // ============================================================================
97 // implementation
98 // ============================================================================
99
100 // ----------------------------------------------------------------------------
101 // private helpers
102 // ----------------------------------------------------------------------------
103
104 namespace
105 {
106
107 wxWindow *wxFindSuitableParent()
108 {
109 wxWindow * const win = wxGetTopLevelParent(wxWindow::FindFocus());
110
111 return win ? win : wxTheApp->GetTopWindow();
112 }
113
114 wxString 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
127 wxString 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
142 wxDocument::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
151 bool wxDocument::DeleteContents()
152 {
153 return true;
154 }
155
156 wxDocument::~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
171 bool wxDocument::Close()
172 {
173 if ( !OnSaveModified() )
174 return false;
175
176 return OnCloseDocument();
177 }
178
179 bool 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.
190 bool 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
234 wxView *wxDocument::GetFirstView() const
235 {
236 if ( m_documentViews.empty() )
237 return NULL;
238
239 return static_cast<wxView *>(m_documentViews.GetFirst()->GetData());
240 }
241
242 wxDocManager *wxDocument::GetDocumentManager() const
243 {
244 return m_documentTemplate ? m_documentTemplate->GetDocumentManager() : NULL;
245 }
246
247 bool 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
263 bool 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
274 bool 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
362 bool 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
380 bool 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
398 wxSTD istream& wxDocument::LoadObject(wxSTD istream& stream)
399 #else
400 wxInputStream& wxDocument::LoadObject(wxInputStream& stream)
401 #endif
402 {
403 return stream;
404 }
405
406 #if wxUSE_STD_IOSTREAM
407 wxSTD ostream& wxDocument::SaveObject(wxSTD ostream& stream)
408 #else
409 wxOutputStream& wxDocument::SaveObject(wxOutputStream& stream)
410 #endif
411 {
412 return stream;
413 }
414
415 bool 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
423 bool 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
435 wxString 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
448 wxString 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
459 wxWindow *wxDocument::GetDocumentWindow() const
460 {
461 wxView * const view = GetFirstView();
462
463 return view ? view->GetFrame() : wxTheApp->GetTopWindow();
464 }
465
466 wxCommandProcessor *wxDocument::OnCreateCommandProcessor()
467 {
468 return new wxCommandProcessor;
469 }
470
471 // true if safe to close
472 bool 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
503 bool wxDocument::Draw(wxDC& WXUNUSED(context))
504 {
505 return true;
506 }
507
508 bool 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
518 bool wxDocument::RemoveView(wxView *view)
519 {
520 (void)m_documentViews.DeleteObject(view);
521 OnChangedViewList();
522 return true;
523 }
524
525 bool 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.
533 void wxDocument::OnChangedViewList()
534 {
535 if ( m_documentViews.empty() && OnSaveModified() )
536 delete this;
537 }
538
539 void 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
551 void 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
562 void wxDocument::SetFilename(const wxString& filename, bool notifyViews)
563 {
564 m_documentFile = filename;
565 OnChangeFilename(notifyViews);
566 }
567
568 void 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
583 bool 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
606 bool 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
640 wxView::wxView()
641 {
642 m_viewDocument = NULL;
643
644 m_viewFrame = NULL;
645 }
646
647 wxView::~wxView()
648 {
649 GetDocumentManager()->ActivateView(this, false);
650 m_viewDocument->RemoveView(this);
651 }
652
653 bool wxView::TryValidator(wxEvent& event)
654 {
655 wxDocument * const doc = GetDocument();
656 return doc && doc->ProcessEventHere(event);
657 }
658
659 void wxView::OnActivateView(bool WXUNUSED(activate),
660 wxView *WXUNUSED(activeView),
661 wxView *WXUNUSED(deactiveView))
662 {
663 }
664
665 void wxView::OnPrint(wxDC *dc, wxObject *WXUNUSED(info))
666 {
667 OnDraw(dc);
668 }
669
670 void wxView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint))
671 {
672 }
673
674 void wxView::OnChangeFilename()
675 {
676 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
677 // generic MDI implementation so use SetLabel rather than SetTitle.
678 // It should cause SetTitle() for top level windows.
679 wxWindow *win = GetFrame();
680 if (!win) return;
681
682 wxDocument *doc = GetDocument();
683 if (!doc) return;
684
685 win->SetLabel(doc->GetUserReadableName());
686 }
687
688 void wxView::SetDocument(wxDocument *doc)
689 {
690 m_viewDocument = doc;
691 if (doc)
692 doc->AddView(this);
693 }
694
695 bool wxView::Close(bool deleteWindow)
696 {
697 return OnClose(deleteWindow);
698 }
699
700 void wxView::Activate(bool activate)
701 {
702 if (GetDocument() && GetDocumentManager())
703 {
704 OnActivateView(activate, this, GetDocumentManager()->GetCurrentView());
705 GetDocumentManager()->ActivateView(this, activate);
706 }
707 }
708
709 bool wxView::OnClose(bool WXUNUSED(deleteWindow))
710 {
711 return GetDocument() ? GetDocument()->Close() : true;
712 }
713
714 #if wxUSE_PRINTING_ARCHITECTURE
715 wxPrintout *wxView::OnCreatePrintout()
716 {
717 return new wxDocPrintout(this);
718 }
719 #endif // wxUSE_PRINTING_ARCHITECTURE
720
721 // ----------------------------------------------------------------------------
722 // wxDocTemplate
723 // ----------------------------------------------------------------------------
724
725 wxDocTemplate::wxDocTemplate(wxDocManager *manager,
726 const wxString& descr,
727 const wxString& filter,
728 const wxString& dir,
729 const wxString& ext,
730 const wxString& docTypeName,
731 const wxString& viewTypeName,
732 wxClassInfo *docClassInfo,
733 wxClassInfo *viewClassInfo,
734 long flags)
735 {
736 m_documentManager = manager;
737 m_description = descr;
738 m_directory = dir;
739 m_defaultExt = ext;
740 m_fileFilter = filter;
741 m_flags = flags;
742 m_docTypeName = docTypeName;
743 m_viewTypeName = viewTypeName;
744 m_documentManager->AssociateTemplate(this);
745
746 m_docClassInfo = docClassInfo;
747 m_viewClassInfo = viewClassInfo;
748 }
749
750 wxDocTemplate::~wxDocTemplate()
751 {
752 m_documentManager->DisassociateTemplate(this);
753 }
754
755 // Tries to dynamically construct an object of the right class.
756 wxDocument *wxDocTemplate::CreateDocument(const wxString& path, long flags)
757 {
758 wxDocument * const doc = DoCreateDocument();
759
760 // VZ: this code doesn't delete doc if InitDocument() (i.e. doc->OnCreate())
761 // fails, is this intentional?
762
763 return doc && InitDocument(doc, path, flags) ? doc : NULL;
764 }
765
766 bool
767 wxDocTemplate::InitDocument(wxDocument* doc, const wxString& path, long flags)
768 {
769 doc->SetFilename(path);
770 doc->SetDocumentTemplate(this);
771 GetDocumentManager()->AddDocument(doc);
772 doc->SetCommandProcessor(doc->OnCreateCommandProcessor());
773
774 if (doc->OnCreate(path, flags))
775 return true;
776
777 if (GetDocumentManager()->GetDocuments().Member(doc))
778 doc->DeleteAllViews();
779 return false;
780 }
781
782 wxView *wxDocTemplate::CreateView(wxDocument *doc, long flags)
783 {
784 wxScopedPtr<wxView> view(DoCreateView());
785 if ( !view )
786 return NULL;
787
788 view->SetDocument(doc);
789 if ( !view->OnCreate(doc, flags) )
790 return NULL;
791
792 return view.release();
793 }
794
795 // The default (very primitive) format detection: check is the extension is
796 // that of the template
797 bool wxDocTemplate::FileMatchesTemplate(const wxString& path)
798 {
799 wxStringTokenizer parser (GetFileFilter(), wxT(";"));
800 wxString anything = wxT ("*");
801 while (parser.HasMoreTokens())
802 {
803 wxString filter = parser.GetNextToken();
804 wxString filterExt = FindExtension (filter);
805 if ( filter.IsSameAs (anything) ||
806 filterExt.IsSameAs (anything) ||
807 filterExt.IsSameAs (FindExtension (path)) )
808 return true;
809 }
810 return GetDefaultExtension().IsSameAs(FindExtension(path));
811 }
812
813 wxDocument *wxDocTemplate::DoCreateDocument()
814 {
815 if (!m_docClassInfo)
816 return NULL;
817
818 return static_cast<wxDocument *>(m_docClassInfo->CreateObject());
819 }
820
821 wxView *wxDocTemplate::DoCreateView()
822 {
823 if (!m_viewClassInfo)
824 return NULL;
825
826 return static_cast<wxView *>(m_viewClassInfo->CreateObject());
827 }
828
829 // ----------------------------------------------------------------------------
830 // wxDocManager
831 // ----------------------------------------------------------------------------
832
833 BEGIN_EVENT_TABLE(wxDocManager, wxEvtHandler)
834 EVT_MENU(wxID_OPEN, wxDocManager::OnFileOpen)
835 EVT_MENU(wxID_CLOSE, wxDocManager::OnFileClose)
836 EVT_MENU(wxID_CLOSE_ALL, wxDocManager::OnFileCloseAll)
837 EVT_MENU(wxID_REVERT, wxDocManager::OnFileRevert)
838 EVT_MENU(wxID_NEW, wxDocManager::OnFileNew)
839 EVT_MENU(wxID_SAVE, wxDocManager::OnFileSave)
840 EVT_MENU(wxID_SAVEAS, wxDocManager::OnFileSaveAs)
841 EVT_MENU(wxID_UNDO, wxDocManager::OnUndo)
842 EVT_MENU(wxID_REDO, wxDocManager::OnRedo)
843
844 EVT_UPDATE_UI(wxID_OPEN, wxDocManager::OnUpdateFileOpen)
845 EVT_UPDATE_UI(wxID_CLOSE, wxDocManager::OnUpdateDisableIfNoDoc)
846 EVT_UPDATE_UI(wxID_CLOSE_ALL, wxDocManager::OnUpdateDisableIfNoDoc)
847 EVT_UPDATE_UI(wxID_REVERT, wxDocManager::OnUpdateDisableIfNoDoc)
848 EVT_UPDATE_UI(wxID_NEW, wxDocManager::OnUpdateFileNew)
849 EVT_UPDATE_UI(wxID_SAVE, wxDocManager::OnUpdateFileSave)
850 EVT_UPDATE_UI(wxID_SAVEAS, wxDocManager::OnUpdateDisableIfNoDoc)
851 EVT_UPDATE_UI(wxID_UNDO, wxDocManager::OnUpdateUndo)
852 EVT_UPDATE_UI(wxID_REDO, wxDocManager::OnUpdateRedo)
853
854 #if wxUSE_PRINTING_ARCHITECTURE
855 EVT_MENU(wxID_PRINT, wxDocManager::OnPrint)
856 EVT_MENU(wxID_PREVIEW, wxDocManager::OnPreview)
857
858 EVT_UPDATE_UI(wxID_PRINT, wxDocManager::OnUpdateDisableIfNoDoc)
859 EVT_UPDATE_UI(wxID_PREVIEW, wxDocManager::OnUpdateDisableIfNoDoc)
860 #endif
861 END_EVENT_TABLE()
862
863 wxDocManager* wxDocManager::sm_docManager = NULL;
864
865 wxDocManager::wxDocManager(long WXUNUSED(flags), bool initialize)
866 {
867 wxASSERT_MSG( !sm_docManager, "multiple wxDocManagers not allowed" );
868
869 sm_docManager = this;
870
871 m_defaultDocumentNameCounter = 1;
872 m_currentView = NULL;
873 m_maxDocsOpen = INT_MAX;
874 m_fileHistory = NULL;
875 if ( initialize )
876 Initialize();
877 }
878
879 wxDocManager::~wxDocManager()
880 {
881 Clear();
882 delete m_fileHistory;
883 sm_docManager = NULL;
884 }
885
886 // closes the specified document
887 bool wxDocManager::CloseDocument(wxDocument* doc, bool force)
888 {
889 if ( !doc->Close() && !force )
890 return false;
891
892 // Implicitly deletes the document when
893 // the last view is deleted
894 doc->DeleteAllViews();
895
896 // Check we're really deleted
897 if (m_docs.Member(doc))
898 delete doc;
899
900 return true;
901 }
902
903 bool 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
922 bool 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
940 bool wxDocManager::Initialize()
941 {
942 m_fileHistory = OnCreateFileHistory();
943 return true;
944 }
945
946 wxString wxDocManager::GetLastDirectory() const
947 {
948 // use the system-dependent default location for the document files if
949 // we're being opened for the first time
950 if ( m_lastDirectory.empty() )
951 {
952 wxDocManager * const self = const_cast<wxDocManager *>(this);
953 self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir();
954 }
955
956 return m_lastDirectory;
957 }
958
959 wxFileHistory *wxDocManager::OnCreateFileHistory()
960 {
961 return new wxFileHistory;
962 }
963
964 void wxDocManager::OnFileClose(wxCommandEvent& WXUNUSED(event))
965 {
966 wxDocument *doc = GetCurrentDocument();
967 if (!doc)
968 return;
969 if (doc->Close())
970 {
971 doc->DeleteAllViews();
972 if (m_docs.Member(doc))
973 delete doc;
974 }
975 }
976
977 void wxDocManager::OnFileCloseAll(wxCommandEvent& WXUNUSED(event))
978 {
979 CloseDocuments(false);
980 }
981
982 void wxDocManager::OnFileNew(wxCommandEvent& WXUNUSED(event))
983 {
984 CreateNewDocument();
985 }
986
987 void wxDocManager::OnFileOpen(wxCommandEvent& WXUNUSED(event))
988 {
989 if ( !CreateDocument("") )
990 {
991 OnOpenFileFailure();
992 }
993 }
994
995 void wxDocManager::OnFileRevert(wxCommandEvent& WXUNUSED(event))
996 {
997 wxDocument *doc = GetCurrentDocument();
998 if (!doc)
999 return;
1000 doc->Revert();
1001 }
1002
1003 void wxDocManager::OnFileSave(wxCommandEvent& WXUNUSED(event))
1004 {
1005 wxDocument *doc = GetCurrentDocument();
1006 if (!doc)
1007 return;
1008 doc->Save();
1009 }
1010
1011 void wxDocManager::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))
1012 {
1013 wxDocument *doc = GetCurrentDocument();
1014 if (!doc)
1015 return;
1016 doc->SaveAs();
1017 }
1018
1019 void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event))
1020 {
1021 #if wxUSE_PRINTING_ARCHITECTURE
1022 wxView *view = GetActiveView();
1023 if (!view)
1024 return;
1025
1026 wxPrintout *printout = view->OnCreatePrintout();
1027 if (printout)
1028 {
1029 wxPrinter printer;
1030 printer.Print(view->GetFrame(), printout, true);
1031
1032 delete printout;
1033 }
1034 #endif // wxUSE_PRINTING_ARCHITECTURE
1035 }
1036
1037 void wxDocManager::OnPreview(wxCommandEvent& WXUNUSED(event))
1038 {
1039 #if wxUSE_PRINTING_ARCHITECTURE
1040 wxView *view = GetActiveView();
1041 if (!view)
1042 return;
1043
1044 wxPrintout *printout = view->OnCreatePrintout();
1045 if (printout)
1046 {
1047 // Pass two printout objects: for preview, and possible printing.
1048 wxPrintPreviewBase *
1049 preview = new wxPrintPreview(printout, view->OnCreatePrintout());
1050 if ( !preview->Ok() )
1051 {
1052 delete preview;
1053 wxLogError(_("Print preview creation failed."));
1054 return;
1055 }
1056
1057 wxPreviewFrame *
1058 frame = new wxPreviewFrame(preview, wxTheApp->GetTopWindow(),
1059 _("Print Preview"));
1060 frame->Centre(wxBOTH);
1061 frame->Initialize();
1062 frame->Show(true);
1063 }
1064 #endif // wxUSE_PRINTING_ARCHITECTURE
1065 }
1066
1067 void wxDocManager::OnUndo(wxCommandEvent& event)
1068 {
1069 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1070 if ( !cmdproc )
1071 {
1072 event.Skip();
1073 return;
1074 }
1075
1076 cmdproc->Undo();
1077 }
1078
1079 void wxDocManager::OnRedo(wxCommandEvent& event)
1080 {
1081 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1082 if ( !cmdproc )
1083 {
1084 event.Skip();
1085 return;
1086 }
1087
1088 cmdproc->Redo();
1089 }
1090
1091 // Handlers for UI update commands
1092
1093 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent& event)
1094 {
1095 // CreateDocument() (which is called from OnFileOpen) may succeed
1096 // only when there is at least a template:
1097 event.Enable( GetTemplates().GetCount()>0 );
1098 }
1099
1100 void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent& event)
1101 {
1102 event.Enable( GetCurrentDocument() != NULL );
1103 }
1104
1105 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event)
1106 {
1107 // CreateDocument() (which is called from OnFileNew) may succeed
1108 // only when there is at least a template:
1109 event.Enable( GetTemplates().GetCount()>0 );
1110 }
1111
1112 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event)
1113 {
1114 wxDocument * const doc = GetCurrentDocument();
1115 event.Enable( doc && !doc->AlreadySaved() );
1116 }
1117
1118 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event)
1119 {
1120 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1121 if ( !cmdproc )
1122 {
1123 event.Enable(false);
1124 return;
1125 }
1126
1127 event.Enable(cmdproc->CanUndo());
1128 cmdproc->SetMenuStrings();
1129 }
1130
1131 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event)
1132 {
1133 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1134 if ( !cmdproc )
1135 {
1136 event.Enable(false);
1137 return;
1138 }
1139
1140 event.Enable(cmdproc->CanRedo());
1141 cmdproc->SetMenuStrings();
1142 }
1143
1144 wxView *wxDocManager::GetActiveView() const
1145 {
1146 wxView *view = GetCurrentView();
1147
1148 if ( !view && !m_docs.empty() )
1149 {
1150 // if we have exactly one document, consider its view to be the current
1151 // one
1152 //
1153 // VZ: I'm not exactly sure why is this needed but this is how this
1154 // code used to behave before the bug #9518 was fixed and it seems
1155 // safer to preserve the old logic
1156 wxList::compatibility_iterator node = m_docs.GetFirst();
1157 if ( !node->GetNext() )
1158 {
1159 wxDocument *doc = static_cast<wxDocument *>(node->GetData());
1160 view = doc->GetFirstView();
1161 }
1162 //else: we have more than one document
1163 }
1164
1165 return view;
1166 }
1167
1168 bool wxDocManager::TryValidator(wxEvent& event)
1169 {
1170 wxView * const view = GetActiveView();
1171 return view && view->ProcessEventHere(event);
1172 }
1173
1174 namespace
1175 {
1176
1177 // helper function: return only the visible templates
1178 wxDocTemplates GetVisibleTemplates(const wxList& allTemplates)
1179 {
1180 // select only the visible templates
1181 const size_t totalNumTemplates = allTemplates.GetCount();
1182 wxDocTemplates templates;
1183 if ( totalNumTemplates )
1184 {
1185 templates.reserve(totalNumTemplates);
1186
1187 for ( wxList::const_iterator i = allTemplates.begin(),
1188 end = allTemplates.end();
1189 i != end;
1190 ++i )
1191 {
1192 wxDocTemplate * const temp = (wxDocTemplate *)*i;
1193 if ( temp->IsVisible() )
1194 templates.push_back(temp);
1195 }
1196 }
1197
1198 return templates;
1199 }
1200
1201 } // anonymous namespace
1202
1203 wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags)
1204 {
1205 // this ought to be const but SelectDocumentType/Path() are not
1206 // const-correct and can't be changed as, being virtual, this risks
1207 // breaking user code overriding them
1208 wxDocTemplates templates(GetVisibleTemplates(m_templates));
1209 const size_t numTemplates = templates.size();
1210 if ( !numTemplates )
1211 {
1212 // no templates can be used, can't create document
1213 return NULL;
1214 }
1215
1216
1217 // normally user should select the template to use but wxDOC_SILENT flag we
1218 // choose one ourselves
1219 wxString path = pathOrig; // may be modified below
1220 wxDocTemplate *temp;
1221 if ( flags & wxDOC_SILENT )
1222 {
1223 wxASSERT_MSG( !path.empty(),
1224 "using empty path with wxDOC_SILENT doesn't make sense" );
1225
1226 temp = FindTemplateForPath(path);
1227 if ( !temp )
1228 {
1229 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1230 path);
1231 }
1232 }
1233 else // not silent, ask the user
1234 {
1235 // for the new file we need just the template, for an existing one we
1236 // need the template and the path, unless it's already specified
1237 if ( (flags & wxDOC_NEW) || !path.empty() )
1238 temp = SelectDocumentType(&templates[0], numTemplates);
1239 else
1240 temp = SelectDocumentPath(&templates[0], numTemplates, path, flags);
1241 }
1242
1243 if ( !temp )
1244 return NULL;
1245
1246 // check whether the document with this path is already opened
1247 if ( !path.empty() )
1248 {
1249 const wxFileName fn(path);
1250 for ( wxList::const_iterator i = m_docs.begin(); i != m_docs.end(); ++i )
1251 {
1252 wxDocument * const doc = (wxDocument*)*i;
1253
1254 if ( fn == doc->GetFilename() )
1255 {
1256 // file already open, just activate it and return
1257 if ( doc->GetFirstView() )
1258 {
1259 ActivateView(doc->GetFirstView());
1260 if ( doc->GetDocumentWindow() )
1261 doc->GetDocumentWindow()->SetFocus();
1262 return doc;
1263 }
1264 }
1265 }
1266 }
1267
1268
1269 // no, we need to create a new document
1270
1271
1272 // if we've reached the max number of docs, close the first one.
1273 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen )
1274 {
1275 if ( !CloseDocument((wxDocument *)GetDocuments().GetFirst()->GetData()) )
1276 {
1277 // can't open the new document if closing the old one failed
1278 return NULL;
1279 }
1280 }
1281
1282
1283 // do create and initialize the new document finally
1284 wxDocument * const docNew = temp->CreateDocument(path, flags);
1285 if ( !docNew )
1286 return NULL;
1287
1288 docNew->SetDocumentName(temp->GetDocumentName());
1289 docNew->SetDocumentTemplate(temp);
1290
1291 // call the appropriate function depending on whether we're creating a new
1292 // file or opening an existing one
1293 if ( !(flags & wxDOC_NEW ? docNew->OnNewDocument()
1294 : docNew->OnOpenDocument(path)) )
1295 {
1296 // Document is implicitly deleted by DeleteAllViews
1297 docNew->DeleteAllViews();
1298 return NULL;
1299 }
1300
1301 // add the successfully opened file to MRU, but only if we're going to be
1302 // able to reopen it successfully later which requires the template for
1303 // this document to be retrievable from the file extension
1304 if ( !(flags & wxDOC_NEW) && temp->FileMatchesTemplate(path) )
1305 AddFileToHistory(path);
1306
1307 return docNew;
1308 }
1309
1310 wxView *wxDocManager::CreateView(wxDocument *doc, long flags)
1311 {
1312 wxDocTemplates templates(GetVisibleTemplates(m_templates));
1313 const size_t numTemplates = templates.size();
1314
1315 if ( numTemplates == 0 )
1316 return NULL;
1317
1318 wxDocTemplate * const
1319 temp = numTemplates == 1 ? templates[0]
1320 : SelectViewType(&templates[0], numTemplates);
1321
1322 if ( !temp )
1323 return NULL;
1324
1325 wxView *view = temp->CreateView(doc, flags);
1326 if ( view )
1327 view->SetViewName(temp->GetViewName());
1328 return view;
1329 }
1330
1331 // Not yet implemented
1332 void
1333 wxDocManager::DeleteTemplate(wxDocTemplate *WXUNUSED(temp), long WXUNUSED(flags))
1334 {
1335 }
1336
1337 // Not yet implemented
1338 bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc))
1339 {
1340 return false;
1341 }
1342
1343 wxDocument *wxDocManager::GetCurrentDocument() const
1344 {
1345 wxView * const view = GetActiveView();
1346 return view ? view->GetDocument() : NULL;
1347 }
1348
1349 wxCommandProcessor *wxDocManager::GetCurrentCommandProcessor() const
1350 {
1351 wxDocument * const doc = GetCurrentDocument();
1352 return doc ? doc->GetCommandProcessor() : NULL;
1353 }
1354
1355 // Make a default name for a new document
1356 #if WXWIN_COMPATIBILITY_2_8
1357 bool wxDocManager::MakeDefaultName(wxString& WXUNUSED(name))
1358 {
1359 // we consider that this function can only be overridden by the user code,
1360 // not called by it as it only makes sense to call it internally, so we
1361 // don't bother to return anything from here
1362 return false;
1363 }
1364 #endif // WXWIN_COMPATIBILITY_2_8
1365
1366 wxString wxDocManager::MakeNewDocumentName()
1367 {
1368 wxString name;
1369
1370 #if WXWIN_COMPATIBILITY_2_8
1371 if ( !MakeDefaultName(name) )
1372 #endif // WXWIN_COMPATIBILITY_2_8
1373 {
1374 name.Printf(_("unnamed%d"), m_defaultDocumentNameCounter);
1375 m_defaultDocumentNameCounter++;
1376 }
1377
1378 return name;
1379 }
1380
1381 // Make a frame title (override this to do something different)
1382 // If docName is empty, a document is not currently active.
1383 wxString wxDocManager::MakeFrameTitle(wxDocument* doc)
1384 {
1385 wxString appName = wxTheApp->GetAppDisplayName();
1386 wxString title;
1387 if (!doc)
1388 title = appName;
1389 else
1390 {
1391 wxString docName = doc->GetUserReadableName();
1392 title = docName + wxString(_(" - ")) + appName;
1393 }
1394 return title;
1395 }
1396
1397
1398 // Not yet implemented
1399 wxDocTemplate *wxDocManager::MatchTemplate(const wxString& WXUNUSED(path))
1400 {
1401 return NULL;
1402 }
1403
1404 // File history management
1405 void wxDocManager::AddFileToHistory(const wxString& file)
1406 {
1407 if (m_fileHistory)
1408 m_fileHistory->AddFileToHistory(file);
1409 }
1410
1411 void wxDocManager::RemoveFileFromHistory(size_t i)
1412 {
1413 if (m_fileHistory)
1414 m_fileHistory->RemoveFileFromHistory(i);
1415 }
1416
1417 wxString wxDocManager::GetHistoryFile(size_t i) const
1418 {
1419 wxString histFile;
1420
1421 if (m_fileHistory)
1422 histFile = m_fileHistory->GetHistoryFile(i);
1423
1424 return histFile;
1425 }
1426
1427 void wxDocManager::FileHistoryUseMenu(wxMenu *menu)
1428 {
1429 if (m_fileHistory)
1430 m_fileHistory->UseMenu(menu);
1431 }
1432
1433 void wxDocManager::FileHistoryRemoveMenu(wxMenu *menu)
1434 {
1435 if (m_fileHistory)
1436 m_fileHistory->RemoveMenu(menu);
1437 }
1438
1439 #if wxUSE_CONFIG
1440 void wxDocManager::FileHistoryLoad(const wxConfigBase& config)
1441 {
1442 if (m_fileHistory)
1443 m_fileHistory->Load(config);
1444 }
1445
1446 void wxDocManager::FileHistorySave(wxConfigBase& config)
1447 {
1448 if (m_fileHistory)
1449 m_fileHistory->Save(config);
1450 }
1451 #endif
1452
1453 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu* menu)
1454 {
1455 if (m_fileHistory)
1456 m_fileHistory->AddFilesToMenu(menu);
1457 }
1458
1459 void wxDocManager::FileHistoryAddFilesToMenu()
1460 {
1461 if (m_fileHistory)
1462 m_fileHistory->AddFilesToMenu();
1463 }
1464
1465 size_t wxDocManager::GetHistoryFilesCount() const
1466 {
1467 return m_fileHistory ? m_fileHistory->GetCount() : 0;
1468 }
1469
1470
1471 // Find out the document template via matching in the document file format
1472 // against that of the template
1473 wxDocTemplate *wxDocManager::FindTemplateForPath(const wxString& path)
1474 {
1475 wxDocTemplate *theTemplate = NULL;
1476
1477 // Find the template which this extension corresponds to
1478 for (size_t i = 0; i < m_templates.GetCount(); i++)
1479 {
1480 wxDocTemplate *temp = (wxDocTemplate *)m_templates.Item(i)->GetData();
1481 if ( temp->FileMatchesTemplate(path) )
1482 {
1483 theTemplate = temp;
1484 break;
1485 }
1486 }
1487 return theTemplate;
1488 }
1489
1490 // Prompts user to open a file, using file specs in templates.
1491 // Must extend the file selector dialog or implement own; OR
1492 // match the extension to the template extension.
1493
1494 wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates,
1495 int noTemplates,
1496 wxString& path,
1497 long WXUNUSED(flags),
1498 bool WXUNUSED(save))
1499 {
1500 #ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1501 wxString descrBuf;
1502
1503 for (int i = 0; i < noTemplates; i++)
1504 {
1505 if (templates[i]->IsVisible())
1506 {
1507 // add a '|' to separate this filter from the previous one
1508 if ( !descrBuf.empty() )
1509 descrBuf << wxT('|');
1510
1511 descrBuf << templates[i]->GetDescription()
1512 << wxT(" (") << templates[i]->GetFileFilter() << wxT(") |")
1513 << templates[i]->GetFileFilter();
1514 }
1515 }
1516 #else
1517 wxString descrBuf = wxT("*.*");
1518 wxUnusedVar(noTemplates);
1519 #endif
1520
1521 int FilterIndex = -1;
1522
1523 wxWindow* parent = wxFindSuitableParent();
1524
1525 wxString pathTmp = wxFileSelectorEx(_("Open File"),
1526 GetLastDirectory(),
1527 wxEmptyString,
1528 &FilterIndex,
1529 descrBuf,
1530 0,
1531 parent);
1532
1533 wxDocTemplate *theTemplate = NULL;
1534 if (!pathTmp.empty())
1535 {
1536 if (!wxFileExists(pathTmp))
1537 {
1538 wxString msgTitle;
1539 if (!wxTheApp->GetAppDisplayName().empty())
1540 msgTitle = wxTheApp->GetAppDisplayName();
1541 else
1542 msgTitle = wxString(_("File error"));
1543
1544 wxMessageBox(_("Sorry, could not open this file."),
1545 msgTitle,
1546 wxOK | wxICON_EXCLAMATION | wxCENTRE,
1547 parent);
1548
1549 path = wxEmptyString;
1550 return NULL;
1551 }
1552
1553 SetLastDirectory(wxPathOnly(pathTmp));
1554
1555 path = pathTmp;
1556
1557 // first choose the template using the extension, if this fails (i.e.
1558 // wxFileSelectorEx() didn't fill it), then use the path
1559 if ( FilterIndex != -1 )
1560 theTemplate = templates[FilterIndex];
1561 if ( !theTemplate )
1562 theTemplate = FindTemplateForPath(path);
1563 if ( !theTemplate )
1564 {
1565 // Since we do not add files with non-default extensions to the
1566 // file history this can only happen if the application changes the
1567 // allowed templates in runtime.
1568 wxMessageBox(_("Sorry, the format for this file is unknown."),
1569 _("Open File"),
1570 wxOK | wxICON_EXCLAMATION | wxCENTRE,
1571 parent);
1572 }
1573 }
1574 else
1575 {
1576 path.clear();
1577 }
1578
1579 return theTemplate;
1580 }
1581
1582 wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1583 int noTemplates, bool sort)
1584 {
1585 wxArrayString strings;
1586 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1587 int i;
1588 int n = 0;
1589
1590 for (i = 0; i < noTemplates; i++)
1591 {
1592 if (templates[i]->IsVisible())
1593 {
1594 int j;
1595 bool want = true;
1596 for (j = 0; j < n; j++)
1597 {
1598 //filter out NOT unique documents + view combinations
1599 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1600 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1601 )
1602 want = false;
1603 }
1604
1605 if ( want )
1606 {
1607 strings.Add(templates[i]->m_description);
1608
1609 data[n] = templates[i];
1610 n ++;
1611 }
1612 }
1613 } // for
1614
1615 if (sort)
1616 {
1617 strings.Sort(); // ascending sort
1618 // Yes, this will be slow, but template lists
1619 // are typically short.
1620 int j;
1621 n = strings.Count();
1622 for (i = 0; i < n; i++)
1623 {
1624 for (j = 0; j < noTemplates; j++)
1625 {
1626 if (strings[i] == templates[j]->m_description)
1627 data[i] = templates[j];
1628 }
1629 }
1630 }
1631
1632 wxDocTemplate *theTemplate;
1633
1634 switch ( n )
1635 {
1636 case 0:
1637 // no visible templates, hence nothing to choose from
1638 theTemplate = NULL;
1639 break;
1640
1641 case 1:
1642 // don't propose the user to choose if he has no choice
1643 theTemplate = data[0];
1644 break;
1645
1646 default:
1647 // propose the user to choose one of several
1648 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1649 (
1650 _("Select a document template"),
1651 _("Templates"),
1652 strings,
1653 (void **)data.get(),
1654 wxFindSuitableParent()
1655 );
1656 }
1657
1658 return theTemplate;
1659 }
1660
1661 wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1662 int noTemplates, bool sort)
1663 {
1664 wxArrayString strings;
1665 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1666 int i;
1667 int n = 0;
1668
1669 for (i = 0; i < noTemplates; i++)
1670 {
1671 wxDocTemplate *templ = templates[i];
1672 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1673 {
1674 int j;
1675 bool want = true;
1676 for (j = 0; j < n; j++)
1677 {
1678 //filter out NOT unique views
1679 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1680 want = false;
1681 }
1682
1683 if ( want )
1684 {
1685 strings.Add(templ->m_viewTypeName);
1686 data[n] = templ;
1687 n ++;
1688 }
1689 }
1690 }
1691
1692 if (sort)
1693 {
1694 strings.Sort(); // ascending sort
1695 // Yes, this will be slow, but template lists
1696 // are typically short.
1697 int j;
1698 n = strings.Count();
1699 for (i = 0; i < n; i++)
1700 {
1701 for (j = 0; j < noTemplates; j++)
1702 {
1703 if (strings[i] == templates[j]->m_viewTypeName)
1704 data[i] = templates[j];
1705 }
1706 }
1707 }
1708
1709 wxDocTemplate *theTemplate;
1710
1711 // the same logic as above
1712 switch ( n )
1713 {
1714 case 0:
1715 theTemplate = NULL;
1716 break;
1717
1718 case 1:
1719 theTemplate = data[0];
1720 break;
1721
1722 default:
1723 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1724 (
1725 _("Select a document view"),
1726 _("Views"),
1727 strings,
1728 (void **)data.get(),
1729 wxFindSuitableParent()
1730 );
1731
1732 }
1733
1734 return theTemplate;
1735 }
1736
1737 void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1738 {
1739 if (!m_templates.Member(temp))
1740 m_templates.Append(temp);
1741 }
1742
1743 void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1744 {
1745 m_templates.DeleteObject(temp);
1746 }
1747
1748 // Add and remove a document from the manager's list
1749 void wxDocManager::AddDocument(wxDocument *doc)
1750 {
1751 if (!m_docs.Member(doc))
1752 m_docs.Append(doc);
1753 }
1754
1755 void wxDocManager::RemoveDocument(wxDocument *doc)
1756 {
1757 m_docs.DeleteObject(doc);
1758 }
1759
1760 // Views or windows should inform the document manager
1761 // when a view is going in or out of focus
1762 void wxDocManager::ActivateView(wxView *view, bool activate)
1763 {
1764 if ( activate )
1765 {
1766 m_currentView = view;
1767 }
1768 else // deactivate
1769 {
1770 if ( m_currentView == view )
1771 {
1772 // don't keep stale pointer
1773 m_currentView = NULL;
1774 }
1775 }
1776 }
1777
1778 // ----------------------------------------------------------------------------
1779 // Default document child frame
1780 // ----------------------------------------------------------------------------
1781
1782 BEGIN_EVENT_TABLE(wxDocChildFrame, wxFrame)
1783 EVT_ACTIVATE(wxDocChildFrame::OnActivate)
1784 EVT_CLOSE(wxDocChildFrame::OnCloseWindow)
1785 END_EVENT_TABLE()
1786
1787 wxDocChildFrame::wxDocChildFrame(wxDocument *doc,
1788 wxView *view,
1789 wxFrame *frame,
1790 wxWindowID id,
1791 const wxString& title,
1792 const wxPoint& pos,
1793 const wxSize& size,
1794 long style,
1795 const wxString& name)
1796 : wxFrame(frame, id, title, pos, size, style, name)
1797 {
1798 m_childDocument = doc;
1799 m_childView = view;
1800 if (view)
1801 view->SetFrame(this);
1802 }
1803
1804 bool wxDocChildFrame::TryValidator(wxEvent& event)
1805 {
1806 if ( !m_childView )
1807 return false;
1808
1809 // FIXME: why is this needed here?
1810 m_childView->Activate(true);
1811
1812 return m_childView->ProcessEventHere(event);
1813 }
1814
1815 void wxDocChildFrame::OnActivate(wxActivateEvent& event)
1816 {
1817 wxFrame::OnActivate(event);
1818
1819 if (m_childView)
1820 m_childView->Activate(event.GetActive());
1821 }
1822
1823 void wxDocChildFrame::OnCloseWindow(wxCloseEvent& event)
1824 {
1825 if ( !m_childView )
1826 return;
1827
1828 // passing false to Close() means to not delete associated window
1829 if ( event.CanVeto() && !m_childView->Close(false) )
1830 {
1831 event.Veto();
1832 return;
1833 }
1834
1835 m_childView->Activate(false);
1836 delete m_childView;
1837 m_childView = NULL;
1838 m_childDocument = NULL;
1839
1840 Destroy();
1841 }
1842
1843 // ----------------------------------------------------------------------------
1844 // Default parent frame
1845 // ----------------------------------------------------------------------------
1846
1847 BEGIN_EVENT_TABLE(wxDocParentFrame, wxFrame)
1848 EVT_MENU(wxID_EXIT, wxDocParentFrame::OnExit)
1849 EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocParentFrame::OnMRUFile)
1850 EVT_CLOSE(wxDocParentFrame::OnCloseWindow)
1851 END_EVENT_TABLE()
1852
1853 wxDocParentFrame::wxDocParentFrame()
1854 {
1855 m_docManager = NULL;
1856 }
1857
1858 wxDocParentFrame::wxDocParentFrame(wxDocManager *manager,
1859 wxFrame *frame,
1860 wxWindowID id,
1861 const wxString& title,
1862 const wxPoint& pos,
1863 const wxSize& size,
1864 long style,
1865 const wxString& name)
1866 : wxFrame(frame, id, title, pos, size, style, name)
1867 {
1868 m_docManager = manager;
1869 }
1870
1871 bool wxDocParentFrame::Create(wxDocManager *manager,
1872 wxFrame *frame,
1873 wxWindowID id,
1874 const wxString& title,
1875 const wxPoint& pos,
1876 const wxSize& size,
1877 long style,
1878 const wxString& name)
1879 {
1880 m_docManager = manager;
1881 return base_type::Create(frame, id, title, pos, size, style, name);
1882 }
1883
1884 void wxDocParentFrame::OnExit(wxCommandEvent& WXUNUSED(event))
1885 {
1886 Close();
1887 }
1888
1889 void wxDocParentFrame::OnMRUFile(wxCommandEvent& event)
1890 {
1891 int n = event.GetId() - wxID_FILE1; // the index in MRU list
1892 wxString filename(m_docManager->GetHistoryFile(n));
1893 if ( filename.empty() )
1894 return;
1895
1896 wxString errMsg; // must contain exactly one "%s" if non-empty
1897 if ( wxFile::Exists(filename) )
1898 {
1899 // try to open it
1900 if ( m_docManager->CreateDocument(filename, wxDOC_SILENT) )
1901 return;
1902
1903 errMsg = _("The file '%s' couldn't be opened.");
1904 }
1905 else // file doesn't exist
1906 {
1907 errMsg = _("The file '%s' doesn't exist and couldn't be opened.");
1908 }
1909
1910
1911 wxASSERT_MSG( !errMsg.empty(), "should have an error message" );
1912
1913 // remove the file which we can't open from the MRU list
1914 m_docManager->RemoveFileFromHistory(n);
1915
1916 // and tell the user about it
1917 wxLogError(errMsg + '\n' +
1918 _("It has been removed from the most recently used files list."),
1919 filename);
1920 }
1921
1922 // Extend event processing to search the view's event table
1923 bool wxDocParentFrame::TryValidator(wxEvent& event)
1924 {
1925 return m_docManager && m_docManager->ProcessEventHere(event);
1926 }
1927
1928 // Define the behaviour for the frame closing
1929 // - must delete all frames except for the main one.
1930 void wxDocParentFrame::OnCloseWindow(wxCloseEvent& event)
1931 {
1932 if (m_docManager->Clear(!event.CanVeto()))
1933 {
1934 Destroy();
1935 }
1936 else
1937 event.Veto();
1938 }
1939
1940 #if wxUSE_PRINTING_ARCHITECTURE
1941
1942 wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
1943 : wxPrintout(title)
1944 {
1945 m_printoutView = view;
1946 }
1947
1948 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
1949 {
1950 wxDC *dc = GetDC();
1951
1952 // Get the logical pixels per inch of screen and printer
1953 int ppiScreenX, ppiScreenY;
1954 GetPPIScreen(&ppiScreenX, &ppiScreenY);
1955 wxUnusedVar(ppiScreenY);
1956 int ppiPrinterX, ppiPrinterY;
1957 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
1958 wxUnusedVar(ppiPrinterY);
1959
1960 // This scales the DC so that the printout roughly represents the
1961 // the screen scaling. The text point size _should_ be the right size
1962 // but in fact is too small for some reason. This is a detail that will
1963 // need to be addressed at some point but can be fudged for the
1964 // moment.
1965 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
1966
1967 // Now we have to check in case our real page size is reduced
1968 // (e.g. because we're drawing to a print preview memory DC)
1969 int pageWidth, pageHeight;
1970 int w, h;
1971 dc->GetSize(&w, &h);
1972 GetPageSizePixels(&pageWidth, &pageHeight);
1973 wxUnusedVar(pageHeight);
1974
1975 // If printer pageWidth == current DC width, then this doesn't
1976 // change. But w might be the preview bitmap width, so scale down.
1977 float overallScale = scale * (float)(w/(float)pageWidth);
1978 dc->SetUserScale(overallScale, overallScale);
1979
1980 if (m_printoutView)
1981 {
1982 m_printoutView->OnDraw(dc);
1983 }
1984 return true;
1985 }
1986
1987 bool wxDocPrintout::HasPage(int pageNum)
1988 {
1989 return (pageNum == 1);
1990 }
1991
1992 bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
1993 {
1994 if (!wxPrintout::OnBeginDocument(startPage, endPage))
1995 return false;
1996
1997 return true;
1998 }
1999
2000 void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage,
2001 int *selPageFrom, int *selPageTo)
2002 {
2003 *minPage = 1;
2004 *maxPage = 1;
2005 *selPageFrom = 1;
2006 *selPageTo = 1;
2007 }
2008
2009 #endif // wxUSE_PRINTING_ARCHITECTURE
2010
2011 // ----------------------------------------------------------------------------
2012 // File history (a.k.a. MRU, most recently used, files list)
2013 // ----------------------------------------------------------------------------
2014
2015 wxFileHistory::wxFileHistory(size_t maxFiles, wxWindowID idBase)
2016 {
2017 m_fileMaxFiles = maxFiles;
2018 m_idBase = idBase;
2019 }
2020
2021 void wxFileHistory::AddFileToHistory(const wxString& file)
2022 {
2023 // check if we don't already have this file
2024 const wxFileName fnNew(file);
2025 size_t i,
2026 numFiles = m_fileHistory.size();
2027 for ( i = 0; i < numFiles; i++ )
2028 {
2029 if ( fnNew == m_fileHistory[i] )
2030 {
2031 // we do have it, move it to the top of the history
2032 RemoveFileFromHistory(i);
2033 numFiles--;
2034 break;
2035 }
2036 }
2037
2038 // if we already have a full history, delete the one at the end
2039 if ( numFiles == m_fileMaxFiles )
2040 {
2041 RemoveFileFromHistory(--numFiles);
2042 }
2043
2044 // add a new menu item to all file menus (they will be updated below)
2045 for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2046 node;
2047 node = node->GetNext() )
2048 {
2049 wxMenu * const menu = (wxMenu *)node->GetData();
2050
2051 if ( !numFiles && menu->GetMenuItemCount() )
2052 menu->AppendSeparator();
2053
2054 // label doesn't matter, it will be set below anyhow, but it can't
2055 // be empty (this is supposed to indicate a stock item)
2056 menu->Append(m_idBase + numFiles, " ");
2057 }
2058
2059 // insert the new file in the beginning of the file history
2060 m_fileHistory.insert(m_fileHistory.begin(), file);
2061 numFiles++;
2062
2063 // update the labels in all menus
2064 for ( i = 0; i < numFiles; i++ )
2065 {
2066 // if in same directory just show the filename; otherwise the full path
2067 const wxFileName fnOld(m_fileHistory[i]);
2068
2069 wxString pathInMenu;
2070 if ( fnOld.GetPath() == fnNew.GetPath() )
2071 {
2072 pathInMenu = fnOld.GetFullName();
2073 }
2074 else // file in different directory
2075 {
2076 // absolute path; could also set relative path
2077 pathInMenu = m_fileHistory[i];
2078 }
2079
2080 for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2081 node;
2082 node = node->GetNext() )
2083 {
2084 wxMenu * const menu = (wxMenu *)node->GetData();
2085
2086 menu->SetLabel(m_idBase + i, GetMRUEntryLabel(i, pathInMenu));
2087 }
2088 }
2089 }
2090
2091 void wxFileHistory::RemoveFileFromHistory(size_t i)
2092 {
2093 size_t numFiles = m_fileHistory.size();
2094 wxCHECK_RET( i < numFiles,
2095 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2096
2097 // delete the element from the array
2098 m_fileHistory.RemoveAt(i);
2099 numFiles--;
2100
2101 for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2102 node;
2103 node = node->GetNext() )
2104 {
2105 wxMenu * const menu = (wxMenu *) node->GetData();
2106
2107 // shift filenames up
2108 for ( size_t j = i; j < numFiles; j++ )
2109 {
2110 menu->SetLabel(m_idBase + j, GetMRUEntryLabel(j, m_fileHistory[j]));
2111 }
2112
2113 // delete the last menu item which is unused now
2114 const wxWindowID lastItemId = m_idBase + numFiles;
2115 if ( menu->FindItem(lastItemId) )
2116 menu->Delete(lastItemId);
2117
2118 // delete the last separator too if no more files are left
2119 if ( m_fileHistory.empty() )
2120 {
2121 const wxMenuItemList::compatibility_iterator
2122 nodeLast = menu->GetMenuItems().GetLast();
2123 if ( nodeLast )
2124 {
2125 wxMenuItem * const lastMenuItem = nodeLast->GetData();
2126 if ( lastMenuItem->IsSeparator() )
2127 menu->Delete(lastMenuItem);
2128 }
2129 //else: menu is empty somehow
2130 }
2131 }
2132 }
2133
2134 void wxFileHistory::UseMenu(wxMenu *menu)
2135 {
2136 if ( !m_fileMenus.Member(menu) )
2137 m_fileMenus.Append(menu);
2138 }
2139
2140 void wxFileHistory::RemoveMenu(wxMenu *menu)
2141 {
2142 m_fileMenus.DeleteObject(menu);
2143 }
2144
2145 #if wxUSE_CONFIG
2146 void wxFileHistory::Load(const wxConfigBase& config)
2147 {
2148 m_fileHistory.Clear();
2149
2150 wxString buf;
2151 buf.Printf(wxT("file%d"), 1);
2152
2153 wxString historyFile;
2154 while ((m_fileHistory.GetCount() < m_fileMaxFiles) &&
2155 config.Read(buf, &historyFile) && !historyFile.empty())
2156 {
2157 m_fileHistory.Add(historyFile);
2158
2159 buf.Printf(wxT("file%d"), (int)m_fileHistory.GetCount()+1);
2160 historyFile = wxEmptyString;
2161 }
2162
2163 AddFilesToMenu();
2164 }
2165
2166 void wxFileHistory::Save(wxConfigBase& config)
2167 {
2168 size_t i;
2169 for (i = 0; i < m_fileMaxFiles; i++)
2170 {
2171 wxString buf;
2172 buf.Printf(wxT("file%d"), (int)i+1);
2173 if (i < m_fileHistory.GetCount())
2174 config.Write(buf, wxString(m_fileHistory[i]));
2175 else
2176 config.Write(buf, wxEmptyString);
2177 }
2178 }
2179 #endif // wxUSE_CONFIG
2180
2181 void wxFileHistory::AddFilesToMenu()
2182 {
2183 if ( m_fileHistory.empty() )
2184 return;
2185
2186 for ( wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2187 node;
2188 node = node->GetNext() )
2189 {
2190 AddFilesToMenu((wxMenu *) node->GetData());
2191 }
2192 }
2193
2194 void wxFileHistory::AddFilesToMenu(wxMenu* menu)
2195 {
2196 if ( m_fileHistory.empty() )
2197 return;
2198
2199 if ( menu->GetMenuItemCount() )
2200 menu->AppendSeparator();
2201
2202 for ( size_t i = 0; i < m_fileHistory.GetCount(); i++ )
2203 {
2204 menu->Append(m_idBase + i, GetMRUEntryLabel(i, m_fileHistory[i]));
2205 }
2206 }
2207
2208 // ----------------------------------------------------------------------------
2209 // Permits compatibility with existing file formats and functions that
2210 // manipulate files directly
2211 // ----------------------------------------------------------------------------
2212
2213 #if wxUSE_STD_IOSTREAM
2214
2215 bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream)
2216 {
2217 wxFFile file(filename, _T("rb"));
2218 if ( !file.IsOpened() )
2219 return false;
2220
2221 char buf[4096];
2222
2223 size_t nRead;
2224 do
2225 {
2226 nRead = file.Read(buf, WXSIZEOF(buf));
2227 if ( file.Error() )
2228 return false;
2229
2230 stream.write(buf, nRead);
2231 if ( !stream )
2232 return false;
2233 }
2234 while ( !file.Eof() );
2235
2236 return true;
2237 }
2238
2239 bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename)
2240 {
2241 wxFFile file(filename, _T("wb"));
2242 if ( !file.IsOpened() )
2243 return false;
2244
2245 char buf[4096];
2246 do
2247 {
2248 stream.read(buf, WXSIZEOF(buf));
2249 if ( !stream.bad() ) // fail may be set on EOF, don't use operator!()
2250 {
2251 if ( !file.Write(buf, stream.gcount()) )
2252 return false;
2253 }
2254 }
2255 while ( !stream.eof() );
2256
2257 return true;
2258 }
2259
2260 #else // !wxUSE_STD_IOSTREAM
2261
2262 bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream)
2263 {
2264 wxFFile file(filename, _T("rb"));
2265 if ( !file.IsOpened() )
2266 return false;
2267
2268 char buf[4096];
2269
2270 size_t nRead;
2271 do
2272 {
2273 nRead = file.Read(buf, WXSIZEOF(buf));
2274 if ( file.Error() )
2275 return false;
2276
2277 stream.Write(buf, nRead);
2278 if ( !stream )
2279 return false;
2280 }
2281 while ( !file.Eof() );
2282
2283 return true;
2284 }
2285
2286 bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename)
2287 {
2288 wxFFile file(filename, _T("wb"));
2289 if ( !file.IsOpened() )
2290 return false;
2291
2292 char buf[4096];
2293 for ( ;; )
2294 {
2295 stream.Read(buf, WXSIZEOF(buf));
2296
2297 const size_t nRead = stream.LastRead();
2298 if ( !nRead )
2299 {
2300 if ( stream.Eof() )
2301 break;
2302
2303 return false;
2304 }
2305
2306 if ( !file.Write(buf, nRead) )
2307 return false;
2308 }
2309
2310 return true;
2311 }
2312
2313 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2314
2315 #endif // wxUSE_DOC_VIEW_ARCHITECTURE