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