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