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