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