Implemented delayed closing of an existing document
[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 return NULL;
1104 }
1105 }
1106
1107 wxDocTemplate *temp = templates[0];
1108 delete[] templates;
1109 wxDocument *newDoc = temp->CreateDocument(path, flags);
1110
1111 if (newDoc)
1112 {
1113 newDoc->SetDocumentName(temp->GetDocumentName());
1114 newDoc->SetDocumentTemplate(temp);
1115 newDoc->OnNewDocument();
1116 }
1117 return newDoc;
1118 }
1119
1120 wxDocTemplate *temp = SelectDocumentType(templates, n);
1121 delete[] templates;
1122 if (temp)
1123 {
1124 if (docToClose)
1125 {
1126 if (!CloseDocument(docToClose, FALSE))
1127 {
1128 return NULL;
1129 }
1130 }
1131
1132 wxDocument *newDoc = temp->CreateDocument(path, flags);
1133
1134 if (newDoc)
1135 {
1136 newDoc->SetDocumentName(temp->GetDocumentName());
1137 newDoc->SetDocumentTemplate(temp);
1138 newDoc->OnNewDocument();
1139 }
1140 return newDoc;
1141 }
1142 else
1143 return (wxDocument *) NULL;
1144 }
1145
1146 // Existing document
1147 wxDocTemplate *temp = (wxDocTemplate *) NULL;
1148
1149 wxString path2(wxT(""));
1150 if (path != wxT(""))
1151 path2 = path;
1152
1153 if (flags & wxDOC_SILENT)
1154 temp = FindTemplateForPath(path2);
1155 else
1156 temp = SelectDocumentPath(templates, n, path2, flags);
1157
1158 delete[] templates;
1159
1160 if (temp)
1161 {
1162 if (docToClose)
1163 {
1164 if (!CloseDocument(docToClose, FALSE))
1165 {
1166 return NULL;
1167 }
1168 }
1169
1170 wxDocument *newDoc = temp->CreateDocument(path2, flags);
1171 if (newDoc)
1172 {
1173 newDoc->SetDocumentName(temp->GetDocumentName());
1174 newDoc->SetDocumentTemplate(temp);
1175 if (!newDoc->OnOpenDocument(path2))
1176 {
1177 newDoc->DeleteAllViews();
1178 // delete newDoc; // Implicitly deleted by DeleteAllViews
1179 return (wxDocument *) NULL;
1180 }
1181 AddFileToHistory(path2);
1182 }
1183 return newDoc;
1184 }
1185
1186 return (wxDocument *) NULL;
1187 }
1188
1189 wxView *wxDocManager::CreateView(wxDocument *doc, long flags)
1190 {
1191 wxDocTemplate **templates = new wxDocTemplate *[m_templates.GetCount()];
1192 int n =0;
1193
1194 for (size_t i = 0; i < m_templates.GetCount(); i++)
1195 {
1196 wxDocTemplate *temp = (wxDocTemplate *)(m_templates.Item(i)->GetData());
1197 if (temp->IsVisible())
1198 {
1199 if (temp->GetDocumentName() == doc->GetDocumentName())
1200 {
1201 templates[n] = temp;
1202 n ++;
1203 }
1204 }
1205 }
1206 if (n == 0)
1207 {
1208 delete[] templates;
1209 return (wxView *) NULL;
1210 }
1211 if (n == 1)
1212 {
1213 wxDocTemplate *temp = templates[0];
1214 delete[] templates;
1215 wxView *view = temp->CreateView(doc, flags);
1216 if (view)
1217 view->SetViewName(temp->GetViewName());
1218 return view;
1219 }
1220
1221 wxDocTemplate *temp = SelectViewType(templates, n);
1222 delete[] templates;
1223 if (temp)
1224 {
1225 wxView *view = temp->CreateView(doc, flags);
1226 if (view)
1227 view->SetViewName(temp->GetViewName());
1228 return view;
1229 }
1230 else
1231 return (wxView *) NULL;
1232 }
1233
1234 // Not yet implemented
1235 void wxDocManager::DeleteTemplate(wxDocTemplate *WXUNUSED(temp), long WXUNUSED(flags))
1236 {
1237 }
1238
1239 // Not yet implemented
1240 bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc))
1241 {
1242 return FALSE;
1243 }
1244
1245 wxDocument *wxDocManager::GetCurrentDocument() const
1246 {
1247 wxView *view = GetCurrentView();
1248 if (view)
1249 return view->GetDocument();
1250 else
1251 return (wxDocument *) NULL;
1252 }
1253
1254 // Make a default document name
1255 bool wxDocManager::MakeDefaultName(wxString& name)
1256 {
1257 name.Printf(_("unnamed%d"), m_defaultDocumentNameCounter);
1258 m_defaultDocumentNameCounter++;
1259
1260 return TRUE;
1261 }
1262
1263 // Make a frame title (override this to do something different)
1264 // If docName is empty, a document is not currently active.
1265 wxString wxDocManager::MakeFrameTitle(wxDocument* doc)
1266 {
1267 wxString appName = wxTheApp->GetAppName();
1268 wxString title;
1269 if (!doc)
1270 title = appName;
1271 else
1272 {
1273 wxString docName;
1274 doc->GetPrintableName(docName);
1275 title = docName + wxString(_(" - ")) + appName;
1276 }
1277 return title;
1278 }
1279
1280
1281 // Not yet implemented
1282 wxDocTemplate *wxDocManager::MatchTemplate(const wxString& WXUNUSED(path))
1283 {
1284 return (wxDocTemplate *) NULL;
1285 }
1286
1287 // File history management
1288 void wxDocManager::AddFileToHistory(const wxString& file)
1289 {
1290 if (m_fileHistory)
1291 m_fileHistory->AddFileToHistory(file);
1292 }
1293
1294 void wxDocManager::RemoveFileFromHistory(size_t i)
1295 {
1296 if (m_fileHistory)
1297 m_fileHistory->RemoveFileFromHistory(i);
1298 }
1299
1300 wxString wxDocManager::GetHistoryFile(size_t i) const
1301 {
1302 wxString histFile;
1303
1304 if (m_fileHistory)
1305 histFile = m_fileHistory->GetHistoryFile(i);
1306
1307 return histFile;
1308 }
1309
1310 void wxDocManager::FileHistoryUseMenu(wxMenu *menu)
1311 {
1312 if (m_fileHistory)
1313 m_fileHistory->UseMenu(menu);
1314 }
1315
1316 void wxDocManager::FileHistoryRemoveMenu(wxMenu *menu)
1317 {
1318 if (m_fileHistory)
1319 m_fileHistory->RemoveMenu(menu);
1320 }
1321
1322 #if wxUSE_CONFIG
1323 void wxDocManager::FileHistoryLoad(wxConfigBase& config)
1324 {
1325 if (m_fileHistory)
1326 m_fileHistory->Load(config);
1327 }
1328
1329 void wxDocManager::FileHistorySave(wxConfigBase& config)
1330 {
1331 if (m_fileHistory)
1332 m_fileHistory->Save(config);
1333 }
1334 #endif
1335
1336 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu* menu)
1337 {
1338 if (m_fileHistory)
1339 m_fileHistory->AddFilesToMenu(menu);
1340 }
1341
1342 void wxDocManager::FileHistoryAddFilesToMenu()
1343 {
1344 if (m_fileHistory)
1345 m_fileHistory->AddFilesToMenu();
1346 }
1347
1348 size_t wxDocManager::GetNoHistoryFiles() const
1349 {
1350 if (m_fileHistory)
1351 return m_fileHistory->GetNoHistoryFiles();
1352 else
1353 return 0;
1354 }
1355
1356
1357 // Find out the document template via matching in the document file format
1358 // against that of the template
1359 wxDocTemplate *wxDocManager::FindTemplateForPath(const wxString& path)
1360 {
1361 wxDocTemplate *theTemplate = (wxDocTemplate *) NULL;
1362
1363 // Find the template which this extension corresponds to
1364 for (size_t i = 0; i < m_templates.GetCount(); i++)
1365 {
1366 wxDocTemplate *temp = (wxDocTemplate *)m_templates.Item(i)->GetData();
1367 if ( temp->FileMatchesTemplate(path) )
1368 {
1369 theTemplate = temp;
1370 break;
1371 }
1372 }
1373 return theTemplate;
1374 }
1375
1376 // Try to get a more suitable parent frame than the top window,
1377 // for selection dialogs. Otherwise you may get an unexpected
1378 // window being activated when a dialog is shown.
1379 static wxWindow* wxFindSuitableParent()
1380 {
1381 wxWindow* parent = wxTheApp->GetTopWindow();
1382
1383 wxWindow* focusWindow = wxWindow::FindFocus();
1384 if (focusWindow)
1385 {
1386 while (focusWindow &&
1387 !focusWindow->IsKindOf(CLASSINFO(wxDialog)) &&
1388 !focusWindow->IsKindOf(CLASSINFO(wxFrame)))
1389
1390 focusWindow = focusWindow->GetParent();
1391
1392 if (focusWindow)
1393 parent = focusWindow;
1394 }
1395 return parent;
1396 }
1397
1398 // Prompts user to open a file, using file specs in templates.
1399 // How to implement in wxWindows? Must extend the file selector
1400 // dialog or implement own; OR match the extension to the
1401 // template extension.
1402
1403 wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates,
1404 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1405 int noTemplates,
1406 #else
1407 int WXUNUSED(noTemplates),
1408 #endif
1409 wxString& path,
1410 long WXUNUSED(flags),
1411 bool WXUNUSED(save))
1412 {
1413 // We can only have multiple filters in Windows and GTK
1414 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1415 wxString descrBuf;
1416
1417 int i;
1418 for (i = 0; i < noTemplates; i++)
1419 {
1420 if (templates[i]->IsVisible())
1421 {
1422 // add a '|' to separate this filter from the previous one
1423 if ( !descrBuf.IsEmpty() )
1424 descrBuf << wxT('|');
1425
1426 descrBuf << templates[i]->GetDescription()
1427 << wxT(" (") << templates[i]->GetFileFilter() << wxT(") |")
1428 << templates[i]->GetFileFilter();
1429 }
1430 }
1431 #else
1432 wxString descrBuf = wxT("*.*");
1433 #endif
1434
1435 int FilterIndex = -1;
1436
1437 wxWindow* parent = wxFindSuitableParent();
1438
1439 wxString pathTmp = wxFileSelectorEx(_("Select a file"),
1440 m_lastDirectory,
1441 wxT(""),
1442 &FilterIndex,
1443 descrBuf,
1444 0,
1445 parent);
1446
1447 wxDocTemplate *theTemplate = (wxDocTemplate *)NULL;
1448 if (!pathTmp.IsEmpty())
1449 {
1450 if (!wxFileExists(pathTmp))
1451 {
1452 wxString msgTitle;
1453 if (!wxTheApp->GetAppName().IsEmpty())
1454 msgTitle = wxTheApp->GetAppName();
1455 else
1456 msgTitle = wxString(_("File error"));
1457
1458 (void)wxMessageBox(_("Sorry, could not open this file."), msgTitle, wxOK | wxICON_EXCLAMATION,
1459 parent);
1460
1461 path = wxT("");
1462 return (wxDocTemplate *) NULL;
1463 }
1464 m_lastDirectory = wxPathOnly(pathTmp);
1465
1466 path = pathTmp;
1467
1468 // first choose the template using the extension, if this fails (i.e.
1469 // wxFileSelectorEx() didn't fill it), then use the path
1470 if ( FilterIndex != -1 )
1471 theTemplate = templates[FilterIndex];
1472 if ( !theTemplate )
1473 theTemplate = FindTemplateForPath(path);
1474 }
1475 else
1476 {
1477 path = wxT("");
1478 }
1479
1480 return theTemplate;
1481
1482 #if 0
1483 // In all other windowing systems, until we have more advanced
1484 // file selectors, we must select the document type (template) first, and
1485 // _then_ pop up the file selector.
1486 wxDocTemplate *temp = SelectDocumentType(templates, noTemplates);
1487 if (!temp)
1488 return (wxDocTemplate *) NULL;
1489
1490 wxChar *pathTmp = wxFileSelector(_("Select a file"), wxT(""), wxT(""),
1491 temp->GetDefaultExtension(),
1492 temp->GetFileFilter(),
1493 0, wxTheApp->GetTopWindow());
1494
1495 if (pathTmp)
1496 {
1497 path = pathTmp;
1498 return temp;
1499 }
1500 else
1501 return (wxDocTemplate *) NULL;
1502 #endif // 0
1503 }
1504
1505 wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1506 int noTemplates, bool sort)
1507 {
1508 wxArrayString strings(sort);
1509 wxDocTemplate **data = new wxDocTemplate *[noTemplates];
1510 int i;
1511 int n = 0;
1512
1513 for (i = 0; i < noTemplates; i++)
1514 {
1515 if (templates[i]->IsVisible())
1516 {
1517 int j;
1518 bool want = TRUE;
1519 for (j = 0; j < n; j++)
1520 {
1521 //filter out NOT unique documents + view combinations
1522 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1523 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1524 )
1525 want = FALSE;
1526 }
1527
1528 if ( want )
1529 {
1530 strings.Add(templates[i]->m_description);
1531
1532 data[n] = templates[i];
1533 n ++;
1534 }
1535 }
1536 } // for
1537
1538 if (sort)
1539 {
1540 // Yes, this will be slow, but template lists
1541 // are typically short.
1542 int j;
1543 n = strings.Count();
1544 for (i = 0; i < n; i++)
1545 {
1546 for (j = 0; j < noTemplates; j++)
1547 {
1548 if (strings[i] == templates[j]->m_description)
1549 data[i] = templates[j];
1550 }
1551 }
1552 }
1553
1554 wxDocTemplate *theTemplate;
1555
1556 switch ( n )
1557 {
1558 case 0:
1559 // no visible templates, hence nothing to choose from
1560 theTemplate = NULL;
1561 break;
1562
1563 case 1:
1564 // don't propose the user to choose if he heas no choice
1565 theTemplate = data[0];
1566 break;
1567
1568 default:
1569 // propose the user to choose one of several
1570 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1571 (
1572 _("Select a document template"),
1573 _("Templates"),
1574 strings,
1575 (void **)data,
1576 wxFindSuitableParent()
1577 );
1578 }
1579
1580 delete[] data;
1581
1582 return theTemplate;
1583 }
1584
1585 wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1586 int noTemplates, bool sort)
1587 {
1588 wxArrayString strings(sort);
1589 wxDocTemplate **data = new wxDocTemplate *[noTemplates];
1590 int i;
1591 int n = 0;
1592
1593 for (i = 0; i < noTemplates; i++)
1594 {
1595 wxDocTemplate *templ = templates[i];
1596 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1597 {
1598 int j;
1599 bool want = TRUE;
1600 for (j = 0; j < n; j++)
1601 {
1602 //filter out NOT unique views
1603 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1604 want = FALSE;
1605 }
1606
1607 if ( want )
1608 {
1609 strings.Add(templ->m_viewTypeName);
1610 data[n] = templ;
1611 n ++;
1612 }
1613 }
1614 }
1615
1616 if (sort)
1617 {
1618 // Yes, this will be slow, but template lists
1619 // are typically short.
1620 int j;
1621 n = strings.Count();
1622 for (i = 0; i < n; i++)
1623 {
1624 for (j = 0; j < noTemplates; j++)
1625 {
1626 if (strings[i] == templates[j]->m_viewTypeName)
1627 data[i] = templates[j];
1628 }
1629 }
1630 }
1631
1632 wxDocTemplate *theTemplate;
1633
1634 // the same logic as above
1635 switch ( n )
1636 {
1637 case 0:
1638 theTemplate = (wxDocTemplate *)NULL;
1639 break;
1640
1641 case 1:
1642 theTemplate = data[0];
1643 break;
1644
1645 default:
1646 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1647 (
1648 _("Select a document view"),
1649 _("Views"),
1650 strings,
1651 (void **)data,
1652 wxFindSuitableParent()
1653 );
1654
1655 }
1656
1657 delete[] data;
1658 return theTemplate;
1659 }
1660
1661 void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1662 {
1663 if (!m_templates.Member(temp))
1664 m_templates.Append(temp);
1665 }
1666
1667 void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1668 {
1669 m_templates.DeleteObject(temp);
1670 }
1671
1672 // Add and remove a document from the manager's list
1673 void wxDocManager::AddDocument(wxDocument *doc)
1674 {
1675 if (!m_docs.Member(doc))
1676 m_docs.Append(doc);
1677 }
1678
1679 void wxDocManager::RemoveDocument(wxDocument *doc)
1680 {
1681 m_docs.DeleteObject(doc);
1682 }
1683
1684 // Views or windows should inform the document manager
1685 // when a view is going in or out of focus
1686 void wxDocManager::ActivateView(wxView *view, bool activate, bool WXUNUSED(deleting))
1687 {
1688 // If we're deactiving, and if we're not actually deleting the view, then
1689 // don't reset the current view because we may be going to
1690 // a window without a view.
1691 // WHAT DID I MEAN BY THAT EXACTLY?
1692 /*
1693 if (deleting)
1694 {
1695 if (m_currentView == view)
1696 m_currentView = NULL;
1697 }
1698 else
1699 */
1700 {
1701 if (activate)
1702 m_currentView = view;
1703 else
1704 m_currentView = (wxView *) NULL;
1705 }
1706 }
1707
1708 // ----------------------------------------------------------------------------
1709 // Default document child frame
1710 // ----------------------------------------------------------------------------
1711
1712 BEGIN_EVENT_TABLE(wxDocChildFrame, wxFrame)
1713 EVT_ACTIVATE(wxDocChildFrame::OnActivate)
1714 EVT_CLOSE(wxDocChildFrame::OnCloseWindow)
1715 END_EVENT_TABLE()
1716
1717 wxDocChildFrame::wxDocChildFrame(wxDocument *doc,
1718 wxView *view,
1719 wxFrame *frame,
1720 wxWindowID id,
1721 const wxString& title,
1722 const wxPoint& pos,
1723 const wxSize& size,
1724 long style,
1725 const wxString& name)
1726 : wxFrame(frame, id, title, pos, size, style, name)
1727 {
1728 m_childDocument = doc;
1729 m_childView = view;
1730 if (view)
1731 view->SetFrame(this);
1732 }
1733
1734 wxDocChildFrame::~wxDocChildFrame()
1735 {
1736 }
1737
1738 // Extend event processing to search the view's event table
1739 bool wxDocChildFrame::ProcessEvent(wxEvent& event)
1740 {
1741 if (m_childView)
1742 m_childView->Activate(TRUE);
1743
1744 if ( !m_childView || ! m_childView->ProcessEvent(event) )
1745 {
1746 // Only hand up to the parent if it's a menu command
1747 if (!event.IsKindOf(CLASSINFO(wxCommandEvent)) || !GetParent() || !GetParent()->ProcessEvent(event))
1748 return wxEvtHandler::ProcessEvent(event);
1749 else
1750 return TRUE;
1751 }
1752 else
1753 return TRUE;
1754 }
1755
1756 void wxDocChildFrame::OnActivate(wxActivateEvent& event)
1757 {
1758 wxFrame::OnActivate(event);
1759
1760 if (m_childView)
1761 m_childView->Activate(event.GetActive());
1762 }
1763
1764 void wxDocChildFrame::OnCloseWindow(wxCloseEvent& event)
1765 {
1766 if (m_childView)
1767 {
1768 bool ans = FALSE;
1769 if (!event.CanVeto())
1770 ans = TRUE; // Must delete.
1771 else
1772 ans = m_childView->Close(FALSE); // FALSE means don't delete associated window
1773
1774 if (ans)
1775 {
1776 m_childView->Activate(FALSE);
1777 delete m_childView;
1778 m_childView = (wxView *) NULL;
1779 m_childDocument = (wxDocument *) NULL;
1780
1781 this->Destroy();
1782 }
1783 else
1784 event.Veto();
1785 }
1786 else
1787 event.Veto();
1788 }
1789
1790 // ----------------------------------------------------------------------------
1791 // Default parent frame
1792 // ----------------------------------------------------------------------------
1793
1794 BEGIN_EVENT_TABLE(wxDocParentFrame, wxFrame)
1795 EVT_MENU(wxID_EXIT, wxDocParentFrame::OnExit)
1796 EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocParentFrame::OnMRUFile)
1797 EVT_CLOSE(wxDocParentFrame::OnCloseWindow)
1798 END_EVENT_TABLE()
1799
1800 wxDocParentFrame::wxDocParentFrame(wxDocManager *manager,
1801 wxFrame *frame,
1802 wxWindowID id,
1803 const wxString& title,
1804 const wxPoint& pos,
1805 const wxSize& size,
1806 long style,
1807 const wxString& name)
1808 : wxFrame(frame, id, title, pos, size, style, name)
1809 {
1810 m_docManager = manager;
1811 }
1812
1813 void wxDocParentFrame::OnExit(wxCommandEvent& WXUNUSED(event))
1814 {
1815 Close();
1816 }
1817
1818 void wxDocParentFrame::OnMRUFile(wxCommandEvent& event)
1819 {
1820 int n = event.GetId() - wxID_FILE1; // the index in MRU list
1821 wxString filename(m_docManager->GetHistoryFile(n));
1822 if ( !filename.IsEmpty() )
1823 {
1824 // verify that the file exists before doing anything else
1825 if ( wxFile::Exists(filename) )
1826 {
1827 // try to open it
1828 (void)m_docManager->CreateDocument(filename, wxDOC_SILENT);
1829 }
1830 else
1831 {
1832 // remove the bogus filename from the MRU list and notify the user
1833 // about it
1834 m_docManager->RemoveFileFromHistory(n);
1835
1836 wxLogError(_("The file '%s' doesn't exist and couldn't be opened.\nIt has been removed from the most recently used files list."),
1837 filename.c_str());
1838 }
1839 }
1840 }
1841
1842 // Extend event processing to search the view's event table
1843 bool wxDocParentFrame::ProcessEvent(wxEvent& event)
1844 {
1845 // Try the document manager, then do default processing
1846 if (!m_docManager || !m_docManager->ProcessEvent(event))
1847 return wxEvtHandler::ProcessEvent(event);
1848 else
1849 return TRUE;
1850 }
1851
1852 // Define the behaviour for the frame closing
1853 // - must delete all frames except for the main one.
1854 void wxDocParentFrame::OnCloseWindow(wxCloseEvent& event)
1855 {
1856 if (m_docManager->Clear(!event.CanVeto()))
1857 {
1858 this->Destroy();
1859 }
1860 else
1861 event.Veto();
1862 }
1863
1864 #if wxUSE_PRINTING_ARCHITECTURE
1865
1866 wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
1867 : wxPrintout(title)
1868 {
1869 m_printoutView = view;
1870 }
1871
1872 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
1873 {
1874 wxDC *dc = GetDC();
1875
1876 // Get the logical pixels per inch of screen and printer
1877 int ppiScreenX, ppiScreenY;
1878 GetPPIScreen(&ppiScreenX, &ppiScreenY);
1879 int ppiPrinterX, ppiPrinterY;
1880 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
1881
1882 // This scales the DC so that the printout roughly represents the
1883 // the screen scaling. The text point size _should_ be the right size
1884 // but in fact is too small for some reason. This is a detail that will
1885 // need to be addressed at some point but can be fudged for the
1886 // moment.
1887 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
1888
1889 // Now we have to check in case our real page size is reduced
1890 // (e.g. because we're drawing to a print preview memory DC)
1891 int pageWidth, pageHeight;
1892 int w, h;
1893 dc->GetSize(&w, &h);
1894 GetPageSizePixels(&pageWidth, &pageHeight);
1895
1896 // If printer pageWidth == current DC width, then this doesn't
1897 // change. But w might be the preview bitmap width, so scale down.
1898 float overallScale = scale * (float)(w/(float)pageWidth);
1899 dc->SetUserScale(overallScale, overallScale);
1900
1901 if (m_printoutView)
1902 {
1903 m_printoutView->OnDraw(dc);
1904 }
1905 return TRUE;
1906 }
1907
1908 bool wxDocPrintout::HasPage(int pageNum)
1909 {
1910 return (pageNum == 1);
1911 }
1912
1913 bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
1914 {
1915 if (!wxPrintout::OnBeginDocument(startPage, endPage))
1916 return FALSE;
1917
1918 return TRUE;
1919 }
1920
1921 void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage, int *selPageFrom, int *selPageTo)
1922 {
1923 *minPage = 1;
1924 *maxPage = 1;
1925 *selPageFrom = 1;
1926 *selPageTo = 1;
1927 }
1928
1929 #endif // wxUSE_PRINTING_ARCHITECTURE
1930
1931 // ----------------------------------------------------------------------------
1932 // File history processor
1933 // ----------------------------------------------------------------------------
1934
1935 wxFileHistory::wxFileHistory(size_t maxFiles, wxWindowID idBase)
1936 {
1937 m_fileMaxFiles = maxFiles;
1938 m_idBase = idBase;
1939 m_fileHistoryN = 0;
1940 m_fileHistory = new wxChar *[m_fileMaxFiles];
1941 }
1942
1943 wxFileHistory::~wxFileHistory()
1944 {
1945 size_t i;
1946 for (i = 0; i < m_fileHistoryN; i++)
1947 delete[] m_fileHistory[i];
1948 delete[] m_fileHistory;
1949 }
1950
1951 // File history management
1952 void wxFileHistory::AddFileToHistory(const wxString& file)
1953 {
1954 size_t i;
1955
1956 // Check we don't already have this file
1957 for (i = 0; i < m_fileHistoryN; i++)
1958 {
1959 if ( m_fileHistory[i] && (file == m_fileHistory[i]) )
1960 {
1961 // we do have it, move it to the top of the history
1962 RemoveFileFromHistory (i);
1963 AddFileToHistory (file);
1964 return;
1965 }
1966 }
1967
1968 // if we already have a full history, delete the one at the end
1969 if ( m_fileMaxFiles == m_fileHistoryN )
1970 {
1971 RemoveFileFromHistory (m_fileHistoryN - 1);
1972 AddFileToHistory (file);
1973 return;
1974 }
1975
1976 // Add to the project file history:
1977 // Move existing files (if any) down so we can insert file at beginning.
1978 if (m_fileHistoryN < m_fileMaxFiles)
1979 {
1980 wxNode* node = m_fileMenus.GetFirst();
1981 while (node)
1982 {
1983 wxMenu* menu = (wxMenu*) node->GetData();
1984 if ( m_fileHistoryN == 0 && menu->GetMenuItemCount() )
1985 {
1986 menu->AppendSeparator();
1987 }
1988 menu->Append(m_idBase+m_fileHistoryN, _("[EMPTY]"));
1989 node = node->GetNext();
1990 }
1991 m_fileHistoryN ++;
1992 }
1993 // Shuffle filenames down
1994 for (i = (m_fileHistoryN-1); i > 0; i--)
1995 {
1996 m_fileHistory[i] = m_fileHistory[i-1];
1997 }
1998 m_fileHistory[0] = copystring(file);
1999
2000 // this is the directory of the last opened file
2001 wxString pathCurrent;
2002 wxSplitPath( m_fileHistory[0], &pathCurrent, NULL, NULL );
2003 for (i = 0; i < m_fileHistoryN; i++)
2004 {
2005 if ( m_fileHistory[i] )
2006 {
2007 // if in same directory just show the filename; otherwise the full
2008 // path
2009 wxString pathInMenu, path, filename, ext;
2010 wxSplitPath( m_fileHistory[i], &path, &filename, &ext );
2011 if ( path == pathCurrent )
2012 {
2013 pathInMenu = filename;
2014 if ( !ext.empty() )
2015 pathInMenu = pathInMenu + wxFILE_SEP_EXT + ext;
2016 }
2017 else
2018 {
2019 // absolute path; could also set relative path
2020 pathInMenu = m_fileHistory[i];
2021 }
2022
2023 wxString buf;
2024 buf.Printf(s_MRUEntryFormat, i + 1, pathInMenu.c_str());
2025 wxNode* node = m_fileMenus.GetFirst();
2026 while (node)
2027 {
2028 wxMenu* menu = (wxMenu*) node->GetData();
2029 menu->SetLabel(m_idBase + i, buf);
2030 node = node->GetNext();
2031 }
2032 }
2033 }
2034 }
2035
2036 void wxFileHistory::RemoveFileFromHistory(size_t i)
2037 {
2038 wxCHECK_RET( i < m_fileHistoryN,
2039 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2040
2041 // delete the element from the array (could use memmove() too...)
2042 delete [] m_fileHistory[i];
2043
2044 size_t j;
2045 for ( j = i; j < m_fileHistoryN - 1; j++ )
2046 {
2047 m_fileHistory[j] = m_fileHistory[j + 1];
2048 }
2049
2050 wxNode* node = m_fileMenus.GetFirst();
2051 while ( node )
2052 {
2053 wxMenu* menu = (wxMenu*) node->GetData();
2054
2055
2056 // shuffle filenames up
2057 wxString buf;
2058 for ( j = i; j < m_fileHistoryN - 1; j++ )
2059 {
2060 buf.Printf(s_MRUEntryFormat, j + 1, m_fileHistory[j]);
2061 menu->SetLabel(m_idBase + j, buf);
2062 }
2063
2064 node = node->GetNext();
2065
2066 // delete the last menu item which is unused now
2067 wxWindowID lastItemId = m_idBase + m_fileHistoryN - 1;
2068 if (menu->FindItem(lastItemId))
2069 {
2070 menu->Delete(lastItemId);
2071 }
2072
2073 // delete the last separator too if no more files are left
2074 if ( m_fileHistoryN == 1 )
2075 {
2076 wxMenuItemList::Node *node = menu->GetMenuItems().GetLast();
2077 if ( node )
2078 {
2079 wxMenuItem *menuItem = node->GetData();
2080 if ( menuItem->IsSeparator() )
2081 {
2082 menu->Delete(menuItem);
2083 }
2084 //else: should we search backwards for the last separator?
2085 }
2086 //else: menu is empty somehow
2087 }
2088 }
2089
2090 m_fileHistoryN--;
2091 }
2092
2093 wxString wxFileHistory::GetHistoryFile(size_t i) const
2094 {
2095 wxString s;
2096 if ( i < m_fileHistoryN )
2097 {
2098 s = m_fileHistory[i];
2099 }
2100 else
2101 {
2102 wxFAIL_MSG( wxT("bad index in wxFileHistory::GetHistoryFile") );
2103 }
2104
2105 return s;
2106 }
2107
2108 void wxFileHistory::UseMenu(wxMenu *menu)
2109 {
2110 if (!m_fileMenus.Member(menu))
2111 m_fileMenus.Append(menu);
2112 }
2113
2114 void wxFileHistory::RemoveMenu(wxMenu *menu)
2115 {
2116 m_fileMenus.DeleteObject(menu);
2117 }
2118
2119 #if wxUSE_CONFIG
2120 void wxFileHistory::Load(wxConfigBase& config)
2121 {
2122 m_fileHistoryN = 0;
2123 wxString buf;
2124 buf.Printf(wxT("file%d"), (int)m_fileHistoryN+1);
2125 wxString historyFile;
2126 while ((m_fileHistoryN < m_fileMaxFiles) && config.Read(buf, &historyFile) && (historyFile != wxT("")))
2127 {
2128 m_fileHistory[m_fileHistoryN] = copystring((const wxChar*) historyFile);
2129 m_fileHistoryN ++;
2130 buf.Printf(wxT("file%d"), (int)m_fileHistoryN+1);
2131 historyFile = wxT("");
2132 }
2133 AddFilesToMenu();
2134 }
2135
2136 void wxFileHistory::Save(wxConfigBase& config)
2137 {
2138 size_t i;
2139 for (i = 0; i < m_fileHistoryN; i++)
2140 {
2141 wxString buf;
2142 buf.Printf(wxT("file%d"), (int)i+1);
2143 config.Write(buf, wxString(m_fileHistory[i]));
2144 }
2145 }
2146 #endif // wxUSE_CONFIG
2147
2148 void wxFileHistory::AddFilesToMenu()
2149 {
2150 if (m_fileHistoryN > 0)
2151 {
2152 wxNode* node = m_fileMenus.GetFirst();
2153 while (node)
2154 {
2155 wxMenu* menu = (wxMenu*) node->GetData();
2156 if (menu->GetMenuItemCount())
2157 {
2158 menu->AppendSeparator();
2159 }
2160
2161 size_t i;
2162 for (i = 0; i < m_fileHistoryN; i++)
2163 {
2164 if (m_fileHistory[i])
2165 {
2166 wxString buf;
2167 buf.Printf(s_MRUEntryFormat, i+1, m_fileHistory[i]);
2168 menu->Append(m_idBase+i, buf);
2169 }
2170 }
2171 node = node->GetNext();
2172 }
2173 }
2174 }
2175
2176 void wxFileHistory::AddFilesToMenu(wxMenu* menu)
2177 {
2178 if (m_fileHistoryN > 0)
2179 {
2180 if (menu->GetMenuItemCount())
2181 {
2182 menu->AppendSeparator();
2183 }
2184
2185 size_t i;
2186 for (i = 0; i < m_fileHistoryN; i++)
2187 {
2188 if (m_fileHistory[i])
2189 {
2190 wxString buf;
2191 buf.Printf(s_MRUEntryFormat, i+1, m_fileHistory[i]);
2192 menu->Append(m_idBase+i, buf);
2193 }
2194 }
2195 }
2196 }
2197
2198 // ----------------------------------------------------------------------------
2199 // Permits compatibility with existing file formats and functions that
2200 // manipulate files directly
2201 // ----------------------------------------------------------------------------
2202
2203 #if wxUSE_STD_IOSTREAM
2204
2205 bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream)
2206 {
2207 wxFFile file(filename, _T("rb"));
2208 if ( !file.IsOpened() )
2209 return FALSE;
2210
2211 char buf[4096];
2212
2213 size_t nRead;
2214 do
2215 {
2216 nRead = file.Read(buf, WXSIZEOF(buf));
2217 if ( file.Error() )
2218 return FALSE;
2219
2220 stream.write(buf, nRead);
2221 if ( !stream )
2222 return FALSE;
2223 }
2224 while ( !file.Eof() );
2225
2226 return TRUE;
2227 }
2228
2229 bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename)
2230 {
2231 wxFFile file(filename, _T("wb"));
2232 if ( !file.IsOpened() )
2233 return FALSE;
2234
2235 char buf[4096];
2236 do
2237 {
2238 stream.read(buf, WXSIZEOF(buf));
2239 if ( !stream.bad() ) // fail may be set on EOF, don't use operator!()
2240 {
2241 if ( !file.Write(buf, stream.gcount()) )
2242 return FALSE;
2243 }
2244 }
2245 while ( !stream.eof() );
2246
2247 return TRUE;
2248 }
2249
2250 #else // !wxUSE_STD_IOSTREAM
2251
2252 bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream)
2253 {
2254 wxFFile file(filename, _T("rb"));
2255 if ( !file.IsOpened() )
2256 return FALSE;
2257
2258 char buf[4096];
2259
2260 size_t nRead;
2261 do
2262 {
2263 nRead = file.Read(buf, WXSIZEOF(buf));
2264 if ( file.Error() )
2265 return FALSE;
2266
2267 stream.Write(buf, nRead);
2268 if ( !stream )
2269 return FALSE;
2270 }
2271 while ( !file.Eof() );
2272
2273 return TRUE;
2274 }
2275
2276 bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename)
2277 {
2278 wxFFile file(filename, _T("wb"));
2279 if ( !file.IsOpened() )
2280 return FALSE;
2281
2282 char buf[4096];
2283 do
2284 {
2285 stream.Read(buf, WXSIZEOF(buf));
2286
2287 const size_t nRead = stream.LastRead();
2288 if ( !nRead || !file.Write(buf, nRead) )
2289 return FALSE;
2290 }
2291 while ( !stream.Eof() );
2292
2293 return TRUE;
2294 }
2295
2296 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2297
2298 #endif // wxUSE_DOC_VIEW_ARCHITECTURE
2299