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