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