]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/docview.cpp
Don't generate AUINOTEBOOK_BG_DCLICK when clicking inactive arrow.
[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
901 EVT_UPDATE_UI(wxID_PRINT, wxDocManager::OnUpdateDisableIfNoDoc)
902 EVT_UPDATE_UI(wxID_PREVIEW, wxDocManager::OnUpdateDisableIfNoDoc)
903#endif
904END_EVENT_TABLE()
905
906wxDocManager* wxDocManager::sm_docManager = NULL;
907
908wxDocManager::wxDocManager(long WXUNUSED(flags), bool initialize)
909{
910 sm_docManager = this;
911
912 m_defaultDocumentNameCounter = 1;
913 m_currentView = NULL;
914 m_maxDocsOpen = INT_MAX;
915 m_fileHistory = NULL;
916 if ( initialize )
917 Initialize();
918}
919
920wxDocManager::~wxDocManager()
921{
922 Clear();
923 delete m_fileHistory;
924 sm_docManager = NULL;
925}
926
927// closes the specified document
928bool wxDocManager::CloseDocument(wxDocument* doc, bool force)
929{
930 if ( !doc->Close() && !force )
931 return false;
932
933 // Implicitly deletes the document when
934 // the last view is deleted
935 doc->DeleteAllViews();
936
937 // Check we're really deleted
938 if (m_docs.Member(doc))
939 delete doc;
940
941 return true;
942}
943
944bool wxDocManager::CloseDocuments(bool force)
945{
946 wxList::compatibility_iterator node = m_docs.GetFirst();
947 while (node)
948 {
949 wxDocument *doc = (wxDocument *)node->GetData();
950 wxList::compatibility_iterator next = node->GetNext();
951
952 if (!CloseDocument(doc, force))
953 return false;
954
955 // This assumes that documents are not connected in
956 // any way, i.e. deleting one document does NOT
957 // delete another.
958 node = next;
959 }
960 return true;
961}
962
963bool wxDocManager::Clear(bool force)
964{
965 if (!CloseDocuments(force))
966 return false;
967
968 m_currentView = NULL;
969
970 wxList::compatibility_iterator node = m_templates.GetFirst();
971 while (node)
972 {
973 wxDocTemplate *templ = (wxDocTemplate*) node->GetData();
974 wxList::compatibility_iterator next = node->GetNext();
975 delete templ;
976 node = next;
977 }
978 return true;
979}
980
981bool wxDocManager::Initialize()
982{
983 m_fileHistory = OnCreateFileHistory();
984 return true;
985}
986
987wxString wxDocManager::GetLastDirectory() const
988{
989 // if we haven't determined the last used directory yet, do it now
990 if ( m_lastDirectory.empty() )
991 {
992 // we're going to modify m_lastDirectory in this const method, so do it
993 // via non-const self pointer instead of const this one
994 wxDocManager * const self = const_cast<wxDocManager *>(this);
995
996 // first try to reuse the directory of the most recently opened file:
997 // this ensures that if the user opens a file, closes the program and
998 // runs it again the "Open file" dialog will open in the directory of
999 // the last file he used
1000 if ( m_fileHistory && m_fileHistory->GetCount() )
1001 {
1002 const wxString lastOpened = m_fileHistory->GetHistoryFile(0);
1003 const wxFileName fn(lastOpened);
1004 if ( fn.DirExists() )
1005 {
1006 self->m_lastDirectory = fn.GetPath();
1007 }
1008 //else: should we try the next one?
1009 }
1010 //else: no history yet
1011
1012 // if we don't have any files in the history (yet?), use the
1013 // system-dependent default location for the document files
1014 if ( m_lastDirectory.empty() )
1015 {
1016 self->m_lastDirectory = wxStandardPaths::Get().GetAppDocumentsDir();
1017 }
1018 }
1019
1020 return m_lastDirectory;
1021}
1022
1023wxFileHistory *wxDocManager::OnCreateFileHistory()
1024{
1025 return new wxFileHistory;
1026}
1027
1028void wxDocManager::OnFileClose(wxCommandEvent& WXUNUSED(event))
1029{
1030 wxDocument *doc = GetCurrentDocument();
1031 if (!doc)
1032 return;
1033 if (doc->Close())
1034 {
1035 doc->DeleteAllViews();
1036 if (m_docs.Member(doc))
1037 delete doc;
1038 }
1039}
1040
1041void wxDocManager::OnFileCloseAll(wxCommandEvent& WXUNUSED(event))
1042{
1043 CloseDocuments(false);
1044}
1045
1046void wxDocManager::OnFileNew(wxCommandEvent& WXUNUSED(event))
1047{
1048 CreateNewDocument();
1049}
1050
1051void wxDocManager::OnFileOpen(wxCommandEvent& WXUNUSED(event))
1052{
1053 if ( !CreateDocument("") )
1054 {
1055 OnOpenFileFailure();
1056 }
1057}
1058
1059void wxDocManager::OnFileRevert(wxCommandEvent& WXUNUSED(event))
1060{
1061 wxDocument *doc = GetCurrentDocument();
1062 if (!doc)
1063 return;
1064 doc->Revert();
1065}
1066
1067void wxDocManager::OnFileSave(wxCommandEvent& WXUNUSED(event))
1068{
1069 wxDocument *doc = GetCurrentDocument();
1070 if (!doc)
1071 return;
1072 doc->Save();
1073}
1074
1075void wxDocManager::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))
1076{
1077 wxDocument *doc = GetCurrentDocument();
1078 if (!doc)
1079 return;
1080 doc->SaveAs();
1081}
1082
1083void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event))
1084{
1085#if wxUSE_PRINTING_ARCHITECTURE
1086 wxView *view = GetActiveView();
1087 if (!view)
1088 return;
1089
1090 wxPrintout *printout = view->OnCreatePrintout();
1091 if (printout)
1092 {
1093 wxPrinter printer;
1094 printer.Print(view->GetFrame(), printout, true);
1095
1096 delete printout;
1097 }
1098#endif // wxUSE_PRINTING_ARCHITECTURE
1099}
1100
1101#if wxUSE_PRINTING_ARCHITECTURE
1102wxPreviewFrame* wxDocManager::CreatePreviewFrame(wxPrintPreviewBase* preview,
1103 wxWindow *parent,
1104 const wxString& title)
1105{
1106 return new wxPreviewFrame(preview, parent, title);
1107}
1108#endif // wxUSE_PRINTING_ARCHITECTURE
1109
1110void wxDocManager::OnPreview(wxCommandEvent& WXUNUSED(event))
1111{
1112#if wxUSE_PRINTING_ARCHITECTURE
1113 wxBusyCursor busy;
1114 wxView *view = GetActiveView();
1115 if (!view)
1116 return;
1117
1118 wxPrintout *printout = view->OnCreatePrintout();
1119 if (printout)
1120 {
1121 // Pass two printout objects: for preview, and possible printing.
1122 wxPrintPreviewBase *
1123 preview = new wxPrintPreview(printout, view->OnCreatePrintout());
1124 if ( !preview->Ok() )
1125 {
1126 delete preview;
1127 wxLogError(_("Print preview creation failed."));
1128 return;
1129 }
1130
1131 wxPreviewFrame* frame = CreatePreviewFrame(preview,
1132 wxTheApp->GetTopWindow(),
1133 _("Print Preview"));
1134 wxCHECK_RET( frame, "should create a print preview frame" );
1135
1136 frame->Centre(wxBOTH);
1137 frame->Initialize();
1138 frame->Show(true);
1139 }
1140#endif // wxUSE_PRINTING_ARCHITECTURE
1141}
1142
1143void wxDocManager::OnUndo(wxCommandEvent& event)
1144{
1145 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1146 if ( !cmdproc )
1147 {
1148 event.Skip();
1149 return;
1150 }
1151
1152 cmdproc->Undo();
1153}
1154
1155void wxDocManager::OnRedo(wxCommandEvent& event)
1156{
1157 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1158 if ( !cmdproc )
1159 {
1160 event.Skip();
1161 return;
1162 }
1163
1164 cmdproc->Redo();
1165}
1166
1167// Handlers for UI update commands
1168
1169void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent& event)
1170{
1171 // CreateDocument() (which is called from OnFileOpen) may succeed
1172 // only when there is at least a template:
1173 event.Enable( GetTemplates().GetCount()>0 );
1174}
1175
1176void wxDocManager::OnUpdateDisableIfNoDoc(wxUpdateUIEvent& event)
1177{
1178 event.Enable( GetCurrentDocument() != NULL );
1179}
1180
1181void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent& event)
1182{
1183 wxDocument* doc = GetCurrentDocument();
1184 event.Enable(doc && doc->IsModified() && doc->GetDocumentSaved());
1185}
1186
1187void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event)
1188{
1189 // CreateDocument() (which is called from OnFileNew) may succeed
1190 // only when there is at least a template:
1191 event.Enable( GetTemplates().GetCount()>0 );
1192}
1193
1194void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event)
1195{
1196 wxDocument * const doc = GetCurrentDocument();
1197 event.Enable( doc && !doc->AlreadySaved() );
1198}
1199
1200void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event)
1201{
1202 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1203 if ( !cmdproc )
1204 {
1205 event.Enable(false);
1206 return;
1207 }
1208
1209 event.Enable(cmdproc->CanUndo());
1210 cmdproc->SetMenuStrings();
1211}
1212
1213void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event)
1214{
1215 wxCommandProcessor * const cmdproc = GetCurrentCommandProcessor();
1216 if ( !cmdproc )
1217 {
1218 event.Enable(false);
1219 return;
1220 }
1221
1222 event.Enable(cmdproc->CanRedo());
1223 cmdproc->SetMenuStrings();
1224}
1225
1226wxView *wxDocManager::GetActiveView() const
1227{
1228 wxView *view = GetCurrentView();
1229
1230 if ( !view && !m_docs.empty() )
1231 {
1232 // if we have exactly one document, consider its view to be the current
1233 // one
1234 //
1235 // VZ: I'm not exactly sure why is this needed but this is how this
1236 // code used to behave before the bug #9518 was fixed and it seems
1237 // safer to preserve the old logic
1238 wxList::compatibility_iterator node = m_docs.GetFirst();
1239 if ( !node->GetNext() )
1240 {
1241 wxDocument *doc = static_cast<wxDocument *>(node->GetData());
1242 view = doc->GetFirstView();
1243 }
1244 //else: we have more than one document
1245 }
1246
1247 return view;
1248}
1249
1250bool wxDocManager::TryBefore(wxEvent& event)
1251{
1252 wxView * const view = GetActiveView();
1253 return view && view->ProcessEventLocally(event);
1254}
1255
1256namespace
1257{
1258
1259// helper function: return only the visible templates
1260wxDocTemplates GetVisibleTemplates(const wxList& allTemplates)
1261{
1262 // select only the visible templates
1263 const size_t totalNumTemplates = allTemplates.GetCount();
1264 wxDocTemplates templates;
1265 if ( totalNumTemplates )
1266 {
1267 templates.reserve(totalNumTemplates);
1268
1269 for ( wxList::const_iterator i = allTemplates.begin(),
1270 end = allTemplates.end();
1271 i != end;
1272 ++i )
1273 {
1274 wxDocTemplate * const temp = (wxDocTemplate *)*i;
1275 if ( temp->IsVisible() )
1276 templates.push_back(temp);
1277 }
1278 }
1279
1280 return templates;
1281}
1282
1283} // anonymous namespace
1284
1285wxDocument *wxDocManager::CreateDocument(const wxString& pathOrig, long flags)
1286{
1287 // this ought to be const but SelectDocumentType/Path() are not
1288 // const-correct and can't be changed as, being virtual, this risks
1289 // breaking user code overriding them
1290 wxDocTemplates templates(GetVisibleTemplates(m_templates));
1291 const size_t numTemplates = templates.size();
1292 if ( !numTemplates )
1293 {
1294 // no templates can be used, can't create document
1295 return NULL;
1296 }
1297
1298
1299 // normally user should select the template to use but wxDOC_SILENT flag we
1300 // choose one ourselves
1301 wxString path = pathOrig; // may be modified below
1302 wxDocTemplate *temp;
1303 if ( flags & wxDOC_SILENT )
1304 {
1305 wxASSERT_MSG( !path.empty(),
1306 "using empty path with wxDOC_SILENT doesn't make sense" );
1307
1308 temp = FindTemplateForPath(path);
1309 if ( !temp )
1310 {
1311 wxLogWarning(_("The format of file '%s' couldn't be determined."),
1312 path);
1313 }
1314 }
1315 else // not silent, ask the user
1316 {
1317 // for the new file we need just the template, for an existing one we
1318 // need the template and the path, unless it's already specified
1319 if ( (flags & wxDOC_NEW) || !path.empty() )
1320 temp = SelectDocumentType(&templates[0], numTemplates);
1321 else
1322 temp = SelectDocumentPath(&templates[0], numTemplates, path, flags);
1323 }
1324
1325 if ( !temp )
1326 return NULL;
1327
1328 // check whether the document with this path is already opened
1329 if ( !path.empty() )
1330 {
1331 const wxFileName fn(path);
1332 for ( wxList::const_iterator i = m_docs.begin(); i != m_docs.end(); ++i )
1333 {
1334 wxDocument * const doc = (wxDocument*)*i;
1335
1336 if ( fn == doc->GetFilename() )
1337 {
1338 // file already open, just activate it and return
1339 if ( doc->GetFirstView() )
1340 {
1341 ActivateView(doc->GetFirstView());
1342 if ( doc->GetDocumentWindow() )
1343 doc->GetDocumentWindow()->SetFocus();
1344 return doc;
1345 }
1346 }
1347 }
1348 }
1349
1350
1351 // no, we need to create a new document
1352
1353
1354 // if we've reached the max number of docs, close the first one.
1355 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen )
1356 {
1357 if ( !CloseDocument((wxDocument *)GetDocuments().GetFirst()->GetData()) )
1358 {
1359 // can't open the new document if closing the old one failed
1360 return NULL;
1361 }
1362 }
1363
1364
1365 // do create and initialize the new document finally
1366 wxDocument * const docNew = temp->CreateDocument(path, flags);
1367 if ( !docNew )
1368 return NULL;
1369
1370 docNew->SetDocumentName(temp->GetDocumentName());
1371 docNew->SetDocumentTemplate(temp);
1372
1373 wxTRY
1374 {
1375 // call the appropriate function depending on whether we're creating a
1376 // new file or opening an existing one
1377 if ( !(flags & wxDOC_NEW ? docNew->OnNewDocument()
1378 : docNew->OnOpenDocument(path)) )
1379 {
1380 docNew->DeleteAllViews();
1381 return NULL;
1382 }
1383 }
1384 wxCATCH_ALL( docNew->DeleteAllViews(); throw; )
1385
1386 // add the successfully opened file to MRU, but only if we're going to be
1387 // able to reopen it successfully later which requires the template for
1388 // this document to be retrievable from the file extension
1389 if ( !(flags & wxDOC_NEW) && temp->FileMatchesTemplate(path) )
1390 AddFileToHistory(path);
1391
1392 return docNew;
1393}
1394
1395wxView *wxDocManager::CreateView(wxDocument *doc, long flags)
1396{
1397 wxDocTemplates templates(GetVisibleTemplates(m_templates));
1398 const size_t numTemplates = templates.size();
1399
1400 if ( numTemplates == 0 )
1401 return NULL;
1402
1403 wxDocTemplate * const
1404 temp = numTemplates == 1 ? templates[0]
1405 : SelectViewType(&templates[0], numTemplates);
1406
1407 if ( !temp )
1408 return NULL;
1409
1410 wxView *view = temp->CreateView(doc, flags);
1411 if ( view )
1412 view->SetViewName(temp->GetViewName());
1413 return view;
1414}
1415
1416// Not yet implemented
1417void
1418wxDocManager::DeleteTemplate(wxDocTemplate *WXUNUSED(temp), long WXUNUSED(flags))
1419{
1420}
1421
1422// Not yet implemented
1423bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc))
1424{
1425 return false;
1426}
1427
1428wxDocument *wxDocManager::GetCurrentDocument() const
1429{
1430 wxView * const view = GetActiveView();
1431 return view ? view->GetDocument() : NULL;
1432}
1433
1434wxCommandProcessor *wxDocManager::GetCurrentCommandProcessor() const
1435{
1436 wxDocument * const doc = GetCurrentDocument();
1437 return doc ? doc->GetCommandProcessor() : NULL;
1438}
1439
1440// Make a default name for a new document
1441#if WXWIN_COMPATIBILITY_2_8
1442bool wxDocManager::MakeDefaultName(wxString& WXUNUSED(name))
1443{
1444 // we consider that this function can only be overridden by the user code,
1445 // not called by it as it only makes sense to call it internally, so we
1446 // don't bother to return anything from here
1447 return false;
1448}
1449#endif // WXWIN_COMPATIBILITY_2_8
1450
1451wxString wxDocManager::MakeNewDocumentName()
1452{
1453 wxString name;
1454
1455#if WXWIN_COMPATIBILITY_2_8
1456 if ( !MakeDefaultName(name) )
1457#endif // WXWIN_COMPATIBILITY_2_8
1458 {
1459 name.Printf(_("unnamed%d"), m_defaultDocumentNameCounter);
1460 m_defaultDocumentNameCounter++;
1461 }
1462
1463 return name;
1464}
1465
1466// Make a frame title (override this to do something different)
1467// If docName is empty, a document is not currently active.
1468wxString wxDocManager::MakeFrameTitle(wxDocument* doc)
1469{
1470 wxString appName = wxTheApp->GetAppDisplayName();
1471 wxString title;
1472 if (!doc)
1473 title = appName;
1474 else
1475 {
1476 wxString docName = doc->GetUserReadableName();
1477 title = docName + wxString(_(" - ")) + appName;
1478 }
1479 return title;
1480}
1481
1482
1483// Not yet implemented
1484wxDocTemplate *wxDocManager::MatchTemplate(const wxString& WXUNUSED(path))
1485{
1486 return NULL;
1487}
1488
1489// File history management
1490void wxDocManager::AddFileToHistory(const wxString& file)
1491{
1492 if (m_fileHistory)
1493 m_fileHistory->AddFileToHistory(file);
1494}
1495
1496void wxDocManager::RemoveFileFromHistory(size_t i)
1497{
1498 if (m_fileHistory)
1499 m_fileHistory->RemoveFileFromHistory(i);
1500}
1501
1502wxString wxDocManager::GetHistoryFile(size_t i) const
1503{
1504 wxString histFile;
1505
1506 if (m_fileHistory)
1507 histFile = m_fileHistory->GetHistoryFile(i);
1508
1509 return histFile;
1510}
1511
1512void wxDocManager::FileHistoryUseMenu(wxMenu *menu)
1513{
1514 if (m_fileHistory)
1515 m_fileHistory->UseMenu(menu);
1516}
1517
1518void wxDocManager::FileHistoryRemoveMenu(wxMenu *menu)
1519{
1520 if (m_fileHistory)
1521 m_fileHistory->RemoveMenu(menu);
1522}
1523
1524#if wxUSE_CONFIG
1525void wxDocManager::FileHistoryLoad(const wxConfigBase& config)
1526{
1527 if (m_fileHistory)
1528 m_fileHistory->Load(config);
1529}
1530
1531void wxDocManager::FileHistorySave(wxConfigBase& config)
1532{
1533 if (m_fileHistory)
1534 m_fileHistory->Save(config);
1535}
1536#endif
1537
1538void wxDocManager::FileHistoryAddFilesToMenu(wxMenu* menu)
1539{
1540 if (m_fileHistory)
1541 m_fileHistory->AddFilesToMenu(menu);
1542}
1543
1544void wxDocManager::FileHistoryAddFilesToMenu()
1545{
1546 if (m_fileHistory)
1547 m_fileHistory->AddFilesToMenu();
1548}
1549
1550size_t wxDocManager::GetHistoryFilesCount() const
1551{
1552 return m_fileHistory ? m_fileHistory->GetCount() : 0;
1553}
1554
1555
1556// Find out the document template via matching in the document file format
1557// against that of the template
1558wxDocTemplate *wxDocManager::FindTemplateForPath(const wxString& path)
1559{
1560 wxDocTemplate *theTemplate = NULL;
1561
1562 // Find the template which this extension corresponds to
1563 for (size_t i = 0; i < m_templates.GetCount(); i++)
1564 {
1565 wxDocTemplate *temp = (wxDocTemplate *)m_templates.Item(i)->GetData();
1566 if ( temp->FileMatchesTemplate(path) )
1567 {
1568 theTemplate = temp;
1569 break;
1570 }
1571 }
1572 return theTemplate;
1573}
1574
1575// Prompts user to open a file, using file specs in templates.
1576// Must extend the file selector dialog or implement own; OR
1577// match the extension to the template extension.
1578
1579wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates,
1580 int noTemplates,
1581 wxString& path,
1582 long WXUNUSED(flags),
1583 bool WXUNUSED(save))
1584{
1585#ifdef wxHAS_MULTIPLE_FILEDLG_FILTERS
1586 wxString descrBuf;
1587
1588 for (int i = 0; i < noTemplates; i++)
1589 {
1590 if (templates[i]->IsVisible())
1591 {
1592 // add a '|' to separate this filter from the previous one
1593 if ( !descrBuf.empty() )
1594 descrBuf << wxT('|');
1595
1596 descrBuf << templates[i]->GetDescription()
1597 << wxT(" (") << templates[i]->GetFileFilter() << wxT(") |")
1598 << templates[i]->GetFileFilter();
1599 }
1600 }
1601#else
1602 wxString descrBuf = wxT("*.*");
1603 wxUnusedVar(noTemplates);
1604#endif
1605
1606 int FilterIndex = -1;
1607
1608 wxString pathTmp = wxFileSelectorEx(_("Open File"),
1609 GetLastDirectory(),
1610 wxEmptyString,
1611 &FilterIndex,
1612 descrBuf,
1613 wxFD_OPEN | wxFD_FILE_MUST_EXIST);
1614
1615 wxDocTemplate *theTemplate = NULL;
1616 if (!pathTmp.empty())
1617 {
1618 if (!wxFileExists(pathTmp))
1619 {
1620 wxString msgTitle;
1621 if (!wxTheApp->GetAppDisplayName().empty())
1622 msgTitle = wxTheApp->GetAppDisplayName();
1623 else
1624 msgTitle = wxString(_("File error"));
1625
1626 wxMessageBox(_("Sorry, could not open this file."),
1627 msgTitle,
1628 wxOK | wxICON_EXCLAMATION | wxCENTRE);
1629
1630 path = wxEmptyString;
1631 return NULL;
1632 }
1633
1634 SetLastDirectory(wxPathOnly(pathTmp));
1635
1636 path = pathTmp;
1637
1638 // first choose the template using the extension, if this fails (i.e.
1639 // wxFileSelectorEx() didn't fill it), then use the path
1640 if ( FilterIndex != -1 )
1641 theTemplate = templates[FilterIndex];
1642 if ( !theTemplate )
1643 theTemplate = FindTemplateForPath(path);
1644 if ( !theTemplate )
1645 {
1646 // Since we do not add files with non-default extensions to the
1647 // file history this can only happen if the application changes the
1648 // allowed templates in runtime.
1649 wxMessageBox(_("Sorry, the format for this file is unknown."),
1650 _("Open File"),
1651 wxOK | wxICON_EXCLAMATION | wxCENTRE);
1652 }
1653 }
1654 else
1655 {
1656 path.clear();
1657 }
1658
1659 return theTemplate;
1660}
1661
1662wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1663 int noTemplates, bool sort)
1664{
1665 wxArrayString strings;
1666 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1667 int i;
1668 int n = 0;
1669
1670 for (i = 0; i < noTemplates; i++)
1671 {
1672 if (templates[i]->IsVisible())
1673 {
1674 int j;
1675 bool want = true;
1676 for (j = 0; j < n; j++)
1677 {
1678 //filter out NOT unique documents + view combinations
1679 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1680 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1681 )
1682 want = false;
1683 }
1684
1685 if ( want )
1686 {
1687 strings.Add(templates[i]->m_description);
1688
1689 data[n] = templates[i];
1690 n ++;
1691 }
1692 }
1693 } // for
1694
1695 if (sort)
1696 {
1697 strings.Sort(); // ascending sort
1698 // Yes, this will be slow, but template lists
1699 // are typically short.
1700 int j;
1701 n = strings.Count();
1702 for (i = 0; i < n; i++)
1703 {
1704 for (j = 0; j < noTemplates; j++)
1705 {
1706 if (strings[i] == templates[j]->m_description)
1707 data[i] = templates[j];
1708 }
1709 }
1710 }
1711
1712 wxDocTemplate *theTemplate;
1713
1714 switch ( n )
1715 {
1716 case 0:
1717 // no visible templates, hence nothing to choose from
1718 theTemplate = NULL;
1719 break;
1720
1721 case 1:
1722 // don't propose the user to choose if he has no choice
1723 theTemplate = data[0];
1724 break;
1725
1726 default:
1727 // propose the user to choose one of several
1728 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1729 (
1730 _("Select a document template"),
1731 _("Templates"),
1732 strings,
1733 (void **)data.get()
1734 );
1735 }
1736
1737 return theTemplate;
1738}
1739
1740wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1741 int noTemplates, bool sort)
1742{
1743 wxArrayString strings;
1744 wxScopedArray<wxDocTemplate *> data(new wxDocTemplate *[noTemplates]);
1745 int i;
1746 int n = 0;
1747
1748 for (i = 0; i < noTemplates; i++)
1749 {
1750 wxDocTemplate *templ = templates[i];
1751 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1752 {
1753 int j;
1754 bool want = true;
1755 for (j = 0; j < n; j++)
1756 {
1757 //filter out NOT unique views
1758 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1759 want = false;
1760 }
1761
1762 if ( want )
1763 {
1764 strings.Add(templ->m_viewTypeName);
1765 data[n] = templ;
1766 n ++;
1767 }
1768 }
1769 }
1770
1771 if (sort)
1772 {
1773 strings.Sort(); // ascending sort
1774 // Yes, this will be slow, but template lists
1775 // are typically short.
1776 int j;
1777 n = strings.Count();
1778 for (i = 0; i < n; i++)
1779 {
1780 for (j = 0; j < noTemplates; j++)
1781 {
1782 if (strings[i] == templates[j]->m_viewTypeName)
1783 data[i] = templates[j];
1784 }
1785 }
1786 }
1787
1788 wxDocTemplate *theTemplate;
1789
1790 // the same logic as above
1791 switch ( n )
1792 {
1793 case 0:
1794 theTemplate = NULL;
1795 break;
1796
1797 case 1:
1798 theTemplate = data[0];
1799 break;
1800
1801 default:
1802 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1803 (
1804 _("Select a document view"),
1805 _("Views"),
1806 strings,
1807 (void **)data.get()
1808 );
1809
1810 }
1811
1812 return theTemplate;
1813}
1814
1815void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1816{
1817 if (!m_templates.Member(temp))
1818 m_templates.Append(temp);
1819}
1820
1821void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1822{
1823 m_templates.DeleteObject(temp);
1824}
1825
1826// Add and remove a document from the manager's list
1827void wxDocManager::AddDocument(wxDocument *doc)
1828{
1829 if (!m_docs.Member(doc))
1830 m_docs.Append(doc);
1831}
1832
1833void wxDocManager::RemoveDocument(wxDocument *doc)
1834{
1835 m_docs.DeleteObject(doc);
1836}
1837
1838// Views or windows should inform the document manager
1839// when a view is going in or out of focus
1840void wxDocManager::ActivateView(wxView *view, bool activate)
1841{
1842 if ( activate )
1843 {
1844 m_currentView = view;
1845 }
1846 else // deactivate
1847 {
1848 if ( m_currentView == view )
1849 {
1850 // don't keep stale pointer
1851 m_currentView = NULL;
1852 }
1853 }
1854}
1855
1856// ----------------------------------------------------------------------------
1857// wxDocChildFrameAnyBase
1858// ----------------------------------------------------------------------------
1859
1860bool wxDocChildFrameAnyBase::CloseView(wxCloseEvent& event)
1861{
1862 if ( m_childView )
1863 {
1864 // notice that we must call wxView::Close() and OnClose() called from
1865 // it in any case, even if we know that we are going to close anyhow
1866 if ( !m_childView->Close(false) && event.CanVeto() )
1867 {
1868 event.Veto();
1869 return false;
1870 }
1871
1872 m_childView->Activate(false);
1873
1874 // it is important to reset m_childView frame pointer to NULL before
1875 // deleting it because while normally it is the frame which deletes the
1876 // view when it's closed, the view also closes the frame if it is
1877 // deleted directly not by us as indicated by its doc child frame
1878 // pointer still being set
1879 m_childView->SetDocChildFrame(NULL);
1880 delete m_childView;
1881 m_childView = NULL;
1882 }
1883
1884 m_childDocument = NULL;
1885
1886 return true;
1887}
1888
1889// ----------------------------------------------------------------------------
1890// wxDocParentFrameAnyBase
1891// ----------------------------------------------------------------------------
1892
1893void wxDocParentFrameAnyBase::DoOpenMRUFile(unsigned n)
1894{
1895 wxString filename(m_docManager->GetHistoryFile(n));
1896 if ( filename.empty() )
1897 return;
1898
1899 wxString errMsg; // must contain exactly one "%s" if non-empty
1900 if ( wxFile::Exists(filename) )
1901 {
1902 // try to open it
1903 if ( m_docManager->CreateDocument(filename, wxDOC_SILENT) )
1904 return;
1905
1906 errMsg = _("The file '%s' couldn't be opened.");
1907 }
1908 else // file doesn't exist
1909 {
1910 errMsg = _("The file '%s' doesn't exist and couldn't be opened.");
1911 }
1912
1913
1914 wxASSERT_MSG( !errMsg.empty(), "should have an error message" );
1915
1916 // remove the file which we can't open from the MRU list
1917 m_docManager->RemoveFileFromHistory(n);
1918
1919 // and tell the user about it
1920 wxLogError(errMsg + '\n' +
1921 _("It has been removed from the most recently used files list."),
1922 filename);
1923}
1924
1925#if wxUSE_PRINTING_ARCHITECTURE
1926
1927wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
1928 : wxPrintout(title)
1929{
1930 m_printoutView = view;
1931}
1932
1933bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
1934{
1935 wxDC *dc = GetDC();
1936
1937 // Get the logical pixels per inch of screen and printer
1938 int ppiScreenX, ppiScreenY;
1939 GetPPIScreen(&ppiScreenX, &ppiScreenY);
1940 wxUnusedVar(ppiScreenY);
1941 int ppiPrinterX, ppiPrinterY;
1942 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
1943 wxUnusedVar(ppiPrinterY);
1944
1945 // This scales the DC so that the printout roughly represents the
1946 // the screen scaling. The text point size _should_ be the right size
1947 // but in fact is too small for some reason. This is a detail that will
1948 // need to be addressed at some point but can be fudged for the
1949 // moment.
1950 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
1951
1952 // Now we have to check in case our real page size is reduced
1953 // (e.g. because we're drawing to a print preview memory DC)
1954 int pageWidth, pageHeight;
1955 int w, h;
1956 dc->GetSize(&w, &h);
1957 GetPageSizePixels(&pageWidth, &pageHeight);
1958 wxUnusedVar(pageHeight);
1959
1960 // If printer pageWidth == current DC width, then this doesn't
1961 // change. But w might be the preview bitmap width, so scale down.
1962 float overallScale = scale * (float)(w/(float)pageWidth);
1963 dc->SetUserScale(overallScale, overallScale);
1964
1965 if (m_printoutView)
1966 {
1967 m_printoutView->OnDraw(dc);
1968 }
1969 return true;
1970}
1971
1972bool wxDocPrintout::HasPage(int pageNum)
1973{
1974 return (pageNum == 1);
1975}
1976
1977bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
1978{
1979 if (!wxPrintout::OnBeginDocument(startPage, endPage))
1980 return false;
1981
1982 return true;
1983}
1984
1985void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage,
1986 int *selPageFrom, int *selPageTo)
1987{
1988 *minPage = 1;
1989 *maxPage = 1;
1990 *selPageFrom = 1;
1991 *selPageTo = 1;
1992}
1993
1994#endif // wxUSE_PRINTING_ARCHITECTURE
1995
1996// ----------------------------------------------------------------------------
1997// Permits compatibility with existing file formats and functions that
1998// manipulate files directly
1999// ----------------------------------------------------------------------------
2000
2001#if wxUSE_STD_IOSTREAM
2002
2003bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream)
2004{
2005#if wxUSE_FFILE
2006 wxFFile file(filename, wxT("rb"));
2007#elif wxUSE_FILE
2008 wxFile file(filename, wxFile::read);
2009#endif
2010 if ( !file.IsOpened() )
2011 return false;
2012
2013 char buf[4096];
2014
2015 size_t nRead;
2016 do
2017 {
2018 nRead = file.Read(buf, WXSIZEOF(buf));
2019 if ( file.Error() )
2020 return false;
2021
2022 stream.write(buf, nRead);
2023 if ( !stream )
2024 return false;
2025 }
2026 while ( !file.Eof() );
2027
2028 return true;
2029}
2030
2031bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename)
2032{
2033#if wxUSE_FFILE
2034 wxFFile file(filename, wxT("wb"));
2035#elif wxUSE_FILE
2036 wxFile file(filename, wxFile::write);
2037#endif
2038 if ( !file.IsOpened() )
2039 return false;
2040
2041 char buf[4096];
2042 do
2043 {
2044 stream.read(buf, WXSIZEOF(buf));
2045 if ( !stream.bad() ) // fail may be set on EOF, don't use operator!()
2046 {
2047 if ( !file.Write(buf, stream.gcount()) )
2048 return false;
2049 }
2050 }
2051 while ( !stream.eof() );
2052
2053 return true;
2054}
2055
2056#else // !wxUSE_STD_IOSTREAM
2057
2058bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream)
2059{
2060#if wxUSE_FFILE
2061 wxFFile file(filename, wxT("rb"));
2062#elif wxUSE_FILE
2063 wxFile file(filename, wxFile::read);
2064#endif
2065 if ( !file.IsOpened() )
2066 return false;
2067
2068 char buf[4096];
2069
2070 size_t nRead;
2071 do
2072 {
2073 nRead = file.Read(buf, WXSIZEOF(buf));
2074 if ( file.Error() )
2075 return false;
2076
2077 stream.Write(buf, nRead);
2078 if ( !stream )
2079 return false;
2080 }
2081 while ( !file.Eof() );
2082
2083 return true;
2084}
2085
2086bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename)
2087{
2088#if wxUSE_FFILE
2089 wxFFile file(filename, wxT("wb"));
2090#elif wxUSE_FILE
2091 wxFile file(filename, wxFile::write);
2092#endif
2093 if ( !file.IsOpened() )
2094 return false;
2095
2096 char buf[4096];
2097 for ( ;; )
2098 {
2099 stream.Read(buf, WXSIZEOF(buf));
2100
2101 const size_t nRead = stream.LastRead();
2102 if ( !nRead )
2103 {
2104 if ( stream.Eof() )
2105 break;
2106
2107 return false;
2108 }
2109
2110 if ( !file.Write(buf, nRead) )
2111 return false;
2112 }
2113
2114 return true;
2115}
2116
2117#endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2118
2119#endif // wxUSE_DOC_VIEW_ARCHITECTURE