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