1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/docview.cpp
3 // Purpose: Document/view classes
4 // Author: Julian Smart
7 // RCS-ID: $Id: docview.cpp 51392 2008-01-26 23:23:09Z VZ $
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_DOC_VIEW_ARCHITECTURE
29 #include "wx/docview.h"
33 #include "wx/string.h"
37 #include "wx/dialog.h"
39 #include "wx/filedlg.h"
42 #include "wx/msgdlg.h"
44 #include "wx/choicdlg.h"
50 #include "wx/filename.h"
53 #if wxUSE_PRINTING_ARCHITECTURE
54 #include "wx/prntbase.h"
55 #include "wx/printdlg.h"
58 #include "wx/confbase.h"
60 #include "wx/cmdproc.h"
61 #include "wx/tokenzr.h"
66 #if wxUSE_STD_IOSTREAM
67 #include "wx/ioswrap.h"
74 #include "wx/wfstream.h"
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 IMPLEMENT_ABSTRACT_CLASS(wxDocument, wxEvtHandler)
82 IMPLEMENT_ABSTRACT_CLASS(wxView, wxEvtHandler)
83 IMPLEMENT_ABSTRACT_CLASS(wxDocTemplate, wxObject)
84 IMPLEMENT_DYNAMIC_CLASS(wxDocManager, wxEvtHandler)
85 IMPLEMENT_CLASS(wxDocChildFrame, wxFrame)
86 IMPLEMENT_CLASS(wxDocParentFrame, wxFrame)
88 #if wxUSE_PRINTING_ARCHITECTURE
89 IMPLEMENT_DYNAMIC_CLASS(wxDocPrintout, wxPrintout)
92 IMPLEMENT_DYNAMIC_CLASS(wxFileHistory, wxObject)
94 // ----------------------------------------------------------------------------
95 // function prototypes
96 // ----------------------------------------------------------------------------
98 static wxWindow* wxFindSuitableParent(void);
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 static const wxChar *s_MRUEntryFormat = wxT("&%d %s");
106 // ============================================================================
108 // ============================================================================
110 // ----------------------------------------------------------------------------
112 // ----------------------------------------------------------------------------
114 static wxString FindExtension(const wxChar *path)
117 wxSplitPath(path, NULL, NULL, &ext);
119 // VZ: extensions are considered not case sensitive - is this really a good
121 return ext.MakeLower();
124 // ----------------------------------------------------------------------------
125 // Definition of wxDocument
126 // ----------------------------------------------------------------------------
128 wxDocument::wxDocument(wxDocument *parent)
130 m_documentModified = false;
131 m_documentParent = parent;
132 m_documentTemplate = (wxDocTemplate *) NULL;
133 m_commandProcessor = (wxCommandProcessor*) NULL;
137 bool wxDocument::DeleteContents()
142 wxDocument::~wxDocument()
146 if (m_commandProcessor)
147 delete m_commandProcessor;
149 if (GetDocumentManager())
150 GetDocumentManager()->RemoveDocument(this);
152 // Not safe to do here, since it'll invoke virtual view functions
153 // expecting to see valid derived objects: and by the time we get here,
154 // we've called destructors higher up.
158 bool wxDocument::Close()
160 if (OnSaveModified())
161 return OnCloseDocument();
166 bool wxDocument::OnCloseDocument()
168 // Tell all views that we're about to close
175 // Note that this implicitly deletes the document when the last view is
177 bool wxDocument::DeleteAllViews()
179 wxDocManager* manager = GetDocumentManager();
181 // first check if all views agree to be closed
182 const wxList::iterator end = m_documentViews.end();
183 for ( wxList::iterator i = m_documentViews.begin(); i != end; ++i )
185 wxView *view = (wxView *)*i;
186 if ( !view->Close() )
190 // all views agreed to close, now do close them
191 if ( m_documentViews.empty() )
193 // normally the document would be implicitly deleted when the last view
194 // is, but if don't have any views, do it here instead
195 if ( manager && manager->GetDocuments().Member(this) )
200 // as we delete elements we iterate over, don't use the usual "from
201 // begin to end" loop
204 wxView *view = (wxView *)*m_documentViews.begin();
206 bool isLastOne = m_documentViews.size() == 1;
208 // this always deletes the node implicitly and if this is the last
209 // view also deletes this object itself (also implicitly, great),
210 // so we can't test for m_documentViews.empty() after calling this!
221 wxView *wxDocument::GetFirstView() const
223 if (m_documentViews.GetCount() == 0)
224 return (wxView *) NULL;
225 return (wxView *)m_documentViews.GetFirst()->GetData();
228 wxDocManager *wxDocument::GetDocumentManager() const
230 return (m_documentTemplate ? m_documentTemplate->GetDocumentManager() : (wxDocManager*) NULL);
233 bool wxDocument::OnNewDocument()
235 if (!OnSaveModified())
238 if (OnCloseDocument()==false) return false;
241 SetDocumentSaved(false);
244 GetDocumentManager()->MakeDefaultName(name);
246 SetFilename(name, true);
251 bool wxDocument::Save()
253 if (!IsModified() && m_savedYet)
256 if ( m_documentFile.empty() || !m_savedYet )
259 return OnSaveDocument(m_documentFile);
262 bool wxDocument::SaveAs()
264 wxDocTemplate *docTemplate = GetDocumentTemplate();
268 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
269 wxString filter = docTemplate->GetDescription() + wxT(" (") + docTemplate->GetFileFilter() + wxT(")|") + docTemplate->GetFileFilter();
271 // Now see if there are some other template with identical view and document
272 // classes, whose filters may also be used.
274 if (docTemplate->GetViewClassInfo() && docTemplate->GetDocClassInfo())
276 wxList::compatibility_iterator node = docTemplate->GetDocumentManager()->GetTemplates().GetFirst();
279 wxDocTemplate *t = (wxDocTemplate*) node->GetData();
281 if (t->IsVisible() && t != docTemplate &&
282 t->GetViewClassInfo() == docTemplate->GetViewClassInfo() &&
283 t->GetDocClassInfo() == docTemplate->GetDocClassInfo())
285 // add a '|' to separate this filter from the previous one
286 if ( !filter.empty() )
289 filter << t->GetDescription() << wxT(" (") << t->GetFileFilter() << wxT(") |")
290 << t->GetFileFilter();
293 node = node->GetNext();
297 wxString filter = docTemplate->GetFileFilter() ;
299 wxString defaultDir = docTemplate->GetDirectory();
300 if (defaultDir.IsEmpty())
301 defaultDir = wxPathOnly(GetFilename());
303 wxString tmp = wxFileSelector(_("Save as"),
305 wxFileNameFromPath(GetFilename()),
306 docTemplate->GetDefaultExtension(),
308 wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
309 GetDocumentWindow());
314 wxString fileName(tmp);
315 wxString path, name, ext;
316 wxSplitPath(fileName, & path, & name, & ext);
320 fileName += wxT(".");
321 fileName += docTemplate->GetDefaultExtension();
324 // Modified by TN 2010.5.15. Moved from below
325 // Files that were not saved correctly are not added to the FileHistory.
326 if (!OnSaveDocument(fileName))
329 SetFilename(fileName);
330 SetTitle(wxFileNameFromPath(fileName));
332 // Notify the views that the filename has changed
333 wxList::compatibility_iterator node = m_documentViews.GetFirst();
336 wxView *view = (wxView *)node->GetData();
337 view->OnChangeFilename();
338 node = node->GetNext();
341 // Modified by TN 2010.5.15. Moved before SetFilename() call
342 // Files that were not saved correctly are not added to the FileHistory.
343 // if (!OnSaveDocument(m_documentFile))
346 // A file that doesn't use the default extension of its document template cannot be opened
347 // via the FileHistory, so we do not add it.
348 if (docTemplate->FileMatchesTemplate(fileName))
350 GetDocumentManager()->AddFileToHistory(fileName);
354 // The user will probably not be able to open the file again, so
355 // we could warn about the wrong file-extension here.
360 bool wxDocument::OnSaveDocument(const wxString& file)
365 if ( !DoSaveDocument(file) )
370 SetDocumentSaved(true);
372 wxFileName fn(file) ;
373 fn.MacSetDefaultTypeAndCreator() ;
378 bool wxDocument::OnOpenDocument(const wxString& file)
380 if (!OnSaveModified())
383 if ( !DoOpenDocument(file) )
386 SetFilename(file, true);
395 #if wxUSE_STD_IOSTREAM
396 wxSTD istream& wxDocument::LoadObject(wxSTD istream& stream)
398 wxInputStream& wxDocument::LoadObject(wxInputStream& stream)
404 #if wxUSE_STD_IOSTREAM
405 wxSTD ostream& wxDocument::SaveObject(wxSTD ostream& stream)
407 wxOutputStream& wxDocument::SaveObject(wxOutputStream& stream)
413 /* Taken from wxWidgets 2.9.3 and changed GetAppDisplayName() to GetAppName() */
414 bool wxDocument::Revert()
418 _("Discard changes and reload the last saved version?"),
419 wxTheApp->GetAppName(),
420 wxYES_NO | wxCANCEL | wxICON_QUESTION,
425 if ( !DoOpenDocument(GetFilename()) )
434 // Get title, or filename if no title, else unnamed
435 bool wxDocument::GetPrintableName(wxString& buf) const
437 if (!m_documentTitle.empty())
439 buf = m_documentTitle;
442 else if (!m_documentFile.empty())
444 buf = wxFileNameFromPath(m_documentFile);
454 wxWindow *wxDocument::GetDocumentWindow() const
456 wxView *view = GetFirstView();
458 return view->GetFrame();
460 return wxTheApp->GetTopWindow();
463 wxCommandProcessor *wxDocument::OnCreateCommandProcessor()
465 return new wxCommandProcessor;
468 // true if safe to close
469 bool wxDocument::OnSaveModified()
474 GetPrintableName(title);
477 if (!wxTheApp->GetAppName().empty())
478 msgTitle = wxTheApp->GetAppName();
480 msgTitle = wxString(_("Warning"));
483 prompt.Printf(_("Do you want to save changes to document %s?"),
484 (const wxChar *)title);
485 int res = wxMessageBox(prompt, msgTitle,
486 wxYES_NO|wxCANCEL|wxICON_QUESTION,
487 GetDocumentWindow());
493 else if (res == wxYES)
495 else if (res == wxCANCEL)
501 bool wxDocument::Draw(wxDC& WXUNUSED(context))
506 bool wxDocument::AddView(wxView *view)
508 if (!m_documentViews.Member(view))
510 m_documentViews.Append(view);
516 bool wxDocument::RemoveView(wxView *view)
518 (void)m_documentViews.DeleteObject(view);
523 bool wxDocument::OnCreate(const wxString& WXUNUSED(path), long flags)
525 if (GetDocumentTemplate()->CreateView(this, flags))
531 // Called after a view is added or removed.
532 // The default implementation deletes the document if
533 // there are no more views.
534 void wxDocument::OnChangedViewList()
536 if (m_documentViews.GetCount() == 0)
538 if (OnSaveModified())
545 void wxDocument::UpdateAllViews(wxView *sender, wxObject *hint)
547 wxList::compatibility_iterator node = m_documentViews.GetFirst();
550 wxView *view = (wxView *)node->GetData();
552 view->OnUpdate(sender, hint);
553 node = node->GetNext();
557 void wxDocument::NotifyClosing()
559 wxList::compatibility_iterator node = m_documentViews.GetFirst();
562 wxView *view = (wxView *)node->GetData();
563 view->OnClosingDocument();
564 node = node->GetNext();
568 void wxDocument::SetFilename(const wxString& filename, bool notifyViews)
570 m_documentFile = filename;
573 // Notify the views that the filename has changed
574 wxList::compatibility_iterator node = m_documentViews.GetFirst();
577 wxView *view = (wxView *)node->GetData();
578 view->OnChangeFilename();
579 node = node->GetNext();
584 bool wxDocument::DoSaveDocument(const wxString& file)
587 if (!wxTheApp->GetAppName().empty())
588 msgTitle = wxTheApp->GetAppName();
590 msgTitle = wxString(_("File error"));
592 #if wxUSE_STD_IOSTREAM
593 wxSTD ofstream store(file.mb_str(), wxSTD ios::binary);
594 if (store.fail() || store.bad())
596 wxFileOutputStream store(file);
597 if (store.GetLastError() != wxSTREAM_NO_ERROR)
600 (void)wxMessageBox(_("Sorry, could not open this file for saving."), msgTitle, wxOK | wxICON_EXCLAMATION,
601 GetDocumentWindow());
605 if (!SaveObject(store))
607 (void)wxMessageBox(_("Sorry, could not save this file."), msgTitle, wxOK | wxICON_EXCLAMATION,
608 GetDocumentWindow());
616 bool wxDocument::DoOpenDocument(const wxString& file)
618 #if wxUSE_STD_IOSTREAM
619 wxSTD ifstream store(file.mb_str(), wxSTD ios::binary);
620 if (!store.fail() && !store.bad())
622 wxFileInputStream store(file);
623 if (store.GetLastError() == wxSTREAM_NO_ERROR)
626 #if wxUSE_STD_IOSTREAM
628 if ( !!store || store.eof() )
630 int res = LoadObject(store).GetLastError();
631 if ( res == wxSTREAM_NO_ERROR || res == wxSTREAM_EOF )
636 wxLogError(_("Sorry, could not open this file."));
641 // ----------------------------------------------------------------------------
643 // ----------------------------------------------------------------------------
647 m_viewDocument = (wxDocument*) NULL;
649 m_viewFrame = (wxFrame *) NULL;
654 GetDocumentManager()->ActivateView(this, false);
655 m_viewDocument->RemoveView(this);
658 // Extend event processing to search the document's event table
659 bool wxView::ProcessEvent(wxEvent& event)
661 if ( !GetDocument() || !GetDocument()->ProcessEvent(event) )
662 return wxEvtHandler::ProcessEvent(event);
667 void wxView::OnActivateView(bool WXUNUSED(activate), wxView *WXUNUSED(activeView), wxView *WXUNUSED(deactiveView))
671 void wxView::OnPrint(wxDC *dc, wxObject *WXUNUSED(info))
676 void wxView::OnUpdate(wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint))
680 void wxView::OnChangeFilename()
682 // GetFrame can return wxWindow rather than wxTopLevelWindow due to
683 // generic MDI implementation so use SetLabel rather than SetTitle.
684 // It should cause SetTitle() for top level windows.
685 wxWindow *win = GetFrame();
688 wxDocument *doc = GetDocument();
692 doc->GetPrintableName(name);
696 void wxView::SetDocument(wxDocument *doc)
698 m_viewDocument = doc;
703 bool wxView::Close(bool deleteWindow)
705 if (OnClose(deleteWindow))
711 void wxView::Activate(bool activate)
713 if (GetDocument() && GetDocumentManager())
715 OnActivateView(activate, this, GetDocumentManager()->GetCurrentView());
716 GetDocumentManager()->ActivateView(this, activate);
720 bool wxView::OnClose(bool WXUNUSED(deleteWindow))
722 return GetDocument() ? GetDocument()->Close() : true;
725 #if wxUSE_PRINTING_ARCHITECTURE
726 wxPrintout *wxView::OnCreatePrintout()
728 return new wxDocPrintout(this);
730 #endif // wxUSE_PRINTING_ARCHITECTURE
732 // ----------------------------------------------------------------------------
734 // ----------------------------------------------------------------------------
736 wxDocTemplate::wxDocTemplate(wxDocManager *manager,
737 const wxString& descr,
738 const wxString& filter,
741 const wxString& docTypeName,
742 const wxString& viewTypeName,
743 wxClassInfo *docClassInfo,
744 wxClassInfo *viewClassInfo,
747 m_documentManager = manager;
748 m_description = descr;
751 m_fileFilter = filter;
753 m_docTypeName = docTypeName;
754 m_viewTypeName = viewTypeName;
755 m_documentManager->AssociateTemplate(this);
757 m_docClassInfo = docClassInfo;
758 m_viewClassInfo = viewClassInfo;
761 wxDocTemplate::~wxDocTemplate()
763 m_documentManager->DisassociateTemplate(this);
766 // Tries to dynamically construct an object of the right class.
767 wxDocument *wxDocTemplate::CreateDocument(const wxString& path, long flags)
769 wxDocument *doc = DoCreateDocument();
771 return (wxDocument *) NULL;
773 if (InitDocument(doc, path, flags))
779 return (wxDocument *) NULL;
783 bool wxDocTemplate::InitDocument(wxDocument* doc, const wxString& path, long flags)
785 doc->SetFilename(path);
786 doc->SetDocumentTemplate(this);
787 GetDocumentManager()->AddDocument(doc);
788 doc->SetCommandProcessor(doc->OnCreateCommandProcessor());
790 if (doc->OnCreate(path, flags))
794 if (GetDocumentManager()->GetDocuments().Member(doc))
795 doc->DeleteAllViews();
800 wxView *wxDocTemplate::CreateView(wxDocument *doc, long flags)
802 wxView *view = DoCreateView();
804 return (wxView *) NULL;
806 view->SetDocument(doc);
807 if (view->OnCreate(doc, flags))
814 return (wxView *) NULL;
818 // The default (very primitive) format detection: check is the extension is
819 // that of the template
820 bool wxDocTemplate::FileMatchesTemplate(const wxString& path)
822 wxStringTokenizer parser (GetFileFilter(), wxT(";"));
823 wxString anything = wxT ("*");
824 while (parser.HasMoreTokens())
826 wxString filter = parser.GetNextToken();
827 wxString filterExt = FindExtension (filter);
828 if ( filter.IsSameAs (anything) ||
829 filterExt.IsSameAs (anything) ||
830 filterExt.IsSameAs (FindExtension (path)) )
833 return GetDefaultExtension().IsSameAs(FindExtension(path));
836 wxDocument *wxDocTemplate::DoCreateDocument()
839 return (wxDocument *) NULL;
841 return (wxDocument *)m_docClassInfo->CreateObject();
844 wxView *wxDocTemplate::DoCreateView()
846 if (!m_viewClassInfo)
847 return (wxView *) NULL;
849 return (wxView *)m_viewClassInfo->CreateObject();
852 // ----------------------------------------------------------------------------
854 // ----------------------------------------------------------------------------
856 BEGIN_EVENT_TABLE(wxDocManager, wxEvtHandler)
857 EVT_MENU(wxID_OPEN, wxDocManager::OnFileOpen)
858 EVT_MENU(wxID_CLOSE, wxDocManager::OnFileClose)
859 EVT_MENU(wxID_CLOSE_ALL, wxDocManager::OnFileCloseAll)
860 EVT_MENU(wxID_REVERT, wxDocManager::OnFileRevert)
861 EVT_MENU(wxID_NEW, wxDocManager::OnFileNew)
862 EVT_MENU(wxID_SAVE, wxDocManager::OnFileSave)
863 EVT_MENU(wxID_SAVEAS, wxDocManager::OnFileSaveAs)
864 EVT_MENU(wxID_UNDO, wxDocManager::OnUndo)
865 EVT_MENU(wxID_REDO, wxDocManager::OnRedo)
867 EVT_UPDATE_UI(wxID_OPEN, wxDocManager::OnUpdateFileOpen)
868 EVT_UPDATE_UI(wxID_CLOSE, wxDocManager::OnUpdateFileClose)
869 EVT_UPDATE_UI(wxID_CLOSE_ALL, wxDocManager::OnUpdateFileClose)
870 EVT_UPDATE_UI(wxID_REVERT, wxDocManager::OnUpdateFileRevert)
871 EVT_UPDATE_UI(wxID_NEW, wxDocManager::OnUpdateFileNew)
872 EVT_UPDATE_UI(wxID_SAVE, wxDocManager::OnUpdateFileSave)
873 EVT_UPDATE_UI(wxID_SAVEAS, wxDocManager::OnUpdateFileSaveAs)
874 EVT_UPDATE_UI(wxID_UNDO, wxDocManager::OnUpdateUndo)
875 EVT_UPDATE_UI(wxID_REDO, wxDocManager::OnUpdateRedo)
877 #if wxUSE_PRINTING_ARCHITECTURE
878 EVT_MENU(wxID_PRINT, wxDocManager::OnPrint)
879 EVT_MENU(wxID_PREVIEW, wxDocManager::OnPreview)
881 EVT_UPDATE_UI(wxID_PRINT, wxDocManager::OnUpdatePrint)
882 EVT_UPDATE_UI(wxID_PREVIEW, wxDocManager::OnUpdatePreview)
886 wxDocManager* wxDocManager::sm_docManager = (wxDocManager*) NULL;
888 wxDocManager::wxDocManager(long flags, bool initialize)
890 m_defaultDocumentNameCounter = 1;
892 m_currentView = (wxView *) NULL;
893 m_maxDocsOpen = 10000;
894 m_fileHistory = (wxFileHistory *) NULL;
897 sm_docManager = this;
900 wxDocManager::~wxDocManager()
904 delete m_fileHistory;
905 sm_docManager = (wxDocManager*) NULL;
908 // closes the specified document
909 bool wxDocManager::CloseDocument(wxDocument* doc, bool force)
911 if (doc->Close() || force)
913 // Implicitly deletes the document when
914 // the last view is deleted
915 doc->DeleteAllViews();
917 // Check we're really deleted
918 if (m_docs.Member(doc))
926 bool wxDocManager::CloseDocuments(bool force)
928 wxList::compatibility_iterator node = m_docs.GetFirst();
931 wxDocument *doc = (wxDocument *)node->GetData();
932 wxList::compatibility_iterator next = node->GetNext();
934 if (!CloseDocument(doc, force))
937 // This assumes that documents are not connected in
938 // any way, i.e. deleting one document does NOT
945 bool wxDocManager::Clear(bool force)
947 if (!CloseDocuments(force))
950 m_currentView = NULL;
952 wxList::compatibility_iterator node = m_templates.GetFirst();
955 wxDocTemplate *templ = (wxDocTemplate*) node->GetData();
956 wxList::compatibility_iterator next = node->GetNext();
963 bool wxDocManager::Initialize()
965 m_fileHistory = OnCreateFileHistory();
969 wxFileHistory *wxDocManager::OnCreateFileHistory()
971 return new wxFileHistory;
974 void wxDocManager::OnFileClose(wxCommandEvent& WXUNUSED(event))
976 wxDocument *doc = GetCurrentDocument();
981 doc->DeleteAllViews();
982 if (m_docs.Member(doc))
987 void wxDocManager::OnFileCloseAll(wxCommandEvent& WXUNUSED(event))
989 CloseDocuments(false);
992 void wxDocManager::OnFileNew(wxCommandEvent& WXUNUSED(event))
994 CreateDocument( wxEmptyString, wxDOC_NEW );
997 void wxDocManager::OnFileOpen(wxCommandEvent& WXUNUSED(event))
999 if ( !CreateDocument( wxEmptyString, 0) )
1001 OnOpenFileFailure();
1005 void wxDocManager::OnFileRevert(wxCommandEvent& WXUNUSED(event))
1007 wxDocument *doc = GetCurrentDocument();
1013 void wxDocManager::OnFileSave(wxCommandEvent& WXUNUSED(event))
1015 wxDocument *doc = GetCurrentDocument();
1021 void wxDocManager::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))
1023 wxDocument *doc = GetCurrentDocument();
1029 void wxDocManager::OnPrint(wxCommandEvent& WXUNUSED(event))
1031 #if wxUSE_PRINTING_ARCHITECTURE
1032 wxView *view = GetCurrentView();
1036 wxPrintout *printout = view->OnCreatePrintout();
1040 printer.Print(view->GetFrame(), printout, true);
1044 #endif // wxUSE_PRINTING_ARCHITECTURE
1047 void wxDocManager::OnPreview(wxCommandEvent& WXUNUSED(event))
1049 #if wxUSE_PRINTING_ARCHITECTURE
1050 wxView *view = GetCurrentView();
1054 wxPrintout *printout = view->OnCreatePrintout();
1057 // Pass two printout objects: for preview, and possible printing.
1058 wxPrintPreviewBase *preview = new wxPrintPreview(printout, view->OnCreatePrintout());
1059 if ( !preview->Ok() )
1062 wxMessageBox( _("Sorry, print preview needs a printer to be installed.") );
1066 wxPreviewFrame *frame = new wxPreviewFrame(preview, (wxFrame *)wxTheApp->GetTopWindow(), _("Print Preview"),
1067 wxPoint(100, 100), wxSize(600, 650));
1068 frame->Centre(wxBOTH);
1069 frame->Initialize();
1072 #endif // wxUSE_PRINTING_ARCHITECTURE
1075 void wxDocManager::OnUndo(wxCommandEvent& event)
1077 wxDocument *doc = GetCurrentDocument();
1080 if (doc->GetCommandProcessor())
1081 doc->GetCommandProcessor()->Undo();
1086 void wxDocManager::OnRedo(wxCommandEvent& event)
1088 wxDocument *doc = GetCurrentDocument();
1091 if (doc->GetCommandProcessor())
1092 doc->GetCommandProcessor()->Redo();
1097 // Handlers for UI update commands
1099 void wxDocManager::OnUpdateFileOpen(wxUpdateUIEvent& event)
1101 event.Enable( true );
1104 void wxDocManager::OnUpdateFileClose(wxUpdateUIEvent& event)
1106 wxDocument *doc = GetCurrentDocument();
1107 event.Enable( (doc != (wxDocument*) NULL) );
1110 /* Taken from wxWidgets 2.9.3 */
1111 void wxDocManager::OnUpdateFileRevert(wxUpdateUIEvent& event)
1113 wxDocument *doc = GetCurrentDocument();
1114 event.Enable( (doc != (wxDocument*) NULL) && doc->IsModified() && doc->GetDocumentSaved() );
1117 void wxDocManager::OnUpdateFileNew(wxUpdateUIEvent& event)
1119 event.Enable( true );
1122 void wxDocManager::OnUpdateFileSave(wxUpdateUIEvent& event)
1124 wxDocument *doc = GetCurrentDocument();
1125 event.Enable( doc && doc->IsModified() );
1128 void wxDocManager::OnUpdateFileSaveAs(wxUpdateUIEvent& event)
1130 wxDocument *doc = GetCurrentDocument();
1131 event.Enable( (doc != (wxDocument*) NULL) );
1134 void wxDocManager::OnUpdateUndo(wxUpdateUIEvent& event)
1136 wxDocument *doc = GetCurrentDocument();
1138 event.Enable(false);
1139 else if (!doc->GetCommandProcessor())
1143 event.Enable( doc->GetCommandProcessor()->CanUndo() );
1144 doc->GetCommandProcessor()->SetMenuStrings();
1148 void wxDocManager::OnUpdateRedo(wxUpdateUIEvent& event)
1150 wxDocument *doc = GetCurrentDocument();
1152 event.Enable(false);
1153 else if (!doc->GetCommandProcessor())
1157 event.Enable( doc->GetCommandProcessor()->CanRedo() );
1158 doc->GetCommandProcessor()->SetMenuStrings();
1162 void wxDocManager::OnUpdatePrint(wxUpdateUIEvent& event)
1164 wxDocument *doc = GetCurrentDocument();
1165 event.Enable( (doc != (wxDocument*) NULL) );
1168 void wxDocManager::OnUpdatePreview(wxUpdateUIEvent& event)
1170 wxDocument *doc = GetCurrentDocument();
1171 event.Enable( (doc != (wxDocument*) NULL) );
1174 wxView *wxDocManager::GetCurrentView() const
1177 return m_currentView;
1178 if (m_docs.GetCount() == 1)
1180 wxDocument* doc = (wxDocument*) m_docs.GetFirst()->GetData();
1181 return doc->GetFirstView();
1183 return (wxView *) NULL;
1186 // Extend event processing to search the view's event table
1187 bool wxDocManager::ProcessEvent(wxEvent& event)
1189 wxView* view = GetCurrentView();
1192 if (view->ProcessEvent(event))
1195 return wxEvtHandler::ProcessEvent(event);
1198 wxDocument *wxDocManager::CreateDocument(const wxString& path, long flags)
1200 wxDocTemplate **templates = new wxDocTemplate *[m_templates.GetCount()];
1203 for (size_t i = 0; i < m_templates.GetCount(); i++)
1205 wxDocTemplate *temp = (wxDocTemplate *)(m_templates.Item(i)->GetData());
1206 if (temp->IsVisible())
1208 templates[n] = temp;
1215 return (wxDocument *) NULL;
1218 wxDocument* docToClose = NULL;
1220 // If we've reached the max number of docs, close the
1222 if ( (int)GetDocuments().GetCount() >= m_maxDocsOpen )
1224 wxDocument *doc = (wxDocument *)GetDocuments().GetFirst()->GetData();
1228 // New document: user chooses a template, unless there's only one.
1229 if (flags & wxDOC_NEW)
1235 if (!CloseDocument(docToClose, false))
1242 wxDocTemplate *temp = templates[0];
1244 wxDocument *newDoc = temp->CreateDocument(path, flags);
1248 newDoc->SetDocumentName(temp->GetDocumentName());
1249 newDoc->SetDocumentTemplate(temp);
1250 if (!newDoc->OnNewDocument() )
1252 // Document is implicitly deleted by DeleteAllViews
1253 newDoc->DeleteAllViews();
1260 wxDocTemplate *temp = SelectDocumentType(templates, n);
1266 if (!CloseDocument(docToClose, false))
1272 wxDocument *newDoc = temp->CreateDocument(path, flags);
1276 newDoc->SetDocumentName(temp->GetDocumentName());
1277 newDoc->SetDocumentTemplate(temp);
1278 if (!newDoc->OnNewDocument() )
1280 // Document is implicitly deleted by DeleteAllViews
1281 newDoc->DeleteAllViews();
1288 return (wxDocument *) NULL;
1291 // Existing document
1292 wxDocTemplate *temp;
1294 wxString path2 = path;
1296 if (flags & wxDOC_SILENT)
1298 temp = FindTemplateForPath(path2);
1301 // Since we do not add files with non-default extensions to the FileHistory this
1302 // can only happen if the application changes the allowed templates in runtime.
1303 (void)wxMessageBox(_("Sorry, the format for this file is unknown."),
1305 wxOK | wxICON_EXCLAMATION, wxFindSuitableParent());
1309 temp = SelectDocumentPath(templates, n, path2, flags);
1317 if (!CloseDocument(docToClose, false))
1323 //see if this file is already open
1324 for (size_t i = 0; i < GetDocuments().GetCount(); ++i)
1326 wxDocument* currentDoc = (wxDocument*)(GetDocuments().Item(i)->GetData());
1328 //file paths are case-insensitive on Windows
1329 if (path2.CmpNoCase(currentDoc->GetFilename()) == 0)
1331 if (path2.Cmp(currentDoc->GetFilename()) == 0)
1334 //file already open. Just activate it and return
1335 if (currentDoc->GetFirstView())
1337 ActivateView(currentDoc->GetFirstView(), true);
1338 if (currentDoc->GetDocumentWindow())
1339 currentDoc->GetDocumentWindow()->SetFocus();
1345 wxDocument *newDoc = temp->CreateDocument(path2, flags);
1348 newDoc->SetDocumentName(temp->GetDocumentName());
1349 newDoc->SetDocumentTemplate(temp);
1350 if (!newDoc->OnOpenDocument(path2))
1352 newDoc->DeleteAllViews();
1353 // delete newDoc; // Implicitly deleted by DeleteAllViews
1354 return (wxDocument *) NULL;
1356 // A file that doesn't use the default extension of its document
1357 // template cannot be opened via the FileHistory, so we do not
1359 if (temp->FileMatchesTemplate(path2))
1360 AddFileToHistory(path2);
1365 return (wxDocument *) NULL;
1368 wxView *wxDocManager::CreateView(wxDocument *doc, long flags)
1370 wxDocTemplate **templates = new wxDocTemplate *[m_templates.GetCount()];
1373 for (size_t i = 0; i < m_templates.GetCount(); i++)
1375 wxDocTemplate *temp = (wxDocTemplate *)(m_templates.Item(i)->GetData());
1376 if (temp->IsVisible())
1378 if (temp->GetDocumentName() == doc->GetDocumentName())
1380 templates[n] = temp;
1388 return (wxView *) NULL;
1392 wxDocTemplate *temp = templates[0];
1394 wxView *view = temp->CreateView(doc, flags);
1396 view->SetViewName(temp->GetViewName());
1400 wxDocTemplate *temp = SelectViewType(templates, n);
1404 wxView *view = temp->CreateView(doc, flags);
1406 view->SetViewName(temp->GetViewName());
1410 return (wxView *) NULL;
1413 // Not yet implemented
1414 void wxDocManager::DeleteTemplate(wxDocTemplate *WXUNUSED(temp), long WXUNUSED(flags))
1418 // Not yet implemented
1419 bool wxDocManager::FlushDoc(wxDocument *WXUNUSED(doc))
1424 wxDocument *wxDocManager::GetCurrentDocument() const
1426 wxView *view = GetCurrentView();
1428 return view->GetDocument();
1430 return (wxDocument *) NULL;
1433 // Make a default document name
1434 bool wxDocManager::MakeDefaultName(wxString& name)
1436 name.Printf(_("unnamed%d"), m_defaultDocumentNameCounter);
1437 m_defaultDocumentNameCounter++;
1442 // Make a frame title (override this to do something different)
1443 // If docName is empty, a document is not currently active.
1444 wxString wxDocManager::MakeFrameTitle(wxDocument* doc)
1446 wxString appName = wxTheApp->GetAppName();
1453 doc->GetPrintableName(docName);
1454 title = docName + wxString(_(" - ")) + appName;
1460 // Not yet implemented
1461 wxDocTemplate *wxDocManager::MatchTemplate(const wxString& WXUNUSED(path))
1463 return (wxDocTemplate *) NULL;
1466 // File history management
1467 void wxDocManager::AddFileToHistory(const wxString& file)
1470 m_fileHistory->AddFileToHistory(file);
1473 void wxDocManager::RemoveFileFromHistory(size_t i)
1476 m_fileHistory->RemoveFileFromHistory(i);
1479 wxString wxDocManager::GetHistoryFile(size_t i) const
1484 histFile = m_fileHistory->GetHistoryFile(i);
1489 void wxDocManager::FileHistoryUseMenu(wxMenu *menu)
1492 m_fileHistory->UseMenu(menu);
1495 void wxDocManager::FileHistoryRemoveMenu(wxMenu *menu)
1498 m_fileHistory->RemoveMenu(menu);
1502 void wxDocManager::FileHistoryLoad(wxConfigBase& config)
1505 m_fileHistory->Load(config);
1508 void wxDocManager::FileHistorySave(wxConfigBase& config)
1511 m_fileHistory->Save(config);
1515 void wxDocManager::FileHistoryAddFilesToMenu(wxMenu* menu)
1518 m_fileHistory->AddFilesToMenu(menu);
1521 void wxDocManager::FileHistoryAddFilesToMenu()
1524 m_fileHistory->AddFilesToMenu();
1527 size_t wxDocManager::GetHistoryFilesCount() const
1529 return m_fileHistory ? m_fileHistory->GetCount() : 0;
1533 // Find out the document template via matching in the document file format
1534 // against that of the template
1535 wxDocTemplate *wxDocManager::FindTemplateForPath(const wxString& path)
1537 wxDocTemplate *theTemplate = (wxDocTemplate *) NULL;
1539 // Find the template which this extension corresponds to
1540 for (size_t i = 0; i < m_templates.GetCount(); i++)
1542 wxDocTemplate *temp = (wxDocTemplate *)m_templates.Item(i)->GetData();
1543 if ( temp->FileMatchesTemplate(path) )
1552 // Try to get a more suitable parent frame than the top window,
1553 // for selection dialogs. Otherwise you may get an unexpected
1554 // window being activated when a dialog is shown.
1555 static wxWindow* wxFindSuitableParent()
1557 wxWindow* parent = wxTheApp->GetTopWindow();
1559 wxWindow* focusWindow = wxWindow::FindFocus();
1562 while (focusWindow &&
1563 !focusWindow->IsKindOf(CLASSINFO(wxDialog)) &&
1564 !focusWindow->IsKindOf(CLASSINFO(wxFrame)))
1566 focusWindow = focusWindow->GetParent();
1569 parent = focusWindow;
1574 // Prompts user to open a file, using file specs in templates.
1575 // Must extend the file selector dialog or implement own; OR
1576 // match the extension to the template extension.
1578 wxDocTemplate *wxDocManager::SelectDocumentPath(wxDocTemplate **templates,
1579 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1582 int WXUNUSED(noTemplates),
1585 long WXUNUSED(flags),
1586 bool WXUNUSED(save))
1588 // We can only have multiple filters in Windows and GTK
1589 #if defined(__WXMSW__) || defined(__WXGTK__) || defined(__WXMAC__)
1593 for (i = 0; i < noTemplates; i++)
1595 if (templates[i]->IsVisible())
1597 // add a '|' to separate this filter from the previous one
1598 if ( !descrBuf.empty() )
1599 descrBuf << wxT('|');
1601 descrBuf << templates[i]->GetDescription()
1602 << wxT(" (") << templates[i]->GetFileFilter() << wxT(") |")
1603 << templates[i]->GetFileFilter();
1607 wxString descrBuf = wxT("*.*");
1610 int FilterIndex = -1;
1612 wxWindow* parent = wxFindSuitableParent();
1614 wxString pathTmp = wxFileSelectorEx(_("Select a file"),
1622 wxDocTemplate *theTemplate = (wxDocTemplate *)NULL;
1623 if (!pathTmp.empty())
1625 if (!wxFileExists(pathTmp))
1628 if (!wxTheApp->GetAppName().empty())
1629 msgTitle = wxTheApp->GetAppName();
1631 msgTitle = wxString(_("File error"));
1633 (void)wxMessageBox(_("Sorry, could not open this file."), msgTitle, wxOK | wxICON_EXCLAMATION,
1636 path = wxEmptyString;
1637 return (wxDocTemplate *) NULL;
1639 m_lastDirectory = wxPathOnly(pathTmp);
1643 // first choose the template using the extension, if this fails (i.e.
1644 // wxFileSelectorEx() didn't fill it), then use the path
1645 if ( FilterIndex != -1 )
1646 theTemplate = templates[FilterIndex];
1648 theTemplate = FindTemplateForPath(path);
1651 // Since we do not add files with non-default extensions to the FileHistory this
1652 // can only happen if the application changes the allowed templates in runtime.
1653 (void)wxMessageBox(_("Sorry, the format for this file is unknown."),
1655 wxOK | wxICON_EXCLAMATION, wxFindSuitableParent());
1660 path = wxEmptyString;
1666 wxDocTemplate *wxDocManager::SelectDocumentType(wxDocTemplate **templates,
1667 int noTemplates, bool sort)
1669 wxArrayString strings;
1670 wxDocTemplate **data = new wxDocTemplate *[noTemplates];
1674 for (i = 0; i < noTemplates; i++)
1676 if (templates[i]->IsVisible())
1680 for (j = 0; j < n; j++)
1682 //filter out NOT unique documents + view combinations
1683 if ( templates[i]->m_docTypeName == data[j]->m_docTypeName &&
1684 templates[i]->m_viewTypeName == data[j]->m_viewTypeName
1691 strings.Add(templates[i]->m_description);
1693 data[n] = templates[i];
1701 strings.Sort(); // ascending sort
1702 // Yes, this will be slow, but template lists
1703 // are typically short.
1705 n = strings.Count();
1706 for (i = 0; i < n; i++)
1708 for (j = 0; j < noTemplates; j++)
1710 if (strings[i] == templates[j]->m_description)
1711 data[i] = templates[j];
1716 wxDocTemplate *theTemplate;
1721 // no visible templates, hence nothing to choose from
1726 // don't propose the user to choose if he heas no choice
1727 theTemplate = data[0];
1731 // propose the user to choose one of several
1732 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1734 _("Select a document template"),
1738 wxFindSuitableParent()
1747 wxDocTemplate *wxDocManager::SelectViewType(wxDocTemplate **templates,
1748 int noTemplates, bool sort)
1750 wxArrayString strings;
1751 wxDocTemplate **data = new wxDocTemplate *[noTemplates];
1755 for (i = 0; i < noTemplates; i++)
1757 wxDocTemplate *templ = templates[i];
1758 if ( templ->IsVisible() && !templ->GetViewName().empty() )
1762 for (j = 0; j < n; j++)
1764 //filter out NOT unique views
1765 if ( templates[i]->m_viewTypeName == data[j]->m_viewTypeName )
1771 strings.Add(templ->m_viewTypeName);
1780 strings.Sort(); // ascending sort
1781 // Yes, this will be slow, but template lists
1782 // are typically short.
1784 n = strings.Count();
1785 for (i = 0; i < n; i++)
1787 for (j = 0; j < noTemplates; j++)
1789 if (strings[i] == templates[j]->m_viewTypeName)
1790 data[i] = templates[j];
1795 wxDocTemplate *theTemplate;
1797 // the same logic as above
1801 theTemplate = (wxDocTemplate *)NULL;
1805 theTemplate = data[0];
1809 theTemplate = (wxDocTemplate *)wxGetSingleChoiceData
1811 _("Select a document view"),
1815 wxFindSuitableParent()
1824 void wxDocManager::AssociateTemplate(wxDocTemplate *temp)
1826 if (!m_templates.Member(temp))
1827 m_templates.Append(temp);
1830 void wxDocManager::DisassociateTemplate(wxDocTemplate *temp)
1832 m_templates.DeleteObject(temp);
1835 // Add and remove a document from the manager's list
1836 void wxDocManager::AddDocument(wxDocument *doc)
1838 if (!m_docs.Member(doc))
1842 void wxDocManager::RemoveDocument(wxDocument *doc)
1844 m_docs.DeleteObject(doc);
1847 // Views or windows should inform the document manager
1848 // when a view is going in or out of focus
1849 void wxDocManager::ActivateView(wxView *view, bool activate)
1853 m_currentView = view;
1857 if ( m_currentView == view )
1859 // don't keep stale pointer
1860 m_currentView = (wxView *) NULL;
1865 // ----------------------------------------------------------------------------
1866 // Default document child frame
1867 // ----------------------------------------------------------------------------
1869 BEGIN_EVENT_TABLE(wxDocChildFrame, wxFrame)
1870 EVT_ACTIVATE(wxDocChildFrame::OnActivate)
1871 EVT_CLOSE(wxDocChildFrame::OnCloseWindow)
1874 wxDocChildFrame::wxDocChildFrame(wxDocument *doc,
1878 const wxString& title,
1882 const wxString& name)
1883 : wxFrame(frame, id, title, pos, size, style, name)
1885 m_childDocument = doc;
1888 view->SetFrame(this);
1891 // Extend event processing to search the view's event table
1892 bool wxDocChildFrame::ProcessEvent(wxEvent& event)
1895 m_childView->Activate(true);
1897 if ( !m_childView || ! m_childView->ProcessEvent(event) )
1899 // Only hand up to the parent if it's a menu command
1900 if (!event.IsKindOf(CLASSINFO(wxCommandEvent)) || !GetParent() || !GetParent()->ProcessEvent(event))
1901 return wxEvtHandler::ProcessEvent(event);
1909 void wxDocChildFrame::OnActivate(wxActivateEvent& event)
1911 wxFrame::OnActivate(event);
1914 m_childView->Activate(event.GetActive());
1917 void wxDocChildFrame::OnCloseWindow(wxCloseEvent& event)
1921 bool ans = event.CanVeto()
1922 ? m_childView->Close(false) // false means don't delete associated window
1923 : true; // Must delete.
1927 m_childView->Activate(false);
1929 m_childView = (wxView *) NULL;
1930 m_childDocument = (wxDocument *) NULL;
1941 // ----------------------------------------------------------------------------
1942 // Default parent frame
1943 // ----------------------------------------------------------------------------
1945 BEGIN_EVENT_TABLE(wxDocParentFrame, wxFrame)
1946 EVT_MENU(wxID_EXIT, wxDocParentFrame::OnExit)
1947 EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocParentFrame::OnMRUFile)
1948 EVT_CLOSE(wxDocParentFrame::OnCloseWindow)
1951 wxDocParentFrame::wxDocParentFrame()
1953 m_docManager = NULL;
1956 wxDocParentFrame::wxDocParentFrame(wxDocManager *manager,
1959 const wxString& title,
1963 const wxString& name)
1964 : wxFrame(frame, id, title, pos, size, style, name)
1966 m_docManager = manager;
1969 bool wxDocParentFrame::Create(wxDocManager *manager,
1972 const wxString& title,
1976 const wxString& name)
1978 m_docManager = manager;
1979 return base_type::Create(frame, id, title, pos, size, style, name);
1982 void wxDocParentFrame::OnExit(wxCommandEvent& WXUNUSED(event))
1987 void wxDocParentFrame::OnMRUFile(wxCommandEvent& event)
1989 int n = event.GetId() - wxID_FILE1; // the index in MRU list
1990 wxString filename(m_docManager->GetHistoryFile(n));
1991 if ( !filename.empty() )
1993 // verify that the file exists before doing anything else
1994 if ( wxFile::Exists(filename) )
1997 if (!m_docManager->CreateDocument(filename, wxDOC_SILENT))
1999 // remove the file from the MRU list. The user should already be notified.
2000 m_docManager->RemoveFileFromHistory(n);
2002 wxLogError(_("The file '%s' couldn't be opened.\nIt has been removed from the most recently used files list."),
2008 // remove the bogus filename from the MRU list and notify the user
2010 m_docManager->RemoveFileFromHistory(n);
2012 wxLogError(_("The file '%s' doesn't exist and couldn't be opened.\nIt has been removed from the most recently used files list."),
2018 // Extend event processing to search the view's event table
2019 bool wxDocParentFrame::ProcessEvent(wxEvent& event)
2021 // Try the document manager, then do default processing
2022 if (!m_docManager || !m_docManager->ProcessEvent(event))
2023 return wxEvtHandler::ProcessEvent(event);
2028 // Define the behaviour for the frame closing
2029 // - must delete all frames except for the main one.
2030 void wxDocParentFrame::OnCloseWindow(wxCloseEvent& event)
2032 if (m_docManager->Clear(!event.CanVeto()))
2040 #if wxUSE_PRINTING_ARCHITECTURE
2042 wxDocPrintout::wxDocPrintout(wxView *view, const wxString& title)
2045 m_printoutView = view;
2048 bool wxDocPrintout::OnPrintPage(int WXUNUSED(page))
2052 // Get the logical pixels per inch of screen and printer
2053 int ppiScreenX, ppiScreenY;
2054 GetPPIScreen(&ppiScreenX, &ppiScreenY);
2055 wxUnusedVar(ppiScreenY);
2056 int ppiPrinterX, ppiPrinterY;
2057 GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
2058 wxUnusedVar(ppiPrinterY);
2060 // This scales the DC so that the printout roughly represents the
2061 // the screen scaling. The text point size _should_ be the right size
2062 // but in fact is too small for some reason. This is a detail that will
2063 // need to be addressed at some point but can be fudged for the
2065 float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
2067 // Now we have to check in case our real page size is reduced
2068 // (e.g. because we're drawing to a print preview memory DC)
2069 int pageWidth, pageHeight;
2071 dc->GetSize(&w, &h);
2072 GetPageSizePixels(&pageWidth, &pageHeight);
2073 wxUnusedVar(pageHeight);
2075 // If printer pageWidth == current DC width, then this doesn't
2076 // change. But w might be the preview bitmap width, so scale down.
2077 float overallScale = scale * (float)(w/(float)pageWidth);
2078 dc->SetUserScale(overallScale, overallScale);
2082 m_printoutView->OnDraw(dc);
2087 bool wxDocPrintout::HasPage(int pageNum)
2089 return (pageNum == 1);
2092 bool wxDocPrintout::OnBeginDocument(int startPage, int endPage)
2094 if (!wxPrintout::OnBeginDocument(startPage, endPage))
2100 void wxDocPrintout::GetPageInfo(int *minPage, int *maxPage, int *selPageFrom, int *selPageTo)
2108 #endif // wxUSE_PRINTING_ARCHITECTURE
2110 // ----------------------------------------------------------------------------
2111 // File history processor
2112 // ----------------------------------------------------------------------------
2114 static inline wxChar* MYcopystring(const wxString& s)
2116 wxChar* copy = new wxChar[s.length() + 1];
2117 return wxStrcpy(copy, s.c_str());
2120 static inline wxChar* MYcopystring(const wxChar* s)
2122 wxChar* copy = new wxChar[wxStrlen(s) + 1];
2123 return wxStrcpy(copy, s);
2126 wxFileHistory::wxFileHistory(size_t maxFiles, wxWindowID idBase)
2128 m_fileMaxFiles = maxFiles;
2131 m_fileHistory = new wxChar *[m_fileMaxFiles];
2134 wxFileHistory::~wxFileHistory()
2137 for (i = 0; i < m_fileHistoryN; i++)
2138 delete[] m_fileHistory[i];
2139 delete[] m_fileHistory;
2142 // File history management
2143 void wxFileHistory::AddFileToHistory(const wxString& file)
2147 // Check we don't already have this file
2148 for (i = 0; i < m_fileHistoryN; i++)
2150 #if defined( __WXMSW__ ) // Add any other OSes with case insensitive file names
2151 wxString testString;
2152 if ( m_fileHistory[i] )
2153 testString = m_fileHistory[i];
2154 if ( m_fileHistory[i] && ( file.Lower() == testString.Lower() ) )
2156 if ( m_fileHistory[i] && ( file == m_fileHistory[i] ) )
2159 // we do have it, move it to the top of the history
2160 RemoveFileFromHistory (i);
2161 AddFileToHistory (file);
2166 // if we already have a full history, delete the one at the end
2167 if ( m_fileMaxFiles == m_fileHistoryN )
2169 RemoveFileFromHistory (m_fileHistoryN - 1);
2170 AddFileToHistory (file);
2174 // Add to the project file history:
2175 // Move existing files (if any) down so we can insert file at beginning.
2176 if (m_fileHistoryN < m_fileMaxFiles)
2178 wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2181 wxMenu* menu = (wxMenu*) node->GetData();
2182 if ( m_fileHistoryN == 0 && menu->GetMenuItemCount() )
2184 menu->AppendSeparator();
2186 menu->Append(m_idBase+m_fileHistoryN, _("[EMPTY]"));
2187 node = node->GetNext();
2191 // Shuffle filenames down
2192 for (i = (m_fileHistoryN-1); i > 0; i--)
2194 m_fileHistory[i] = m_fileHistory[i-1];
2196 m_fileHistory[0] = MYcopystring(file);
2198 // this is the directory of the last opened file
2199 wxString pathCurrent;
2200 wxSplitPath( m_fileHistory[0], &pathCurrent, NULL, NULL );
2201 for (i = 0; i < m_fileHistoryN; i++)
2203 if ( m_fileHistory[i] )
2205 // if in same directory just show the filename; otherwise the full
2207 wxString pathInMenu, path, filename, ext;
2208 wxSplitPath( m_fileHistory[i], &path, &filename, &ext );
2209 if ( path == pathCurrent )
2211 pathInMenu = filename;
2213 pathInMenu = pathInMenu + wxFILE_SEP_EXT + ext;
2217 // absolute path; could also set relative path
2218 pathInMenu = m_fileHistory[i];
2221 // we need to quote '&' characters which are used for mnemonics
2222 pathInMenu.Replace(_T("&"), _T("&&"));
2224 buf.Printf(s_MRUEntryFormat, i + 1, pathInMenu.c_str());
2225 wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2228 wxMenu* menu = (wxMenu*) node->GetData();
2229 menu->SetLabel(m_idBase + i, buf);
2230 node = node->GetNext();
2236 void wxFileHistory::RemoveFileFromHistory(size_t i)
2238 wxCHECK_RET( i < m_fileHistoryN,
2239 wxT("invalid index in wxFileHistory::RemoveFileFromHistory") );
2241 // delete the element from the array (could use memmove() too...)
2242 delete [] m_fileHistory[i];
2245 for ( j = i; j < m_fileHistoryN - 1; j++ )
2247 m_fileHistory[j] = m_fileHistory[j + 1];
2250 wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2253 wxMenu* menu = (wxMenu*) node->GetData();
2255 // shuffle filenames up
2257 for ( j = i; j < m_fileHistoryN - 1; j++ )
2259 buf.Printf(s_MRUEntryFormat, j + 1, m_fileHistory[j]);
2260 menu->SetLabel(m_idBase + j, buf);
2263 node = node->GetNext();
2265 // delete the last menu item which is unused now
2266 wxWindowID lastItemId = m_idBase + wx_truncate_cast(wxWindowID, m_fileHistoryN) - 1;
2267 if (menu->FindItem(lastItemId))
2269 menu->Delete(lastItemId);
2272 // delete the last separator too if no more files are left
2273 if ( m_fileHistoryN == 1 )
2275 wxMenuItemList::compatibility_iterator nodeLast = menu->GetMenuItems().GetLast();
2278 wxMenuItem *menuItem = nodeLast->GetData();
2279 if ( menuItem->IsSeparator() )
2281 menu->Delete(menuItem);
2283 //else: should we search backwards for the last separator?
2285 //else: menu is empty somehow
2292 wxString wxFileHistory::GetHistoryFile(size_t i) const
2295 if ( i < m_fileHistoryN )
2297 s = m_fileHistory[i];
2301 wxFAIL_MSG( wxT("bad index in wxFileHistory::GetHistoryFile") );
2307 void wxFileHistory::UseMenu(wxMenu *menu)
2309 if (!m_fileMenus.Member(menu))
2310 m_fileMenus.Append(menu);
2313 void wxFileHistory::RemoveMenu(wxMenu *menu)
2315 m_fileMenus.DeleteObject(menu);
2319 void wxFileHistory::Load(wxConfigBase& config)
2323 buf.Printf(wxT("file%d"), (int)m_fileHistoryN+1);
2324 wxString historyFile;
2325 while ((m_fileHistoryN < m_fileMaxFiles) && config.Read(buf, &historyFile) && (!historyFile.empty()))
2327 m_fileHistory[m_fileHistoryN] = MYcopystring((const wxChar*) historyFile);
2329 buf.Printf(wxT("file%d"), (int)m_fileHistoryN+1);
2330 historyFile = wxEmptyString;
2335 void wxFileHistory::Save(wxConfigBase& config)
2338 for (i = 0; i < m_fileMaxFiles; i++)
2341 buf.Printf(wxT("file%d"), (int)i+1);
2342 if (i < m_fileHistoryN)
2343 config.Write(buf, wxString(m_fileHistory[i]));
2345 config.Write(buf, wxEmptyString);
2348 #endif // wxUSE_CONFIG
2350 void wxFileHistory::AddFilesToMenu()
2352 if (m_fileHistoryN > 0)
2354 wxList::compatibility_iterator node = m_fileMenus.GetFirst();
2357 wxMenu* menu = (wxMenu*) node->GetData();
2358 if (menu->GetMenuItemCount())
2360 menu->AppendSeparator();
2364 for (i = 0; i < m_fileHistoryN; i++)
2366 if (m_fileHistory[i])
2369 buf.Printf(s_MRUEntryFormat, i+1, m_fileHistory[i]);
2370 menu->Append(m_idBase+i, buf);
2373 node = node->GetNext();
2378 void wxFileHistory::AddFilesToMenu(wxMenu* menu)
2380 if (m_fileHistoryN > 0)
2382 if (menu->GetMenuItemCount())
2384 menu->AppendSeparator();
2388 for (i = 0; i < m_fileHistoryN; i++)
2390 if (m_fileHistory[i])
2393 buf.Printf(s_MRUEntryFormat, i+1, m_fileHistory[i]);
2394 menu->Append(m_idBase+i, buf);
2400 // ----------------------------------------------------------------------------
2401 // Permits compatibility with existing file formats and functions that
2402 // manipulate files directly
2403 // ----------------------------------------------------------------------------
2405 #if wxUSE_STD_IOSTREAM
2407 bool wxTransferFileToStream(const wxString& filename, wxSTD ostream& stream)
2409 wxFFile file(filename, _T("rb"));
2410 if ( !file.IsOpened() )
2418 nRead = file.Read(buf, WXSIZEOF(buf));
2422 stream.write(buf, nRead);
2426 while ( !file.Eof() );
2431 bool wxTransferStreamToFile(wxSTD istream& stream, const wxString& filename)
2433 wxFFile file(filename, _T("wb"));
2434 if ( !file.IsOpened() )
2440 stream.read(buf, WXSIZEOF(buf));
2441 if ( !stream.bad() ) // fail may be set on EOF, don't use operator!()
2443 if ( !file.Write(buf, stream.gcount()) )
2447 while ( !stream.eof() );
2452 #else // !wxUSE_STD_IOSTREAM
2454 bool wxTransferFileToStream(const wxString& filename, wxOutputStream& stream)
2456 wxFFile file(filename, _T("rb"));
2457 if ( !file.IsOpened() )
2465 nRead = file.Read(buf, WXSIZEOF(buf));
2469 stream.Write(buf, nRead);
2473 while ( !file.Eof() );
2478 bool wxTransferStreamToFile(wxInputStream& stream, const wxString& filename)
2480 wxFFile file(filename, _T("wb"));
2481 if ( !file.IsOpened() )
2487 stream.Read(buf, WXSIZEOF(buf));
2489 const size_t nRead = stream.LastRead();
2498 if ( !file.Write(buf, nRead) )
2505 #endif // wxUSE_STD_IOSTREAM/!wxUSE_STD_IOSTREAM
2507 #endif // wxUSE_DOC_VIEW_ARCHITECTURE