From 86b0298d5af5ed49e3534afa4a0a8933aa2ce508 Mon Sep 17 00:00:00 2001 From: Steffen Olszewski Date: Wed, 16 Mar 2022 20:27:56 +0100 Subject: [PATCH] Reformat project sources according to current code style definitions Apply automatic code formatting by using clang-format. Manually adjust some aspects not covered by clang-format, mostly create block structures by adding newlines. --- plugins/additional/additional.cpp | 4421 +++++++++--------- plugins/containers/bookutils.h | 257 +- plugins/containers/containers.cpp | 1486 +++--- plugins/forms/forms.cpp | 559 +-- plugins/layout/layout.cpp | 1235 +++-- sdk/plugin_interface/component.h | 348 +- sdk/plugin_interface/fontcontainer.h | 111 +- sdk/plugin_interface/forms/wizard.cpp | 251 +- sdk/plugin_interface/forms/wizard.h | 94 +- sdk/plugin_interface/plugin.h | 318 +- sdk/plugin_interface/xrcconv.cpp | 1683 ++++--- sdk/plugin_interface/xrcconv.h | 115 +- src/codegen/codegen.cpp | 1814 ++++---- src/codegen/codegen.h | 579 ++- src/codegen/codeparser.cpp | 487 +- src/codegen/codeparser.h | 201 +- src/codegen/codewriter.cpp | 274 +- src/codegen/codewriter.h | 176 +- src/codegen/cppcg.cpp | 3887 ++++++++-------- src/codegen/cppcg.h | 494 +- src/codegen/luacg.cpp | 3277 +++++++------ src/codegen/luacg.h | 391 +- src/codegen/phpcg.cpp | 2722 +++++------ src/codegen/phpcg.h | 361 +- src/codegen/pythoncg.cpp | 3207 ++++++------- src/codegen/pythoncg.h | 395 +- src/codegen/xrccg.cpp | 358 +- src/codegen/xrccg.h | 20 +- src/maingui.cpp | 717 ++- src/maingui.h | 29 +- src/model/database.cpp | 2479 +++++----- src/model/database.h | 446 +- src/model/objectbase.cpp | 1149 +++-- src/model/objectbase.h | 1083 +++-- src/model/types.cpp | 171 +- src/model/types.h | 216 +- src/model/xrcfilter.cpp | 327 +- src/model/xrcfilter.h | 24 +- src/rad/about.cpp | 139 +- src/rad/about.h | 32 +- src/rad/appdata.cpp | 4865 +++++++++----------- src/rad/appdata.h | 481 +- src/rad/auitabart.h | 29 +- src/rad/bitmaps.cpp | 90 +- src/rad/bitmaps.h | 13 +- src/rad/cmdproc.cpp | 76 +- src/rad/cmdproc.h | 76 +- src/rad/codeeditor/codeeditor.cpp | 165 +- src/rad/codeeditor/codeeditor.h | 13 +- src/rad/cpppanel/cpppanel.cpp | 630 ++- src/rad/cpppanel/cpppanel.h | 48 +- src/rad/customkeys.cpp | 68 +- src/rad/customkeys.h | 13 +- src/rad/dataobject/dataobject.cpp | 183 +- src/rad/dataobject/dataobject.h | 28 +- src/rad/designer/innerframe.cpp | 784 ++-- src/rad/designer/innerframe.h | 64 +- src/rad/designer/menubar.cpp | 42 +- src/rad/designer/menubar.h | 45 +- src/rad/designer/resizablepanel.cpp | 207 +- src/rad/designer/resizablepanel.h | 39 +- src/rad/designer/visualeditor.cpp | 2638 +++++------ src/rad/designer/visualeditor.h | 214 +- src/rad/designer/visualobj.cpp | 184 +- src/rad/designer/visualobj.h | 33 +- src/rad/designer/window_buttons.h | 5 +- src/rad/dialogfindcomponent.cpp | 64 +- src/rad/dialogfindcomponent.h | 24 +- src/rad/genericpanel.cpp | 24 +- src/rad/genericpanel.h | 14 +- src/rad/geninheritclass/geninhertclass.cpp | 94 +- src/rad/geninheritclass/geninhertclass.h | 59 +- src/rad/inspector/objinspect.cpp | 2079 ++++----- src/rad/inspector/objinspect.h | 129 +- src/rad/inspector/wxfbadvprops.cpp | 1092 ++--- src/rad/inspector/wxfbadvprops.h | 131 +- src/rad/luapanel/luapanel.cpp | 515 +-- src/rad/luapanel/luapanel.h | 41 +- src/rad/mainframe.cpp | 2742 ++++++----- src/rad/mainframe.h | 278 +- src/rad/menueditor.cpp | 686 ++- src/rad/menueditor.h | 55 +- src/rad/objecttree/objecttree.cpp | 974 ++-- src/rad/objecttree/objecttree.h | 119 +- src/rad/palette.cpp | 323 +- src/rad/palette.h | 45 +- src/rad/phppanel/phppanel.cpp | 519 +-- src/rad/phppanel/phppanel.h | 41 +- src/rad/pythonpanel/pythonpanel.cpp | 551 ++- src/rad/pythonpanel/pythonpanel.h | 49 +- src/rad/revision.h | 2 +- src/rad/title.cpp | 46 +- src/rad/title.h | 15 +- src/rad/version.h | 3 +- src/rad/wxfbevent.cpp | 87 +- src/rad/wxfbevent.h | 88 +- src/rad/wxfbmanager.cpp | 181 +- src/rad/wxfbmanager.h | 40 +- src/rad/xrcpanel/xrcpanel.cpp | 361 +- src/rad/xrcpanel/xrcpanel.h | 32 +- src/rad/xrcpreview/xrcpreview.cpp | 361 +- src/rad/xrcpreview/xrcpreview.h | 10 +- src/utils/annoyingdialog.cpp | 216 +- src/utils/annoyingdialog.h | 65 +- src/utils/debug.h | 41 +- src/utils/filetocarray.cpp | 272 +- src/utils/filetocarray.h | 5 +- src/utils/m_wxfb.cpp | 16 +- src/utils/stringutils.cpp | 672 ++- src/utils/stringutils.h | 38 +- src/utils/typeconv.cpp | 1752 ++++--- src/utils/typeconv.h | 133 +- src/utils/wxfbdefs.h | 37 +- src/utils/wxfbexception.h | 35 +- src/utils/wxfbipc.cpp | 358 +- src/utils/wxfbipc.h | 55 +- src/utils/wxlogstring.h | 34 +- 117 files changed, 29842 insertions(+), 33127 deletions(-) diff --git a/plugins/additional/additional.cpp b/plugins/additional/additional.cpp index 965f1e878..734a000bc 100644 --- a/plugins/additional/additional.cpp +++ b/plugins/additional/additional.cpp @@ -23,41 +23,39 @@ // /////////////////////////////////////////////////////////////////////////////// -#include "logo.xpm" -#include "smiley.xpm" - -#include #include -#include - #include +#include +#include #include #include +#include +#include #include #include -#include -#include -#include +#include #include -#include -#include #include -#include #include -#include - -#include -#include -#include -#include +#include #include +#include #include +#include +#include +#include +#include + +#include +#include + +#include "logo.xpm" +#include "smiley.xpm" #ifdef USE_MEDIACTRL -#include + #include #endif -/////////////////////////////////////////////////////////////////////////////// /** Event handler for events generated by controls in this plugin @@ -65,49 +63,44 @@ Event handler for events generated by controls in this plugin class ComponentEvtHandler : public wxEvtHandler { private: - wxWindow* m_window; - IManager* m_manager; + wxWindow* m_window; + IManager* m_manager; public: - ComponentEvtHandler( wxWindow* win, IManager* manager ) - : - m_window( win ), - m_manager( manager ) - { - } + ComponentEvtHandler(wxWindow* win, IManager* manager) : m_window(win), m_manager(manager) {} protected: - void OnGridClick( wxGridEvent& event ); - void OnGridColSize( wxGridSizeEvent& event ); - void OnGridRowSize( wxGridSizeEvent& event ); - void OnColourPickerColourChanged(wxColourPickerEvent& event); - void OnFontPickerFontChanged(wxFontPickerEvent& event); - void OnFilePickerFileChanged(wxFileDirPickerEvent& event); - void OnDirPickerDirChanged(wxFileDirPickerEvent& event); - void OnText(wxCommandEvent& event); - void OnGenericDirCtrlExpandItem( wxTreeEvent& event ); - // Enable folding for wxStyledTextCtrl - void OnMarginClick ( wxStyledTextEvent& event ); - void OnRibbonBarPageChanged( wxRibbonBarEvent& event ); - DECLARE_EVENT_TABLE() + void OnGridClick(wxGridEvent& event); + void OnGridColSize(wxGridSizeEvent& event); + void OnGridRowSize(wxGridSizeEvent& event); + void OnColourPickerColourChanged(wxColourPickerEvent& event); + void OnFontPickerFontChanged(wxFontPickerEvent& event); + void OnFilePickerFileChanged(wxFileDirPickerEvent& event); + void OnDirPickerDirChanged(wxFileDirPickerEvent& event); + void OnText(wxCommandEvent& event); + void OnGenericDirCtrlExpandItem(wxTreeEvent& event); + // Enable folding for wxStyledTextCtrl + void OnMarginClick(wxStyledTextEvent& event); + void OnRibbonBarPageChanged(wxRibbonBarEvent& event); + DECLARE_EVENT_TABLE() }; -BEGIN_EVENT_TABLE( ComponentEvtHandler, wxEvtHandler ) - EVT_COLOURPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnColourPickerColourChanged) - EVT_FONTPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnFontPickerFontChanged) - EVT_FILEPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnFilePickerFileChanged) - EVT_DIRPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnDirPickerDirChanged) - EVT_TEXT( wxID_ANY, ComponentEvtHandler::OnText ) +BEGIN_EVENT_TABLE(ComponentEvtHandler, wxEvtHandler) +EVT_COLOURPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnColourPickerColourChanged) +EVT_FONTPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnFontPickerFontChanged) +EVT_FILEPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnFilePickerFileChanged) +EVT_DIRPICKER_CHANGED(wxID_ANY, ComponentEvtHandler::OnDirPickerDirChanged) +EVT_TEXT(wxID_ANY, ComponentEvtHandler::OnText) - // Grid also seems to ignore clicks - EVT_GRID_CELL_LEFT_CLICK( ComponentEvtHandler::OnGridClick ) - EVT_GRID_LABEL_LEFT_CLICK( ComponentEvtHandler::OnGridClick ) +// Grid also seems to ignore clicks +EVT_GRID_CELL_LEFT_CLICK(ComponentEvtHandler::OnGridClick) +EVT_GRID_LABEL_LEFT_CLICK(ComponentEvtHandler::OnGridClick) - EVT_GRID_COL_SIZE( ComponentEvtHandler::OnGridColSize ) - EVT_GRID_ROW_SIZE( ComponentEvtHandler::OnGridRowSize ) +EVT_GRID_COL_SIZE(ComponentEvtHandler::OnGridColSize) +EVT_GRID_ROW_SIZE(ComponentEvtHandler::OnGridRowSize) - EVT_STC_MARGINCLICK(wxID_ANY, ComponentEvtHandler::OnMarginClick) - EVT_RIBBONBAR_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnRibbonBarPageChanged) +EVT_STC_MARGINCLICK(wxID_ANY, ComponentEvtHandler::OnMarginClick) +EVT_RIBBONBAR_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnRibbonBarPageChanged) END_EVENT_TABLE() /** @@ -116,25 +109,19 @@ Event handler for events generated by wxGenericDirCtrl. class GenericDirCtrlEvtHandler : public wxEvtHandler { public: - GenericDirCtrlEvtHandler( wxWindow* win, IManager* manager ) - : - m_window( win ), - m_manager( manager ) - { - } + GenericDirCtrlEvtHandler(wxWindow* win, IManager* manager) : m_window(win), m_manager(manager) {} protected: - void OnGenericDirCtrlLeftClick( wxMouseEvent& event ); - DECLARE_EVENT_TABLE() + void OnGenericDirCtrlLeftClick(wxMouseEvent& event); + DECLARE_EVENT_TABLE() private: - wxWindow* m_window; - IManager* m_manager; - + wxWindow* m_window; + IManager* m_manager; }; -BEGIN_EVENT_TABLE( GenericDirCtrlEvtHandler, wxEvtHandler ) - // GenericDirCtrl also seems to ignore clicks - EVT_LEFT_DOWN( GenericDirCtrlEvtHandler::OnGenericDirCtrlLeftClick ) +BEGIN_EVENT_TABLE(GenericDirCtrlEvtHandler, wxEvtHandler) +// GenericDirCtrl also seems to ignore clicks +EVT_LEFT_DOWN(GenericDirCtrlEvtHandler::OnGenericDirCtrlLeftClick) END_EVENT_TABLE() /////////////////////////////////////////////////////////////////////////////// @@ -142,1316 +129,1280 @@ END_EVENT_TABLE() class CalendarCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - return new wxCalendarCtrl((wxWindow *)parent, wxID_ANY, - wxDefaultDateTime, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - } - - ticpp::Element* ExportToXrc(IObject *obj) override - { - ObjectToXrcFilter xrc(obj, _("wxCalendarCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxCalendarCtrl")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + return new wxCalendarCtrl( + (wxWindow*)parent, wxID_ANY, wxDefaultDateTime, obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxCalendarCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxCalendarCtrl")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class DatePickerCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - return new wxDatePickerCtrl((wxWindow *)parent, wxID_ANY, - wxDefaultDateTime, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxDatePickerCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxDatePickerCtrl")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + return new wxDatePickerCtrl( + (wxWindow*)parent, wxID_ANY, wxDefaultDateTime, obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxDatePickerCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxDatePickerCtrl")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class TimePickerCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - return new wxTimePickerCtrl( ( wxWindow * )parent, wxID_ANY, - wxDefaultDateTime, - obj->GetPropertyAsPoint( _( "pos" ) ), - obj->GetPropertyAsSize( _( "size" ) ), - obj->GetPropertyAsInteger( _( "style" ) ) | obj->GetPropertyAsInteger( _( "window_style" ) ) ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc( obj, _( "wxTimePickerCtrl" ), obj->GetPropertyAsString( _( "name" ) ) ); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter( xrcObj, _( "wxTimePickerCtrl" ) ); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + return new wxTimePickerCtrl( + (wxWindow*)parent, wxID_ANY, wxDefaultDateTime, obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxTimePickerCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxTimePickerCtrl")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; - - class RichTextCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { + wxObject* Create(IObject* obj, wxObject* parent) override + { - wxString text = obj->GetPropertyAsString(_("value")); + wxString text = obj->GetPropertyAsString(_("value")); - wxRichTextCtrl* richText = new wxRichTextCtrl( (wxWindow*)parent, - wxID_ANY, - text, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + wxRichTextCtrl* richText = new wxRichTextCtrl( + (wxWindow*)parent, wxID_ANY, text, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - if (!text.empty()) - { - return richText; - } + if (!text.empty()) { + return richText; + } - wxFont textFont = wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - wxFont boldFont = wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD); - wxFont italicFont = wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_ITALIC, wxFONTWEIGHT_NORMAL); + wxFont textFont = wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont boldFont = wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD); + wxFont italicFont = wxFont(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_ITALIC, wxFONTWEIGHT_NORMAL); - wxFont font(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont font(12, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - wxRichTextCtrl& r = *richText; - r.SetFont(font); - r.BeginSuppressUndo(); + wxRichTextCtrl& r = *richText; + r.SetFont(font); + r.BeginSuppressUndo(); - r.BeginParagraphSpacing(0, 20); + r.BeginParagraphSpacing(0, 20); - r.BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); - r.BeginBold(); + r.BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); + r.BeginBold(); - r.BeginFontSize(14); - r.WriteText(wxT("Welcome to wxRichTextCtrl, a wxWidgets control for editing and presenting styled text and images")); - r.EndFontSize(); - r.Newline(); + r.BeginFontSize(14); + r.WriteText( + wxT("Welcome to wxRichTextCtrl, a wxWidgets control for editing and presenting styled text and images")); + r.EndFontSize(); + r.Newline(); - r.BeginItalic(); - r.WriteText(wxT("by Julian Smart")); - r.EndItalic(); + r.BeginItalic(); + r.WriteText(wxT("by Julian Smart")); + r.EndItalic(); - r.EndBold(); + r.EndBold(); - r.Newline(); - r.WriteImage(wxBitmap(logo_xpm)); + r.Newline(); + r.WriteImage(wxBitmap(logo_xpm)); - r.EndAlignment(); + r.EndAlignment(); - r.Newline(); + r.Newline(); - r.WriteText(wxT("What can you do with this thing? ")); - r.WriteImage(wxBitmap(smiley_xpm)); - r.WriteText(wxT(" Well, you can change text ")); + r.WriteText(wxT("What can you do with this thing? ")); + r.WriteImage(wxBitmap(smiley_xpm)); + r.WriteText(wxT(" Well, you can change text ")); - r.BeginTextColour(wxColour(255, 0, 0)); - r.WriteText(wxT("colour, like this red bit.")); - r.EndTextColour(); + r.BeginTextColour(wxColour(255, 0, 0)); + r.WriteText(wxT("colour, like this red bit.")); + r.EndTextColour(); - r.BeginTextColour(wxColour(0, 0, 255)); - r.WriteText(wxT(" And this blue bit.")); - r.EndTextColour(); + r.BeginTextColour(wxColour(0, 0, 255)); + r.WriteText(wxT(" And this blue bit.")); + r.EndTextColour(); - r.WriteText(wxT(" Naturally you can make things ")); - r.BeginBold(); - r.WriteText(wxT("bold ")); - r.EndBold(); - r.BeginItalic(); - r.WriteText(wxT("or italic ")); - r.EndItalic(); - r.BeginUnderline(); - r.WriteText(wxT("or underlined.")); - r.EndUnderline(); + r.WriteText(wxT(" Naturally you can make things ")); + r.BeginBold(); + r.WriteText(wxT("bold ")); + r.EndBold(); + r.BeginItalic(); + r.WriteText(wxT("or italic ")); + r.EndItalic(); + r.BeginUnderline(); + r.WriteText(wxT("or underlined.")); + r.EndUnderline(); - r.BeginFontSize(14); - r.WriteText(wxT(" Different font sizes on the same line is allowed, too.")); - r.EndFontSize(); + r.BeginFontSize(14); + r.WriteText(wxT(" Different font sizes on the same line is allowed, too.")); + r.EndFontSize(); - r.WriteText(wxT(" Next we'll show an indented paragraph.")); + r.WriteText(wxT(" Next we'll show an indented paragraph.")); - r.BeginLeftIndent(60); - r.Newline(); + r.BeginLeftIndent(60); + r.Newline(); - r.WriteText(wxT("Indented paragraph.")); - r.EndLeftIndent(); + r.WriteText(wxT("Indented paragraph.")); + r.EndLeftIndent(); - r.Newline(); + r.Newline(); - r.WriteText(wxT("Next, we'll show a first-line indent, achieved using BeginLeftIndent(100, -40).")); + r.WriteText(wxT("Next, we'll show a first-line indent, achieved using BeginLeftIndent(100, -40).")); - r.BeginLeftIndent(100, -40); - r.Newline(); + r.BeginLeftIndent(100, -40); + r.Newline(); - r.WriteText(wxT("It was in January, the most down-trodden month of an Edinburgh winter.")); - r.EndLeftIndent(); + r.WriteText(wxT("It was in January, the most down-trodden month of an Edinburgh winter.")); + r.EndLeftIndent(); - r.Newline(); + r.Newline(); - r.WriteText(wxT("Numbered bullets are possible, again using subindents:")); + r.WriteText(wxT("Numbered bullets are possible, again using subindents:")); - r.BeginNumberedBullet(1, 100, 60); - r.Newline(); + r.BeginNumberedBullet(1, 100, 60); + r.Newline(); - r.WriteText(wxT("This is my first item. Note that wxRichTextCtrl doesn't automatically do numbering, but this will be added later.")); - r.EndNumberedBullet(); + r.WriteText( + wxT("This is my first item. Note that wxRichTextCtrl doesn't automatically do numbering, but this will be " + "added later.")); + r.EndNumberedBullet(); - r.BeginNumberedBullet(2, 100, 60); - r.Newline(); + r.BeginNumberedBullet(2, 100, 60); + r.Newline(); - r.WriteText(wxT("This is my second item.")); - r.EndNumberedBullet(); + r.WriteText(wxT("This is my second item.")); + r.EndNumberedBullet(); - r.Newline(); + r.Newline(); - r.WriteText(wxT("The following paragraph is right-indented:")); + r.WriteText(wxT("The following paragraph is right-indented:")); - r.BeginRightIndent(200); - r.Newline(); + r.BeginRightIndent(200); + r.Newline(); - r.WriteText(wxT("It was in January, the most down-trodden month of an Edinburgh winter. An attractive woman came into the cafe, which is nothing remarkable.")); - r.EndRightIndent(); + r.WriteText( + wxT("It was in January, the most down-trodden month of an Edinburgh winter. An attractive woman came into " + "the cafe, which is nothing remarkable.")); + r.EndRightIndent(); - r.Newline(); + r.Newline(); - wxArrayInt tabs; - tabs.Add(400); - tabs.Add(600); - tabs.Add(800); - tabs.Add(1000); - wxTextAttrEx attr; - attr.SetFlags(wxTEXT_ATTR_TABS); - attr.SetTabs(tabs); - r.SetDefaultStyle(attr); + wxArrayInt tabs; + tabs.Add(400); + tabs.Add(600); + tabs.Add(800); + tabs.Add(1000); + wxTextAttrEx attr; + attr.SetFlags(wxTEXT_ATTR_TABS); + attr.SetTabs(tabs); + r.SetDefaultStyle(attr); - r.WriteText(wxT("This line contains tabs:\tFirst tab\tSecond tab\tThird tab")); + r.WriteText(wxT("This line contains tabs:\tFirst tab\tSecond tab\tThird tab")); - r.Newline(); - r.WriteText(wxT("Other notable features of wxRichTextCtrl include:")); + r.Newline(); + r.WriteText(wxT("Other notable features of wxRichTextCtrl include:")); - r.BeginSymbolBullet(wxT('*'), 100, 60); - r.Newline(); - r.WriteText(wxT("Compatibility with wxTextCtrl API")); - r.EndSymbolBullet(); + r.BeginSymbolBullet(wxT('*'), 100, 60); + r.Newline(); + r.WriteText(wxT("Compatibility with wxTextCtrl API")); + r.EndSymbolBullet(); - r.WriteText(wxT("\nNote: this content was generated programmatically and copied from the sample. The images were loaded from inline XPMs. Enjoy wxRichTextCtrl!")); + r.WriteText( + wxT("\nNote: this content was generated programmatically and copied from the sample. The images were loaded " + "from inline XPMs. Enjoy wxRichTextCtrl!")); - r.EndSuppressUndo(); + r.EndSuppressUndo(); - return richText; - } + return richText; + } - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxRichTextCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); - return xrc.GetXrcObject(); - } + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxRichTextCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + return xrc.GetXrcObject(); + } - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxRichTextCtrl")); - filter.AddWindowProperties(); - filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); - return filter.GetXfbObject(); - } + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxRichTextCtrl")); + filter.AddWindowProperties(); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + return filter.GetXfbObject(); + } }; class HtmlWindowComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxHtmlWindow *hw = new wxHtmlWindow((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - wxString dummy_page( - wxT("wxHtmlWindow
") - wxT("This is a dummy page.")); - - hw->SetPage(dummy_page); - - return hw; - } - - ticpp::Element* ExportToXrc(IObject *obj) override - { - ObjectToXrcFilter xrc(obj, _("wxHtmlWindow"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxHtmlWindow")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxHtmlWindow* hw = new wxHtmlWindow( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + wxString dummy_page(wxT("wxHtmlWindow
") wxT("This is a dummy page.")); + + hw->SetPage(dummy_page); + + return hw; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxHtmlWindow"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxHtmlWindow")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; - class ToggleButtonComponent : public ComponentBase, public wxEvtHandler { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxString label = obj->GetPropertyAsString( _("label") ); - wxToggleButton* button = new wxToggleButton((wxWindow *)parent, wxID_ANY, - label, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - if (obj->GetPropertyAsInteger(_("markup")) != 0) { - button->SetLabelMarkup(label); - } - - if (!obj->IsNull(_("bitmap"))) { - button->SetBitmap(obj->GetPropertyAsBitmap(_("bitmap"))); - } - - if (!obj->IsNull(_("disabled"))) { - button->SetBitmapDisabled(obj->GetPropertyAsBitmap(_("disabled"))); - } - - if (!obj->IsNull(_("pressed"))) { - button->SetBitmapPressed(obj->GetPropertyAsBitmap(_("pressed"))); - } - - if (!obj->IsNull(_("focus"))) { - button->SetBitmapFocus(obj->GetPropertyAsBitmap(_("focus"))); - } - - if (!obj->IsNull(_("current"))) { - button->SetBitmapCurrent(obj->GetPropertyAsBitmap(_("current"))); - } - - if (!obj->IsNull(_("position"))) { - button->SetBitmapPosition( - static_cast(obj->GetPropertyAsInteger(_("position")))); - } - - if (!obj->IsNull(_("margins"))) { - button->SetBitmapMargins(obj->GetPropertyAsSize(_("margins"))); - } - - button->SetValue((obj->GetPropertyAsInteger(_("value")) != 0)); - button->Connect( wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, wxCommandEventHandler( ToggleButtonComponent::OnToggle ), NULL, this ); - return button; - } - - void OnToggle( wxCommandEvent& event ) - { - wxToggleButton* window = dynamic_cast< wxToggleButton* >( event.GetEventObject() ); - if ( 0 != window ) - { - wxString value; - value.Printf( wxT("%i"), window->GetValue() ? 1 : 0 ); - GetManager()->ModifyProperty( window, _("value"), value ); - window->SetFocus(); - } - } - - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxToggleButton"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - xrc.AddProperty(_("markup"), _("markup"), XRC_TYPE_BOOL); - xrc.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); - if (!obj->IsNull(_("disabled"))) { - xrc.AddProperty(_("disabled"), _("disabled"), XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("pressed"))) { - xrc.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("focus"))) { - xrc.AddProperty(_("focus"), _("focus"), XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("current"))) { - xrc.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("position"))) { - xrc.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); - } - if (!obj->IsNull(_("margins"))) { - xrc.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); - } - xrc.AddProperty(_("value"),_("checked"), XRC_TYPE_BOOL); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxToggleButton")); - filter.AddWindowProperties(); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - filter.AddProperty(_("markup"), _("markup"), XRC_TYPE_BOOL); - filter.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); - filter.AddProperty(_("disabled"), _("disabled"), XRC_TYPE_BITMAP); - filter.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); - filter.AddProperty(_("focus"), _("focus"), XRC_TYPE_BITMAP); - filter.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); - filter.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); - filter.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); - filter.AddProperty(_("checked"),_("value"), XRC_TYPE_BOOL); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxString label = obj->GetPropertyAsString(_("label")); + wxToggleButton* button = new wxToggleButton( + (wxWindow*)parent, wxID_ANY, label, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + if (obj->GetPropertyAsInteger(_("markup")) != 0) { + button->SetLabelMarkup(label); + } + + if (!obj->IsNull(_("bitmap"))) { + button->SetBitmap(obj->GetPropertyAsBitmap(_("bitmap"))); + } + + if (!obj->IsNull(_("disabled"))) { + button->SetBitmapDisabled(obj->GetPropertyAsBitmap(_("disabled"))); + } + + if (!obj->IsNull(_("pressed"))) { + button->SetBitmapPressed(obj->GetPropertyAsBitmap(_("pressed"))); + } + + if (!obj->IsNull(_("focus"))) { + button->SetBitmapFocus(obj->GetPropertyAsBitmap(_("focus"))); + } + + if (!obj->IsNull(_("current"))) { + button->SetBitmapCurrent(obj->GetPropertyAsBitmap(_("current"))); + } + + if (!obj->IsNull(_("position"))) { + button->SetBitmapPosition(static_cast(obj->GetPropertyAsInteger(_("position")))); + } + + if (!obj->IsNull(_("margins"))) { + button->SetBitmapMargins(obj->GetPropertyAsSize(_("margins"))); + } + + button->SetValue((obj->GetPropertyAsInteger(_("value")) != 0)); + button->Connect( + wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, wxCommandEventHandler(ToggleButtonComponent::OnToggle), NULL, this); + return button; + } + + void OnToggle(wxCommandEvent& event) + { + wxToggleButton* window = dynamic_cast(event.GetEventObject()); + if (0 != window) { + wxString value; + value.Printf(wxT("%i"), window->GetValue() ? 1 : 0); + GetManager()->ModifyProperty(window, _("value"), value); + window->SetFocus(); + } + } + + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxToggleButton"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("markup"), _("markup"), XRC_TYPE_BOOL); + xrc.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + if (!obj->IsNull(_("disabled"))) { + xrc.AddProperty(_("disabled"), _("disabled"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("pressed"))) { + xrc.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("focus"))) { + xrc.AddProperty(_("focus"), _("focus"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("current"))) { + xrc.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("position"))) { + xrc.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); + } + if (!obj->IsNull(_("margins"))) { + xrc.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); + } + xrc.AddProperty(_("value"), _("checked"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxToggleButton")); + filter.AddWindowProperties(); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + filter.AddProperty(_("markup"), _("markup"), XRC_TYPE_BOOL); + filter.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + filter.AddProperty(_("disabled"), _("disabled"), XRC_TYPE_BITMAP); + filter.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); + filter.AddProperty(_("focus"), _("focus"), XRC_TYPE_BITMAP); + filter.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); + filter.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); + filter.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); + filter.AddProperty(_("checked"), _("value"), XRC_TYPE_BOOL); + return filter.GetXfbObject(); + } }; class BitmapToggleButtonComponent : public ComponentBase, public wxEvtHandler { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxBitmapToggleButton* button = new wxBitmapToggleButton((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsBitmap(_("bitmap")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - // To stay in sync what the generator templates do apply the markup label here as well - if (obj->GetPropertyAsInteger(_("markup")) != 0) { - button->SetLabelMarkup(obj->GetPropertyAsString(_("label"))); - } - - if (!obj->IsNull(_("disabled"))) - { - button->SetBitmapDisabled( obj->GetPropertyAsBitmap( _("disabled") ) ); - } - - if (!obj->IsNull(_("pressed"))) { - button->SetBitmapPressed(obj->GetPropertyAsBitmap(_("pressed"))); - } - - if (!obj->IsNull(_("focus"))) - { - button->SetBitmapFocus( obj->GetPropertyAsBitmap( _("focus") ) ); - } - - if (!obj->IsNull(_("current"))) { - button->SetBitmapCurrent(obj->GetPropertyAsBitmap(_("current"))); - } - - if (!obj->IsNull(_("position"))) { - button->SetBitmapPosition( - static_cast(obj->GetPropertyAsInteger(_("position")))); - } - - if (!obj->IsNull(_("margins"))) { - button->SetBitmapMargins(obj->GetPropertyAsSize(_("margins"))); - } - - button->SetValue( ( obj->GetPropertyAsInteger(_("value")) != 0 ) ); - button->Connect( wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, wxCommandEventHandler( ToggleButtonComponent::OnToggle ), NULL, this ); - - return button; - } - - void OnToggle(wxCommandEvent& event) - { - wxBitmapToggleButton* window = dynamic_cast< wxBitmapToggleButton* >( event.GetEventObject() ); - if ( 0 != window ) - { - wxString value; - value.Printf( wxT("%i"), window->GetValue() ? 1 : 0 ); - GetManager()->ModifyProperty( window, _("value"), value ); - window->SetFocus(); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxBitmapToggleButton"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("bitmap"),_("bitmap"),XRC_TYPE_BITMAP); - if ( !obj->IsNull( _("disabled") ) ) - { - xrc.AddProperty(_("disabled"),_("disabled"),XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("pressed"))) { - xrc.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); - } - if ( !obj->IsNull( _("focus") ) ) - { - xrc.AddProperty(_("focus"),_("focus"),XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("current"))) { - xrc.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); - } - if (!obj->IsNull(_("position"))) { - xrc.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); - } - if (!obj->IsNull(_("margins"))) { - xrc.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); - } - xrc.AddProperty(_("value"),_("checked"), XRC_TYPE_BOOL); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxBitmapToggleButton")); - filter.AddWindowProperties(); - filter.AddProperty(_("bitmap"),_("bitmap"),XRC_TYPE_BITMAP); - filter.AddProperty(_("disabled"),_("disabled"),XRC_TYPE_BITMAP); - filter.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); - filter.AddProperty(_("focus"),_("focus"),XRC_TYPE_BITMAP); - filter.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); - filter.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); - filter.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); - filter.AddProperty(_("checked"),_("value"), XRC_TYPE_BOOL); - return filter.GetXfbObject(); - } - + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxBitmapToggleButton* button = new wxBitmapToggleButton( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsBitmap(_("bitmap")), obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + // To stay in sync what the generator templates do apply the markup label here as well + if (obj->GetPropertyAsInteger(_("markup")) != 0) { + button->SetLabelMarkup(obj->GetPropertyAsString(_("label"))); + } + + if (!obj->IsNull(_("disabled"))) { + button->SetBitmapDisabled(obj->GetPropertyAsBitmap(_("disabled"))); + } + + if (!obj->IsNull(_("pressed"))) { + button->SetBitmapPressed(obj->GetPropertyAsBitmap(_("pressed"))); + } + + if (!obj->IsNull(_("focus"))) { + button->SetBitmapFocus(obj->GetPropertyAsBitmap(_("focus"))); + } + + if (!obj->IsNull(_("current"))) { + button->SetBitmapCurrent(obj->GetPropertyAsBitmap(_("current"))); + } + + if (!obj->IsNull(_("position"))) { + button->SetBitmapPosition(static_cast(obj->GetPropertyAsInteger(_("position")))); + } + + if (!obj->IsNull(_("margins"))) { + button->SetBitmapMargins(obj->GetPropertyAsSize(_("margins"))); + } + + button->SetValue((obj->GetPropertyAsInteger(_("value")) != 0)); + button->Connect( + wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, wxCommandEventHandler(ToggleButtonComponent::OnToggle), NULL, this); + + return button; + } + + void OnToggle(wxCommandEvent& event) + { + wxBitmapToggleButton* window = dynamic_cast(event.GetEventObject()); + if (0 != window) { + wxString value; + value.Printf(wxT("%i"), window->GetValue() ? 1 : 0); + GetManager()->ModifyProperty(window, _("value"), value); + window->SetFocus(); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxBitmapToggleButton"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + if (!obj->IsNull(_("disabled"))) { + xrc.AddProperty(_("disabled"), _("disabled"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("pressed"))) { + xrc.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("focus"))) { + xrc.AddProperty(_("focus"), _("focus"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("current"))) { + xrc.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); + } + if (!obj->IsNull(_("position"))) { + xrc.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); + } + if (!obj->IsNull(_("margins"))) { + xrc.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); + } + xrc.AddProperty(_("value"), _("checked"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxBitmapToggleButton")); + filter.AddWindowProperties(); + filter.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + filter.AddProperty(_("disabled"), _("disabled"), XRC_TYPE_BITMAP); + filter.AddProperty(_("pressed"), _("pressed"), XRC_TYPE_BITMAP); + filter.AddProperty(_("focus"), _("focus"), XRC_TYPE_BITMAP); + filter.AddProperty(_("current"), _("current"), XRC_TYPE_BITMAP); + filter.AddProperty(_("position"), _("position"), XRC_TYPE_TEXT); + filter.AddProperty(_("margins"), _("margins"), XRC_TYPE_SIZE); + filter.AddProperty(_("checked"), _("value"), XRC_TYPE_BOOL); + return filter.GetXfbObject(); + } }; class TreeCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - int style = obj->GetPropertyAsInteger(_("style")); - wxTreeCtrl *tc = new wxTreeCtrl((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - style | obj->GetPropertyAsInteger(_("window_style"))); - - // dummy nodes - wxTreeItemId root = tc->AddRoot(wxT("root node")); - wxTreeItemId node1 = tc->AppendItem(root,wxT("node1")); - wxTreeItemId node2 = tc->AppendItem(root,wxT("node2")); - wxTreeItemId node3 = tc->AppendItem(node2,wxT("node3")); - if ( ( style & wxTR_HIDE_ROOT ) == 0 ) - { - tc->Expand(root); - } - tc->Expand(node1); - tc->Expand(node2); - tc->Expand(node3); - - return tc; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxTreeCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxTreeCtrl")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + int style = obj->GetPropertyAsInteger(_("style")); + wxTreeCtrl* tc = new wxTreeCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + style | obj->GetPropertyAsInteger(_("window_style"))); + + // dummy nodes + wxTreeItemId root = tc->AddRoot(wxT("root node")); + wxTreeItemId node1 = tc->AppendItem(root, wxT("node1")); + wxTreeItemId node2 = tc->AppendItem(root, wxT("node2")); + wxTreeItemId node3 = tc->AppendItem(node2, wxT("node3")); + if ((style & wxTR_HIDE_ROOT) == 0) { + tc->Expand(root); + } + tc->Expand(node1); + tc->Expand(node2); + tc->Expand(node3); + + return tc; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxTreeCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxTreeCtrl")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class ScrollBarComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxScrollBar *sb = new wxScrollBar((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - sb->SetScrollbar(obj->GetPropertyAsInteger(_T("value")), - obj->GetPropertyAsInteger(_T("thumbsize")), - obj->GetPropertyAsInteger(_T("range")), - obj->GetPropertyAsInteger(_T("pagesize"))); - return sb; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxScrollBar"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("value"), _("value"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("thumbsize"), _("thumbsize"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("range"), _("range"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("pagesize"), _("pagesize"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxScrollBar")); - filter.AddWindowProperties(); - filter.AddProperty(_("value"), _("value"), XRC_TYPE_INTEGER); - filter.AddProperty(_("thumbsize"), _("thumbsize"), XRC_TYPE_INTEGER); - filter.AddProperty(_("range"), _("range"), XRC_TYPE_INTEGER); - filter.AddProperty(_("pagesize"), _("pagesize"), XRC_TYPE_INTEGER); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxScrollBar* sb = new wxScrollBar( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + sb->SetScrollbar( + obj->GetPropertyAsInteger(_T("value")), obj->GetPropertyAsInteger(_T("thumbsize")), + obj->GetPropertyAsInteger(_T("range")), obj->GetPropertyAsInteger(_T("pagesize"))); + return sb; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxScrollBar"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("value"), _("value"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("thumbsize"), _("thumbsize"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("range"), _("range"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("pagesize"), _("pagesize"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxScrollBar")); + filter.AddWindowProperties(); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_INTEGER); + filter.AddProperty(_("thumbsize"), _("thumbsize"), XRC_TYPE_INTEGER); + filter.AddProperty(_("range"), _("range"), XRC_TYPE_INTEGER); + filter.AddProperty(_("pagesize"), _("pagesize"), XRC_TYPE_INTEGER); + return filter.GetXfbObject(); + } }; class SpinCtrlComponent : public ComponentBase, public wxEvtHandler { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - int max = obj->GetPropertyAsInteger(_("max")); - int min = obj->GetPropertyAsInteger(_("min")); - wxSpinCtrl* window = new wxSpinCtrl((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsString(_("value")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")), - min < max ? min : max, - max, - obj->GetPropertyAsInteger(_("initial"))); - - window->Connect( wxEVT_COMMAND_SPINCTRL_UPDATED, wxSpinEventHandler( SpinCtrlComponent::OnSpin ), NULL, this ); - return window; - } - - void OnSpin( wxSpinEvent& event ) - { - wxSpinCtrl* window = dynamic_cast< wxSpinCtrl* >( event.GetEventObject() ); - if ( 0 != window ) - { - wxString value; - value.Printf( wxT("%i"), window->GetValue() ); - GetManager()->ModifyProperty( window, _("initial"), value ); - window->SetFocus(); - } - } - - void Cleanup(wxObject* obj) override { - wxSpinCtrl* window = dynamic_cast< wxSpinCtrl* >( obj ); - if ( 0 != window ) - { - window->Disconnect( wxEVT_COMMAND_SPINCTRL_UPDATED, wxSpinEventHandler( SpinCtrlComponent::OnSpin ), NULL, this ); - } - ComponentBase::Cleanup( obj ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxSpinCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("initial"),_("value"), XRC_TYPE_TEXT); - xrc.AddProperty(_("min"),_("min"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("max"),_("max"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxSpinCtrl")); - filter.AddWindowProperties(); - filter.AddProperty(_("value"),_("value"), XRC_TYPE_TEXT); - filter.AddProperty(_("value"),_("initial"), XRC_TYPE_TEXT); - filter.AddProperty(_("min"),_("min"), XRC_TYPE_INTEGER); - filter.AddProperty(_("max"),_("max"), XRC_TYPE_INTEGER); - - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + int max = obj->GetPropertyAsInteger(_("max")); + int min = obj->GetPropertyAsInteger(_("min")); + wxSpinCtrl* window = new wxSpinCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("value")), obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")), min < max ? min : max, + max, obj->GetPropertyAsInteger(_("initial"))); + + window->Connect(wxEVT_COMMAND_SPINCTRL_UPDATED, wxSpinEventHandler(SpinCtrlComponent::OnSpin), NULL, this); + return window; + } + + void OnSpin(wxSpinEvent& event) + { + wxSpinCtrl* window = dynamic_cast(event.GetEventObject()); + if (0 != window) { + wxString value; + value.Printf(wxT("%i"), window->GetValue()); + GetManager()->ModifyProperty(window, _("initial"), value); + window->SetFocus(); + } + } + + void Cleanup(wxObject* obj) override + { + wxSpinCtrl* window = dynamic_cast(obj); + if (0 != window) { + window->Disconnect( + wxEVT_COMMAND_SPINCTRL_UPDATED, wxSpinEventHandler(SpinCtrlComponent::OnSpin), NULL, this); + } + ComponentBase::Cleanup(obj); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxSpinCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("initial"), _("value"), XRC_TYPE_TEXT); + xrc.AddProperty(_("min"), _("min"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("max"), _("max"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxSpinCtrl")); + filter.AddWindowProperties(); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + filter.AddProperty(_("value"), _("initial"), XRC_TYPE_TEXT); + filter.AddProperty(_("min"), _("min"), XRC_TYPE_INTEGER); + filter.AddProperty(_("max"), _("max"), XRC_TYPE_INTEGER); + + return filter.GetXfbObject(); + } }; class SpinCtrlDoubleComponent : public ComponentBase, public wxEvtHandler { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxSpinCtrlDouble* window = new wxSpinCtrlDouble((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsString(_("value")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")), - obj->GetPropertyAsFloat(_("min")), - obj->GetPropertyAsFloat(_("max")), - obj->GetPropertyAsFloat(_("initial")), - obj->GetPropertyAsFloat(_("inc"))); - - window->SetDigits(obj->GetPropertyAsInteger(_("digits"))); - - window->Connect( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, wxSpinEventHandler( SpinCtrlDoubleComponent::OnSpin ), NULL, this ); - return window; - } - - void OnSpin( wxSpinEvent& event ) - { - wxSpinCtrlDouble* window = dynamic_cast< wxSpinCtrlDouble* >( event.GetEventObject() ); - if ( 0 != window ) - { - wxString value; - value.Printf( wxT("%f"), window->GetValue() ); - GetManager()->ModifyProperty( window, _("initial"), value ); - window->SetFocus(); - } - } - - void Cleanup(wxObject* obj) override { - wxSpinCtrlDouble* window = dynamic_cast< wxSpinCtrlDouble* >( obj ); - if ( 0 != window ) - { - window->Disconnect( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, wxSpinEventHandler( SpinCtrlDoubleComponent::OnSpin ), NULL, this ); - } - ComponentBase::Cleanup( obj ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxSpinCtrlDouble"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("initial"),_("value"), XRC_TYPE_TEXT); - xrc.AddProperty(_("min"),_("min"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("max"),_("max"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("inc"),_("inc"), XRC_TYPE_FLOAT); - xrc.AddProperty(_("digits"), _("digits"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxSpinCtrl")); - filter.AddWindowProperties(); - filter.AddProperty(_("value"),_("value"), XRC_TYPE_TEXT); - filter.AddProperty(_("value"),_("initial"), XRC_TYPE_TEXT); - filter.AddProperty(_("min"),_("min"), XRC_TYPE_INTEGER); - filter.AddProperty(_("max"),_("max"), XRC_TYPE_INTEGER); - filter.AddProperty(_("inc"),_("inc"), XRC_TYPE_FLOAT); - filter.AddProperty(_("digits"), _("digits"), XRC_TYPE_INTEGER); - - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxSpinCtrlDouble* window = new wxSpinCtrlDouble( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("value")), obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")), + obj->GetPropertyAsFloat(_("min")), obj->GetPropertyAsFloat(_("max")), obj->GetPropertyAsFloat(_("initial")), + obj->GetPropertyAsFloat(_("inc"))); + + window->SetDigits(obj->GetPropertyAsInteger(_("digits"))); + + window->Connect( + wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, wxSpinEventHandler(SpinCtrlDoubleComponent::OnSpin), NULL, this); + return window; + } + + void OnSpin(wxSpinEvent& event) + { + wxSpinCtrlDouble* window = dynamic_cast(event.GetEventObject()); + if (0 != window) { + wxString value; + value.Printf(wxT("%f"), window->GetValue()); + GetManager()->ModifyProperty(window, _("initial"), value); + window->SetFocus(); + } + } + + void Cleanup(wxObject* obj) override + { + wxSpinCtrlDouble* window = dynamic_cast(obj); + if (0 != window) { + window->Disconnect( + wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, wxSpinEventHandler(SpinCtrlDoubleComponent::OnSpin), NULL, this); + } + ComponentBase::Cleanup(obj); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxSpinCtrlDouble"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("initial"), _("value"), XRC_TYPE_TEXT); + xrc.AddProperty(_("min"), _("min"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("max"), _("max"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("inc"), _("inc"), XRC_TYPE_FLOAT); + xrc.AddProperty(_("digits"), _("digits"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxSpinCtrl")); + filter.AddWindowProperties(); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + filter.AddProperty(_("value"), _("initial"), XRC_TYPE_TEXT); + filter.AddProperty(_("min"), _("min"), XRC_TYPE_INTEGER); + filter.AddProperty(_("max"), _("max"), XRC_TYPE_INTEGER); + filter.AddProperty(_("inc"), _("inc"), XRC_TYPE_FLOAT); + filter.AddProperty(_("digits"), _("digits"), XRC_TYPE_INTEGER); + + return filter.GetXfbObject(); + } }; class SpinButtonComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - return new wxSpinButton((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxSpinButton"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxSpinButton")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + return new wxSpinButton( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxSpinButton"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxSpinButton")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class CheckListBoxComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxArrayString choices (obj->GetPropertyAsArrayString(_("choices"))); - wxCheckListBox *cl = - new wxCheckListBox((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - choices, - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - return cl; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxCheckListBox"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("choices"), _("content"), XRC_TYPE_STRINGLIST); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxCheckListBox")); - filter.AddWindowProperties(); - filter.AddProperty(_("content"), _("choices"), XRC_TYPE_STRINGLIST); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxArrayString choices(obj->GetPropertyAsArrayString(_("choices"))); + wxCheckListBox* cl = new wxCheckListBox( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), choices, + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + return cl; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxCheckListBox"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("choices"), _("content"), XRC_TYPE_STRINGLIST); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxCheckListBox")); + filter.AddWindowProperties(); + filter.AddProperty(_("content"), _("choices"), XRC_TYPE_STRINGLIST); + return filter.GetXfbObject(); + } }; class GridComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxGrid *grid = new wxGrid((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("window_style"))); - - grid->CreateGrid( - obj->GetPropertyAsInteger(_("rows")), - obj->GetPropertyAsInteger(_("cols"))); - - grid->EnableDragColMove( obj->GetPropertyAsInteger( _("drag_col_move") ) != 0 ); - grid->EnableDragColSize( obj->GetPropertyAsInteger( _("drag_col_size") ) != 0 ); - grid->EnableDragGridSize( obj->GetPropertyAsInteger( _("drag_grid_size") ) != 0 ); - grid->EnableDragRowSize( obj->GetPropertyAsInteger( _("drag_row_size") ) != 0 ); - grid->EnableEditing( obj->GetPropertyAsInteger( _("editing") ) != 0 ); - grid->EnableGridLines( obj->GetPropertyAsInteger( _("grid_lines") ) != 0 ); - if ( !obj->IsNull( _("grid_line_color") ) ) - { - grid->SetGridLineColour( obj->GetPropertyAsColour( _("grid_line_color") ) ); - } - grid->SetMargins( obj->GetPropertyAsInteger( _("margin_width") ), obj->GetPropertyAsInteger( _("margin_height") ) ); - - // Label Properties - grid->SetColLabelAlignment( obj->GetPropertyAsInteger( _("col_label_horiz_alignment") ), obj->GetPropertyAsInteger( _("col_label_vert_alignment") ) ); - - wxArrayString columnLabels = obj->GetPropertyAsArrayString( _("col_label_values") ); - for ( int i = 0; i < (int)columnLabels.size() && i < grid->GetNumberCols(); ++i ) - { - grid->SetColLabelValue( i, columnLabels[i] ); - } - - if ( !obj->IsNull( _("col_label_size") ) ) - { - grid->SetColLabelSize( obj->GetPropertyAsInteger( _("col_label_size") ) ); - } - - wxArrayInt columnSizes = obj->GetPropertyAsArrayInt( _("column_sizes") ); - for ( int i = 0; i < (int)columnSizes.size() && i < grid->GetNumberCols(); ++i ) - { - grid->SetColSize( i, columnSizes[i] ); - } - - grid->SetRowLabelAlignment( obj->GetPropertyAsInteger( _("row_label_horiz_alignment") ), obj->GetPropertyAsInteger( _("row_label_vert_alignment") ) ); - - wxArrayString rowLabels = obj->GetPropertyAsArrayString( _("row_label_values") ); - for ( int i = 0; i < (int)rowLabels.size() && i < grid->GetNumberRows(); ++i ) - { - grid->SetRowLabelValue( i, rowLabels[i] ); - } - - if ( !obj->IsNull( _("row_label_size") ) ) - { - grid->SetRowLabelSize( obj->GetPropertyAsInteger( _("row_label_size") ) ); - } - - wxArrayInt rowSizes = obj->GetPropertyAsArrayInt( _("row_sizes") ); - for ( int i = 0; i < (int)rowSizes.size() && i < grid->GetNumberRows(); ++i ) - { - grid->SetRowSize( i, rowSizes[i] ); - } - - if ( !obj->IsNull( _("label_bg") ) ) - { - grid->SetLabelBackgroundColour( obj->GetPropertyAsColour( _("label_bg") ) ); - } - if ( !obj->IsNull( _("label_text") ) ) - { - grid->SetLabelTextColour( obj->GetPropertyAsColour( _("label_text") ) ); - } - if ( !obj->IsNull( _("label_font") ) ) - { - grid->SetLabelFont( obj->GetPropertyAsFont( _("label_font") ) ); - } - - // Default Cell Properties - grid->SetDefaultCellAlignment( obj->GetPropertyAsInteger( _("cell_horiz_alignment") ), obj->GetPropertyAsInteger( _("cell_vert_alignment") ) ); - - if ( !obj->IsNull( _("cell_bg") ) ) - { - grid->SetDefaultCellBackgroundColour( obj->GetPropertyAsColour( _("cell_bg") ) ); - } - if ( !obj->IsNull( _("cell_text") ) ) - { - grid->SetDefaultCellTextColour( obj->GetPropertyAsColour( _("cell_text") ) ); - } - if ( !obj->IsNull( _("cell_font") ) ) - { - grid->SetDefaultCellFont( obj->GetPropertyAsFont( _("cell_font") ) ); - } - - // Example Cell Values - for ( int col = 0; col < grid->GetNumberCols(); ++col ) - { - for ( int row = 0; row < grid->GetNumberRows(); ++row ) - { - grid->SetCellValue( row, col, grid->GetColLabelValue( col ) + wxT("-") + grid->GetRowLabelValue( row ) ); - } - } - - if ( obj->GetPropertyAsInteger( _("autosize_rows") ) != 0 ) - { - grid->AutoSizeRows(); - } - if ( obj->GetPropertyAsInteger( _("autosize_cols") ) != 0 ) - { - grid->AutoSizeColumns(); - } - - grid->PushEventHandler( new ComponentEvtHandler( grid, GetManager() ) ); - - return grid; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxGrid); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxGrid"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxGrid")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxGrid* grid = new wxGrid( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("window_style"))); + + grid->CreateGrid(obj->GetPropertyAsInteger(_("rows")), obj->GetPropertyAsInteger(_("cols"))); + + grid->EnableDragColMove(obj->GetPropertyAsInteger(_("drag_col_move")) != 0); + grid->EnableDragColSize(obj->GetPropertyAsInteger(_("drag_col_size")) != 0); + grid->EnableDragGridSize(obj->GetPropertyAsInteger(_("drag_grid_size")) != 0); + grid->EnableDragRowSize(obj->GetPropertyAsInteger(_("drag_row_size")) != 0); + grid->EnableEditing(obj->GetPropertyAsInteger(_("editing")) != 0); + grid->EnableGridLines(obj->GetPropertyAsInteger(_("grid_lines")) != 0); + if (!obj->IsNull(_("grid_line_color"))) { + grid->SetGridLineColour(obj->GetPropertyAsColour(_("grid_line_color"))); + } + grid->SetMargins(obj->GetPropertyAsInteger(_("margin_width")), obj->GetPropertyAsInteger(_("margin_height"))); + + // Label Properties + grid->SetColLabelAlignment( + obj->GetPropertyAsInteger(_("col_label_horiz_alignment")), + obj->GetPropertyAsInteger(_("col_label_vert_alignment"))); + + wxArrayString columnLabels = obj->GetPropertyAsArrayString(_("col_label_values")); + for (int i = 0; i < (int)columnLabels.size() && i < grid->GetNumberCols(); ++i) { + grid->SetColLabelValue(i, columnLabels[i]); + } + + if (!obj->IsNull(_("col_label_size"))) { + grid->SetColLabelSize(obj->GetPropertyAsInteger(_("col_label_size"))); + } + + wxArrayInt columnSizes = obj->GetPropertyAsArrayInt(_("column_sizes")); + for (int i = 0; i < (int)columnSizes.size() && i < grid->GetNumberCols(); ++i) { + grid->SetColSize(i, columnSizes[i]); + } + + grid->SetRowLabelAlignment( + obj->GetPropertyAsInteger(_("row_label_horiz_alignment")), + obj->GetPropertyAsInteger(_("row_label_vert_alignment"))); + + wxArrayString rowLabels = obj->GetPropertyAsArrayString(_("row_label_values")); + for (int i = 0; i < (int)rowLabels.size() && i < grid->GetNumberRows(); ++i) { + grid->SetRowLabelValue(i, rowLabels[i]); + } + + if (!obj->IsNull(_("row_label_size"))) { + grid->SetRowLabelSize(obj->GetPropertyAsInteger(_("row_label_size"))); + } + + wxArrayInt rowSizes = obj->GetPropertyAsArrayInt(_("row_sizes")); + for (int i = 0; i < (int)rowSizes.size() && i < grid->GetNumberRows(); ++i) { + grid->SetRowSize(i, rowSizes[i]); + } + + if (!obj->IsNull(_("label_bg"))) { + grid->SetLabelBackgroundColour(obj->GetPropertyAsColour(_("label_bg"))); + } + if (!obj->IsNull(_("label_text"))) { + grid->SetLabelTextColour(obj->GetPropertyAsColour(_("label_text"))); + } + if (!obj->IsNull(_("label_font"))) { + grid->SetLabelFont(obj->GetPropertyAsFont(_("label_font"))); + } + + // Default Cell Properties + grid->SetDefaultCellAlignment( + obj->GetPropertyAsInteger(_("cell_horiz_alignment")), obj->GetPropertyAsInteger(_("cell_vert_alignment"))); + + if (!obj->IsNull(_("cell_bg"))) { + grid->SetDefaultCellBackgroundColour(obj->GetPropertyAsColour(_("cell_bg"))); + } + if (!obj->IsNull(_("cell_text"))) { + grid->SetDefaultCellTextColour(obj->GetPropertyAsColour(_("cell_text"))); + } + if (!obj->IsNull(_("cell_font"))) { + grid->SetDefaultCellFont(obj->GetPropertyAsFont(_("cell_font"))); + } + + // Example Cell Values + for (int col = 0; col < grid->GetNumberCols(); ++col) { + for (int row = 0; row < grid->GetNumberRows(); ++row) { + grid->SetCellValue(row, col, grid->GetColLabelValue(col) + wxT("-") + grid->GetRowLabelValue(row)); + } + } + + if (obj->GetPropertyAsInteger(_("autosize_rows")) != 0) { + grid->AutoSizeRows(); + } + if (obj->GetPropertyAsInteger(_("autosize_cols")) != 0) { + grid->AutoSizeColumns(); + } + + grid->PushEventHandler(new ComponentEvtHandler(grid, GetManager())); + + return grid; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxGrid); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxGrid"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxGrid")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnGridClick( wxGridEvent& event ) +void ComponentEvtHandler::OnGridClick(wxGridEvent& event) { - m_manager->SelectObject( m_window ); - event.Skip(); + m_manager->SelectObject(m_window); + event.Skip(); } -void ComponentEvtHandler::OnGridColSize( wxGridSizeEvent& ) +void ComponentEvtHandler::OnGridColSize(wxGridSizeEvent&) { - wxGrid* grid = wxDynamicCast( m_window, wxGrid ); - if ( NULL == grid ) - { - return; - } + wxGrid* grid = wxDynamicCast(m_window, wxGrid); + if (NULL == grid) { + return; + } - wxString sizes; - for ( int i = 0; i < grid->GetNumberCols(); ++i ) - { - sizes += wxString::Format( wxT("%i,"), grid->GetColSize( i ) ); - } - sizes = sizes.substr( 0, sizes.length() - 1 ); + wxString sizes; + for (int i = 0; i < grid->GetNumberCols(); ++i) { sizes += wxString::Format(wxT("%i,"), grid->GetColSize(i)); } + sizes = sizes.substr(0, sizes.length() - 1); - m_manager->ModifyProperty( m_window, _("column_sizes"), sizes, true ); + m_manager->ModifyProperty(m_window, _("column_sizes"), sizes, true); } -void ComponentEvtHandler::OnGridRowSize( wxGridSizeEvent& ) +void ComponentEvtHandler::OnGridRowSize(wxGridSizeEvent&) { - wxGrid* grid = wxDynamicCast( m_window, wxGrid ); - if ( NULL == grid ) - { - return; - } + wxGrid* grid = wxDynamicCast(m_window, wxGrid); + if (NULL == grid) { + return; + } - wxString sizes; - for ( int i = 0; i < grid->GetNumberRows(); ++i ) - { - sizes += wxString::Format( wxT("%i,"), grid->GetRowSize( i ) ); - } - sizes = sizes.substr( 0, sizes.length() - 1 ); + wxString sizes; + for (int i = 0; i < grid->GetNumberRows(); ++i) { sizes += wxString::Format(wxT("%i,"), grid->GetRowSize(i)); } + sizes = sizes.substr(0, sizes.length() - 1); - m_manager->ModifyProperty( m_window, _("row_sizes"), sizes, true ); + m_manager->ModifyProperty(m_window, _("row_sizes"), sizes, true); } class PickerComponentBase : public ComponentBase, public wxEvtHandler { public: - void OnLeftClick( wxMouseEvent& event ) - { - wxWindow* window = dynamic_cast< wxWindow* >( event.GetEventObject() ); - wxPickerBase* picker = dynamic_cast< wxPickerBase* >( window->GetParent() ); - if ( 0 != picker ) - { - if ( !GetManager()->SelectObject( picker ) ) - { - event.Skip(); - } - } - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxPickerBase* picker = dynamic_cast< wxPickerBase* >( wxobject ); - if ( picker != 0 ) - { - picker->GetPickerCtrl()->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( PickerComponentBase::OnLeftClick ), NULL, this ); - - wxTextCtrl* text = picker->GetTextCtrl(); - if ( 0 != text ) - { - text->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( PickerComponentBase::OnLeftClick ), NULL, this ); - } - } - } - - void Cleanup(wxObject* obj) override { - wxPickerBase* picker = dynamic_cast< wxPickerBase* >( obj ); - if ( picker != 0 ) - { - picker->GetPickerCtrl()->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( PickerComponentBase::OnLeftClick ), NULL, this ); - - wxTextCtrl* text = picker->GetTextCtrl(); - if ( 0 != text ) - { - text->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( PickerComponentBase::OnLeftClick ), NULL, this ); - } - } - ComponentBase::Cleanup( obj ); - } + void OnLeftClick(wxMouseEvent& event) + { + wxWindow* window = dynamic_cast(event.GetEventObject()); + wxPickerBase* picker = dynamic_cast(window->GetParent()); + if (0 != picker) { + if (!GetManager()->SelectObject(picker)) { + event.Skip(); + } + } + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxPickerBase* picker = dynamic_cast(wxobject); + if (picker != 0) { + picker->GetPickerCtrl()->Connect( + wxEVT_LEFT_DOWN, wxMouseEventHandler(PickerComponentBase::OnLeftClick), NULL, this); + + wxTextCtrl* text = picker->GetTextCtrl(); + if (0 != text) { + text->Connect(wxEVT_LEFT_DOWN, wxMouseEventHandler(PickerComponentBase::OnLeftClick), NULL, this); + } + } + } + + void Cleanup(wxObject* obj) override + { + wxPickerBase* picker = dynamic_cast(obj); + if (picker != 0) { + picker->GetPickerCtrl()->Disconnect( + wxEVT_LEFT_DOWN, wxMouseEventHandler(PickerComponentBase::OnLeftClick), NULL, this); + + wxTextCtrl* text = picker->GetTextCtrl(); + if (0 != text) { + text->Disconnect(wxEVT_LEFT_DOWN, wxMouseEventHandler(PickerComponentBase::OnLeftClick), NULL, this); + } + } + ComponentBase::Cleanup(obj); + } }; class ColourPickerComponent : public PickerComponentBase { private: - public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxColourPickerCtrl* colourpicker = new wxColourPickerCtrl( - (wxWindow*)parent, - obj->GetPropertyAsInteger(_("id")), - obj->GetPropertyAsColour(_("colour")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) - ); - - colourpicker->PushEventHandler( new ComponentEvtHandler( colourpicker, GetManager() ) ); - return colourpicker; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxColourPickerCtrl); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxColourPickerCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddProperty(_("colour"),_("value"),XRC_TYPE_COLOUR); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxColourPickerCtrl")); - filter.AddProperty(_("value"),_("colour"),XRC_TYPE_COLOUR); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxColourPickerCtrl* colourpicker = new wxColourPickerCtrl( + (wxWindow*)parent, obj->GetPropertyAsInteger(_("id")), obj->GetPropertyAsColour(_("colour")), + obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + colourpicker->PushEventHandler(new ComponentEvtHandler(colourpicker, GetManager())); + return colourpicker; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxColourPickerCtrl); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxColourPickerCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddProperty(_("colour"), _("value"), XRC_TYPE_COLOUR); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxColourPickerCtrl")); + filter.AddProperty(_("value"), _("colour"), XRC_TYPE_COLOUR); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnColourPickerColourChanged( wxColourPickerEvent& ) +void ComponentEvtHandler::OnColourPickerColourChanged(wxColourPickerEvent&) { - wxColourPickerCtrl* window = wxDynamicCast( m_window, wxColourPickerCtrl ); - if ( window != NULL ) - { - wxColour colour = window->GetColour(); - m_manager->ModifyProperty( window, _("colour"), wxString::Format(wxT("%d,%d,%d"),colour.Red(),colour.Green(),colour.Blue()) ); - } + wxColourPickerCtrl* window = wxDynamicCast(m_window, wxColourPickerCtrl); + if (window != NULL) { + wxColour colour = window->GetColour(); + m_manager->ModifyProperty( + window, _("colour"), wxString::Format(wxT("%d,%d,%d"), colour.Red(), colour.Green(), colour.Blue())); + } } class FontPickerComponent : public PickerComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxFontPickerCtrl* picker = new wxFontPickerCtrl( - (wxWindow*)parent, - obj->GetPropertyAsInteger(_("id")), - obj->GetPropertyAsFont(_("value")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) - ); - - if ( !obj->IsNull( _("max_point_size") ) ) - { - picker->SetMaxPointSize( obj->GetPropertyAsInteger( _("max_point_size") ) ); - } - - picker->PushEventHandler( new ComponentEvtHandler( picker, GetManager() ) ); - return picker; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxFontPickerCtrl); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxFontPickerCtrl"), obj->GetPropertyAsString(_("name"))); - if ( !obj->IsNull( _("value") ) ) - { - xrc.AddProperty(_("value"),_("value"),XRC_TYPE_FONT); - } - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxFontPickerCtrl")); - filter.AddProperty(_("value"),_("value"),XRC_TYPE_FONT); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxFontPickerCtrl* picker = new wxFontPickerCtrl( + (wxWindow*)parent, obj->GetPropertyAsInteger(_("id")), obj->GetPropertyAsFont(_("value")), + obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + if (!obj->IsNull(_("max_point_size"))) { + picker->SetMaxPointSize(obj->GetPropertyAsInteger(_("max_point_size"))); + } + + picker->PushEventHandler(new ComponentEvtHandler(picker, GetManager())); + return picker; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxFontPickerCtrl); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxFontPickerCtrl"), obj->GetPropertyAsString(_("name"))); + if (!obj->IsNull(_("value"))) { + xrc.AddProperty(_("value"), _("value"), XRC_TYPE_FONT); + } + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxFontPickerCtrl")); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_FONT); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnFontPickerFontChanged( wxFontPickerEvent& ) +void ComponentEvtHandler::OnFontPickerFontChanged(wxFontPickerEvent&) { - wxFontPickerCtrl* window = wxDynamicCast( m_window, wxFontPickerCtrl ); - if ( window != NULL ) - { - wxFont font = window->GetSelectedFont(); - m_manager->ModifyProperty( window, _("value"), wxString::Format( wxT("%s,%d,%d,%d"), font.GetFaceName().c_str(), font.GetStyle(), font.GetWeight(), font.GetPointSize() ) ); - } + wxFontPickerCtrl* window = wxDynamicCast(m_window, wxFontPickerCtrl); + if (window != NULL) { + wxFont font = window->GetSelectedFont(); + m_manager->ModifyProperty( + window, _("value"), + wxString::Format( + wxT("%s,%d,%d,%d"), font.GetFaceName().c_str(), font.GetStyle(), font.GetWeight(), font.GetPointSize())); + } } class FilePickerComponent : public PickerComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxFilePickerCtrl* picker = new wxFilePickerCtrl( - (wxWindow*)parent, - obj->GetPropertyAsInteger(_("id")), - obj->GetPropertyAsString(_("value")), - obj->GetPropertyAsString(_("message")), - obj->GetPropertyAsString(_("wildcard")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) - ); - - picker->PushEventHandler( new ComponentEvtHandler( picker, GetManager() ) ); - return picker; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxFilePickerCtrl); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxFilePickerCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddProperty(_("value"),_("value"),XRC_TYPE_TEXT); - xrc.AddProperty(_("message"),_("message"),XRC_TYPE_TEXT); - xrc.AddProperty(_("wildcard"),_("wildcard"),XRC_TYPE_TEXT); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxFilePickerCtrl")); - filter.AddProperty(_("value"),_("value"),XRC_TYPE_TEXT); - filter.AddProperty(_("message"),_("message"),XRC_TYPE_TEXT); - filter.AddProperty(_("wildcard"),_("wildcard"),XRC_TYPE_TEXT); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxFilePickerCtrl* picker = new wxFilePickerCtrl( + (wxWindow*)parent, obj->GetPropertyAsInteger(_("id")), obj->GetPropertyAsString(_("value")), + obj->GetPropertyAsString(_("message")), obj->GetPropertyAsString(_("wildcard")), + obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + picker->PushEventHandler(new ComponentEvtHandler(picker, GetManager())); + return picker; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxFilePickerCtrl); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxFilePickerCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + xrc.AddProperty(_("message"), _("message"), XRC_TYPE_TEXT); + xrc.AddProperty(_("wildcard"), _("wildcard"), XRC_TYPE_TEXT); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxFilePickerCtrl")); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + filter.AddProperty(_("message"), _("message"), XRC_TYPE_TEXT); + filter.AddProperty(_("wildcard"), _("wildcard"), XRC_TYPE_TEXT); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnFilePickerFileChanged( wxFileDirPickerEvent& ) +void ComponentEvtHandler::OnFilePickerFileChanged(wxFileDirPickerEvent&) { - wxFilePickerCtrl* window = wxDynamicCast( m_window, wxFilePickerCtrl ); - if ( window != NULL ) - { - m_manager->ModifyProperty( window, _("value"), window->GetPath() ); - } + wxFilePickerCtrl* window = wxDynamicCast(m_window, wxFilePickerCtrl); + if (window != NULL) { + m_manager->ModifyProperty(window, _("value"), window->GetPath()); + } } class DirPickerComponent : public PickerComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxDirPickerCtrl* picker = new wxDirPickerCtrl( - (wxWindow*)parent, - obj->GetPropertyAsInteger(_("id")), - obj->GetPropertyAsString(_("value")), - obj->GetPropertyAsString(_("message")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) - ); - - picker->PushEventHandler( new ComponentEvtHandler( picker, GetManager() ) ); - return picker; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxDirPickerCtrl); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxDirPickerCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddProperty(_("value"),_("value"),XRC_TYPE_TEXT); - xrc.AddProperty(_("message"),_("message"),XRC_TYPE_TEXT); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxDirPickerCtrl")); - filter.AddProperty(_("value"),_("value"),XRC_TYPE_TEXT); - filter.AddProperty(_("message"),_("message"),XRC_TYPE_TEXT); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxDirPickerCtrl* picker = new wxDirPickerCtrl( + (wxWindow*)parent, obj->GetPropertyAsInteger(_("id")), obj->GetPropertyAsString(_("value")), + obj->GetPropertyAsString(_("message")), obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + picker->PushEventHandler(new ComponentEvtHandler(picker, GetManager())); + return picker; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxDirPickerCtrl); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxDirPickerCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + xrc.AddProperty(_("message"), _("message"), XRC_TYPE_TEXT); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxDirPickerCtrl")); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + filter.AddProperty(_("message"), _("message"), XRC_TYPE_TEXT); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnDirPickerDirChanged( wxFileDirPickerEvent& ) +void ComponentEvtHandler::OnDirPickerDirChanged(wxFileDirPickerEvent&) { - wxDirPickerCtrl* window = wxDynamicCast( m_window, wxDirPickerCtrl ); - if ( window != NULL ) - { - m_manager->ModifyProperty( window, _("value"), window->GetPath() ); - } + wxDirPickerCtrl* window = wxDynamicCast(m_window, wxDirPickerCtrl); + if (window != NULL) { + m_manager->ModifyProperty(window, _("value"), window->GetPath()); + } } class HyperlinkComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxHyperlinkCtrl* ctrl = new wxHyperlinkCtrl( - (wxWindow*)parent, wxID_ANY, - obj->GetPropertyAsString(_("label")), - obj->GetPropertyAsString(_("url")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) - ); - - if ( !obj->IsNull( _("hover_color") ) ) - { - ctrl->SetHoverColour( obj->GetPropertyAsColour( _("hover_color") ) ); - } - if ( !obj->IsNull( _("normal_color") ) ) - { - ctrl->SetNormalColour( obj->GetPropertyAsColour( _("normal_color") ) ); - } - if ( !obj->IsNull( _("visited_color") ) ) - { - ctrl->SetVisitedColour( obj->GetPropertyAsColour( _("visited_color") ) ); - } - - return ctrl; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxHyperlinkCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - xrc.AddPropertyValue(_("url"), obj->GetPropertyAsString(_("url"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxHyperlinkCtrl")); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - - try - { - ticpp::Element *urlElement = xrcObj->FirstChildElement("url"); - wxString url(urlElement->GetText().c_str(), wxConvUTF8); - - filter.AddPropertyValue(_("url"), url); - } - catch(ticpp::Exception&) - { - } - - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxHyperlinkCtrl* ctrl = new wxHyperlinkCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("label")), obj->GetPropertyAsString(_("url")), + obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + if (!obj->IsNull(_("hover_color"))) { + ctrl->SetHoverColour(obj->GetPropertyAsColour(_("hover_color"))); + } + if (!obj->IsNull(_("normal_color"))) { + ctrl->SetNormalColour(obj->GetPropertyAsColour(_("normal_color"))); + } + if (!obj->IsNull(_("visited_color"))) { + ctrl->SetVisitedColour(obj->GetPropertyAsColour(_("visited_color"))); + } + + return ctrl; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxHyperlinkCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddPropertyValue(_("url"), obj->GetPropertyAsString(_("url"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxHyperlinkCtrl")); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + + try { + ticpp::Element* urlElement = xrcObj->FirstChildElement("url"); + wxString url(urlElement->GetText().c_str(), wxConvUTF8); + + filter.AddPropertyValue(_("url"), url); + } catch (ticpp::Exception&) { + } + + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class GenericDirCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxGenericDirCtrl* ctrl = new wxGenericDirCtrl( - (wxWindow*)parent, - wxID_ANY, - obj->GetPropertyAsString(_("defaultfolder")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")), - obj->GetPropertyAsString(_("filter")), - obj->GetPropertyAsInteger(_("defaultfilter")) - ); - - ctrl->ShowHidden( obj->GetPropertyAsInteger( _("show_hidden") ) != 0 ); - ctrl->GetTreeCtrl()->PushEventHandler( new GenericDirCtrlEvtHandler( ctrl, GetManager() ) ); - return ctrl; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxGenericDirCtrl); - if (window) - { - window->GetTreeCtrl()->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxGenericDirCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddProperty(_("defaultfolder"),_("defaultfolder"),XRC_TYPE_TEXT); - xrc.AddProperty(_("filter"),_("filter"),XRC_TYPE_TEXT); - xrc.AddProperty(_("defaultfilter"),_("defaultfilter"),XRC_TYPE_INTEGER); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxGenericDirCtrl")); - filter.AddProperty(_("defaultfolder"),_("defaultfolder"),XRC_TYPE_TEXT); - filter.AddProperty(_("filter"),_("filter"),XRC_TYPE_TEXT); - filter.AddProperty(_("defaultfilter"),_("defaultfilter"),XRC_TYPE_INTEGER); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxGenericDirCtrl* ctrl = new wxGenericDirCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("defaultfolder")), obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")), + obj->GetPropertyAsString(_("filter")), obj->GetPropertyAsInteger(_("defaultfilter"))); + + ctrl->ShowHidden(obj->GetPropertyAsInteger(_("show_hidden")) != 0); + ctrl->GetTreeCtrl()->PushEventHandler(new GenericDirCtrlEvtHandler(ctrl, GetManager())); + return ctrl; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxGenericDirCtrl); + if (window) { + window->GetTreeCtrl()->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxGenericDirCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddProperty(_("defaultfolder"), _("defaultfolder"), XRC_TYPE_TEXT); + xrc.AddProperty(_("filter"), _("filter"), XRC_TYPE_TEXT); + xrc.AddProperty(_("defaultfilter"), _("defaultfilter"), XRC_TYPE_INTEGER); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxGenericDirCtrl")); + filter.AddProperty(_("defaultfolder"), _("defaultfolder"), XRC_TYPE_TEXT); + filter.AddProperty(_("filter"), _("filter"), XRC_TYPE_TEXT); + filter.AddProperty(_("defaultfilter"), _("defaultfilter"), XRC_TYPE_INTEGER); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void GenericDirCtrlEvtHandler::OnGenericDirCtrlLeftClick( wxMouseEvent& event ) +void GenericDirCtrlEvtHandler::OnGenericDirCtrlLeftClick(wxMouseEvent& event) { - m_manager->SelectObject( m_window ); - event.Skip(); + m_manager->SelectObject(m_window); + event.Skip(); } class CustomControlComponent : public ComponentBase { public: - wxObject* Create(IObject* /*obj*/, wxObject* parent) override { - return new wxPanel((wxWindow *)parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, obj->GetPropertyAsString(_("class")), obj->GetPropertyAsString(_("name"))); - return xrc.GetXrcObject(); - } + wxObject* Create(IObject* /*obj*/, wxObject* parent) override + { + return new wxPanel((wxWindow*)parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, obj->GetPropertyAsString(_("class")), obj->GetPropertyAsString(_("name"))); + return xrc.GetXrcObject(); + } }; class CustomCodeComponent : public ComponentBase @@ -1461,126 +1412,130 @@ class CustomCodeComponent : public ComponentBase class SearchCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxSearchCtrl* sc = new wxSearchCtrl((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsString(_("value")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - if ( !obj->IsNull( _("search_button") ) ) - { - sc->ShowSearchButton(obj->GetPropertyAsInteger(_("search_button")) != 0); - } - - if ( !obj->IsNull( _("cancel_button") ) ) - { - sc->ShowCancelButton(obj->GetPropertyAsInteger(_("cancel_button")) != 0); - } - - sc->PushEventHandler( new ComponentEvtHandler( sc, GetManager() ) ); - - return sc; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxSearchCtrl); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxSearchCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("value"),_("value"),XRC_TYPE_TEXT); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxSearchCtrl")); - filter.AddWindowProperties(); - filter.AddProperty(_("value"),_("value"),XRC_TYPE_TEXT); - return filter.GetXfbObject(); - } - + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxSearchCtrl* sc = new wxSearchCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("value")), obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + if (!obj->IsNull(_("search_button"))) { + sc->ShowSearchButton(obj->GetPropertyAsInteger(_("search_button")) != 0); + } + + if (!obj->IsNull(_("cancel_button"))) { + sc->ShowCancelButton(obj->GetPropertyAsInteger(_("cancel_button")) != 0); + } + + sc->PushEventHandler(new ComponentEvtHandler(sc, GetManager())); + + return sc; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxSearchCtrl); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxSearchCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxSearchCtrl")); + filter.AddWindowProperties(); + filter.AddProperty(_("value"), _("value"), XRC_TYPE_TEXT); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnText( wxCommandEvent& event) +void ComponentEvtHandler::OnText(wxCommandEvent& event) { - wxSearchCtrl* sc = wxDynamicCast( m_window, wxSearchCtrl ); - if ( sc != NULL ) - { - m_manager->ModifyProperty( m_window, _("value"), sc->GetValue() ); - sc->SetInsertionPointEnd(); - sc->SetFocus(); - } - - event.Skip(); + wxSearchCtrl* sc = wxDynamicCast(m_window, wxSearchCtrl); + if (sc != NULL) { + m_manager->ModifyProperty(m_window, _("value"), sc->GetValue()); + sc->SetInsertionPointEnd(); + sc->SetFocus(); + } + + event.Skip(); } #ifdef USE_MEDIACTRL class MediaCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxMediaCtrl* mc = new wxMediaCtrl((wxWindow *)parent, wxID_ANY, wxT(""),obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - if ( !obj->IsNull( _("file") ) ) - { - if( mc->Load( obj->GetPropertyAsString( _("file") ) ) ) - { - if (!obj->IsNull( _("playback_rate"))) mc->SetPlaybackRate(obj->GetPropertyAsFloat(_("playback_rate"))); - if (!obj->IsNull( _("volume")) && (obj->GetPropertyAsFloat(_("volume"))>=0)&&(obj->GetPropertyAsFloat(_("volume"))<=1)) - mc->SetPlaybackRate(obj->GetPropertyAsFloat(_("volume"))); - if (!obj->IsNull(_("player_controls"))) - { - if( obj->GetPropertyAsString( _("player_controls") ) == wxT("STEP") ) mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_STEP); - if( obj->GetPropertyAsString( _("player_controls") ) == wxT("VOLUME") ) mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_VOLUME); - if( obj->GetPropertyAsString( _("player_controls") ) == wxT("DEFAULT") ) mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_DEFAULT); - if( obj->GetPropertyAsString( _("player_controls") ) == wxT("NONE") ) mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_NONE); - - } - - if ( !obj->IsNull( _("play") ) && ( obj->GetPropertyAsInteger( _("play") ) == 1 ) ) mc->Play(); - else - mc->Stop(); - - //GetManager()->ModifyProperty( m_window, wxT("size"), mc->GetBestSize() ); - } - } - - if(!obj->IsNull(_("style"))) mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_STEP); - - mc->PushEventHandler( new ComponentEvtHandler( mc, GetManager() ) ); - - return mc; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxMediaCtrl); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxMediaCtrl"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxMediaCtrl")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxMediaCtrl* mc = new wxMediaCtrl( + (wxWindow*)parent, wxID_ANY, wxT(""), obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + if (!obj->IsNull(_("file"))) { + if (mc->Load(obj->GetPropertyAsString(_("file")))) { + if (!obj->IsNull(_("playback_rate"))) + mc->SetPlaybackRate(obj->GetPropertyAsFloat(_("playback_rate"))); + if ( + !obj->IsNull(_("volume")) && (obj->GetPropertyAsFloat(_("volume")) >= 0) && + (obj->GetPropertyAsFloat(_("volume")) <= 1)) + mc->SetPlaybackRate(obj->GetPropertyAsFloat(_("volume"))); + if (!obj->IsNull(_("player_controls"))) { + if (obj->GetPropertyAsString(_("player_controls")) == wxT("STEP")) + mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_STEP); + if (obj->GetPropertyAsString(_("player_controls")) == wxT("VOLUME")) + mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_VOLUME); + if (obj->GetPropertyAsString(_("player_controls")) == wxT("DEFAULT")) + mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_DEFAULT); + if (obj->GetPropertyAsString(_("player_controls")) == wxT("NONE")) + mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_NONE); + } + + if (!obj->IsNull(_("play")) && (obj->GetPropertyAsInteger(_("play")) == 1)) + mc->Play(); + else + mc->Stop(); + + // GetManager()->ModifyProperty( m_window, wxT("size"), mc->GetBestSize() ); + } + } + + if (!obj->IsNull(_("style"))) + mc->ShowPlayerControls(wxMEDIACTRLPLAYERCONTROLS_STEP); + + mc->PushEventHandler(new ComponentEvtHandler(mc, GetManager())); + + return mc; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxMediaCtrl); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxMediaCtrl"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxMediaCtrl")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; #endif @@ -1592,297 +1547,282 @@ class TimerComponent : public ComponentBase class PropertyGridComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxPropertyGrid* pg = new wxPropertyGrid((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(wxT("pos")), - obj->GetPropertyAsSize(wxT("size")), - obj->GetPropertyAsInteger(wxT("style")) | - obj->GetPropertyAsInteger(wxT("window_style")) ); - - if ( !obj->GetPropertyAsString(wxT("extra_style")).empty() ) - { - pg->SetExtraStyle( obj->GetPropertyAsInteger( wxT("extra_style") ) ); - } - - return pg; - } - - /*void Cleanup( wxObject* ) - { - // Prevent assert for missing event handler - }*/ - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxPropertyGrid* pg = wxDynamicCast( wxobject, wxPropertyGrid); - if ( NULL == pg ) - { - // very very strange - return; - } - - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if (childObj->GetClassName() == _("propGridItem")) - { - if (childObj->GetPropertyAsString( _("type") ) == _("Category") ) - { - pg->Append( new wxPropertyCategory( childObj->GetPropertyAsString( _("label") ), childObj->GetPropertyAsString( _("label") ) ) ); - } - else - { - wxPGProperty *prop = wxDynamicCast( wxCreateDynamicObject( wxT("wx") + (childObj->GetPropertyAsString( _("type") ) ) + wxT("Property") ), wxPGProperty ); - if( prop ) - { - prop->SetLabel( childObj->GetPropertyAsString( _("label") ) ); - prop->SetName( childObj->GetPropertyAsString( _("label") ) ); - pg->Append( prop ); - - if( childObj->GetPropertyAsString( _("help") ) != wxEmptyString ) - { - pg->SetPropertyHelpString( prop, childObj->GetPropertyAsString( _("help") ) ); - } - } - } - } - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxPropertyGrid* pg = new wxPropertyGrid( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(wxT("pos")), obj->GetPropertyAsSize(wxT("size")), + obj->GetPropertyAsInteger(wxT("style")) | obj->GetPropertyAsInteger(wxT("window_style"))); + + if (!obj->GetPropertyAsString(wxT("extra_style")).empty()) { + pg->SetExtraStyle(obj->GetPropertyAsInteger(wxT("extra_style"))); + } + + return pg; + } + + /*void Cleanup( wxObject* ) + { + // Prevent assert for missing event handler + }*/ + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxPropertyGrid* pg = wxDynamicCast(wxobject, wxPropertyGrid); + if (NULL == pg) { + // very very strange + return; + } + + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (childObj->GetClassName() == _("propGridItem")) { + if (childObj->GetPropertyAsString(_("type")) == _("Category")) { + pg->Append(new wxPropertyCategory( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsString(_("label")))); + } else { + wxPGProperty* prop = wxDynamicCast( + wxCreateDynamicObject(wxT("wx") + (childObj->GetPropertyAsString(_("type"))) + wxT("Property")), + wxPGProperty); + if (prop) { + prop->SetLabel(childObj->GetPropertyAsString(_("label"))); + prop->SetName(childObj->GetPropertyAsString(_("label"))); + pg->Append(prop); + + if (childObj->GetPropertyAsString(_("help")) != wxEmptyString) { + pg->SetPropertyHelpString(prop, childObj->GetPropertyAsString(_("help"))); + } + } + } + } + } + } }; class PropertyGridManagerComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxPropertyGridManager* pgman = new wxPropertyGridManager((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(wxT("pos")), - obj->GetPropertyAsSize(wxT("size")), - obj->GetPropertyAsInteger(wxT("style")) | - obj->GetPropertyAsInteger(wxT("window_style"))); + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxPropertyGridManager* pgman = new wxPropertyGridManager( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(wxT("pos")), obj->GetPropertyAsSize(wxT("size")), + obj->GetPropertyAsInteger(wxT("style")) | obj->GetPropertyAsInteger(wxT("window_style"))); + + if (!obj->GetPropertyAsString(wxT("extra_style")).empty()) { + pgman->SetExtraStyle(obj->GetPropertyAsInteger(wxT("extra_style"))); + } - if ( !obj->GetPropertyAsString( wxT("extra_style") ).empty() ) - { - pgman->SetExtraStyle( obj->GetPropertyAsInteger( wxT("extra_style") ) ); - } + pgman->ShowHeader(obj->GetPropertyAsInteger(wxT("show_header")) != 0); - pgman->ShowHeader(obj->GetPropertyAsInteger(wxT("show_header")) != 0); + // Adding a page sets target page to the one added, so + // we don't have to call SetTargetPage if we are filling + // it right after adding. + /*wxPropertyGridPage* pg = pgman->AddPage( _("First Page") ); - // Adding a page sets target page to the one added, so - // we don't have to call SetTargetPage if we are filling - // it right after adding. - /*wxPropertyGridPage* pg = pgman->AddPage( _("First Page") ); + pg->Append( new wxPropertyCategory( _("Sample Category") ) ); - pg->Append( new wxPropertyCategory( _("Sample Category") ) ); + // Add string property + wxPGProperty *id = pg->Append( new wxStringProperty( _("Label"), wxPG_LABEL, _("Initial Value") ) ); + pg->SetPropertyHelpString( id, _("A string property") ); - // Add string property - wxPGProperty *id = pg->Append( new wxStringProperty( _("Label"), wxPG_LABEL, _("Initial Value") ) ); - pg->SetPropertyHelpString( id, _("A string property") ); - - // Add int property - pg->Append( new wxIntProperty ( wxT("IntProperty"), wxPG_LABEL, 12345678 ) ); - - // Add float property (value type is actually double) - pg->Append( new wxFloatProperty ( wxT("FloatProperty"), wxPG_LABEL, 12345.678 ) ); - - // Add a bool property - pg->Append( new wxBoolProperty ( wxT("BoolProperty"), wxPG_LABEL, false ) ); - pg->Append( new wxBoolProperty ( wxT("BoolPropertyAsCheckbox"), wxPG_LABEL, true ) ); - pg->SetPropertyAttribute( wxT("BoolPropertyAsCheckbox"), wxPG_BOOL_USE_CHECKBOX, (long)1 ); - - // Add an enum property - wxArrayString strings; - strings.Add( _("Herbivore") ); - strings.Add( _("Carnivore") ); - strings.Add( _("Omnivore") ); - - wxArrayInt indexes; - indexes.Add( 0 ); - indexes.Add( 1 ); - indexes.Add( 2 ); - - pg->Append( new wxEnumProperty( wxT("EnumProperty"), wxPG_LABEL, strings, indexes, 0 ) ); - - pg->Append( new wxPropertyCategory( _("Low Priority Properties") ) ); - - // A string property that can be edited in a separate editor dialog. - pg->Append( new wxLongStringProperty( wxT("LongStringProperty"), wxPG_LABEL, - wxString(_("This is much longer string than the ") ) + - wxString(_("first one. Edit it by clicking the button.") ) ) ); - - // String editor with dir selector button. - pg->Append( new wxDirProperty( wxT("DirProperty"), wxPG_LABEL, ::wxGetUserHome() ) ); - - // A file selector property. - pg->Append( new wxFileProperty( wxT("FileProperty"), wxPG_LABEL, wxEmptyString ) ); - - wxPropertyGridPage* pg2 = pgman->AddPage( _("Second Page") ); - - pg2->Append( new wxPropertyCategory( _("Sample Parent Property"), wxPG_LABEL ) ); - - wxPGProperty* carProp2 = pg2->Append( new wxStringProperty( _("Car"), wxPG_LABEL, wxT("") ) ); - pg2->AppendIn( carProp2, new wxStringProperty( _("Model"), wxPG_LABEL, wxT("Lamborghini Diablo SV") ) ); - pg2->AppendIn( carProp2, new wxIntProperty( _("Engine Size (cc)"), wxPG_LABEL, 5707) ); - - wxPGProperty* speedsProp2 = pg2->AppendIn( carProp2, new wxStringProperty( _("Speeds"), wxPG_LABEL, wxT("") ) ); - pg2->AppendIn( speedsProp2, new wxIntProperty( _("Max. Speed (mph)"), wxPG_LABEL, 300 ) ); - pg2->AppendIn( speedsProp2, new wxFloatProperty( _("0-100 mph (sec)"), wxPG_LABEL, 3.9 ) ); - pg2->AppendIn( speedsProp2, new wxFloatProperty( _("1/4 mile (sec)"), wxPG_LABEL, 8.6) ); - - pg2->AppendIn( carProp2, new wxIntProperty( _("Price ($)"), wxPG_LABEL, 300000 ) ); - - if ( obj->GetPropertyAsInteger( wxT("include_advanced") ) ) - { - pg2->Append( new wxPropertyCategory( _("Advanced Properties"), wxPG_LABEL ) ); - // wxArrayStringProperty embeds a wxArrayString. - pg2->Append( new wxArrayStringProperty( _("Example of ArrayStringProperty"), wxT("ArrayStringProp") ) ); - - // Image file property. Wildcard is auto-generated from available - // image handlers, so it is not set this time. - pg2->Append( new wxImageFileProperty( _("Example of ImageFileProperty"), wxT("ImageFileProp") ) ); - - // Font property has sub-properties. - pg2->Append( new wxFontProperty( _("Font"), wxPG_LABEL ) ); - - // Colour property with arbitrary colour. - pg2->Append( new wxColourProperty( _("My Colour 1"), wxPG_LABEL, wxColour( 242, 109, 0 ) ) ); - - // System colour property. - pg2->Append( new wxSystemColourProperty( _("My SysColour 1"), wxPG_LABEL, wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW ) ) ); - - // System colour property with custom colour. - pg2->Append( new wxSystemColourProperty( _("My SysColour 2"), wxPG_LABEL, wxColour( 0, 200, 160 ) ) ); - - // Cursor property - pg2->Append( new wxCursorProperty( _("My Cursor"), wxPG_LABEL, wxCURSOR_ARROW ) ); - }*/ - - return pgman; - } -/* - void Cleanup( wxObject* ) - { - // Prevent assert for missing event handler - }*/ - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxPropertyGridManager* pgm = wxDynamicCast( wxobject, wxPropertyGridManager); - if ( NULL == pgm ) - { - // very very strange - return; - } - - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if (childObj->GetClassName() == _("propGridPage")) - { - wxPropertyGridPage *page = pgm->AddPage( childObj->GetPropertyAsString( _("label") ), childObj->GetPropertyAsBitmap( _("bitmap") ) ); - - for( size_t j = 0; j < childObj->GetChildCount(); ++j ) - { - IObject* innerChildObj = childObj->GetChildPtr( j ); - if (innerChildObj->GetClassName() == _("propGridItem")) - { - if (innerChildObj->GetPropertyAsString( _("type") ) == _("Category") ) - { - page->Append( new wxPropertyCategory( innerChildObj->GetPropertyAsString( _("label") ), innerChildObj->GetPropertyAsString( _("label") ) ) ); - } - else - { - wxPGProperty *prop = wxDynamicCast( wxCreateDynamicObject( wxT("wx") + (innerChildObj->GetPropertyAsString( _("type") ) ) + wxT("Property") ), wxPGProperty ); - if( prop ) - { - prop->SetLabel( innerChildObj->GetPropertyAsString( _("label") ) ); - prop->SetName( innerChildObj->GetPropertyAsString( _("label") ) ); - page->Append( prop ); - - if( innerChildObj->GetPropertyAsString( _("help") ) != wxEmptyString ) - { - page->SetPropertyHelpString( prop, innerChildObj->GetPropertyAsString( _("help") ) ); - } - } - } - } - } - } - } - - if( count ) - { - pgm->SelectPage( 0 ); - } - - pgm->Update(); - } + // Add int property + pg->Append( new wxIntProperty ( wxT("IntProperty"), wxPG_LABEL, 12345678 ) ); + + // Add float property (value type is actually double) + pg->Append( new wxFloatProperty ( wxT("FloatProperty"), wxPG_LABEL, 12345.678 ) ); + + // Add a bool property + pg->Append( new wxBoolProperty ( wxT("BoolProperty"), wxPG_LABEL, false ) ); + pg->Append( new wxBoolProperty ( wxT("BoolPropertyAsCheckbox"), wxPG_LABEL, true ) ); + pg->SetPropertyAttribute( wxT("BoolPropertyAsCheckbox"), wxPG_BOOL_USE_CHECKBOX, (long)1 ); + + // Add an enum property + wxArrayString strings; + strings.Add( _("Herbivore") ); + strings.Add( _("Carnivore") ); + strings.Add( _("Omnivore") ); + + wxArrayInt indexes; + indexes.Add( 0 ); + indexes.Add( 1 ); + indexes.Add( 2 ); + + pg->Append( new wxEnumProperty( wxT("EnumProperty"), wxPG_LABEL, strings, indexes, 0 ) ); + + pg->Append( new wxPropertyCategory( _("Low Priority Properties") ) ); + + // A string property that can be edited in a separate editor dialog. + pg->Append( new wxLongStringProperty( wxT("LongStringProperty"), wxPG_LABEL, + wxString(_("This is much longer string + than the ") ) + wxString(_("first one. Edit it by clicking the button.") ) ) ); + + // String editor with dir selector button. + pg->Append( new wxDirProperty( wxT("DirProperty"), wxPG_LABEL, ::wxGetUserHome() ) ); + + // A file selector property. + pg->Append( new wxFileProperty( wxT("FileProperty"), wxPG_LABEL, wxEmptyString ) ); + + wxPropertyGridPage* pg2 = pgman->AddPage( _("Second Page") ); + + pg2->Append( new wxPropertyCategory( _("Sample Parent Property"), wxPG_LABEL ) ); + + wxPGProperty* carProp2 = pg2->Append( new wxStringProperty( _("Car"), wxPG_LABEL, wxT("") ) ); + pg2->AppendIn( carProp2, new wxStringProperty( _("Model"), wxPG_LABEL, wxT("Lamborghini Diablo SV") ) ); + pg2->AppendIn( carProp2, new wxIntProperty( _("Engine Size (cc)"), wxPG_LABEL, 5707) ); + + wxPGProperty* speedsProp2 = pg2->AppendIn( carProp2, new wxStringProperty( _("Speeds"), wxPG_LABEL, + wxT("") ) ); pg2->AppendIn( speedsProp2, new wxIntProperty( _("Max. Speed (mph)"), wxPG_LABEL, 300 ) + ); pg2->AppendIn( speedsProp2, new wxFloatProperty( _("0-100 mph (sec)"), wxPG_LABEL, 3.9 ) ); pg2->AppendIn( + speedsProp2, new wxFloatProperty( _("1/4 mile (sec)"), wxPG_LABEL, 8.6) ); + + pg2->AppendIn( carProp2, new wxIntProperty( _("Price ($)"), wxPG_LABEL, 300000 ) ); + + if ( obj->GetPropertyAsInteger( wxT("include_advanced") ) ) + { + pg2->Append( new wxPropertyCategory( _("Advanced Properties"), wxPG_LABEL ) ); + // wxArrayStringProperty embeds a wxArrayString. + pg2->Append( new wxArrayStringProperty( _("Example of ArrayStringProperty"), wxT("ArrayStringProp") ) ); + + // Image file property. Wildcard is auto-generated from available + // image handlers, so it is not set this time. + pg2->Append( new wxImageFileProperty( _("Example of ImageFileProperty"), wxT("ImageFileProp") ) ); + + // Font property has sub-properties. + pg2->Append( new wxFontProperty( _("Font"), wxPG_LABEL ) ); + + // Colour property with arbitrary colour. + pg2->Append( new wxColourProperty( _("My Colour 1"), wxPG_LABEL, wxColour( 242, 109, 0 ) ) ); + + // System colour property. + pg2->Append( new wxSystemColourProperty( _("My SysColour 1"), wxPG_LABEL, wxSystemSettings::GetColour( + wxSYS_COLOUR_WINDOW ) ) ); + + // System colour property with custom colour. + pg2->Append( new wxSystemColourProperty( _("My SysColour 2"), wxPG_LABEL, wxColour( 0, 200, 160 ) ) ); + + // Cursor property + pg2->Append( new wxCursorProperty( _("My Cursor"), wxPG_LABEL, wxCURSOR_ARROW ) ); + }*/ + + return pgman; + } + /* + void Cleanup( wxObject* ) + { + // Prevent assert for missing event handler + }*/ + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxPropertyGridManager* pgm = wxDynamicCast(wxobject, wxPropertyGridManager); + if (NULL == pgm) { + // very very strange + return; + } + + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (childObj->GetClassName() == _("propGridPage")) { + wxPropertyGridPage* page = + pgm->AddPage(childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsBitmap(_("bitmap"))); + + for (size_t j = 0; j < childObj->GetChildCount(); ++j) { + IObject* innerChildObj = childObj->GetChildPtr(j); + if (innerChildObj->GetClassName() == _("propGridItem")) { + if (innerChildObj->GetPropertyAsString(_("type")) == _("Category")) { + page->Append(new wxPropertyCategory( + innerChildObj->GetPropertyAsString(_("label")), + innerChildObj->GetPropertyAsString(_("label")))); + } else { + wxPGProperty* prop = wxDynamicCast( + wxCreateDynamicObject( + wxT("wx") + (innerChildObj->GetPropertyAsString(_("type"))) + wxT("Property")), + wxPGProperty); + if (prop) { + prop->SetLabel(innerChildObj->GetPropertyAsString(_("label"))); + prop->SetName(innerChildObj->GetPropertyAsString(_("label"))); + page->Append(prop); + + if (innerChildObj->GetPropertyAsString(_("help")) != wxEmptyString) { + page->SetPropertyHelpString(prop, innerChildObj->GetPropertyAsString(_("help"))); + } + } + } + } + } + } + } + + if (count) { + pgm->SelectPage(0); + } + + pgm->Update(); + } }; -class PropertyGridItemComponent : public ComponentBase{}; -class PropertyGridPageComponent : public ComponentBase{}; +class PropertyGridItemComponent : public ComponentBase +{ +}; +class PropertyGridPageComponent : public ComponentBase +{ +}; class StyledTextComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxStyledTextCtrl* m_code = new wxStyledTextCtrl( (wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("window_style")), - obj->GetPropertyAsString(_("name")) - ); - - // Line Numbers - if ( 0 != obj->GetPropertyAsInteger(_("line_numbers") ) ) - { - m_code->SetMarginType( 0, wxSTC_MARGIN_NUMBER ); - m_code->SetMarginWidth( 0, m_code->TextWidth (wxSTC_STYLE_LINENUMBER, wxT("_99999")) ); - } - else - { - m_code->SetMarginWidth( 0, 0 ); - } - - // markers - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS); - m_code->MarkerSetBackground (wxSTC_MARKNUM_FOLDER, wxColour (wxT("BLACK"))); - m_code->MarkerSetForeground (wxSTC_MARKNUM_FOLDER, wxColour (wxT("WHITE"))); - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS); - m_code->MarkerSetBackground (wxSTC_MARKNUM_FOLDEROPEN, wxColour (wxT("BLACK"))); - m_code->MarkerSetForeground (wxSTC_MARKNUM_FOLDEROPEN, wxColour (wxT("WHITE"))); - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_EMPTY); - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUS); - m_code->MarkerSetBackground (wxSTC_MARKNUM_FOLDEREND, wxColour (wxT("BLACK"))); - m_code->MarkerSetForeground (wxSTC_MARKNUM_FOLDEREND, wxColour (wxT("WHITE"))); - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUS); - m_code->MarkerSetBackground (wxSTC_MARKNUM_FOLDEROPENMID, wxColour (wxT("BLACK"))); - m_code->MarkerSetForeground (wxSTC_MARKNUM_FOLDEROPENMID, wxColour (wxT("WHITE"))); - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_EMPTY); - m_code->MarkerDefine (wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_EMPTY); - - // folding - if ( 0 != obj->GetPropertyAsInteger(_("folding") ) ) - { - m_code->SetMarginType (1, wxSTC_MARGIN_SYMBOL); - m_code->SetMarginMask (1, wxSTC_MASK_FOLDERS); - m_code->SetMarginWidth (1, 16); - m_code->SetMarginSensitive (1, true); - - m_code->SetProperty( wxT("fold"), wxT("1") ); - m_code->SetFoldFlags( wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED ); - } - else - { - m_code->SetMarginWidth( 1, 0 ); - } - m_code->SetIndentationGuides(obj->GetPropertyAsInteger(_("indentation_guides"))); - - m_code->SetMarginWidth( 2, 0 ); - - m_code->SetLexer(wxSTC_LEX_CPP); - m_code->SetKeyWords(0, wxT("asm auto bool break case catch char class const const_cast \ + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxStyledTextCtrl* m_code = new wxStyledTextCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("window_style")), obj->GetPropertyAsString(_("name"))); + + // Line Numbers + if (0 != obj->GetPropertyAsInteger(_("line_numbers"))) { + m_code->SetMarginType(0, wxSTC_MARGIN_NUMBER); + m_code->SetMarginWidth(0, m_code->TextWidth(wxSTC_STYLE_LINENUMBER, wxT("_99999"))); + } else { + m_code->SetMarginWidth(0, 0); + } + + // markers + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDER, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDER, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDEROPEN, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDEROPEN, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_EMPTY); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDEREND, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDEREND, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDEROPENMID, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDEROPENMID, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_EMPTY); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_EMPTY); + + // folding + if (0 != obj->GetPropertyAsInteger(_("folding"))) { + m_code->SetMarginType(1, wxSTC_MARGIN_SYMBOL); + m_code->SetMarginMask(1, wxSTC_MASK_FOLDERS); + m_code->SetMarginWidth(1, 16); + m_code->SetMarginSensitive(1, true); + + m_code->SetProperty(wxT("fold"), wxT("1")); + m_code->SetFoldFlags(wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED); + } else { + m_code->SetMarginWidth(1, 0); + } + m_code->SetIndentationGuides(obj->GetPropertyAsInteger(_("indentation_guides"))); + + m_code->SetMarginWidth(2, 0); + + m_code->SetLexer(wxSTC_LEX_CPP); + m_code->SetKeyWords(0, wxT("asm auto bool break case catch char class const const_cast \ continue default delete do double dynamic_cast else enum explicit \ export extern false float for friend goto if inline int long \ mutable namespace new operator private protected public register \ @@ -1891,775 +1831,686 @@ class StyledTextComponent : public ComponentBase typename union unsigned using virtual void volatile wchar_t \ while")); - wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - if ( !obj->GetPropertyAsString(_("font")).empty() ) - { - font = obj->GetPropertyAsFont(_("font")); - } - - m_code->StyleSetFont(wxSTC_STYLE_DEFAULT, font ); - - m_code->StyleClearAll(); - m_code->StyleSetBold(wxSTC_C_WORD, true); - m_code->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); - m_code->StyleSetForeground(wxSTC_C_STRING, *wxRED); - m_code->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); - m_code->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); - m_code->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); - m_code->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0)); - m_code->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0)); - m_code->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); - m_code->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE ); - m_code->SetUseTabs( ( 0 != obj->GetPropertyAsInteger( _("use_tabs") ) ) ); - m_code->SetTabWidth( obj->GetPropertyAsInteger( _("tab_width") ) ); - m_code->SetTabIndents( ( 0 != obj->GetPropertyAsInteger( _("tab_indents") ) ) ); - m_code->SetBackSpaceUnIndents( ( 0 != obj->GetPropertyAsInteger( _("backspace_unindents") ) ) ); - m_code->SetIndent( obj->GetPropertyAsInteger( _("tab_width") ) ); - m_code->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); - m_code->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); - m_code->SetViewEOL( ( 0 != obj->GetPropertyAsInteger( _("view_eol") ) ) ); - m_code->SetViewWhiteSpace(obj->GetPropertyAsInteger(_("view_whitespace"))); - - m_code->SetCaretWidth(2); - - m_code->SetText( wxT( "/** Sample Class to Display wxScintilla */\n" ) - wxT( "class ScintillaSampleCode\n" ) - wxT( "{\n" ) - wxT( "private:\n" ) - wxT( "\tint m_privateMember;\n\n" ) - wxT( "public:\n\n" ) - wxT( "\t// Sample Member Function\n" ) - wxT( "\tint SampleFunction( int sample = 0 )\n" ) - wxT( "\t{\n" ) - wxT( "\t\treturn sample;\n" ) - wxT( "\t}\n" ) - wxT( "};\n" ) - ); - - m_code->PushEventHandler( new ComponentEvtHandler( m_code, GetManager() ) ); - - return m_code; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxStyledTextCtrl); - if (window) - { - window->PopEventHandler(true); - } - } + wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + if (!obj->GetPropertyAsString(_("font")).empty()) { + font = obj->GetPropertyAsFont(_("font")); + } + + m_code->StyleSetFont(wxSTC_STYLE_DEFAULT, font); + + m_code->StyleClearAll(); + m_code->StyleSetBold(wxSTC_C_WORD, true); + m_code->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); + m_code->StyleSetForeground(wxSTC_C_STRING, *wxRED); + m_code->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); + m_code->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); + m_code->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); + m_code->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0)); + m_code->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0)); + m_code->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); + m_code->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); + m_code->SetUseTabs((0 != obj->GetPropertyAsInteger(_("use_tabs")))); + m_code->SetTabWidth(obj->GetPropertyAsInteger(_("tab_width"))); + m_code->SetTabIndents((0 != obj->GetPropertyAsInteger(_("tab_indents")))); + m_code->SetBackSpaceUnIndents((0 != obj->GetPropertyAsInteger(_("backspace_unindents")))); + m_code->SetIndent(obj->GetPropertyAsInteger(_("tab_width"))); + m_code->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); + m_code->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); + m_code->SetViewEOL((0 != obj->GetPropertyAsInteger(_("view_eol")))); + m_code->SetViewWhiteSpace(obj->GetPropertyAsInteger(_("view_whitespace"))); + + m_code->SetCaretWidth(2); + + m_code->SetText(wxT("/** Sample Class to Display wxScintilla */\n") wxT("class ScintillaSampleCode\n") + wxT("{\n") wxT("private:\n") wxT("\tint m_privateMember;\n\n") wxT("public:\n\n") + wxT("\t// Sample Member Function\n") wxT("\tint SampleFunction( int sample = 0 )\n") + wxT("\t{\n") wxT("\t\treturn sample;\n") wxT("\t}\n") wxT("};\n")); + + m_code->PushEventHandler(new ComponentEvtHandler(m_code, GetManager())); + + return m_code; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxStyledTextCtrl); + if (window) { + window->PopEventHandler(true); + } + } }; -void ComponentEvtHandler::OnMarginClick( wxStyledTextEvent& event ) -{ - wxStyledTextCtrl* scintilla = wxDynamicCast( m_window, wxStyledTextCtrl ); - if ( scintilla != NULL ) - { - if ( event.GetMargin() == 1 ) - { - int lineClick = scintilla->LineFromPosition( event.GetPosition() ); - int levelClick = scintilla->GetFoldLevel( lineClick ); - if ( ( levelClick & wxSTC_FOLDLEVELHEADERFLAG ) > 0 ) - { - scintilla->ToggleFold( lineClick ); - } - } - } - event.Skip(); +void ComponentEvtHandler::OnMarginClick(wxStyledTextEvent& event) +{ + wxStyledTextCtrl* scintilla = wxDynamicCast(m_window, wxStyledTextCtrl); + if (scintilla != NULL) { + if (event.GetMargin() == 1) { + int lineClick = scintilla->LineFromPosition(event.GetPosition()); + int levelClick = scintilla->GetFoldLevel(lineClick); + if ((levelClick & wxSTC_FOLDLEVELHEADERFLAG) > 0) { + scintilla->ToggleFold(lineClick); + } + } + } + event.Skip(); } class DataViewModel : public wxDataViewModel { public: - unsigned int GetChildren(const wxDataViewItem&, - wxDataViewItemArray& /*children*/) const override { - return 0; - } - unsigned int GetColumnCount() const override { - return 0; - } - wxString GetColumnType(unsigned int /*col*/) const override { - return wxVariant("Dummy").GetType(); - } - wxDataViewItem GetParent(const wxDataViewItem&) const override { - return wxDataViewItem( NULL ); - } - bool IsContainer(const wxDataViewItem&) const override { - return false; - } - void GetValue(wxVariant&, const wxDataViewItem&, unsigned int /*col*/) const override { - } - bool SetValue(const wxVariant&, const wxDataViewItem&, unsigned int /*col*/) override { - return true; - } + unsigned int GetChildren(const wxDataViewItem&, wxDataViewItemArray& /*children*/) const override { return 0; } + unsigned int GetColumnCount() const override { return 0; } + wxString GetColumnType(unsigned int /*col*/) const override { return wxVariant("Dummy").GetType(); } + wxDataViewItem GetParent(const wxDataViewItem&) const override { return wxDataViewItem(NULL); } + bool IsContainer(const wxDataViewItem&) const override { return false; } + void GetValue(wxVariant&, const wxDataViewItem&, unsigned int /*col*/) const override {} + bool SetValue(const wxVariant&, const wxDataViewItem&, unsigned int /*col*/) override { return true; } }; class DataViewCtrl : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxDataViewCtrl* dataViewCtrl = new wxDataViewCtrl((wxWindow *)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("window_style"))); - - wxObjectDataPtr model; - model = new DataViewModel; - dataViewCtrl->AssociateModel( model.get() ); - - return dataViewCtrl; - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxDataViewCtrl* list = wxDynamicCast( wxobject, wxDataViewCtrl); - if ( NULL == list ) - { - // very very strange - return; - } - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if (childObj->GetClassName() == _("dataViewColumn")) - { - if (childObj->GetPropertyAsString( _("type")) == _("Text")) - { - auto* col = list->AppendTextColumn( - childObj->GetPropertyAsString(_("label")), - childObj->GetPropertyAsInteger(_("model_column")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("Toggle")) - { - auto* col = list->AppendToggleColumn( - childObj->GetPropertyAsString(_("label")), - childObj->GetPropertyAsInteger(_("model_column")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("Progress")) - { - auto* col = list->AppendProgressColumn( - childObj->GetPropertyAsString(_("label")), - childObj->GetPropertyAsInteger(_("model_column")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("IconText")) - { - auto* col = list->AppendIconTextColumn( - childObj->GetPropertyAsString(_("label")), - childObj->GetPropertyAsInteger(_("model_column")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("Date")) - { - auto* col = list->AppendDateColumn( - childObj->GetPropertyAsString(_("label")), - childObj->GetPropertyAsInteger(_("model_column")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("Bitmap")) - { - auto* col = list->AppendBitmapColumn( - childObj->GetPropertyAsString(_("label")), - childObj->GetPropertyAsInteger(_("model_column")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - } - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxDataViewCtrl* dataViewCtrl = new wxDataViewCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("window_style"))); + + wxObjectDataPtr model; + model = new DataViewModel; + dataViewCtrl->AssociateModel(model.get()); + + return dataViewCtrl; + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxDataViewCtrl* list = wxDynamicCast(wxobject, wxDataViewCtrl); + if (NULL == list) { + // very very strange + return; + } + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (childObj->GetClassName() == _("dataViewColumn")) { + if (childObj->GetPropertyAsString(_("type")) == _("Text")) { + auto* col = list->AppendTextColumn( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsInteger(_("model_column")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("Toggle")) { + auto* col = list->AppendToggleColumn( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsInteger(_("model_column")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("Progress")) { + auto* col = list->AppendProgressColumn( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsInteger(_("model_column")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("IconText")) { + auto* col = list->AppendIconTextColumn( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsInteger(_("model_column")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("Date")) { + auto* col = list->AppendDateColumn( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsInteger(_("model_column")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("Bitmap")) { + auto* col = list->AppendBitmapColumn( + childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsInteger(_("model_column")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } + } + } + } }; class DataViewTreeCtrl : public ComponentBase { public: - wxObject* Create( IObject* obj, wxObject* parent ) override - { - wxDataViewTreeCtrl* dataViewTreeCtrl = new wxDataViewTreeCtrl((wxWindow *)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("window_style"))); - - return dataViewTreeCtrl; - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxDataViewTreeCtrl* dataViewTreeCtrl = new wxDataViewTreeCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("window_style"))); + + return dataViewTreeCtrl; + } }; class DataViewListCtrl : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxDataViewListCtrl* dataViewListCtrl = new wxDataViewListCtrl((wxWindow *)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("window_style"))); - - return dataViewListCtrl; - } - - void OnCreated( wxObject* wxobject, wxWindow* /*wxparent*/ ) override - { - wxDataViewListCtrl* list = wxDynamicCast( wxobject, wxDataViewListCtrl); - if ( NULL == list ) - { - // very very strange - return; - } - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if (childObj->GetClassName() == _("dataViewListColumn")) - { - if (childObj->GetPropertyAsString( _("type")) == _("Text")) - { - auto* col = list->AppendTextColumn( - childObj->GetPropertyAsString(_("label")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("Toggle")) - { - auto* col = list->AppendToggleColumn( - childObj->GetPropertyAsString(_("label")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("Progress")) - { - auto* col = list->AppendProgressColumn( - childObj->GetPropertyAsString(_("label")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - else if (childObj->GetPropertyAsString( _("type")) == _("IconText")) - { - auto* col = list->AppendIconTextColumn( - childObj->GetPropertyAsString(_("label")), - static_cast(childObj->GetPropertyAsInteger(_("mode"))), - childObj->GetPropertyAsInteger(_("width")), - static_cast(childObj->GetPropertyAsInteger(_("align"))), - childObj->GetPropertyAsInteger(_("flags")) - ); - if (!childObj->IsNull(_("ellipsize"))) - { - col->GetRenderer()->EnableEllipsize(static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); - } - } - } - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxDataViewListCtrl* dataViewListCtrl = new wxDataViewListCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("window_style"))); + + return dataViewListCtrl; + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxDataViewListCtrl* list = wxDynamicCast(wxobject, wxDataViewListCtrl); + if (NULL == list) { + // very very strange + return; + } + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (childObj->GetClassName() == _("dataViewListColumn")) { + if (childObj->GetPropertyAsString(_("type")) == _("Text")) { + auto* col = list->AppendTextColumn( + childObj->GetPropertyAsString(_("label")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("Toggle")) { + auto* col = list->AppendToggleColumn( + childObj->GetPropertyAsString(_("label")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("Progress")) { + auto* col = list->AppendProgressColumn( + childObj->GetPropertyAsString(_("label")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } else if (childObj->GetPropertyAsString(_("type")) == _("IconText")) { + auto* col = list->AppendIconTextColumn( + childObj->GetPropertyAsString(_("label")), + static_cast(childObj->GetPropertyAsInteger(_("mode"))), + childObj->GetPropertyAsInteger(_("width")), + static_cast(childObj->GetPropertyAsInteger(_("align"))), + childObj->GetPropertyAsInteger(_("flags"))); + if (!childObj->IsNull(_("ellipsize"))) { + col->GetRenderer()->EnableEllipsize( + static_cast(childObj->GetPropertyAsInteger(_("ellipsize")))); + } + } + } + } + } }; -class DataViewListColumn : public ComponentBase{}; +class DataViewListColumn : public ComponentBase +{ +}; -class DataViewColumn : public ComponentBase{}; +class DataViewColumn : public ComponentBase +{ +}; /////////////////////////////////////////////////////////////////////////////// class wxcoreTreeListCtrlComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxTreeListCtrl* treeListCtrl = new wxTreeListCtrl( (wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - return treeListCtrl; - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - // initialize tree - wxTreeListCtrl* treeListCtrl = wxDynamicCast( wxobject, wxTreeListCtrl ); - int colCount = treeListCtrl->GetColumnCount(); - - // Check for columns - if ( 0 == colCount ) - { - return; - } - - wxTreeListItem root = treeListCtrl->GetRootItem(); - - wxTreeListItem treeListParent; - wxTreeListItem treeListItem; - int n = 0; - - // Build tree. - treeListItem = treeListCtrl->AppendItem( root, wxString::Format( _("Item #%d"), ++n ) ); - FillItem( treeListCtrl, treeListItem, colCount, n ); - - treeListParent = treeListItem; - for ( int i = 0; i < 5; ++i ) - { - treeListItem = treeListCtrl->AppendItem( treeListParent, wxString::Format( _("Item #%d"), ++n ) ); - FillItem( treeListCtrl, treeListItem, colCount, n ); - } - treeListCtrl->Expand( treeListParent ); - - treeListParent = treeListItem; - for ( int i = 0; i < 5; ++i ) - { - treeListItem = treeListCtrl->AppendItem( treeListParent, wxString::Format( _("Item #%d"), ++n ) ); - FillItem( treeListCtrl, treeListItem, colCount, n ); - } - treeListCtrl->Expand( treeListParent ); - } - - void FillItem( wxTreeListCtrl* treeListCtrl, wxTreeListItem itemId, int colCount, int row ) - { - for ( int i = 0; i < colCount; ++i ) - { - treeListCtrl->SetItemText( itemId, i, wxString::Format( _("Item #%d, column #%d" ), row, i ) ); - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxTreeListCtrl* treeListCtrl = new wxTreeListCtrl( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + return treeListCtrl; + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + // initialize tree + wxTreeListCtrl* treeListCtrl = wxDynamicCast(wxobject, wxTreeListCtrl); + int colCount = treeListCtrl->GetColumnCount(); + + // Check for columns + if (0 == colCount) { + return; + } + + wxTreeListItem root = treeListCtrl->GetRootItem(); + + wxTreeListItem treeListParent; + wxTreeListItem treeListItem; + int n = 0; + + // Build tree. + treeListItem = treeListCtrl->AppendItem(root, wxString::Format(_("Item #%d"), ++n)); + FillItem(treeListCtrl, treeListItem, colCount, n); + + treeListParent = treeListItem; + for (int i = 0; i < 5; ++i) { + treeListItem = treeListCtrl->AppendItem(treeListParent, wxString::Format(_("Item #%d"), ++n)); + FillItem(treeListCtrl, treeListItem, colCount, n); + } + treeListCtrl->Expand(treeListParent); + + treeListParent = treeListItem; + for (int i = 0; i < 5; ++i) { + treeListItem = treeListCtrl->AppendItem(treeListParent, wxString::Format(_("Item #%d"), ++n)); + FillItem(treeListCtrl, treeListItem, colCount, n); + } + treeListCtrl->Expand(treeListParent); + } + + void FillItem(wxTreeListCtrl* treeListCtrl, wxTreeListItem itemId, int colCount, int row) + { + for (int i = 0; i < colCount; ++i) { + treeListCtrl->SetItemText(itemId, i, wxString::Format(_("Item #%d, column #%d"), row, i)); + } + } }; class wxcoreTreeListCtrlColumnComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - IObject* obj = GetManager()->GetIObject( wxobject ); - wxTreeListCtrl* treeList = wxDynamicCast( wxparent, wxTreeListCtrl ); - - if ( !( obj && treeList ) ) - { - wxLogError( _("wxcoreTreeListCtrlColumnComponent is missing its wxFormBuilder object(%i) or its parent(%i)"), obj,treeList ); - return; - } - - treeList->AppendColumn( obj->GetPropertyAsString( _("name") ), - obj->GetPropertyAsInteger( _("width") ), - static_cast< wxAlignment >( obj->GetPropertyAsInteger( _("alignment") ) ), - obj->GetPropertyAsInteger( _("flag") ) ); - } - - void OnSelected(wxObject*) override { - } + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + IObject* obj = GetManager()->GetIObject(wxobject); + wxTreeListCtrl* treeList = wxDynamicCast(wxparent, wxTreeListCtrl); + + if (!(obj && treeList)) { + wxLogError( + _("wxcoreTreeListCtrlColumnComponent is missing its wxFormBuilder object(%i) or its parent(%i)"), obj, + treeList); + return; + } + + treeList->AppendColumn( + obj->GetPropertyAsString(_("name")), obj->GetPropertyAsInteger(_("width")), + static_cast(obj->GetPropertyAsInteger(_("alignment"))), obj->GetPropertyAsInteger(_("flag"))); + } + + void OnSelected(wxObject*) override {} }; class RibbonBarComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxRibbonBar *rb = new wxRibbonBar((wxWindow*)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) ); - - if( obj->GetPropertyAsString( _("theme")) == _("Default")) - rb->SetArtProvider( new wxRibbonDefaultArtProvider ); - else if( obj->GetPropertyAsString( _("theme")) == _("Generic")) - rb->SetArtProvider( new wxRibbonAUIArtProvider ); - else if( obj->GetPropertyAsString( _("theme")) == _("MSW") ) - rb->SetArtProvider( new wxRibbonMSWArtProvider ); - - rb->PushEventHandler( new ComponentEvtHandler( rb, GetManager() ) ); - - return rb; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxRibbonBar); - if (window) - { - window->PopEventHandler(true); - } - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxRibbonBar* rb = wxDynamicCast( wxobject, wxRibbonBar ); - if ( NULL == rb ) - { - // very very strange - return; - } - - rb->Realize(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxRibbonBar* rb = new wxRibbonBar( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + if (obj->GetPropertyAsString(_("theme")) == _("Default")) + rb->SetArtProvider(new wxRibbonDefaultArtProvider); + else if (obj->GetPropertyAsString(_("theme")) == _("Generic")) + rb->SetArtProvider(new wxRibbonAUIArtProvider); + else if (obj->GetPropertyAsString(_("theme")) == _("MSW")) + rb->SetArtProvider(new wxRibbonMSWArtProvider); + + rb->PushEventHandler(new ComponentEvtHandler(rb, GetManager())); + + return rb; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxRibbonBar); + if (window) { + window->PopEventHandler(true); + } + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxRibbonBar* rb = wxDynamicCast(wxobject, wxRibbonBar); + if (NULL == rb) { + // very very strange + return; + } + + rb->Realize(); + } }; -void ComponentEvtHandler::OnRibbonBarPageChanged( wxRibbonBarEvent& event ) -{ - if ( m_window != event.GetEventObject() ) - { - return; - } - - wxRibbonBar *rb = wxDynamicCast( event.GetEventObject(), wxRibbonBar ); - if( rb == NULL ) - { - return; - } - - int selPage = rb->GetActivePage(); - - size_t count = m_manager->GetChildCount( m_window ); - for ( size_t i = 0; i < count; i++ ) - { - wxObject* wxChild = m_manager->GetChild( m_window, i ); - IObject* iChild = m_manager->GetIObject( wxChild ); - if ( iChild ) - { - if (int(i) == selPage && iChild->GetPropertyAsInteger(_("select")) == 0) { - m_manager->ModifyProperty( wxChild, _("select"), wxT("1"), false ); - } else if (int(i) != selPage && iChild->GetPropertyAsInteger(_("select")) != 0) { - m_manager->ModifyProperty( wxChild, _("select"), wxT("0"), false ); - } - } - } - - // Select the corresponding ribbon page in the object tree - if ( NULL != rb ) - { - m_manager->SelectObject( rb->GetPage( selPage ) ); - } +void ComponentEvtHandler::OnRibbonBarPageChanged(wxRibbonBarEvent& event) +{ + if (m_window != event.GetEventObject()) { + return; + } + + wxRibbonBar* rb = wxDynamicCast(event.GetEventObject(), wxRibbonBar); + if (rb == NULL) { + return; + } + + int selPage = rb->GetActivePage(); + + size_t count = m_manager->GetChildCount(m_window); + for (size_t i = 0; i < count; i++) { + wxObject* wxChild = m_manager->GetChild(m_window, i); + IObject* iChild = m_manager->GetIObject(wxChild); + if (iChild) { + if (int(i) == selPage && iChild->GetPropertyAsInteger(_("select")) == 0) { + m_manager->ModifyProperty(wxChild, _("select"), wxT("1"), false); + } else if (int(i) != selPage && iChild->GetPropertyAsInteger(_("select")) != 0) { + m_manager->ModifyProperty(wxChild, _("select"), wxT("0"), false); + } + } + } + + // Select the corresponding ribbon page in the object tree + if (NULL != rb) { + m_manager->SelectObject(rb->GetPage(selPage)); + } } class RibbonPageComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxRibbonPage *rbpage = new wxRibbonPage((wxRibbonBar*)parent, - wxID_ANY, - obj->GetPropertyAsString(_("label")), - obj->GetPropertyAsBitmap(_("bitmap")), - 0); - - if (obj->GetPropertyAsInteger(_("select")) != 0) { - ((wxRibbonBar*)parent)->SetActivePage(rbpage); - } - - //rbpage->PushEventHandler( new ComponentEvtHandler( rbpage, GetManager() ) ); - - return rbpage; - } - - /* - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxRibbonPage); - if (window) - { - window->PopEventHandler(true); - } - } - */ + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxRibbonPage* rbpage = new wxRibbonPage( + (wxRibbonBar*)parent, wxID_ANY, obj->GetPropertyAsString(_("label")), obj->GetPropertyAsBitmap(_("bitmap")), + 0); + + if (obj->GetPropertyAsInteger(_("select")) != 0) { + ((wxRibbonBar*)parent)->SetActivePage(rbpage); + } + + // rbpage->PushEventHandler( new ComponentEvtHandler( rbpage, GetManager() ) ); + + return rbpage; + } + + /* + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxRibbonPage); + if (window) + { + window->PopEventHandler(true); + } + } + */ }; class RibbonPanelComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxRibbonPanel *rbp = new wxRibbonPanel((wxRibbonPage*)parent, - wxID_ANY, - obj->GetPropertyAsString(_("label")), - obj->GetPropertyAsBitmap(_("bitmap")), - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style")) ); - - //rbp->PushEventHandler( new ComponentEvtHandler( rbp, GetManager() ) ); - - return rbp; - } - - /* - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxRibbonPanel); - if (window) - { - window->PopEventHandler(true); - } - } - */ + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxRibbonPanel* rbp = new wxRibbonPanel( + (wxRibbonPage*)parent, wxID_ANY, obj->GetPropertyAsString(_("label")), obj->GetPropertyAsBitmap(_("bitmap")), + obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + // rbp->PushEventHandler( new ComponentEvtHandler( rbp, GetManager() ) ); + + return rbp; + } + + /* + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxRibbonPanel); + if (window) + { + window->PopEventHandler(true); + } + } + */ }; class RibbonButtonBarComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxRibbonButtonBar *rbb = new wxRibbonButtonBar((wxRibbonPanel*)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - 0); - - //rbb->PushEventHandler( new ComponentEvtHandler( rbb, GetManager() ) ); - - return rbb; - } - - /* - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxRibbonButtonBar); - if (window) - { - window->PopEventHandler(true); - } - } - */ - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxRibbonButtonBar* rb = wxDynamicCast( wxobject, wxRibbonButtonBar ); - if ( NULL == rb ) - { - // very very strange - return; - } - - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if (childObj->GetClassName() == wxT("ribbonButton")) - { - rb->AddButton(wxID_ANY, - childObj->GetPropertyAsString( _("label") ), - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } else if (childObj->GetClassName() == wxT("ribbonDropdownButton")) - { - rb->AddDropdownButton(wxID_ANY, - childObj->GetPropertyAsString( _("label") ), - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } else if (childObj->GetClassName() == wxT("ribbonHybridButton")) - { - rb->AddHybridButton(wxID_ANY, - childObj->GetPropertyAsString( _("label") ), - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } else if (childObj->GetClassName() == wxT("ribbonToggleButton")) - { - rb->AddToggleButton(wxID_ANY, - childObj->GetPropertyAsString( _("label") ), - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxRibbonButtonBar* rbb = new wxRibbonButtonBar( + (wxRibbonPanel*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), 0); + + // rbb->PushEventHandler( new ComponentEvtHandler( rbb, GetManager() ) ); + + return rbb; + } + + /* + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxRibbonButtonBar); + if (window) + { + window->PopEventHandler(true); + } + } + */ + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxRibbonButtonBar* rb = wxDynamicCast(wxobject, wxRibbonButtonBar); + if (NULL == rb) { + // very very strange + return; + } + + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (childObj->GetClassName() == wxT("ribbonButton")) { + rb->AddButton( + wxID_ANY, childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsBitmap(_("bitmap")), + childObj->GetPropertyAsString(_("help"))); + } else if (childObj->GetClassName() == wxT("ribbonDropdownButton")) { + rb->AddDropdownButton( + wxID_ANY, childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsBitmap(_("bitmap")), + childObj->GetPropertyAsString(_("help"))); + } else if (childObj->GetClassName() == wxT("ribbonHybridButton")) { + rb->AddHybridButton( + wxID_ANY, childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsBitmap(_("bitmap")), + childObj->GetPropertyAsString(_("help"))); + } else if (childObj->GetClassName() == wxT("ribbonToggleButton")) { + rb->AddToggleButton( + wxID_ANY, childObj->GetPropertyAsString(_("label")), childObj->GetPropertyAsBitmap(_("bitmap")), + childObj->GetPropertyAsString(_("help"))); + } + } + } }; -class RibbonButtonComponent : public ComponentBase{}; -class RibbonDropdownButtonComponent : public ComponentBase{}; -class RibbonHybridButtonComponent : public ComponentBase{}; -class RibbonToggleButtonComponent : public ComponentBase{}; +class RibbonButtonComponent : public ComponentBase +{ +}; +class RibbonDropdownButtonComponent : public ComponentBase +{ +}; +class RibbonHybridButtonComponent : public ComponentBase +{ +}; +class RibbonToggleButtonComponent : public ComponentBase +{ +}; class RibbonToolBarComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxRibbonToolBar *rbb = new wxRibbonToolBar((wxRibbonPanel*)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - 0 ); - - //rbb->PushEventHandler( new ComponentEvtHandler( rbb, GetManager() ) ); - - return rbb; - } - - /* - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxRibbonToolBar); - if (window) - { - window->PopEventHandler(true); - } - } - */ - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxRibbonToolBar* rb = wxDynamicCast( wxobject, wxRibbonToolBar ); - if ( NULL == rb ) - { - // very very strange - return; - } - - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if (wxT("ribbonTool") == childObj->GetClassName() ) - { - rb->AddTool(wxID_ANY, - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } else if (wxT("ribbonDropdownTool") == childObj->GetClassName() ) - { - rb->AddDropdownTool(wxID_ANY, - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } else if (wxT("ribbonHybridTool") == childObj->GetClassName() ) - { - rb->AddHybridTool(wxID_ANY, - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - } else if (wxT("ribbonToggleTool") == childObj->GetClassName() ) - { - rb->AddToggleTool(wxID_ANY, - childObj->GetPropertyAsBitmap( _("bitmap") ), - childObj->GetPropertyAsString( _("help") ) ); - - } - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxRibbonToolBar* rbb = new wxRibbonToolBar( + (wxRibbonPanel*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), 0); + + // rbb->PushEventHandler( new ComponentEvtHandler( rbb, GetManager() ) ); + + return rbb; + } + + /* + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxRibbonToolBar); + if (window) + { + window->PopEventHandler(true); + } + } + */ + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxRibbonToolBar* rb = wxDynamicCast(wxobject, wxRibbonToolBar); + if (NULL == rb) { + // very very strange + return; + } + + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (wxT("ribbonTool") == childObj->GetClassName()) { + rb->AddTool( + wxID_ANY, childObj->GetPropertyAsBitmap(_("bitmap")), childObj->GetPropertyAsString(_("help"))); + } else if (wxT("ribbonDropdownTool") == childObj->GetClassName()) { + rb->AddDropdownTool( + wxID_ANY, childObj->GetPropertyAsBitmap(_("bitmap")), childObj->GetPropertyAsString(_("help"))); + } else if (wxT("ribbonHybridTool") == childObj->GetClassName()) { + rb->AddHybridTool( + wxID_ANY, childObj->GetPropertyAsBitmap(_("bitmap")), childObj->GetPropertyAsString(_("help"))); + } else if (wxT("ribbonToggleTool") == childObj->GetClassName()) { + rb->AddToggleTool( + wxID_ANY, childObj->GetPropertyAsBitmap(_("bitmap")), childObj->GetPropertyAsString(_("help"))); + } + } + } }; -class RibbonToolComponent : public ComponentBase{}; -class RibbonDropdownToolComponent : public ComponentBase{}; -class RibbonHybridToolComponent : public ComponentBase{}; -class RibbonToggleToolComponent : public ComponentBase{}; +class RibbonToolComponent : public ComponentBase +{ +}; +class RibbonDropdownToolComponent : public ComponentBase +{ +}; +class RibbonHybridToolComponent : public ComponentBase +{ +}; +class RibbonToggleToolComponent : public ComponentBase +{ +}; class RibbonGalleryComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxRibbonGallery *ribbonGallery = new wxRibbonGallery((wxRibbonPanel*)parent, - wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - 0); - - //ribbonGallery->PushEventHandler( new ComponentEvtHandler( ribbonGallery, GetManager() ) ); - - return ribbonGallery; - } - - /* - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxRibbonGallery); - if (window) - { - window->PopEventHandler(true); - } - } - */ - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxRibbonGallery* rg = wxDynamicCast( wxobject, wxRibbonGallery ); - if ( NULL == rg ) - { - // very very strange - return; - } - - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if ( wxT("ribbonGalleryItem") == childObj->GetClassName() ) - { - rg->Append(childObj->GetPropertyAsBitmap( _("bitmap") ), wxID_ANY ); - } - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxRibbonGallery* ribbonGallery = new wxRibbonGallery( + (wxRibbonPanel*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), 0); + + // ribbonGallery->PushEventHandler( new ComponentEvtHandler( ribbonGallery, GetManager() ) ); + + return ribbonGallery; + } + + /* + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxRibbonGallery); + if (window) + { + window->PopEventHandler(true); + } + } + */ + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxRibbonGallery* rg = wxDynamicCast(wxobject, wxRibbonGallery); + if (NULL == rg) { + // very very strange + return; + } + + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (wxT("ribbonGalleryItem") == childObj->GetClassName()) { + rg->Append(childObj->GetPropertyAsBitmap(_("bitmap")), wxID_ANY); + } + } + } }; -class RibbonGalleryItemComponent : public ComponentBase{}; +class RibbonGalleryItemComponent : public ComponentBase +{ +}; /////////////////////////////////////////////////////////////////////////////// BEGIN_LIBRARY() -WINDOW_COMPONENT("wxCalendarCtrl",CalendarCtrlComponent) -WINDOW_COMPONENT("wxDatePickerCtrl",DatePickerCtrlComponent) -WINDOW_COMPONENT("wxTimePickerCtrl",TimePickerCtrlComponent) +WINDOW_COMPONENT("wxCalendarCtrl", CalendarCtrlComponent) +WINDOW_COMPONENT("wxDatePickerCtrl", DatePickerCtrlComponent) +WINDOW_COMPONENT("wxTimePickerCtrl", TimePickerCtrlComponent) WINDOW_COMPONENT("wxHtmlWindow", HtmlWindowComponent) -WINDOW_COMPONENT("wxToggleButton",ToggleButtonComponent) -WINDOW_COMPONENT("wxBitmapToggleButton",BitmapToggleButtonComponent) -WINDOW_COMPONENT("wxTreeCtrl",TreeCtrlComponent) -WINDOW_COMPONENT("wxGrid",GridComponent) -WINDOW_COMPONENT("wxScrollBar",ScrollBarComponent) -WINDOW_COMPONENT("wxSpinCtrl",SpinCtrlComponent) -WINDOW_COMPONENT("wxSpinButton",SpinButtonComponent) +WINDOW_COMPONENT("wxToggleButton", ToggleButtonComponent) +WINDOW_COMPONENT("wxBitmapToggleButton", BitmapToggleButtonComponent) +WINDOW_COMPONENT("wxTreeCtrl", TreeCtrlComponent) +WINDOW_COMPONENT("wxGrid", GridComponent) +WINDOW_COMPONENT("wxScrollBar", ScrollBarComponent) +WINDOW_COMPONENT("wxSpinCtrl", SpinCtrlComponent) +WINDOW_COMPONENT("wxSpinButton", SpinButtonComponent) WINDOW_COMPONENT("CustomControl", CustomControlComponent) ABSTRACT_COMPONENT("CustomCode", CustomCodeComponent) -WINDOW_COMPONENT("wxDataViewCtrl", DataViewCtrl ) -WINDOW_COMPONENT("wxDataViewTreeCtrl", DataViewTreeCtrl ) -WINDOW_COMPONENT("wxDataViewListCtrl", DataViewListCtrl ) +WINDOW_COMPONENT("wxDataViewCtrl", DataViewCtrl) +WINDOW_COMPONENT("wxDataViewTreeCtrl", DataViewTreeCtrl) +WINDOW_COMPONENT("wxDataViewListCtrl", DataViewListCtrl) ABSTRACT_COMPONENT("dataViewListColumn", DataViewListColumn) ABSTRACT_COMPONENT("dataViewColumn", DataViewColumn) WINDOW_COMPONENT("wxRibbonBar", RibbonBarComponent) @@ -2679,14 +2530,14 @@ ABSTRACT_COMPONENT("ribbonToggleTool", RibbonToggleToolComponent) ABSTRACT_COMPONENT("ribbonGalleryItem", RibbonGalleryItemComponent) // wxCheckListBox -WINDOW_COMPONENT("wxCheckListBox",CheckListBoxComponent) +WINDOW_COMPONENT("wxCheckListBox", CheckListBoxComponent) #ifdef USE_MEDIACTRL -WINDOW_COMPONENT("wxMediaCtrl",MediaCtrlComponent) +WINDOW_COMPONENT("wxMediaCtrl", MediaCtrlComponent) #endif // wxRichTextCtrl -WINDOW_COMPONENT( "wxRichTextCtrl", RichTextCtrlComponent ) +WINDOW_COMPONENT("wxRichTextCtrl", RichTextCtrlComponent) MACRO(wxTE_PROCESS_ENTER); MACRO(wxTE_PROCESS_TAB); MACRO(wxTE_READONLY); @@ -2742,7 +2593,7 @@ MACRO(wxTE_CENTER); MACRO(wxTE_RIGHT); MACRO(wxTE_CAPITALIZE); -WINDOW_COMPONENT("wxSpinCtrlDouble",SpinCtrlDoubleComponent) +WINDOW_COMPONENT("wxSpinCtrlDouble", SpinCtrlDoubleComponent) // wxCalendarCtrl MACRO(wxCAL_SUNDAY_FIRST) @@ -2763,7 +2614,7 @@ MACRO(wxDP_DEFAULT) // wxTimePickerCtrl -MACRO( wxTP_DEFAULT ) +MACRO(wxTP_DEFAULT) // wxHtmlWindow @@ -2805,7 +2656,7 @@ MACRO(wxSP_HORIZONTAL) MACRO(wxSP_VERTICAL) // wxGenericDirCtrl -WINDOW_COMPONENT("wxGenericDirCtrl",GenericDirCtrlComponent) +WINDOW_COMPONENT("wxGenericDirCtrl", GenericDirCtrlComponent) MACRO(wxDIRCTRL_DIR_ONLY) MACRO(wxDIRCTRL_3D_INTERNAL) MACRO(wxDIRCTRL_SELECT_FIRST) @@ -2851,7 +2702,7 @@ MACRO(wxPG_TOOLBAR) MACRO(wxPG_NO_INTERNAL_BORDER) // wxStyledTextCtrl -WINDOW_COMPONENT("wxStyledTextCtrl", StyledTextComponent ) +WINDOW_COMPONENT("wxStyledTextCtrl", StyledTextComponent) // wxDataViewCtrl MACRO(wxDV_SINGLE) @@ -2906,7 +2757,7 @@ MACRO(wxRIBBON_PANEL_FLEXIBLE) // wxTreeListCtrl -WINDOW_COMPONENT( "wxTreeListCtrl", wxcoreTreeListCtrlComponent ) +WINDOW_COMPONENT("wxTreeListCtrl", wxcoreTreeListCtrlComponent) MACRO(wxTL_SINGLE) MACRO(wxTL_MULTIPLE) MACRO(wxTL_CHECKBOX) @@ -2914,7 +2765,7 @@ MACRO(wxTL_3STATE) MACRO(wxTL_USER_3STATE) MACRO(wxTR_DEFAULT_STYLE) -ABSTRACT_COMPONENT( "wxTreeListCtrlColumn", wxcoreTreeListCtrlColumnComponent ) +ABSTRACT_COMPONENT("wxTreeListCtrlColumn", wxcoreTreeListCtrlColumnComponent) MACRO(wxCOL_RESIZABLE) MACRO(wxCOL_SORTABLE) MACRO(wxCOL_REORDERABLE) diff --git a/plugins/containers/bookutils.h b/plugins/containers/bookutils.h index 31a973537..c1de0190b 100644 --- a/plugins/containers/bookutils.h +++ b/plugins/containers/bookutils.h @@ -21,160 +21,145 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef PLUGINS_CONTAINERS_BOOKUTILS_H #define PLUGINS_CONTAINERS_BOOKUTILS_H -#include -#include #include -#include + +#include #include +#include #include -#include + +#include +#include #ifdef wxUSE_COLLPANE -#include + #include #endif + class SuppressEventHandlers { private: - std::vector< wxEvtHandler* > m_handlers; - wxWindow* m_window; + std::vector m_handlers; + wxWindow* m_window; public: - SuppressEventHandlers( wxWindow* window ) - : - m_window( window ) - { - while ( window->GetEventHandler() != window ) - { - m_handlers.push_back( window->PopEventHandler() ); - } - } - - ~SuppressEventHandlers() - { - std::vector< wxEvtHandler* >::reverse_iterator handler; - for ( handler = m_handlers.rbegin(); handler != m_handlers.rend(); ++handler ) - { - m_window->PushEventHandler( *handler ); - } - } + SuppressEventHandlers(wxWindow* window) : m_window(window) + { + while (window->GetEventHandler() != window) { m_handlers.push_back(window->PopEventHandler()); } + } + + ~SuppressEventHandlers() + { + std::vector::reverse_iterator handler; + for (handler = m_handlers.rbegin(); handler != m_handlers.rend(); ++handler) { + m_window->PushEventHandler(*handler); + } + } }; namespace BookUtils { - template < class T > - void AddImageList( IObject* obj, T* book ) - { - if ( !obj->GetPropertyAsString( _("bitmapsize") ).empty() ) - { - wxSize imageSize = obj->GetPropertyAsSize(_("bitmapsize")); - wxImageList* images = new wxImageList( imageSize.GetWidth(), imageSize.GetHeight() ); - wxImage image = wxBitmap( default_xpm ).ConvertToImage(); - images->Add( image.Scale( imageSize.GetWidth(), imageSize.GetHeight() ) ); - book->AssignImageList( images ); - } - } - - template < class T > - void OnCreated( wxObject* wxobject, wxWindow* wxparent, IManager* manager, wxString name ) - { - // Easy read-only property access - IObject* obj = manager->GetIObject( wxobject ); - - T* book = wxDynamicCast( wxparent, T ); - - //This wouldn't compile in MinGW - strange - ///wxWindow* page = wxDynamicCast( manager->GetChild( wxobject, 0 ), wxWindow ); - - // Do this instead - wxObject* child = manager->GetChild( wxobject, 0 ); - wxWindow* page = NULL; - if ( child->IsKindOf(CLASSINFO(wxWindow))) - { - page = (wxWindow*)child; - } - - // Error checking - if ( !( obj && book && page ) ) - { - wxLogError( _("%s is missing its wxFormBuilder object(%p), its parent(%p), or its child(%p)"), name.c_str(), obj, book, page ); - return; - } - - // Prevent event handling by wxFB - these aren't user generated events - SuppressEventHandlers suppress( book ); - - // Save selection - int selection = book->GetSelection(); - book->AddPage( page, obj->GetPropertyAsString( _("label") ) ); - - // Apply image to page - IObject* parentObj = manager->GetIObject( wxparent ); - if ( !parentObj ) - { - wxLogError( _("%s's parent is missing its wxFormBuilder object"), name.c_str() ); - return; - } - - if ( !parentObj->GetPropertyAsString( _("bitmapsize") ).empty() ) - { - if ( !obj->GetPropertyAsString( _("bitmap") ).empty() ) - { - wxSize imageSize = parentObj->GetPropertyAsSize( _("bitmapsize") ); - int width = imageSize.GetWidth(); - int height = imageSize.GetHeight(); - if ( width > 0 && height > 0 ) - { - wxImageList* imageList = book->GetImageList(); - if ( imageList != NULL ) - { - wxImage image = obj->GetPropertyAsBitmap( _("bitmap") ).ConvertToImage(); - imageList->Add( image.Scale( width, height ) ); - book->SetPageImage( book->GetPageCount() - 1, imageList->GetImageCount() - 1 ); - } - } - } - } - - if ( obj->GetPropertyAsString( _("select") ) == wxT("0") && selection >= 0 ) - { - book->SetSelection(selection); - } - else - { - book->SetSelection( book->GetPageCount() - 1 ); - } - } - - template < class T > - void OnSelected( wxObject* wxobject, IManager* manager ) - { - // Get actual page - first child - wxObject* page = manager->GetChild( wxobject, 0 ); - if ( NULL == page ) - { - return; - } - - T* book = wxDynamicCast( manager->GetParent( wxobject ), T ); - if ( book ) - { - for ( size_t i = 0; i < book->GetPageCount(); ++i ) - { - if ( book->GetPage( i ) == page ) - { - // Prevent infinite event loop - SuppressEventHandlers suppress( book ); - - // Select Page - book->SetSelection( i ); - } - } - } - } +template +void AddImageList(IObject* obj, T* book) +{ + if (!obj->GetPropertyAsString(_("bitmapsize")).empty()) { + wxSize imageSize = obj->GetPropertyAsSize(_("bitmapsize")); + wxImageList* images = new wxImageList(imageSize.GetWidth(), imageSize.GetHeight()); + wxImage image = wxBitmap(default_xpm).ConvertToImage(); + images->Add(image.Scale(imageSize.GetWidth(), imageSize.GetHeight())); + book->AssignImageList(images); + } +} + +template +void OnCreated(wxObject* wxobject, wxWindow* wxparent, IManager* manager, wxString name) +{ + // Easy read-only property access + IObject* obj = manager->GetIObject(wxobject); + + T* book = wxDynamicCast(wxparent, T); + + // This wouldn't compile in MinGW - strange + /// wxWindow* page = wxDynamicCast( manager->GetChild( wxobject, 0 ), wxWindow ); + + // Do this instead + wxObject* child = manager->GetChild(wxobject, 0); + wxWindow* page = NULL; + if (child->IsKindOf(CLASSINFO(wxWindow))) { + page = (wxWindow*)child; + } + + // Error checking + if (!(obj && book && page)) { + wxLogError( + _("%s is missing its wxFormBuilder object(%p), its parent(%p), or its child(%p)"), name.c_str(), obj, book, + page); + return; + } + + // Prevent event handling by wxFB - these aren't user generated events + SuppressEventHandlers suppress(book); + + // Save selection + int selection = book->GetSelection(); + book->AddPage(page, obj->GetPropertyAsString(_("label"))); + + // Apply image to page + IObject* parentObj = manager->GetIObject(wxparent); + if (!parentObj) { + wxLogError(_("%s's parent is missing its wxFormBuilder object"), name.c_str()); + return; + } + + if (!parentObj->GetPropertyAsString(_("bitmapsize")).empty()) { + if (!obj->GetPropertyAsString(_("bitmap")).empty()) { + wxSize imageSize = parentObj->GetPropertyAsSize(_("bitmapsize")); + int width = imageSize.GetWidth(); + int height = imageSize.GetHeight(); + if (width > 0 && height > 0) { + wxImageList* imageList = book->GetImageList(); + if (imageList != NULL) { + wxImage image = obj->GetPropertyAsBitmap(_("bitmap")).ConvertToImage(); + imageList->Add(image.Scale(width, height)); + book->SetPageImage(book->GetPageCount() - 1, imageList->GetImageCount() - 1); + } + } + } + } + + if (obj->GetPropertyAsString(_("select")) == wxT("0") && selection >= 0) { + book->SetSelection(selection); + } else { + book->SetSelection(book->GetPageCount() - 1); + } +} + +template +void OnSelected(wxObject* wxobject, IManager* manager) +{ + // Get actual page - first child + wxObject* page = manager->GetChild(wxobject, 0); + if (NULL == page) { + return; + } + + T* book = wxDynamicCast(manager->GetParent(wxobject), T); + if (book) { + for (size_t i = 0; i < book->GetPageCount(); ++i) { + if (book->GetPage(i) == page) { + // Prevent infinite event loop + SuppressEventHandlers suppress(book); + + // Select Page + book->SetSelection(i); + } + } + } } +} // namespace BookUtils -#endif // PLUGINS_CONTAINERS_BOOKUTILS_H +#endif // PLUGINS_CONTAINERS_BOOKUTILS_H diff --git a/plugins/containers/containers.cpp b/plugins/containers/containers.cpp index 07b6bf2c5..ecd64c176 100644 --- a/plugins/containers/containers.cpp +++ b/plugins/containers/containers.cpp @@ -23,112 +23,105 @@ // /////////////////////////////////////////////////////////////////////////////// -// Includes collpane, notebook, listbook, choicebook, auibook -#include "bookutils.h" - -#include #include #include + +#include #include +#include "bookutils.h" + #ifndef __WXGTK__ -#include + #include #endif + /// Event handler for events generated by controls in this plugin class ComponentEvtHandler : public wxEvtHandler { private: - wxWindow* m_window; - IManager* m_manager; + wxWindow* m_window; + IManager* m_manager; public: - ComponentEvtHandler( wxWindow* win, IManager* manager ) - : - m_window( win ), - m_manager( manager ) - { - } + ComponentEvtHandler(wxWindow* win, IManager* manager) : m_window(win), m_manager(manager) {} protected: #ifdef wxUSE_COLLPANE - void OnCollapsiblePaneChanged( wxCollapsiblePaneEvent& event ); + void OnCollapsiblePaneChanged(wxCollapsiblePaneEvent& event); #endif - void OnNotebookPageChanged( wxNotebookEvent& event ); - void OnListbookPageChanged( wxListbookEvent& event ); - void OnChoicebookPageChanged( wxChoicebookEvent& event ); - void OnAuiNotebookPageChanged( wxAuiNotebookEvent& event ); - void OnSplitterSashChanged( wxSplitterEvent& event ); - - template < class T > - void OnBookPageChanged( int selPage, wxEvent* event ) - { - // Only handle events from this book - prevents problems with nested books, because OnSelected is fired on an - // object and all of its parents - if ( m_window != event->GetEventObject() ) - { - return; - } - - if ( selPage < 0 ) - { - return; - } - - size_t count = m_manager->GetChildCount( m_window ); - for ( size_t i = 0; i < count; i++ ) - { - wxObject* wxChild = m_manager->GetChild( m_window, i ); - IObject* iChild = m_manager->GetIObject( wxChild ); - if ( iChild ) - { - if ( (int)i == selPage && !iChild->GetPropertyAsInteger( _("select") ) ) - { - m_manager->ModifyProperty( wxChild, _("select"), wxT("1"), false ); - } - else if ( (int)i != selPage && iChild->GetPropertyAsInteger( _("select") ) ) - { - m_manager->ModifyProperty( wxChild, _("select"), wxT("0"), false ); - } - } - } - - // Select the corresponding panel in the object tree - T* book = wxDynamicCast( m_window, T ); - if ( NULL != book ) - { - m_manager->SelectObject( book->GetPage( selPage ) ); - } - } - - void OnAuiNotebookPageClosed( wxAuiNotebookEvent& event ) - { - wxMessageBox( wxT("wxAuiNotebook pages can normally be closed.\nHowever, it is difficult to design a page that has been closed, so this action has been vetoed."), - wxT("Page Close Vetoed!"), wxICON_INFORMATION, NULL ); - event.Veto(); - } - - void OnAuiNotebookAllowDND( wxAuiNotebookEvent& event ) - { - wxMessageBox( wxT("wxAuiNotebook pages can be dragged to other wxAuiNotebooks if the wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND event is caught and allowed.\nHowever, it is difficult to design a page that has been moved, so this action was not allowed."), - wxT("Page Move Not Allowed!"), wxICON_INFORMATION, NULL ); - event.Veto(); - } - - DECLARE_EVENT_TABLE() + void OnNotebookPageChanged(wxNotebookEvent& event); + void OnListbookPageChanged(wxListbookEvent& event); + void OnChoicebookPageChanged(wxChoicebookEvent& event); + void OnAuiNotebookPageChanged(wxAuiNotebookEvent& event); + void OnSplitterSashChanged(wxSplitterEvent& event); + + template + void OnBookPageChanged(int selPage, wxEvent* event) + { + // Only handle events from this book - prevents problems with nested books, because OnSelected is fired on an + // object and all of its parents + if (m_window != event->GetEventObject()) { + return; + } + + if (selPage < 0) { + return; + } + + size_t count = m_manager->GetChildCount(m_window); + for (size_t i = 0; i < count; i++) { + wxObject* wxChild = m_manager->GetChild(m_window, i); + IObject* iChild = m_manager->GetIObject(wxChild); + if (iChild) { + if ((int)i == selPage && !iChild->GetPropertyAsInteger(_("select"))) { + m_manager->ModifyProperty(wxChild, _("select"), wxT("1"), false); + } else if ((int)i != selPage && iChild->GetPropertyAsInteger(_("select"))) { + m_manager->ModifyProperty(wxChild, _("select"), wxT("0"), false); + } + } + } + + // Select the corresponding panel in the object tree + T* book = wxDynamicCast(m_window, T); + if (NULL != book) { + m_manager->SelectObject(book->GetPage(selPage)); + } + } + + void OnAuiNotebookPageClosed(wxAuiNotebookEvent& event) + { + wxMessageBox( + wxT("wxAuiNotebook pages can normally be closed.\nHowever, it is difficult to design a page that has been " + "closed, so this action has been vetoed."), + wxT("Page Close Vetoed!"), wxICON_INFORMATION, NULL); + event.Veto(); + } + + void OnAuiNotebookAllowDND(wxAuiNotebookEvent& event) + { + wxMessageBox( + wxT("wxAuiNotebook pages can be dragged to other wxAuiNotebooks if the wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND " + "event is caught and allowed.\nHowever, it is difficult to design a page that has been moved, so this " + "action was not allowed."), + wxT("Page Move Not Allowed!"), wxICON_INFORMATION, NULL); + event.Veto(); + } + + DECLARE_EVENT_TABLE() }; -BEGIN_EVENT_TABLE( ComponentEvtHandler, wxEvtHandler ) +BEGIN_EVENT_TABLE(ComponentEvtHandler, wxEvtHandler) #ifdef wxUSE_COLLPANE - EVT_COLLAPSIBLEPANE_CHANGED(wxID_ANY, ComponentEvtHandler::OnCollapsiblePaneChanged) +EVT_COLLAPSIBLEPANE_CHANGED(wxID_ANY, ComponentEvtHandler::OnCollapsiblePaneChanged) #endif - EVT_NOTEBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnNotebookPageChanged) - EVT_LISTBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnListbookPageChanged) - EVT_CHOICEBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnChoicebookPageChanged) - EVT_AUINOTEBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnAuiNotebookPageChanged) - EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY, ComponentEvtHandler::OnAuiNotebookPageClosed) - EVT_AUINOTEBOOK_ALLOW_DND(wxID_ANY, ComponentEvtHandler::OnAuiNotebookAllowDND) - EVT_SPLITTER_SASH_POS_CHANGED(wxID_ANY, ComponentEvtHandler::OnSplitterSashChanged) +EVT_NOTEBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnNotebookPageChanged) +EVT_LISTBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnListbookPageChanged) +EVT_CHOICEBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnChoicebookPageChanged) +EVT_AUINOTEBOOK_PAGE_CHANGED(wxID_ANY, ComponentEvtHandler::OnAuiNotebookPageChanged) +EVT_AUINOTEBOOK_PAGE_CLOSE(wxID_ANY, ComponentEvtHandler::OnAuiNotebookPageClosed) +EVT_AUINOTEBOOK_ALLOW_DND(wxID_ANY, ComponentEvtHandler::OnAuiNotebookAllowDND) +EVT_SPLITTER_SASH_POS_CHANGED(wxID_ANY, ComponentEvtHandler::OnSplitterSashChanged) END_EVENT_TABLE() /////////////////////////////////////////////////////////////////////////////// @@ -136,69 +129,72 @@ END_EVENT_TABLE() class wxCustomSplitterWindow : public wxSplitterWindow { public: - wxCustomSplitterWindow(wxWindow* parent, wxWindowID id, const wxPoint& point = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style=wxSP_3D) - : - wxSplitterWindow( parent, id, point, size, style ), - m_customSashPos( 0 ), - m_customMinPaneSize( 0 ) - { - } - - int m_customSashPos; - int m_customMinPaneSize; - int m_initialSashPos; - - // Used to ensure sash position is correct - void OnIdle( wxIdleEvent& ) - { - Disconnect( wxEVT_IDLE, wxIdleEventHandler( wxCustomSplitterWindow::OnIdle ) ); - - // So the selection of the sizer at its initial position is cleared, then shown at the correct position - Freeze(); - SetSashPosition( m_initialSashPos ); - Layout(); - Refresh(); - Update(); - Thaw(); - } + wxCustomSplitterWindow( + wxWindow* parent, wxWindowID id, const wxPoint& point = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = wxSP_3D) : + wxSplitterWindow(parent, id, point, size, style), m_customSashPos(0), m_customMinPaneSize(0) + { + } + + int m_customSashPos; + int m_customMinPaneSize; + int m_initialSashPos; + + // Used to ensure sash position is correct + void OnIdle(wxIdleEvent&) + { + Disconnect(wxEVT_IDLE, wxIdleEventHandler(wxCustomSplitterWindow::OnIdle)); + + // So the selection of the sizer at its initial position is cleared, then shown at the correct position + Freeze(); + SetSashPosition(m_initialSashPos); + Layout(); + Refresh(); + Update(); + Thaw(); + } private: - bool OnSashPositionChange(int newSashPosition) override { - m_customSashPos = newSashPosition; - return wxSplitterWindow::OnSashPositionChange( newSashPosition ); - } - - void OnDoubleClickSash(int, int) override { - if ( 0 == m_customMinPaneSize ) - { - wxMessageBox( wxT("Double-clicking a wxSplitterWindow sash with the minimum pane size set to 0 would normally unsplit it.\nHowever, it is difficult to design a pane that has been closed, so this action has been vetoed."), - wxT("Unsplit Vetoed!"), wxICON_INFORMATION, NULL ); - } - } + bool OnSashPositionChange(int newSashPosition) override + { + m_customSashPos = newSashPosition; + return wxSplitterWindow::OnSashPositionChange(newSashPosition); + } + void OnDoubleClickSash(int, int) override + { + if (0 == m_customMinPaneSize) { + wxMessageBox( + wxT( + "Double-clicking a wxSplitterWindow sash with the minimum pane size set to 0 would normally unsplit " + "it.\nHowever, it is difficult to design a pane that has been closed, so this action has been vetoed."), + wxT("Unsplit Vetoed!"), wxICON_INFORMATION, NULL); + } + } }; // Since wxGTK 2.8, wxNotebook has been sending page changed events in its destructor - this causes strange behavior -#if defined( __WXGTK__ ) - class wxCustomNotebook : public wxNotebook - { - public: - wxCustomNotebook( wxWindow* parent, wxWindowID id, const wxPoint& point = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0 ) - : - wxNotebook( parent, id, point, size, style ) - { - } - - ~wxCustomNotebook() override { - while ( GetEventHandler() != this ) - { - // Remove and delete extra event handlers - PopEventHandler( true ); - } - } - }; +#if defined(__WXGTK__) +class wxCustomNotebook : public wxNotebook +{ +public: + wxCustomNotebook( + wxWindow* parent, wxWindowID id, const wxPoint& point = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = 0) : + wxNotebook(parent, id, point, size, style) + { + } + + ~wxCustomNotebook() override + { + while (GetEventHandler() != this) { + // Remove and delete extra event handlers + PopEventHandler(true); + } + } +}; #else - typedef wxNotebook wxCustomNotebook; +typedef wxNotebook wxCustomNotebook; #endif /////////////////////////////////////////////////////////////////////////////// @@ -206,316 +202,298 @@ class wxCustomSplitterWindow : public wxSplitterWindow class PanelComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxPanel* panel = new wxPanel((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - return panel; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxPanel"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxPanel")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxPanel* panel = new wxPanel( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + return panel; + } + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxPanel"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxPanel")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; #ifdef wxUSE_COLLPANE class CollapsiblePaneComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxCollapsiblePane* collpane = new wxCollapsiblePane( (wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsString( _("label") ), - obj->GetPropertyAsPoint( _("pos") ), - obj->GetPropertyAsSize( _("size") ), - obj->GetPropertyAsInteger( _("style") ) | obj->GetPropertyAsInteger( _("window_style") ) ); - - collpane->Collapse(obj->GetPropertyAsInteger(_("collapsed")) != 0); - - collpane->PushEventHandler( new ComponentEvtHandler( collpane, GetManager() ) ); - - return collpane; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxCollapsiblePane); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc( obj, _("wxCollapsiblePane"), obj->GetPropertyAsString( _("name") ) ); - xrc.AddWindowProperties(); - xrc.AddProperty( _("label"), _("label"), XRC_TYPE_TEXT ); - xrc.AddProperty( _("collapsed"), _("collapsed"), XRC_TYPE_BOOL ); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter( xrcObj, _("wxCollapsiblePane") ); - filter.AddWindowProperties(); - filter.AddProperty( _("label"), _("label"), XRC_TYPE_TEXT ); - filter.AddProperty( _("collapsed"), _("collapsed"), XRC_TYPE_BOOL ); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxCollapsiblePane* collpane = new wxCollapsiblePane( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("label")), obj->GetPropertyAsPoint(_("pos")), + obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + collpane->Collapse(obj->GetPropertyAsInteger(_("collapsed")) != 0); + collpane->PushEventHandler(new ComponentEvtHandler(collpane, GetManager())); + + return collpane; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxCollapsiblePane); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxCollapsiblePane"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("collapsed"), _("collapsed"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxCollapsiblePane")); + filter.AddWindowProperties(); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + filter.AddProperty(_("collapsed"), _("collapsed"), XRC_TYPE_BOOL); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnCollapsiblePaneChanged( wxCollapsiblePaneEvent& event ) +void ComponentEvtHandler::OnCollapsiblePaneChanged(wxCollapsiblePaneEvent& event) { - wxCollapsiblePane* collpane = wxDynamicCast( m_window, wxCollapsiblePane ); - if ( collpane != NULL ) - { - wxString s = ( event.GetCollapsed() ) ? wxT("1") : wxT("0"); - m_manager->ModifyProperty( collpane, _("collapsed"), s ); - collpane->SetFocus(); - } - - event.Skip(); + wxCollapsiblePane* collpane = wxDynamicCast(m_window, wxCollapsiblePane); + if (collpane != NULL) { + wxString s = (event.GetCollapsed()) ? wxT("1") : wxT("0"); + m_manager->ModifyProperty(collpane, _("collapsed"), s); + collpane->SetFocus(); + } + + event.Skip(); } -#endif // wxUSE_COLLPANE +#endif // wxUSE_COLLPANE class SplitterWindowComponent : public ComponentBase { - wxObject* Create(IObject* obj, wxObject* parent) override { - wxCustomSplitterWindow *splitter = - new wxCustomSplitterWindow((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - (obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))) & ~wxSP_PERMIT_UNSPLIT ); - - if ( !obj->IsNull( _("sashgravity") ) ) - { - float gravity = obj->GetPropertyAsFloat( _("sashgravity") ); - gravity = ( gravity < 0.0 ? 0.0 : gravity ); - gravity = ( gravity > 1.0 ? 1.0 : gravity ); - splitter->SetSashGravity( gravity ); - } - if ( !obj->IsNull( _("min_pane_size") ) ) - { - int minPaneSize = obj->GetPropertyAsInteger( _("min_pane_size") ); - splitter->m_customMinPaneSize = minPaneSize; - minPaneSize = ( minPaneSize < 1 ? 1 : minPaneSize ); - splitter->SetMinimumPaneSize( minPaneSize ); - } - - // Always have a child so it is drawn consistently - splitter->Initialize( new wxPanel( splitter ) ); - - // Used to ensure sash position is correct - splitter->m_initialSashPos = obj->GetPropertyAsInteger( _("sashpos") ); - splitter->Connect( wxEVT_IDLE, wxIdleEventHandler( wxCustomSplitterWindow::OnIdle ) ); - - return splitter; - } - - void Cleanup(wxObject* obj) override - { - // The derived class doesn't implement wxWidgets RTTI so cast to its base class - auto* window = wxDynamicCast(obj, wxSplitterWindow); - if (window) - { - // Because of possible error conditions the handler might not have been pushed - auto* compHandler = dynamic_cast(window->GetEventHandler()); - if (compHandler) - { - window->PopEventHandler(true); - } - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxSplitterWindow"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(_("sashpos"),_("sashpos"),XRC_TYPE_INTEGER); - xrc.AddProperty(_("sashgravity"),_("gravity"),XRC_TYPE_FLOAT); - xrc.AddProperty(_("min_pane_size"),_("minsize"),XRC_TYPE_INTEGER); - if (obj->GetPropertyAsString(_("splitmode")) == wxT("wxSPLIT_VERTICAL")) - xrc.AddPropertyValue(_("orientation"),wxT("vertical")); - else - xrc.AddPropertyValue(_("orientation"),wxT("horizontal")); - - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxSplitterWindow")); - filter.AddWindowProperties(); - filter.AddProperty(_("sashpos"),_("sashpos"),XRC_TYPE_INTEGER); - filter.AddProperty(_("gravity"),_("sashgravity"),XRC_TYPE_FLOAT); - filter.AddProperty(_("minsize"),_("min_pane_size"),XRC_TYPE_INTEGER); - try - { - ticpp::Element *splitmode = xrcObj->FirstChildElement("orientation"); - std::string value = splitmode->GetText(); - if (value == "vertical") - filter.AddPropertyValue(wxT("splitmode"),wxT("wxSPLIT_VERTICAL")); - else - filter.AddPropertyValue(wxT("splitmode"),wxT("wxSPLIT_HORIZONTAL")); - } - catch( ticpp::Exception& ) - { - } - - return filter.GetXfbObject(); - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxCustomSplitterWindow* splitter = wxDynamicCast( wxobject, wxCustomSplitterWindow ); - if ( NULL == splitter ) - { - wxLogError( _("This should be a wxSplitterWindow") ); - return; - } - - // Remove default panel - wxWindow* firstChild = splitter->GetWindow1(); - - size_t childCount = GetManager()->GetChildCount( wxobject ); - switch ( childCount ) - { - case 1: - { - // The child should be a splitteritem - wxObject* splitterItem = GetManager()->GetChild( wxobject, 0 ); - - // This one should be the actual wxWindow - wxWindow* subwindow = wxDynamicCast( GetManager()->GetChild( splitterItem, 0 ), wxWindow ); - if ( NULL == subwindow ) - { - wxLogError( _("A SplitterItem is abstract and must have a child!") ); - return; - } - - if ( firstChild ) - { - splitter->ReplaceWindow( firstChild, subwindow ); - firstChild->Destroy(); - } - else - { - splitter->Initialize( subwindow ); - } - splitter->PushEventHandler( new ComponentEvtHandler( splitter, GetManager() ) ); - break; - } - case 2: - { - // The child should be a splitteritem - wxObject* splitterItem0 = GetManager()->GetChild( wxobject, 0 ); - wxObject* splitterItem1 = GetManager()->GetChild( wxobject, 1 ); - - // This one should be the actual wxWindow - wxWindow* subwindow0 = wxDynamicCast( GetManager()->GetChild( splitterItem0, 0 ), wxWindow ); - wxWindow* subwindow1 = wxDynamicCast( GetManager()->GetChild( splitterItem1, 0 ), wxWindow ); - - if ( NULL == subwindow0 || NULL == subwindow1 ) - { - wxLogError( _("A SplitterItem is abstract and must have a child!") ); - return; - } - - // Get the split mode and sash position - IObject* obj = GetManager()->GetIObject( wxobject ); - if ( obj == NULL ) - { - return; - } - - int sashPos = obj->GetPropertyAsInteger(_("sashpos")); - int splitmode = obj->GetPropertyAsInteger(_("splitmode")); - - if ( firstChild ) - { - splitter->ReplaceWindow( firstChild, subwindow0 ); - firstChild->Destroy(); - } - - if ( splitmode == wxSPLIT_VERTICAL ) - { - splitter->SplitVertically( subwindow0, subwindow1, sashPos ); - } - else - { - splitter->SplitHorizontally( subwindow0, subwindow1, sashPos ); - } - - splitter->PushEventHandler( new ComponentEvtHandler( splitter, GetManager() ) ); - break; - } - default: - return; - } - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxCustomSplitterWindow* splitter = new wxCustomSplitterWindow( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + (obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))) & + ~wxSP_PERMIT_UNSPLIT); + + if (!obj->IsNull(_("sashgravity"))) { + float gravity = obj->GetPropertyAsFloat(_("sashgravity")); + gravity = (gravity < 0.0 ? 0.0 : gravity); + gravity = (gravity > 1.0 ? 1.0 : gravity); + splitter->SetSashGravity(gravity); + } + if (!obj->IsNull(_("min_pane_size"))) { + int minPaneSize = obj->GetPropertyAsInteger(_("min_pane_size")); + splitter->m_customMinPaneSize = minPaneSize; + minPaneSize = (minPaneSize < 1 ? 1 : minPaneSize); + splitter->SetMinimumPaneSize(minPaneSize); + } + + // Always have a child so it is drawn consistently + splitter->Initialize(new wxPanel(splitter)); + + // Used to ensure sash position is correct + splitter->m_initialSashPos = obj->GetPropertyAsInteger(_("sashpos")); + splitter->Connect(wxEVT_IDLE, wxIdleEventHandler(wxCustomSplitterWindow::OnIdle)); + + return splitter; + } + + void Cleanup(wxObject* obj) override + { + // The derived class doesn't implement wxWidgets RTTI so cast to its base class + auto* window = wxDynamicCast(obj, wxSplitterWindow); + if (window) { + // Because of possible error conditions the handler might not have been pushed + auto* compHandler = dynamic_cast(window->GetEventHandler()); + if (compHandler) { + window->PopEventHandler(true); + } + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxSplitterWindow"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(_("sashpos"), _("sashpos"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("sashgravity"), _("gravity"), XRC_TYPE_FLOAT); + xrc.AddProperty(_("min_pane_size"), _("minsize"), XRC_TYPE_INTEGER); + if (obj->GetPropertyAsString(_("splitmode")) == wxT("wxSPLIT_VERTICAL")) + xrc.AddPropertyValue(_("orientation"), wxT("vertical")); + else + xrc.AddPropertyValue(_("orientation"), wxT("horizontal")); + + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxSplitterWindow")); + filter.AddWindowProperties(); + filter.AddProperty(_("sashpos"), _("sashpos"), XRC_TYPE_INTEGER); + filter.AddProperty(_("gravity"), _("sashgravity"), XRC_TYPE_FLOAT); + filter.AddProperty(_("minsize"), _("min_pane_size"), XRC_TYPE_INTEGER); + try { + ticpp::Element* splitmode = xrcObj->FirstChildElement("orientation"); + std::string value = splitmode->GetText(); + if (value == "vertical") + filter.AddPropertyValue(wxT("splitmode"), wxT("wxSPLIT_VERTICAL")); + else + filter.AddPropertyValue(wxT("splitmode"), wxT("wxSPLIT_HORIZONTAL")); + } catch (ticpp::Exception&) { + } + + return filter.GetXfbObject(); + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxCustomSplitterWindow* splitter = wxDynamicCast(wxobject, wxCustomSplitterWindow); + if (NULL == splitter) { + wxLogError(_("This should be a wxSplitterWindow")); + return; + } + + // Remove default panel + wxWindow* firstChild = splitter->GetWindow1(); + + size_t childCount = GetManager()->GetChildCount(wxobject); + switch (childCount) { + case 1: { + // The child should be a splitteritem + wxObject* splitterItem = GetManager()->GetChild(wxobject, 0); + + // This one should be the actual wxWindow + wxWindow* subwindow = wxDynamicCast(GetManager()->GetChild(splitterItem, 0), wxWindow); + if (NULL == subwindow) { + wxLogError(_("A SplitterItem is abstract and must have a child!")); + return; + } + + if (firstChild) { + splitter->ReplaceWindow(firstChild, subwindow); + firstChild->Destroy(); + } else { + splitter->Initialize(subwindow); + } + splitter->PushEventHandler(new ComponentEvtHandler(splitter, GetManager())); + break; + } + case 2: { + // The child should be a splitteritem + wxObject* splitterItem0 = GetManager()->GetChild(wxobject, 0); + wxObject* splitterItem1 = GetManager()->GetChild(wxobject, 1); + + // This one should be the actual wxWindow + wxWindow* subwindow0 = wxDynamicCast(GetManager()->GetChild(splitterItem0, 0), wxWindow); + wxWindow* subwindow1 = wxDynamicCast(GetManager()->GetChild(splitterItem1, 0), wxWindow); + + if (NULL == subwindow0 || NULL == subwindow1) { + wxLogError(_("A SplitterItem is abstract and must have a child!")); + return; + } + + // Get the split mode and sash position + IObject* obj = GetManager()->GetIObject(wxobject); + if (obj == NULL) { + return; + } + + int sashPos = obj->GetPropertyAsInteger(_("sashpos")); + int splitmode = obj->GetPropertyAsInteger(_("splitmode")); + + if (firstChild) { + splitter->ReplaceWindow(firstChild, subwindow0); + firstChild->Destroy(); + } + + if (splitmode == wxSPLIT_VERTICAL) { + splitter->SplitVertically(subwindow0, subwindow1, sashPos); + } else { + splitter->SplitHorizontally(subwindow0, subwindow1, sashPos); + } + + splitter->PushEventHandler(new ComponentEvtHandler(splitter, GetManager())); + break; + } + default: + return; + } + } }; -void ComponentEvtHandler::OnSplitterSashChanged( wxSplitterEvent& ) +void ComponentEvtHandler::OnSplitterSashChanged(wxSplitterEvent&) { - wxCustomSplitterWindow* window = wxDynamicCast( m_window, wxCustomSplitterWindow ); - if ( window != NULL ) - { - if ( window->m_customSashPos != 0 ) - { - m_manager->ModifyProperty( window, _("sashpos"), wxString::Format( wxT("%i"), window->GetSashPosition() ) ); - } - } + wxCustomSplitterWindow* window = wxDynamicCast(m_window, wxCustomSplitterWindow); + if (window != NULL) { + if (window->m_customSashPos != 0) { + m_manager->ModifyProperty(window, _("sashpos"), wxString::Format(wxT("%i"), window->GetSashPosition())); + } + } } class SplitterItemComponent : public ComponentBase { - ticpp::Element* ExportToXrc(IObject* obj) override { - // A __dummyitem__ will be ignored... - ObjectToXrcFilter xrc(obj, _("__dummyitem__"),wxT("")); - return xrc.GetXrcObject(); - } + ticpp::Element* ExportToXrc(IObject* obj) override + { + // A __dummyitem__ will be ignored... + ObjectToXrcFilter xrc(obj, _("__dummyitem__"), wxT("")); + return xrc.GetXrcObject(); + } }; class ScrolledWindowComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxScrolledWindow *sw = new wxScrolledWindow((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - sw->SetScrollRate( - obj->GetPropertyAsInteger(_("scroll_rate_x")), - obj->GetPropertyAsInteger(_("scroll_rate_y"))); + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxScrolledWindow* sw = new wxScrolledWindow( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + sw->SetScrollRate(obj->GetPropertyAsInteger(_("scroll_rate_x")), obj->GetPropertyAsInteger(_("scroll_rate_y"))); return sw; } - ticpp::Element* ExportToXrc(IObject* obj) override { + ticpp::Element* ExportToXrc(IObject* obj) override + { ObjectToXrcFilter xrc(obj, _("wxScrolledWindow"), obj->GetPropertyAsString(_("name"))); xrc.AddWindowProperties(); - xrc.AddPropertyValue( _("scrollrate"), wxString::Format( wxT("%d,%d"), - obj->GetPropertyAsInteger(_("scroll_rate_x")), - obj->GetPropertyAsInteger(_("scroll_rate_y")) ) ); + xrc.AddPropertyValue( + _("scrollrate"), wxString::Format( + wxT("%d,%d"), obj->GetPropertyAsInteger(_("scroll_rate_x")), + obj->GetPropertyAsInteger(_("scroll_rate_y")))); return xrc.GetXrcObject(); } - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { XrcToXfbFilter filter(xrcObj, _("wxScrolledWindow")); filter.AddWindowProperties(); - ticpp::Element *scrollrate = xrcObj->FirstChildElement("scrollrate", false); - if( scrollrate ) { - wxString value( wxString( scrollrate->GetText().c_str(), wxConvUTF8 ) ); - filter.AddPropertyValue( _("scroll_rate_x"), value.BeforeFirst( wxT(',') ) ); - filter.AddPropertyValue( _("scroll_rate_y"), value.AfterFirst( wxT(',') ) ); - } + ticpp::Element* scrollrate = xrcObj->FirstChildElement("scrollrate", false); + if (scrollrate) { + wxString value(wxString(scrollrate->GetText().c_str(), wxConvUTF8)); + filter.AddPropertyValue(_("scroll_rate_x"), value.BeforeFirst(wxT(','))); + filter.AddPropertyValue(_("scroll_rate_y"), value.AfterFirst(wxT(','))); + } return filter.GetXfbObject(); } }; @@ -523,417 +501,423 @@ class ScrolledWindowComponent : public ComponentBase class NotebookComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxNotebook* book = new wxCustomNotebook((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - BookUtils::AddImageList( obj, book ); - - book->PushEventHandler( new ComponentEvtHandler( book, GetManager() ) ); - - return book; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxNotebook); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxNotebook"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxNotebook")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxNotebook* book = new wxCustomNotebook( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + BookUtils::AddImageList(obj, book); + + book->PushEventHandler(new ComponentEvtHandler(book, GetManager())); + + return book; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxNotebook); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxNotebook"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxNotebook")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnNotebookPageChanged( wxNotebookEvent& event ) +void ComponentEvtHandler::OnNotebookPageChanged(wxNotebookEvent& event) { - OnBookPageChanged< wxNotebook >( event.GetSelection(), &event ); - event.Skip(); + OnBookPageChanged(event.GetSelection(), &event); + event.Skip(); } class NotebookPageComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - BookUtils::OnCreated< wxNotebook >( wxobject, wxparent, GetManager(), _("NotebookPageComponent") ); - } - - void OnSelected(wxObject* wxobject) override { - BookUtils::OnSelected< wxNotebook >( wxobject, GetManager() ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("notebookpage")); - xrc.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - xrc.AddProperty(_("select"),_("selected"),XRC_TYPE_BOOL); - if ( !obj->IsNull( _("bitmap") ) ) - { - xrc.AddProperty(_("bitmap"),_("bitmap"),XRC_TYPE_BITMAP); - } - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("notebookpage")); - filter.AddWindowProperties(); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - filter.AddProperty(_("selected"),_("select"),XRC_TYPE_BOOL); - filter.AddProperty(_("bitmap"),_("bitmap"),XRC_TYPE_BITMAP); - return filter.GetXfbObject(); - } + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + BookUtils::OnCreated(wxobject, wxparent, GetManager(), _("NotebookPageComponent")); + } + + void OnSelected(wxObject* wxobject) override { BookUtils::OnSelected(wxobject, GetManager()); } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("notebookpage")); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("select"), _("selected"), XRC_TYPE_BOOL); + if (!obj->IsNull(_("bitmap"))) { + xrc.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + } + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("notebookpage")); + filter.AddWindowProperties(); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + filter.AddProperty(_("selected"), _("select"), XRC_TYPE_BOOL); + filter.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + return filter.GetXfbObject(); + } }; class ListbookComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxListbook* book = new wxListbook((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - BookUtils::AddImageList( obj, book ); - - book->PushEventHandler( new ComponentEvtHandler( book, GetManager() ) ); - - return book; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxListbook); - if (window) - { - window->PopEventHandler(true); - } - } - + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxListbook* book = new wxListbook( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + BookUtils::AddImageList(obj, book); + + book->PushEventHandler(new ComponentEvtHandler(book, GetManager())); + + return book; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxListbook); + if (window) { + window->PopEventHandler(true); + } + } + // Small icon style not supported by GTK -#ifndef __WXGTK__ - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - wxListbook* book = wxDynamicCast( wxparent, wxListbook ); - if ( book ) - { - // Small icon style if bitmapsize is not set - IObject* obj = GetManager()->GetIObject( wxobject ); - if ( obj->GetPropertyAsString( _("bitmapsize") ).empty() ) - { - wxListView* tmpListView = book->GetListView(); - long flags = tmpListView->GetWindowStyleFlag(); - flags = (flags & ~wxLC_ICON) | wxLC_SMALL_ICON; - tmpListView->SetWindowStyleFlag( flags ); - } - } - } +#ifndef __WXGTK__ + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + wxListbook* book = wxDynamicCast(wxparent, wxListbook); + if (book) { + // Small icon style if bitmapsize is not set + IObject* obj = GetManager()->GetIObject(wxobject); + if (obj->GetPropertyAsString(_("bitmapsize")).empty()) { + wxListView* tmpListView = book->GetListView(); + long flags = tmpListView->GetWindowStyleFlag(); + flags = (flags & ~wxLC_ICON) | wxLC_SMALL_ICON; + tmpListView->SetWindowStyleFlag(flags); + } + } + } #endif - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxListbook"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxListbook")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxListbook"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxListbook")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnListbookPageChanged( wxListbookEvent& event ) +void ComponentEvtHandler::OnListbookPageChanged(wxListbookEvent& event) { - OnBookPageChanged< wxListbook >( event.GetSelection(), &event ); - event.Skip(); + OnBookPageChanged(event.GetSelection(), &event); + event.Skip(); } class ListbookPageComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - BookUtils::OnCreated< wxListbook >( wxobject, wxparent, GetManager(), _("ListbookPageComponent") ); - } - - void OnSelected(wxObject* wxobject) override { - BookUtils::OnSelected(wxobject, GetManager()); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("listbookpage")); - xrc.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - xrc.AddProperty(_("select"),_("selected"),XRC_TYPE_BOOL); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("listbookpage")); - filter.AddWindowProperties(); - filter.AddProperty(_("selected"),_("select"),XRC_TYPE_BOOL); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - return filter.GetXfbObject(); - } + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + BookUtils::OnCreated(wxobject, wxparent, GetManager(), _("ListbookPageComponent")); + } + + void OnSelected(wxObject* wxobject) override { BookUtils::OnSelected(wxobject, GetManager()); } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("listbookpage")); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("select"), _("selected"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("listbookpage")); + filter.AddWindowProperties(); + filter.AddProperty(_("selected"), _("select"), XRC_TYPE_BOOL); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + return filter.GetXfbObject(); + } }; class ChoicebookComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxChoicebook* book = new wxChoicebook((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - book->PushEventHandler( new ComponentEvtHandler( book, GetManager() ) ); - - return book; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxChoicebook); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxChoicebook"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxChoicebook")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxChoicebook* book = new wxChoicebook( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + book->PushEventHandler(new ComponentEvtHandler(book, GetManager())); + + return book; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxChoicebook); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxChoicebook"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxChoicebook")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnChoicebookPageChanged( wxChoicebookEvent& event ) +void ComponentEvtHandler::OnChoicebookPageChanged(wxChoicebookEvent& event) { - OnBookPageChanged< wxChoicebook >( event.GetSelection(), &event ); - event.Skip(); + OnBookPageChanged(event.GetSelection(), &event); + event.Skip(); } class ChoicebookPageComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - BookUtils::OnCreated< wxChoicebook >( wxobject, wxparent, GetManager(), _("ChoicebookPageComponent") ); - } - - void OnSelected(wxObject* wxobject) override { - BookUtils::OnSelected< wxChoicebook >( wxobject, GetManager() ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("choicebookpage")); - xrc.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - xrc.AddProperty(_("select"),_("selected"),XRC_TYPE_BOOL); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("choicebookpage")); - filter.AddWindowProperties(); - filter.AddProperty(_("selected"),_("select"),XRC_TYPE_BOOL); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - return filter.GetXfbObject(); - } + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + BookUtils::OnCreated(wxobject, wxparent, GetManager(), _("ChoicebookPageComponent")); + } + + void OnSelected(wxObject* wxobject) override { BookUtils::OnSelected(wxobject, GetManager()); } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("choicebookpage")); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("select"), _("selected"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("choicebookpage")); + filter.AddWindowProperties(); + filter.AddProperty(_("selected"), _("select"), XRC_TYPE_BOOL); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + return filter.GetXfbObject(); + } }; class AuiNotebookComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxAuiNotebook* book = new wxAuiNotebook((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); - - book->SetTabCtrlHeight( obj->GetPropertyAsInteger( _("tab_ctrl_height") ) ); - book->SetUniformBitmapSize( obj->GetPropertyAsSize( _("uniform_bitmap_size") ) ); - - book->PushEventHandler( new ComponentEvtHandler( book, GetManager() ) ); - - return book; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxAuiNotebook); - if (window) - { - window->PopEventHandler(true); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxAuiNotebook"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxAuiNotebook")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxAuiNotebook* book = new wxAuiNotebook( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("style")) | obj->GetPropertyAsInteger(_("window_style"))); + + book->SetTabCtrlHeight(obj->GetPropertyAsInteger(_("tab_ctrl_height"))); + book->SetUniformBitmapSize(obj->GetPropertyAsSize(_("uniform_bitmap_size"))); + + book->PushEventHandler(new ComponentEvtHandler(book, GetManager())); + + return book; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxAuiNotebook); + if (window) { + window->PopEventHandler(true); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxAuiNotebook"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxAuiNotebook")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnAuiNotebookPageChanged( wxAuiNotebookEvent& event ) +void ComponentEvtHandler::OnAuiNotebookPageChanged(wxAuiNotebookEvent& event) { - OnBookPageChanged< wxAuiNotebook >( event.GetSelection(), &event ); - event.Skip(); + OnBookPageChanged(event.GetSelection(), &event); + event.Skip(); } class AuiNotebookPageComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - // Easy read-only property access - IObject* obj = GetManager()->GetIObject( wxobject ); - - wxAuiNotebook* book = wxDynamicCast( wxparent, wxAuiNotebook ); - - //This wouldn't compile in MinGW - strange - ///wxWindow* page = wxDynamicCast( manager->GetChild( wxobject, 0 ), wxWindow ); - - // Do this instead - wxObject* child = GetManager()->GetChild( wxobject, 0 ); - wxWindow* page = NULL; - if ( child->IsKindOf(CLASSINFO(wxWindow))) - { - page = (wxWindow*)child; - } - - // Error checking - if ( !( obj && book && page ) ) - { - wxLogError( _("AuiNotebookPageComponent is missing its wxFormBuilder object(%i), its parent(%i), or its child(%i)"), obj, book, page ); - return; - } - - // Prevent event handling by wxFB - these aren't user generated events - SuppressEventHandlers suppress( book ); - - // Save selection - int selection = book->GetSelection(); - const wxBitmap& bitmap = obj->IsNull( _("bitmap") ) ? wxNullBitmap : obj->GetPropertyAsBitmap( _("bitmap") ); - book->AddPage( page, obj->GetPropertyAsString( _("label") ), false, bitmap ); - - if ( obj->GetPropertyAsString( _("select") ) == wxT("0") && selection >= 0 ) - { - book->SetSelection(selection); - } - else - { - book->SetSelection( book->GetPageCount() - 1 ); - } - } - - void OnSelected(wxObject* wxobject) override { - BookUtils::OnSelected< wxAuiNotebook >( wxobject, GetManager() ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("notebookpage")); - xrc.AddProperty(_("label"),_("label"), XRC_TYPE_TEXT); - xrc.AddProperty(_("selected"),_("selected"), XRC_TYPE_BOOL); - xrc.AddProperty(_("bitmap"),_("bitmap"), XRC_TYPE_BITMAP); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("notebookpage")); - filter.AddWindowProperties(); - filter.AddProperty(_("selected"),_("selected"),XRC_TYPE_BOOL); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - filter.AddProperty(_("bitmap"),_("bitmap"),XRC_TYPE_BITMAP); - return filter.GetXfbObject(); - } + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + // Easy read-only property access + IObject* obj = GetManager()->GetIObject(wxobject); + + wxAuiNotebook* book = wxDynamicCast(wxparent, wxAuiNotebook); + + // This wouldn't compile in MinGW - strange + /// wxWindow* page = wxDynamicCast( manager->GetChild( wxobject, 0 ), wxWindow ); + + // Do this instead + wxObject* child = GetManager()->GetChild(wxobject, 0); + wxWindow* page = NULL; + if (child->IsKindOf(CLASSINFO(wxWindow))) { + page = (wxWindow*)child; + } + + // Error checking + if (!(obj && book && page)) { + wxLogError( + _("AuiNotebookPageComponent is missing its wxFormBuilder object(%i), its parent(%i), or its child(%i)"), + obj, book, page); + return; + } + + // Prevent event handling by wxFB - these aren't user generated events + SuppressEventHandlers suppress(book); + + // Save selection + int selection = book->GetSelection(); + const wxBitmap& bitmap = obj->IsNull(_("bitmap")) ? wxNullBitmap : obj->GetPropertyAsBitmap(_("bitmap")); + book->AddPage(page, obj->GetPropertyAsString(_("label")), false, bitmap); + + if (obj->GetPropertyAsString(_("select")) == wxT("0") && selection >= 0) { + book->SetSelection(selection); + } else { + book->SetSelection(book->GetPageCount() - 1); + } + } + + void OnSelected(wxObject* wxobject) override { BookUtils::OnSelected(wxobject, GetManager()); } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("notebookpage")); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("selected"), _("selected"), XRC_TYPE_BOOL); + xrc.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("notebookpage")); + filter.AddWindowProperties(); + filter.AddProperty(_("selected"), _("selected"), XRC_TYPE_BOOL); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + filter.AddProperty(_("bitmap"), _("bitmap"), XRC_TYPE_BITMAP); + return filter.GetXfbObject(); + } }; class SimplebookComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - return new wxSimplebook((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsPoint(_("pos")), - obj->GetPropertyAsSize(_("size")), - obj->GetPropertyAsInteger(_("window_style"))); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxSimplebook"), obj->GetPropertyAsString(_("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxSimplebook")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + return new wxSimplebook( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(_("pos")), obj->GetPropertyAsSize(_("size")), + obj->GetPropertyAsInteger(_("window_style"))); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxSimplebook"), obj->GetPropertyAsString(_("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxSimplebook")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class SimplebookPageComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* wxparent) override { - BookUtils::OnCreated< wxSimplebook >( wxobject, wxparent, GetManager(), _("SimplebookPageComponent") ); - } - - void OnSelected(wxObject* wxobject) override { - BookUtils::OnSelected< wxSimplebook >( wxobject, GetManager() ); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("simplebookpage")); - xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); - xrc.AddProperty(_("select"), _("selected"), XRC_TYPE_BOOL); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("simplebookpage")); - filter.AddWindowProperties(); - filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); - filter.AddProperty(_("selected"), _("select"), XRC_TYPE_BOOL); - return filter.GetXfbObject(); - } + void OnCreated(wxObject* wxobject, wxWindow* wxparent) override + { + BookUtils::OnCreated(wxobject, wxparent, GetManager(), _("SimplebookPageComponent")); + } + + void OnSelected(wxObject* wxobject) override { BookUtils::OnSelected(wxobject, GetManager()); } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("simplebookpage")); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + xrc.AddProperty(_("select"), _("selected"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("simplebookpage")); + filter.AddWindowProperties(); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + filter.AddProperty(_("selected"), _("select"), XRC_TYPE_BOOL); + return filter.GetXfbObject(); + } }; /////////////////////////////////////////////////////////////////////////////// BEGIN_LIBRARY() -WINDOW_COMPONENT("wxPanel",PanelComponent) +WINDOW_COMPONENT("wxPanel", PanelComponent) #ifdef wxUSE_COLLPANE -WINDOW_COMPONENT( "wxCollapsiblePane", CollapsiblePaneComponent ) +WINDOW_COMPONENT("wxCollapsiblePane", CollapsiblePaneComponent) #endif -WINDOW_COMPONENT("wxSplitterWindow",SplitterWindowComponent) -ABSTRACT_COMPONENT("splitteritem",SplitterItemComponent) +WINDOW_COMPONENT("wxSplitterWindow", SplitterWindowComponent) +ABSTRACT_COMPONENT("splitteritem", SplitterItemComponent) -WINDOW_COMPONENT("wxScrolledWindow",ScrolledWindowComponent) +WINDOW_COMPONENT("wxScrolledWindow", ScrolledWindowComponent) WINDOW_COMPONENT("wxNotebook", NotebookComponent) -ABSTRACT_COMPONENT("notebookpage",NotebookPageComponent) +ABSTRACT_COMPONENT("notebookpage", NotebookPageComponent) WINDOW_COMPONENT("wxListbook", ListbookComponent) ABSTRACT_COMPONENT("listbookpage", ListbookPageComponent) diff --git a/plugins/forms/forms.cpp b/plugins/forms/forms.cpp index fd916a77a..76a919980 100644 --- a/plugins/forms/forms.cpp +++ b/plugins/forms/forms.cpp @@ -25,30 +25,31 @@ // Andrea Zanellato - zanellato.andrea@gmail.com // /////////////////////////////////////////////////////////////////////////////// + +#include + +#include #include #include -#include -#include // Event handler for events generated by controls in this plugin class ComponentEvtHandler : public wxEvtHandler { private: - IManager* m_manager; + IManager* m_manager; public: - ComponentEvtHandler(IManager* manager) : m_manager(manager) { - } + ComponentEvtHandler(IManager* manager) : m_manager(manager) {} protected: - void OnTool( wxCommandEvent& event ); + void OnTool(wxCommandEvent& event); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; -BEGIN_EVENT_TABLE( ComponentEvtHandler, wxEvtHandler ) - EVT_TOOL( wxID_ANY, ComponentEvtHandler::OnTool ) +BEGIN_EVENT_TABLE(ComponentEvtHandler, wxEvtHandler) +EVT_TOOL(wxID_ANY, ComponentEvtHandler::OnTool) END_EVENT_TABLE() // TO-DO: The "Form" type component should be drawn in the designer, so that, @@ -56,308 +57,308 @@ END_EVENT_TABLE() class FrameFormComponent : public ComponentBase { public: - wxObject* Create(IObject* /*obj*/, wxObject* parent) override { - wxPanel *panel = new wxPanel((wxWindow *)parent, wxID_ANY); - panel->SetBackgroundColour(wxColour(50,50,50)); - return panel; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, wxT("wxFrame"), obj->GetPropertyAsString(wxT("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty( wxT("title"), wxT("title"), XRC_TYPE_TEXT); - if ( !obj->IsNull( wxT("center") ) ) - { - xrc.AddPropertyValue( wxT("centered"), wxT("1") ); - } - xrc.AddProperty( wxT("aui_managed"), wxT("aui_managed"), XRC_TYPE_BOOL); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, wxT("Frame")); - filter.AddWindowProperties(); - filter.AddProperty( wxT("title"), wxT("title"), XRC_TYPE_TEXT); - filter.AddProperty(wxT("centered"), wxT("center"), XRC_TYPE_BITLIST); - filter.AddProperty( wxT("aui_managed"), wxT("aui_managed"), XRC_TYPE_BOOL); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* /*obj*/, wxObject* parent) override + { + wxPanel* panel = new wxPanel((wxWindow*)parent, wxID_ANY); + panel->SetBackgroundColour(wxColour(50, 50, 50)); + return panel; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxFrame"), obj->GetPropertyAsString(wxT("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(wxT("title"), wxT("title"), XRC_TYPE_TEXT); + if (!obj->IsNull(wxT("center"))) { + xrc.AddPropertyValue(wxT("centered"), wxT("1")); + } + xrc.AddProperty(wxT("aui_managed"), wxT("aui_managed"), XRC_TYPE_BOOL); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("Frame")); + filter.AddWindowProperties(); + filter.AddProperty(wxT("title"), wxT("title"), XRC_TYPE_TEXT); + filter.AddProperty(wxT("centered"), wxT("center"), XRC_TYPE_BITLIST); + filter.AddProperty(wxT("aui_managed"), wxT("aui_managed"), XRC_TYPE_BOOL); + return filter.GetXfbObject(); + } }; class PanelFormComponent : public ComponentBase { public: - wxObject* Create(IObject* /*obj*/, wxObject* parent) override { - wxPanel *panel = new wxPanel((wxWindow *)parent, wxID_ANY); - return panel; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, wxT("wxPanel"), obj->GetPropertyAsString(wxT("name"))); - xrc.AddWindowProperties(); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, wxT("Panel")); - filter.AddWindowProperties(); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* /*obj*/, wxObject* parent) override + { + wxPanel* panel = new wxPanel((wxWindow*)parent, wxID_ANY); + return panel; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxPanel"), obj->GetPropertyAsString(wxT("name"))); + xrc.AddWindowProperties(); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("Panel")); + filter.AddWindowProperties(); + return filter.GetXfbObject(); + } }; class DialogFormComponent : public ComponentBase { public: - wxObject* Create(IObject* /*obj*/, wxObject* parent) override { - wxPanel *panel = new wxPanel((wxWindow *)parent, wxID_ANY); - return panel; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, wxT("wxDialog"), obj->GetPropertyAsString(wxT("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty( wxT("title"), wxT("title"), XRC_TYPE_TEXT); - if ( !obj->IsNull( wxT("center") ) ) - { - xrc.AddPropertyValue( wxT("centered"), wxT("1") ); - } - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, wxT("Dialog")); - filter.AddWindowProperties(); - filter.AddProperty( wxT("title"), wxT("title"), XRC_TYPE_TEXT); - filter.AddProperty(wxT("centered"), wxT("center"), XRC_TYPE_BITLIST); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* /*obj*/, wxObject* parent) override + { + wxPanel* panel = new wxPanel((wxWindow*)parent, wxID_ANY); + return panel; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxDialog"), obj->GetPropertyAsString(wxT("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(wxT("title"), wxT("title"), XRC_TYPE_TEXT); + if (!obj->IsNull(wxT("center"))) { + xrc.AddPropertyValue(wxT("centered"), wxT("1")); + } + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("Dialog")); + filter.AddWindowProperties(); + filter.AddProperty(wxT("title"), wxT("title"), XRC_TYPE_TEXT); + filter.AddProperty(wxT("centered"), wxT("center"), XRC_TYPE_BITLIST); + return filter.GetXfbObject(); + } }; class MenuBarFormComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* /*parent*/) override { - wxMenuBar *mb = new wxMenuBar(obj->GetPropertyAsInteger(wxT("style")) | - obj->GetPropertyAsInteger(wxT("window_style"))); - return mb; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, wxT("wxMenuBar"), obj->GetPropertyAsString(wxT("name"))); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, wxT("MenuBar")); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* /*parent*/) override + { + wxMenuBar* mb = + new wxMenuBar(obj->GetPropertyAsInteger(wxT("style")) | obj->GetPropertyAsInteger(wxT("window_style"))); + return mb; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxMenuBar"), obj->GetPropertyAsString(wxT("name"))); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("MenuBar")); + return filter.GetXfbObject(); + } }; class ToolBarFormComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxToolBar *tb = new wxToolBar((wxWindow*)parent, wxID_ANY, - obj->GetPropertyAsPoint(wxT("pos")), - obj->GetPropertyAsSize(wxT("size")), - obj->GetPropertyAsInteger(wxT("style")) | obj->GetPropertyAsInteger(wxT("window_style")) | wxTB_NOALIGN | wxTB_NODIVIDER | wxNO_BORDER); - - if (!obj->IsNull(wxT("bitmapsize"))) - tb->SetToolBitmapSize(obj->GetPropertyAsSize(wxT("bitmapsize"))); - if (!obj->IsNull(wxT("margins"))) - { - wxSize margins(obj->GetPropertyAsSize(wxT("margins"))); - tb->SetMargins(margins.GetWidth(), margins.GetHeight()); - } - if (!obj->IsNull(wxT("packing"))) - tb->SetToolPacking(obj->GetPropertyAsInteger(wxT("packing"))); - if (!obj->IsNull(wxT("separation"))) - tb->SetToolSeparation(obj->GetPropertyAsInteger(wxT("separation"))); - - tb->PushEventHandler(new ComponentEvtHandler(GetManager())); - - return tb; - } - - void Cleanup(wxObject* obj) override - { - auto* window = wxDynamicCast(obj, wxToolBar); - if (window) - { - window->PopEventHandler(true); - } - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - wxToolBar* tb = wxDynamicCast( wxobject, wxToolBar ); - if ( NULL == tb ) - { - // very very strange - return; - } - - size_t count = GetManager()->GetChildCount( wxobject ); - for ( size_t i = 0; i < count; ++i ) - { - wxObject* child = GetManager()->GetChild( wxobject, i ); - IObject* childObj = GetManager()->GetIObject( child ); - if ( wxT("tool") == childObj->GetClassName() ) - { - tb->AddTool( wxID_ANY, - childObj->GetPropertyAsString( wxT("label") ), - childObj->GetPropertyAsBitmap( wxT("bitmap") ), - wxNullBitmap, - (wxItemKind)childObj->GetPropertyAsInteger( wxT("kind") ), - childObj->GetPropertyAsString( wxT("help") ), - wxEmptyString, - child - ); - } - else if ( wxT("toolSeparator") == childObj->GetClassName() ) - { - tb->AddSeparator(); - } - else - { - wxControl* control = wxDynamicCast( child, wxControl ); - if ( NULL != control ) - { - tb->AddControl( control ); - } - } - } - tb->Realize(); - - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, wxT("wxToolBar"), obj->GetPropertyAsString(wxT("name"))); - xrc.AddWindowProperties(); - xrc.AddProperty(wxT("bitmapsize"), wxT("bitmapsize"), XRC_TYPE_SIZE); - xrc.AddProperty(wxT("margins"), wxT("margins"), XRC_TYPE_SIZE); - xrc.AddProperty(wxT("packing"), wxT("packing"), XRC_TYPE_INTEGER); - xrc.AddProperty(wxT("separation"), wxT("separation"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, wxT("ToolBar")); - filter.AddWindowProperties(); - filter.AddProperty(wxT("bitmapsize"), wxT("bitmapsize"), XRC_TYPE_SIZE); - filter.AddProperty(wxT("margins"), wxT("margins"), XRC_TYPE_SIZE); - filter.AddProperty(wxT("packing"), wxT("packing"), XRC_TYPE_INTEGER); - filter.AddProperty(wxT("separation"), wxT("separation"), XRC_TYPE_INTEGER); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxToolBar* tb = new wxToolBar( + (wxWindow*)parent, wxID_ANY, obj->GetPropertyAsPoint(wxT("pos")), obj->GetPropertyAsSize(wxT("size")), + obj->GetPropertyAsInteger(wxT("style")) | obj->GetPropertyAsInteger(wxT("window_style")) | wxTB_NOALIGN | + wxTB_NODIVIDER | wxNO_BORDER); + + if (!obj->IsNull(wxT("bitmapsize"))) + tb->SetToolBitmapSize(obj->GetPropertyAsSize(wxT("bitmapsize"))); + if (!obj->IsNull(wxT("margins"))) { + wxSize margins(obj->GetPropertyAsSize(wxT("margins"))); + tb->SetMargins(margins.GetWidth(), margins.GetHeight()); + } + if (!obj->IsNull(wxT("packing"))) + tb->SetToolPacking(obj->GetPropertyAsInteger(wxT("packing"))); + if (!obj->IsNull(wxT("separation"))) + tb->SetToolSeparation(obj->GetPropertyAsInteger(wxT("separation"))); + + tb->PushEventHandler(new ComponentEvtHandler(GetManager())); + + return tb; + } + + void Cleanup(wxObject* obj) override + { + auto* window = wxDynamicCast(obj, wxToolBar); + if (window) { + window->PopEventHandler(true); + } + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + wxToolBar* tb = wxDynamicCast(wxobject, wxToolBar); + if (NULL == tb) { + // very very strange + return; + } + + size_t count = GetManager()->GetChildCount(wxobject); + for (size_t i = 0; i < count; ++i) { + wxObject* child = GetManager()->GetChild(wxobject, i); + IObject* childObj = GetManager()->GetIObject(child); + if (wxT("tool") == childObj->GetClassName()) { + tb->AddTool( + wxID_ANY, childObj->GetPropertyAsString(wxT("label")), childObj->GetPropertyAsBitmap(wxT("bitmap")), + wxNullBitmap, (wxItemKind)childObj->GetPropertyAsInteger(wxT("kind")), + childObj->GetPropertyAsString(wxT("help")), wxEmptyString, child); + } else if (wxT("toolSeparator") == childObj->GetClassName()) { + tb->AddSeparator(); + } else { + wxControl* control = wxDynamicCast(child, wxControl); + if (NULL != control) { + tb->AddControl(control); + } + } + } + tb->Realize(); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxToolBar"), obj->GetPropertyAsString(wxT("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(wxT("bitmapsize"), wxT("bitmapsize"), XRC_TYPE_SIZE); + xrc.AddProperty(wxT("margins"), wxT("margins"), XRC_TYPE_SIZE); + xrc.AddProperty(wxT("packing"), wxT("packing"), XRC_TYPE_INTEGER); + xrc.AddProperty(wxT("separation"), wxT("separation"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("ToolBar")); + filter.AddWindowProperties(); + filter.AddProperty(wxT("bitmapsize"), wxT("bitmapsize"), XRC_TYPE_SIZE); + filter.AddProperty(wxT("margins"), wxT("margins"), XRC_TYPE_SIZE); + filter.AddProperty(wxT("packing"), wxT("packing"), XRC_TYPE_INTEGER); + filter.AddProperty(wxT("separation"), wxT("separation"), XRC_TYPE_INTEGER); + return filter.GetXfbObject(); + } }; -void ComponentEvtHandler::OnTool( wxCommandEvent& event ) +void ComponentEvtHandler::OnTool(wxCommandEvent& event) { - //FIXME: Same as above - - wxToolBar* tb = wxDynamicCast( event.GetEventObject(), wxToolBar ); - if ( NULL == tb ) - { - // very very strange - return; - } - - wxObject* wxobject = tb->GetToolClientData( event.GetId() ); - if ( NULL != wxobject ) - { - m_manager->SelectObject( wxobject ); - } + // FIXME: Same as above + + wxToolBar* tb = wxDynamicCast(event.GetEventObject(), wxToolBar); + if (NULL == tb) { + // very very strange + return; + } + + wxObject* wxobject = tb->GetToolClientData(event.GetId()); + if (NULL != wxobject) { + m_manager->SelectObject(wxobject); + } } class WizardFormComponent : public ComponentBase { public: - wxObject* Create(IObject*, wxObject* parent) override { - wxPanel *wizard = new wxPanel( (wxWindow *)parent ); - return wizard; - } + wxObject* Create(IObject*, wxObject* parent) override + { + wxPanel* wizard = new wxPanel((wxWindow*)parent); + return wizard; + } + + void OnSelected(wxObject*) override { wxLogDebug(wxT("Wizard OnSelected")); } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxWizard"), obj->GetPropertyAsString(wxT("name"))); + xrc.AddWindowProperties(); + xrc.AddProperty(wxT("title"), wxT("title"), XRC_TYPE_TEXT); + if (!obj->IsNull(wxT("center"))) + xrc.AddPropertyValue(wxT("centered"), wxT("1")); + + if (!obj->IsNull(wxT("bitmap"))) + xrc.AddProperty(wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP); - void OnSelected(wxObject*) override { - wxLogDebug( wxT("Wizard OnSelected") ); + return xrc.GetXrcObject(); } - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc( obj, wxT("wxWizard"), obj->GetPropertyAsString( wxT("name") ) ); - xrc.AddWindowProperties(); - xrc.AddProperty( wxT("title"), wxT("title"), XRC_TYPE_TEXT ); - if ( !obj->IsNull( wxT("center") ) ) - xrc.AddPropertyValue( wxT("centered"), wxT("1") ); - - if ( !obj->IsNull( wxT("bitmap") ) ) - xrc.AddProperty( wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP ); - - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter( xrcObj, wxT("Wizard") ); - filter.AddWindowProperties(); - filter.AddProperty( wxT("title"), wxT("title"), XRC_TYPE_TEXT ); - filter.AddProperty( wxT("centered"), wxT("center"), XRC_TYPE_BITLIST ); - filter.AddProperty( wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP ); - return filter.GetXfbObject(); - } + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("Wizard")); + filter.AddWindowProperties(); + filter.AddProperty(wxT("title"), wxT("title"), XRC_TYPE_TEXT); + filter.AddProperty(wxT("centered"), wxT("center"), XRC_TYPE_BITLIST); + filter.AddProperty(wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP); + return filter.GetXfbObject(); + } }; class WizardPageComponent : public ComponentBase { public: - wxObject* Create(IObject* /*obj*/, wxObject* parent) override { - WizardPageSimple *page = new WizardPageSimple( ( Wizard * )parent ); - return page; - } -/* - void OnSelected( wxObject* wxobject, IManager* manager ) - { - wxLogDebug( wxT("WizardPageSimple OnSelected") ); - // Get actual page - first child - wxObject* page = manager->GetChild( wxobject, 0 ); - if ( !page ) - { - return; - } - - Wizard* wizard = wxDynamicCast( manager->GetParent( wxobject ), Wizard ); - if ( wizard ) - { - for ( size_t i = 0; i < wizard->GetPageCount(); ++i ) - { - if ( wizard->GetPage( i ) == page ) - { - // Prevent infinite event loop - wxEvtHandler* wizardEvtHandler = wizard->PopEventHandler(); - wxEvtHandler* vobjEvtHandler = wizard->PopEventHandler(); - - // Select Page - wizard->SetSelection( i ); - - // Restore event handling - wizard->PushEventHandler( vobjEvtHandler ); - wizard->PushEventHandler( wizardEvtHandler ); - } - } - } - } -*/ - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc( obj, wxT("wxWizardPageSimple"), obj->GetPropertyAsString( wxT("name") ) ); + wxObject* Create(IObject* /*obj*/, wxObject* parent) override + { + WizardPageSimple* page = new WizardPageSimple((Wizard*)parent); + return page; + } + /* + void OnSelected( wxObject* wxobject, IManager* manager ) + { + wxLogDebug( wxT("WizardPageSimple OnSelected") ); + // Get actual page - first child + wxObject* page = manager->GetChild( wxobject, 0 ); + if ( !page ) + { + return; + } + + Wizard* wizard = wxDynamicCast( manager->GetParent( wxobject ), Wizard ); + if ( wizard ) + { + for ( size_t i = 0; i < wizard->GetPageCount(); ++i ) + { + if ( wizard->GetPage( i ) == page ) + { + // Prevent infinite event loop + wxEvtHandler* wizardEvtHandler = wizard->PopEventHandler(); + wxEvtHandler* vobjEvtHandler = wizard->PopEventHandler(); + + // Select Page + wizard->SetSelection( i ); + + // Restore event handling + wizard->PushEventHandler( vobjEvtHandler ); + wizard->PushEventHandler( wizardEvtHandler ); + } + } + } + } + */ + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, wxT("wxWizardPageSimple"), obj->GetPropertyAsString(wxT("name"))); xrc.AddWindowProperties(); - if ( !obj->IsNull( wxT("bitmap") ) ) - xrc.AddProperty( wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP ); - return xrc.GetXrcObject(); - } + if (!obj->IsNull(wxT("bitmap"))) + xrc.AddProperty(wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP); + return xrc.GetXrcObject(); + } - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter( xrcObj, wxT("WizardPageSimple") ); + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, wxT("WizardPageSimple")); filter.AddWindowProperties(); - filter.AddProperty( wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP ); - return filter.GetXfbObject(); - } + filter.AddProperty(wxT("bitmap"), wxT("bitmap"), XRC_TYPE_BITMAP); + return filter.GetXfbObject(); + } }; BEGIN_LIBRARY() @@ -365,15 +366,15 @@ BEGIN_LIBRARY() // forms aren't considered as windows ! ABSTRACT_COMPONENT("Frame", FrameFormComponent) ABSTRACT_COMPONENT("Panel", PanelFormComponent) -ABSTRACT_COMPONENT("Dialog",DialogFormComponent) +ABSTRACT_COMPONENT("Dialog", DialogFormComponent) -ABSTRACT_COMPONENT( "Wizard", WizardFormComponent ) +ABSTRACT_COMPONENT("Wizard", WizardFormComponent) MACRO(wxWIZARD_EX_HELPBUTTON) -WINDOW_COMPONENT( "WizardPageSimple", WizardPageComponent ) +WINDOW_COMPONENT("WizardPageSimple", WizardPageComponent) -ABSTRACT_COMPONENT("MenuBar",MenuBarFormComponent) -WINDOW_COMPONENT("ToolBar",ToolBarFormComponent) +ABSTRACT_COMPONENT("MenuBar", MenuBarFormComponent) +WINDOW_COMPONENT("ToolBar", ToolBarFormComponent) // wxWindow style macros MACRO(wxBORDER_DEFAULT) @@ -437,9 +438,9 @@ MACRO(wxMINIMIZE_BOX) MACRO(wxSTAY_ON_TOP) MACRO(wxDIALOG_NO_PARENT) -//wxDialog +// wxDialog MACRO(wxBOTH) -SYNONYMOUS(1,wxBOTH) +SYNONYMOUS(1, wxBOTH) // wxMenuBar MACRO(wxMB_DOCKABLE) diff --git a/plugins/layout/layout.cpp b/plugins/layout/layout.cpp index be47ba392..d855d9d9b 100644 --- a/plugins/layout/layout.cpp +++ b/plugins/layout/layout.cpp @@ -23,713 +23,670 @@ // /////////////////////////////////////////////////////////////////////////////// -#include #include #include #include + +#include #include class SpacerComponent : public ComponentBase { public: - // ImportFromXRC is handled in sizeritem components - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("spacer")); - xrc.AddPropertyPair( _("width"), _("height"), _("size") ); - return xrc.GetXrcObject(); - } + // ImportFromXRC is handled in sizeritem components + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("spacer")); + xrc.AddPropertyPair(_("width"), _("height"), _("size")); + return xrc.GetXrcObject(); + } }; class GBSizerItemComponent : public ComponentBase { public: - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("sizeritem")); - xrc.AddPropertyPair( _("row"), _("column"), _("cellpos") ); - xrc.AddPropertyPair( _("rowspan"), _("colspan"), _("cellspan") ); - xrc.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); - xrc.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - // XrcLoader::GetObject imports spacers as sizeritems - XrcToXfbFilter filter(xrcObj, _("gbsizeritem")); - filter.AddPropertyPair( "cellpos", _("row"), _("column") ); - filter.AddPropertyPair( "cellspan", _("rowspan"), _("colspan") ); - filter.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); - filter.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); - ticpp::Element* sizeritem = filter.GetXfbObject(); - - // XrcLoader::GetObject imports spacers as sizeritems, so check for a spacer - if ( xrcObj->FirstChildElement( "size", false ) && !xrcObj->FirstChildElement( "object", false ) ) - { - // it is a spacer - XrcToXfbFilter spacer( xrcObj, _("spacer") ); - spacer.AddPropertyPair( "size", _("width"), _("height") ); - sizeritem->LinkEndChild( spacer.GetXfbObject() ); - } - - return sizeritem; - } + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("sizeritem")); + xrc.AddPropertyPair(_("row"), _("column"), _("cellpos")); + xrc.AddPropertyPair(_("rowspan"), _("colspan"), _("cellspan")); + xrc.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); + xrc.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + // XrcLoader::GetObject imports spacers as sizeritems + XrcToXfbFilter filter(xrcObj, _("gbsizeritem")); + filter.AddPropertyPair("cellpos", _("row"), _("column")); + filter.AddPropertyPair("cellspan", _("rowspan"), _("colspan")); + filter.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); + filter.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); + ticpp::Element* sizeritem = filter.GetXfbObject(); + + // XrcLoader::GetObject imports spacers as sizeritems, so check for a spacer + if (xrcObj->FirstChildElement("size", false) && !xrcObj->FirstChildElement("object", false)) { + // it is a spacer + XrcToXfbFilter spacer(xrcObj, _("spacer")); + spacer.AddPropertyPair("size", _("width"), _("height")); + sizeritem->LinkEndChild(spacer.GetXfbObject()); + } + + return sizeritem; + } }; class SizerItemComponent : public ComponentBase { public: - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - // Get parent sizer - wxObject* parent = GetManager()->GetParent( wxobject ); - wxSizer* sizer = wxDynamicCast( parent, wxSizer ); - - if ( NULL == sizer ) - { - wxLogError( wxT("The parent of a SizerItem is either missing or not a wxSizer - this should not be possible!") ); - return; - } - - // Get child window - wxObject* child = GetManager()->GetChild( wxobject, 0 ); - if ( NULL == child ) - { - wxLogError( wxT("The SizerItem component has no child - this should not be possible!") ); - return; - } - - // Get IObject for property access - IObject* obj = GetManager()->GetIObject( wxobject ); - IObject* childObj = GetManager()->GetIObject( child ); - - // Add the spacer - if ( _("spacer") == childObj->GetClassName() ) - { - sizer->Add( childObj->GetPropertyAsInteger( _("width") ), - childObj->GetPropertyAsInteger( _("height") ), - obj->GetPropertyAsInteger(_("proportion")), - obj->GetPropertyAsInteger(_("flag")), - obj->GetPropertyAsInteger(_("border")) - ); - return; - } - - // Add the child ( window or sizer ) to the sizer - wxWindow* windowChild = wxDynamicCast( child, wxWindow ); - wxSizer* sizerChild = wxDynamicCast( child, wxSizer ); - - if ( windowChild != NULL ) - { - sizer->Add( windowChild, - obj->GetPropertyAsInteger(_("proportion")), - obj->GetPropertyAsInteger(_("flag")), - obj->GetPropertyAsInteger(_("border"))); - } - else if ( sizerChild != NULL ) - { - sizer->Add( sizerChild, - obj->GetPropertyAsInteger(_("proportion")), - obj->GetPropertyAsInteger(_("flag")), - obj->GetPropertyAsInteger(_("border"))); - } - else - { - wxLogError( wxT("The SizerItem component's child is not a wxWindow or a wxSizer or a spacer - this should not be possible!") ); - } - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("sizeritem")); - xrc.AddProperty(_("proportion"), _("option"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); - xrc.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("sizeritem")); - filter.AddProperty(_("option"), _("proportion"), XRC_TYPE_INTEGER); - filter.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); - filter.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); - ticpp::Element* sizeritem = filter.GetXfbObject(); - - // XrcLoader::GetObject imports spacers as sizeritems, so check for a spacer - if ( xrcObj->FirstChildElement("size", false ) && !xrcObj->FirstChildElement("object", false ) ) - { - // it is a spacer - XrcToXfbFilter spacer( xrcObj, _("spacer") ); - spacer.AddPropertyPair( "size", _("width"), _("height") ); - sizeritem->LinkEndChild( spacer.GetXfbObject() ); - } - return sizeritem; - } + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + // Get parent sizer + wxObject* parent = GetManager()->GetParent(wxobject); + wxSizer* sizer = wxDynamicCast(parent, wxSizer); + + if (NULL == sizer) { + wxLogError( + wxT("The parent of a SizerItem is either missing or not a wxSizer - this should not be possible!")); + return; + } + + // Get child window + wxObject* child = GetManager()->GetChild(wxobject, 0); + if (NULL == child) { + wxLogError(wxT("The SizerItem component has no child - this should not be possible!")); + return; + } + + // Get IObject for property access + IObject* obj = GetManager()->GetIObject(wxobject); + IObject* childObj = GetManager()->GetIObject(child); + + // Add the spacer + if (_("spacer") == childObj->GetClassName()) { + sizer->Add( + childObj->GetPropertyAsInteger(_("width")), childObj->GetPropertyAsInteger(_("height")), + obj->GetPropertyAsInteger(_("proportion")), obj->GetPropertyAsInteger(_("flag")), + obj->GetPropertyAsInteger(_("border"))); + return; + } + + // Add the child ( window or sizer ) to the sizer + wxWindow* windowChild = wxDynamicCast(child, wxWindow); + wxSizer* sizerChild = wxDynamicCast(child, wxSizer); + + if (windowChild != NULL) { + sizer->Add( + windowChild, obj->GetPropertyAsInteger(_("proportion")), obj->GetPropertyAsInteger(_("flag")), + obj->GetPropertyAsInteger(_("border"))); + } else if (sizerChild != NULL) { + sizer->Add( + sizerChild, obj->GetPropertyAsInteger(_("proportion")), obj->GetPropertyAsInteger(_("flag")), + obj->GetPropertyAsInteger(_("border"))); + } else { + wxLogError( + wxT("The SizerItem component's child is not a wxWindow or a wxSizer or a spacer - this should not be " + "possible!")); + } + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("sizeritem")); + xrc.AddProperty(_("proportion"), _("option"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); + xrc.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("sizeritem")); + filter.AddProperty(_("option"), _("proportion"), XRC_TYPE_INTEGER); + filter.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); + filter.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); + ticpp::Element* sizeritem = filter.GetXfbObject(); + + // XrcLoader::GetObject imports spacers as sizeritems, so check for a spacer + if (xrcObj->FirstChildElement("size", false) && !xrcObj->FirstChildElement("object", false)) { + // it is a spacer + XrcToXfbFilter spacer(xrcObj, _("spacer")); + spacer.AddPropertyPair("size", _("width"), _("height")); + sizeritem->LinkEndChild(spacer.GetXfbObject()); + } + return sizeritem; + } }; class BoxSizerComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* /*parent*/) override { - wxBoxSizer *sizer = new wxBoxSizer(obj->GetPropertyAsInteger(_("orient"))); - sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); - return sizer; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxBoxSizer")); - if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); - xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc( ticpp::Element* xrcObj ) override - { - XrcToXfbFilter filter(xrcObj, _("wxBoxSizer")); - filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); - filter.AddProperty(_("orient"),_("orient"),XRC_TYPE_TEXT); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* /*parent*/) override + { + wxBoxSizer* sizer = new wxBoxSizer(obj->GetPropertyAsInteger(_("orient"))); + sizer->SetMinSize(obj->GetPropertyAsSize(_("minimum_size"))); + return sizer; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxBoxSizer")); + if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) + xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); + xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxBoxSizer")); + filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); + filter.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); + return filter.GetXfbObject(); + } }; class WrapSizerComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* /*parent*/) override { - const auto sizer = new wxWrapSizer(obj->GetPropertyAsInteger(_("orient")), - obj->GetPropertyAsInteger(_("flags"))); - sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); - return sizer; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxWrapSizer")); - if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) - { - xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); - } - xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); - xrc.AddProperty(_("flags"), _("flags"), XRC_TYPE_BITLIST); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxWrapSizer")); - filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); - filter.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); - filter.AddProperty(_("flags"), _("flags"), XRC_TYPE_BITLIST); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* /*parent*/) override + { + const auto sizer = + new wxWrapSizer(obj->GetPropertyAsInteger(_("orient")), obj->GetPropertyAsInteger(_("flags"))); + sizer->SetMinSize(obj->GetPropertyAsSize(_("minimum_size"))); + return sizer; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxWrapSizer")); + if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) { + xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); + } + xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); + xrc.AddProperty(_("flags"), _("flags"), XRC_TYPE_BITLIST); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxWrapSizer")); + filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); + filter.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); + filter.AddProperty(_("flags"), _("flags"), XRC_TYPE_BITLIST); + return filter.GetXfbObject(); + } }; class StaticBoxSizerComponent : public ComponentBase { public: - int m_count; - StaticBoxSizerComponent() - { - m_count = 0; - } - wxObject* Create(IObject* obj, wxObject* parent) override { - m_count++; - wxStaticBox* box = new wxStaticBox((wxWindow *)parent, wxID_ANY, - obj->GetPropertyAsString(_("label"))); - - wxStaticBoxSizer* sizer = new wxStaticBoxSizer(box, - obj->GetPropertyAsInteger(_("orient"))); - - sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); - - return sizer; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxStaticBoxSizer")); - if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); - xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); - xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxStaticBoxSizer")); - filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); - filter.AddProperty(_("orient"),_("orient"),XRC_TYPE_TEXT); - filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); - return filter.GetXfbObject(); - } + int m_count; + StaticBoxSizerComponent() { m_count = 0; } + wxObject* Create(IObject* obj, wxObject* parent) override + { + m_count++; + wxStaticBox* box = new wxStaticBox((wxWindow*)parent, wxID_ANY, obj->GetPropertyAsString(_("label"))); + + wxStaticBoxSizer* sizer = new wxStaticBoxSizer(box, obj->GetPropertyAsInteger(_("orient"))); + + sizer->SetMinSize(obj->GetPropertyAsSize(_("minimum_size"))); + + return sizer; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxStaticBoxSizer")); + if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) + xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); + xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); + xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxStaticBoxSizer")); + filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); + filter.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); + filter.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); + return filter.GetXfbObject(); + } }; class GridSizerComponent : public ComponentBase { public: - wxObject* Create(IObject* obj, wxObject* /*parent*/) override { - wxGridSizer *sizer = new wxGridSizer( - obj->GetPropertyAsInteger(_("rows")), - obj->GetPropertyAsInteger(_("cols")), - obj->GetPropertyAsInteger(_("vgap")), - obj->GetPropertyAsInteger(_("hgap"))); - - sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); - - return sizer; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxGridSizer")); - if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); - xrc.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxGridSizer")); - filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); - filter.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); - filter.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); - filter.AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); - filter.AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* /*parent*/) override + { + wxGridSizer* sizer = new wxGridSizer( + obj->GetPropertyAsInteger(_("rows")), obj->GetPropertyAsInteger(_("cols")), + obj->GetPropertyAsInteger(_("vgap")), obj->GetPropertyAsInteger(_("hgap"))); + + sizer->SetMinSize(obj->GetPropertyAsSize(_("minimum_size"))); + + return sizer; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxGridSizer")); + if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) + xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); + xrc.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxGridSizer")); + filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); + filter.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); + filter.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); + filter.AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); + filter.AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); + return filter.GetXfbObject(); + } }; class FlexGridSizerBase : public ComponentBase { public: - void AddProperties( IObject* obj, wxFlexGridSizer* sizer ) - { - for (const auto& col : obj->GetPropertyAsVectorIntPair(_("growablecols"))) - { - sizer->AddGrowableCol(col.first, col.second); - } - for (const auto& row : obj->GetPropertyAsVectorIntPair(_("growablerows"))) - { - sizer->AddGrowableRow(row.first, row.second); - } - sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); - sizer->SetFlexibleDirection( obj->GetPropertyAsInteger(_("flexible_direction")) ); - sizer->SetNonFlexibleGrowMode( (wxFlexSizerGrowMode )obj->GetPropertyAsInteger(_("non_flexible_grow_mode")) ); - } - - void ExportXRCProperties( ObjectToXrcFilter* xrc, IObject* obj ) - { - if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc->AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); - xrc->AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); - xrc->AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); - xrc->AddPropertyValue(_("growablecols"), obj->GetPropertyAsString(_("growablecols"))); - xrc->AddPropertyValue(_("growablerows"), obj->GetPropertyAsString(_("growablerows"))); - } - - void ImportXRCProperties( XrcToXfbFilter* filter ) - { - filter->AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); - filter->AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); - filter->AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); - filter->AddProperty(_("growablecols"),_("growablecols"),XRC_TYPE_TEXT); - filter->AddProperty(_("growablerows"),_("growablerows"),XRC_TYPE_TEXT); - } + void AddProperties(IObject* obj, wxFlexGridSizer* sizer) + { + for (const auto& col : obj->GetPropertyAsVectorIntPair(_("growablecols"))) { + sizer->AddGrowableCol(col.first, col.second); + } + for (const auto& row : obj->GetPropertyAsVectorIntPair(_("growablerows"))) { + sizer->AddGrowableRow(row.first, row.second); + } + sizer->SetMinSize(obj->GetPropertyAsSize(_("minimum_size"))); + sizer->SetFlexibleDirection(obj->GetPropertyAsInteger(_("flexible_direction"))); + sizer->SetNonFlexibleGrowMode((wxFlexSizerGrowMode)obj->GetPropertyAsInteger(_("non_flexible_grow_mode"))); + } + + void ExportXRCProperties(ObjectToXrcFilter* xrc, IObject* obj) + { + if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) + xrc->AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); + xrc->AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); + xrc->AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); + xrc->AddPropertyValue(_("growablecols"), obj->GetPropertyAsString(_("growablecols"))); + xrc->AddPropertyValue(_("growablerows"), obj->GetPropertyAsString(_("growablerows"))); + } + + void ImportXRCProperties(XrcToXfbFilter* filter) + { + filter->AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); + filter->AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); + filter->AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); + filter->AddProperty(_("growablecols"), _("growablecols"), XRC_TYPE_TEXT); + filter->AddProperty(_("growablerows"), _("growablerows"), XRC_TYPE_TEXT); + } }; class FlexGridSizerComponent : public FlexGridSizerBase { public: - wxObject* Create(IObject* obj, wxObject* /*parent*/) override { - wxFlexGridSizer *sizer = new wxFlexGridSizer( - obj->GetPropertyAsInteger(_("rows")), - obj->GetPropertyAsInteger(_("cols")), - obj->GetPropertyAsInteger(_("vgap")), - obj->GetPropertyAsInteger(_("hgap"))); - - AddProperties( obj, sizer ); - - return sizer; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxFlexGridSizer")); - xrc.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); - xrc.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); - ExportXRCProperties( &xrc, obj ); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxFlexGridSizer")); - filter.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); - filter.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); - ImportXRCProperties( &filter ); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* /*parent*/) override + { + wxFlexGridSizer* sizer = new wxFlexGridSizer( + obj->GetPropertyAsInteger(_("rows")), obj->GetPropertyAsInteger(_("cols")), + obj->GetPropertyAsInteger(_("vgap")), obj->GetPropertyAsInteger(_("hgap"))); + + AddProperties(obj, sizer); + + return sizer; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxFlexGridSizer")); + xrc.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); + xrc.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); + ExportXRCProperties(&xrc, obj); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxFlexGridSizer")); + filter.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); + filter.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); + ImportXRCProperties(&filter); + return filter.GetXfbObject(); + } }; class GridBagSizerComponent : public FlexGridSizerBase { private: - wxGBSizerItem* GetGBSizerItem( IObject* sizeritem, const wxGBPosition& position, const wxGBSpan& span, wxObject* child ) - { - IObject* childObj = GetManager()->GetIObject( child ); - - if ( _("spacer") == childObj->GetClassName() ) - { - return new wxGBSizerItem( childObj->GetPropertyAsInteger( _("width") ), - childObj->GetPropertyAsInteger( _("height") ), - position, - span, - sizeritem->GetPropertyAsInteger(_("flag")), - sizeritem->GetPropertyAsInteger(_("border")), - NULL - ); - } - - // Add the child ( window or sizer ) to the sizer - wxWindow* windowChild = wxDynamicCast( child, wxWindow ); - wxSizer* sizerChild = wxDynamicCast( child, wxSizer ); - - if ( windowChild != NULL ) - { - return new wxGBSizerItem( windowChild, - position, - span, - sizeritem->GetPropertyAsInteger(_("flag")), - sizeritem->GetPropertyAsInteger(_("border")), - NULL - ); - } - else if ( sizerChild != NULL ) - { - return new wxGBSizerItem( sizerChild, - position, - span, - sizeritem->GetPropertyAsInteger(_("flag")), - sizeritem->GetPropertyAsInteger(_("border")), - NULL - ); - } - else - { - wxLogError( wxT("The GBSizerItem component's child is not a wxWindow or a wxSizer or a Spacer - this should not be possible!") ); - return NULL; - } - } + wxGBSizerItem* GetGBSizerItem( + IObject* sizeritem, const wxGBPosition& position, const wxGBSpan& span, wxObject* child) + { + IObject* childObj = GetManager()->GetIObject(child); + + if (_("spacer") == childObj->GetClassName()) { + return new wxGBSizerItem( + childObj->GetPropertyAsInteger(_("width")), childObj->GetPropertyAsInteger(_("height")), position, span, + sizeritem->GetPropertyAsInteger(_("flag")), sizeritem->GetPropertyAsInteger(_("border")), NULL); + } + + // Add the child ( window or sizer ) to the sizer + wxWindow* windowChild = wxDynamicCast(child, wxWindow); + wxSizer* sizerChild = wxDynamicCast(child, wxSizer); + + if (windowChild != NULL) { + return new wxGBSizerItem( + windowChild, position, span, sizeritem->GetPropertyAsInteger(_("flag")), + sizeritem->GetPropertyAsInteger(_("border")), NULL); + } else if (sizerChild != NULL) { + return new wxGBSizerItem( + sizerChild, position, span, sizeritem->GetPropertyAsInteger(_("flag")), + sizeritem->GetPropertyAsInteger(_("border")), NULL); + } else { + wxLogError( + wxT("The GBSizerItem component's child is not a wxWindow or a wxSizer or a Spacer - this should not be " + "possible!")); + return NULL; + } + } public: - wxObject* Create(IObject* obj, wxObject* /*parent*/) override { - wxGridBagSizer* sizer = new wxGridBagSizer( - obj->GetPropertyAsInteger(_("vgap")), - obj->GetPropertyAsInteger(_("hgap"))); - - if ( !obj->IsNull( _("empty_cell_size") ) ) - { - sizer->SetEmptyCellSize( obj->GetPropertyAsSize( _("empty_cell_size") ) ); - } - - return sizer; - } - - void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { - // For storing objects whose position needs to be determined - std::vector< std::pair< wxObject*, wxGBSizerItem* > > newObjects; - wxGBPosition lastPosition( 0, 0 ); - - // Get sizer - wxGridBagSizer* sizer = wxDynamicCast( wxobject, wxGridBagSizer ); - if ( NULL == sizer ) - { - wxLogError( wxT("This should be a wxGridBagSizer!") ); - return; - } - - // Add the children - IManager* manager = GetManager(); - size_t count = manager->GetChildCount( wxobject ); - if ( 0 == count ) - { - // wxGridBagSizer gets upset sometimes without children - sizer->Add( 0, 0, wxGBPosition( 0, 0 ) ); - return; - } - for ( size_t i = 0; i < count; ++i ) - { - // Should be a GBSizerItem - wxObject* wxsizerItem = manager->GetChild( wxobject, i ); - IObject* isizerItem = manager->GetIObject( wxsizerItem ); - - // Get the location of the item - wxGBSpan span( isizerItem->GetPropertyAsInteger( _("rowspan") ), isizerItem->GetPropertyAsInteger( _("colspan") ) ); - - int column = isizerItem->GetPropertyAsInteger( _("column") ); - if ( column < 0 ) - { - // Needs to be auto positioned after the other children are added - wxGBSizerItem* item = GetGBSizerItem( isizerItem, lastPosition, span, manager->GetChild( wxsizerItem, 0 ) ); - if ( item != NULL ) - { - newObjects.push_back( std::pair< wxObject*, wxGBSizerItem* >( wxsizerItem, item ) ); - } - continue; - } - - wxGBPosition position( isizerItem->GetPropertyAsInteger( _("row") ), column ); - - // Check for intersection - if ( sizer->CheckForIntersection( position, span ) ) - { - continue; - } - - lastPosition = position; - - // Add the child to the sizer - wxGBSizerItem* item = GetGBSizerItem( isizerItem, position, span, manager->GetChild( wxsizerItem, 0 ) ); - if ( item != NULL ) - { - sizer->Add( item ); - } - } - - std::vector< std::pair< wxObject*, wxGBSizerItem* > >::iterator it; - for ( it = newObjects.begin(); it != newObjects.end(); ++it ) - { - wxGBPosition position = it->second->GetPos(); - wxGBSpan span = it->second->GetSpan(); - int column = position.GetCol(); - while ( sizer->CheckForIntersection( position, span ) ) - { - column++; - position.SetCol( column ); - } - it->second->SetPos( position ); - sizer->Add( it->second ); - GetManager()->ModifyProperty( it->first, _("row"), wxString::Format( wxT("%i"), position.GetRow() ), false ); - GetManager()->ModifyProperty( it->first, _("column"), wxString::Format( wxT("%i"), column ), false ); - } - - AddProperties(manager->GetIObject(wxobject), sizer); - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxGridBagSizer")); - ExportXRCProperties( &xrc, obj ); - return xrc.GetXrcObject(); - } - - ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { - XrcToXfbFilter filter(xrcObj, _("wxGridBagSizer")); - ImportXRCProperties( &filter ); - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* /*parent*/) override + { + wxGridBagSizer* sizer = + new wxGridBagSizer(obj->GetPropertyAsInteger(_("vgap")), obj->GetPropertyAsInteger(_("hgap"))); + + if (!obj->IsNull(_("empty_cell_size"))) { + sizer->SetEmptyCellSize(obj->GetPropertyAsSize(_("empty_cell_size"))); + } + + return sizer; + } + + void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override + { + // For storing objects whose position needs to be determined + std::vector > newObjects; + wxGBPosition lastPosition(0, 0); + + // Get sizer + wxGridBagSizer* sizer = wxDynamicCast(wxobject, wxGridBagSizer); + if (NULL == sizer) { + wxLogError(wxT("This should be a wxGridBagSizer!")); + return; + } + + // Add the children + IManager* manager = GetManager(); + size_t count = manager->GetChildCount(wxobject); + if (0 == count) { + // wxGridBagSizer gets upset sometimes without children + sizer->Add(0, 0, wxGBPosition(0, 0)); + return; + } + for (size_t i = 0; i < count; ++i) { + // Should be a GBSizerItem + wxObject* wxsizerItem = manager->GetChild(wxobject, i); + IObject* isizerItem = manager->GetIObject(wxsizerItem); + + // Get the location of the item + wxGBSpan span( + isizerItem->GetPropertyAsInteger(_("rowspan")), isizerItem->GetPropertyAsInteger(_("colspan"))); + + int column = isizerItem->GetPropertyAsInteger(_("column")); + if (column < 0) { + // Needs to be auto positioned after the other children are added + wxGBSizerItem* item = GetGBSizerItem(isizerItem, lastPosition, span, manager->GetChild(wxsizerItem, 0)); + if (item != NULL) { + newObjects.push_back(std::pair(wxsizerItem, item)); + } + continue; + } + + wxGBPosition position(isizerItem->GetPropertyAsInteger(_("row")), column); + + // Check for intersection + if (sizer->CheckForIntersection(position, span)) { + continue; + } + + lastPosition = position; + + // Add the child to the sizer + wxGBSizerItem* item = GetGBSizerItem(isizerItem, position, span, manager->GetChild(wxsizerItem, 0)); + if (item != NULL) { + sizer->Add(item); + } + } + + std::vector >::iterator it; + for (it = newObjects.begin(); it != newObjects.end(); ++it) { + wxGBPosition position = it->second->GetPos(); + wxGBSpan span = it->second->GetSpan(); + int column = position.GetCol(); + while (sizer->CheckForIntersection(position, span)) { + column++; + position.SetCol(column); + } + it->second->SetPos(position); + sizer->Add(it->second); + GetManager()->ModifyProperty(it->first, _("row"), wxString::Format(wxT("%i"), position.GetRow()), false); + GetManager()->ModifyProperty(it->first, _("column"), wxString::Format(wxT("%i"), column), false); + } + + AddProperties(manager->GetIObject(wxobject), sizer); + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxGridBagSizer")); + ExportXRCProperties(&xrc, obj); + return xrc.GetXrcObject(); + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + XrcToXfbFilter filter(xrcObj, _("wxGridBagSizer")); + ImportXRCProperties(&filter); + return filter.GetXfbObject(); + } }; class StdDialogButtonSizerComponent : public ComponentBase { private: - void AddXRCButton( ticpp::Element* sizer, const std::string& id, const std::string& label ) - { - try - { - ticpp::Element button( "object" ); - button.SetAttribute( "class", "button" ); - - ticpp::Element flag( "flag" ); - flag.SetText( "wxALIGN_CENTER_HORIZONTAL|wxALL" ); - button.LinkEndChild( &flag ); - - ticpp::Element border( "border" ); - border.SetText( "5" ); - button.LinkEndChild( &border ); - - ticpp::Element wxbutton( "object" ); - wxbutton.SetAttribute( "class", "wxButton" ); - wxbutton.SetAttribute( "name", id ); - - ticpp::Element labelEl( "label" ); - labelEl.SetText( label ); - wxbutton.LinkEndChild( &labelEl ); - - button.LinkEndChild( &wxbutton ); - - sizer->LinkEndChild( &button ); - } - catch( ticpp::Exception& ex ) - { - wxLogError( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } - } + void AddXRCButton(ticpp::Element* sizer, const std::string& id, const std::string& label) + { + try { + ticpp::Element button("object"); + button.SetAttribute("class", "button"); + + ticpp::Element flag("flag"); + flag.SetText("wxALIGN_CENTER_HORIZONTAL|wxALL"); + button.LinkEndChild(&flag); + + ticpp::Element border("border"); + border.SetText("5"); + button.LinkEndChild(&border); + + ticpp::Element wxbutton("object"); + wxbutton.SetAttribute("class", "wxButton"); + wxbutton.SetAttribute("name", id); + + ticpp::Element labelEl("label"); + labelEl.SetText(label); + wxbutton.LinkEndChild(&labelEl); + + button.LinkEndChild(&wxbutton); + + sizer->LinkEndChild(&button); + } catch (ticpp::Exception& ex) { + wxLogError(wxString(ex.m_details.c_str(), wxConvUTF8)); + } + } public: - wxObject* Create(IObject* obj, wxObject* parent) override { - wxStdDialogButtonSizer* sizer = new wxStdDialogButtonSizer(); - - sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); - - if (obj->GetPropertyAsInteger(_("OK")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_OK)); - } - if (obj->GetPropertyAsInteger(_("Yes")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_YES)); - } - if (obj->GetPropertyAsInteger(_("Save")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_SAVE)); - } - if (obj->GetPropertyAsInteger(_("Apply")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_APPLY)); - } - if (obj->GetPropertyAsInteger(_("No")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_NO)); - } - if (obj->GetPropertyAsInteger(_("Cancel")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_CANCEL)); - } - if (obj->GetPropertyAsInteger(_("Help")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_HELP)); - } - if (obj->GetPropertyAsInteger(_("ContextHelp")) != 0) { - sizer->AddButton(new wxButton((wxWindow*)parent, wxID_CONTEXT_HELP)); - } - - sizer->Realize(); - return sizer; - } - - ticpp::Element* ExportToXrc(IObject* obj) override { - ObjectToXrcFilter xrc(obj, _("wxStdDialogButtonSizer")); - ticpp::Element* sizer = xrc.GetXrcObject(); - - if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) { - xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); - } - if (obj->GetPropertyAsInteger(_("OK")) != 0) { - AddXRCButton(sizer, "wxID_OK", "&OK"); - } - if (obj->GetPropertyAsInteger(_("Yes")) != 0) { - AddXRCButton(sizer, "wxID_YES", "&Yes"); - } - if (obj->GetPropertyAsInteger(_("Save")) != 0) { - AddXRCButton(sizer, "wxID_SAVE", "&Save"); - } - if (obj->GetPropertyAsInteger(_("Apply")) != 0) { - AddXRCButton(sizer, "wxID_APPLY", "&Apply"); - } - if (obj->GetPropertyAsInteger(_("No")) != 0) { - AddXRCButton(sizer, "wxID_NO", "&No"); - } - if (obj->GetPropertyAsInteger(_("Cancel")) != 0) { - AddXRCButton(sizer, "wxID_CANCEL", "&Cancel"); - } - if (obj->GetPropertyAsInteger(_("Help")) != 0) { - AddXRCButton(sizer, "wxID_HELP", "&Help"); - } - if (obj->GetPropertyAsInteger(_("ContextHelp")) != 0) { - AddXRCButton(sizer, "wxID_CONTEXT_HELP", ""); - } - - return sizer; - } - - ticpp::Element* ImportFromXrc( ticpp::Element* xrcObj ) override - { - std::map< wxString, wxString > buttons; - buttons[ _("OK") ] = wxT("0"); - buttons[ _("Yes") ] = wxT("0"); - buttons[ _("Save") ] = wxT("0"); - buttons[ _("Apply") ] = wxT("0"); - buttons[ _("No") ] = wxT("0"); - buttons[ _("Cancel") ] = wxT("0"); - buttons[ _("Help") ] = wxT("0"); - buttons[ _("ContextHelp") ] = wxT("0"); - - XrcToXfbFilter filter(xrcObj, _("wxStdDialogButtonSizer")); - filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); - - ticpp::Element* button = xrcObj->FirstChildElement( "object", false ); - for ( ; button != 0; button = button->NextSiblingElement( "object", false ) ) - { - try - { - std::string button_class; - button->GetAttribute( "class", &button_class ); - if ( std::string("button") != button_class ) - { - continue; - } - - ticpp::Element* wxbutton = button->FirstChildElement( "object" ); - std::string wxbutton_class; - wxbutton->GetAttribute( "class", &wxbutton_class ); - if ( std::string("wxButton") != wxbutton_class ) - { - continue; - } - - std::string name; - wxbutton->GetAttribute( "name", &name ); - - if ( name == "wxID_OK" ) - { - buttons[ _("OK") ] = wxT("1"); - } - else if ( name == "wxID_YES" ) - { - buttons[ _("Yes") ] = wxT("1"); - } - else if ( name == "wxID_SAVE" ) - { - buttons[ _("Save") ] = wxT("1"); - } - else if ( name == "wxID_APPLY" ) - { - buttons[ _("Apply") ] = wxT("1"); - } - else if ( name == "wxID_NO" ) - { - buttons[ _("No") ] = wxT("1"); - } - else if ( name == "wxID_CANCEL" ) - { - buttons[ _("Cancel") ] = wxT("1"); - } - else if ( name == "wxID_HELP" ) - { - buttons[ _("Help") ] = wxT("1"); - } - else if ( name == "wxID_CONTEXT_HELP" ) - { - buttons[ _("ContextHelp") ] = wxT("1"); - } - } - catch( ticpp::Exception& ) - { - continue; - } - } - - std::map< wxString, wxString >::iterator prop; - for ( prop = buttons.begin(); prop != buttons.end(); ++prop ) - { - filter.AddPropertyValue( prop->first, prop->second ); - } - - xrcObj->Clear(); - - return filter.GetXfbObject(); - } + wxObject* Create(IObject* obj, wxObject* parent) override + { + wxStdDialogButtonSizer* sizer = new wxStdDialogButtonSizer(); + + sizer->SetMinSize(obj->GetPropertyAsSize(_("minimum_size"))); + + if (obj->GetPropertyAsInteger(_("OK")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_OK)); + } + if (obj->GetPropertyAsInteger(_("Yes")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_YES)); + } + if (obj->GetPropertyAsInteger(_("Save")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_SAVE)); + } + if (obj->GetPropertyAsInteger(_("Apply")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_APPLY)); + } + if (obj->GetPropertyAsInteger(_("No")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_NO)); + } + if (obj->GetPropertyAsInteger(_("Cancel")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_CANCEL)); + } + if (obj->GetPropertyAsInteger(_("Help")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_HELP)); + } + if (obj->GetPropertyAsInteger(_("ContextHelp")) != 0) { + sizer->AddButton(new wxButton((wxWindow*)parent, wxID_CONTEXT_HELP)); + } + + sizer->Realize(); + return sizer; + } + + ticpp::Element* ExportToXrc(IObject* obj) override + { + ObjectToXrcFilter xrc(obj, _("wxStdDialogButtonSizer")); + ticpp::Element* sizer = xrc.GetXrcObject(); + + if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) { + xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); + } + if (obj->GetPropertyAsInteger(_("OK")) != 0) { + AddXRCButton(sizer, "wxID_OK", "&OK"); + } + if (obj->GetPropertyAsInteger(_("Yes")) != 0) { + AddXRCButton(sizer, "wxID_YES", "&Yes"); + } + if (obj->GetPropertyAsInteger(_("Save")) != 0) { + AddXRCButton(sizer, "wxID_SAVE", "&Save"); + } + if (obj->GetPropertyAsInteger(_("Apply")) != 0) { + AddXRCButton(sizer, "wxID_APPLY", "&Apply"); + } + if (obj->GetPropertyAsInteger(_("No")) != 0) { + AddXRCButton(sizer, "wxID_NO", "&No"); + } + if (obj->GetPropertyAsInteger(_("Cancel")) != 0) { + AddXRCButton(sizer, "wxID_CANCEL", "&Cancel"); + } + if (obj->GetPropertyAsInteger(_("Help")) != 0) { + AddXRCButton(sizer, "wxID_HELP", "&Help"); + } + if (obj->GetPropertyAsInteger(_("ContextHelp")) != 0) { + AddXRCButton(sizer, "wxID_CONTEXT_HELP", ""); + } + + return sizer; + } + + ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override + { + std::map buttons; + buttons[_("OK")] = wxT("0"); + buttons[_("Yes")] = wxT("0"); + buttons[_("Save")] = wxT("0"); + buttons[_("Apply")] = wxT("0"); + buttons[_("No")] = wxT("0"); + buttons[_("Cancel")] = wxT("0"); + buttons[_("Help")] = wxT("0"); + buttons[_("ContextHelp")] = wxT("0"); + + XrcToXfbFilter filter(xrcObj, _("wxStdDialogButtonSizer")); + filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); + + ticpp::Element* button = xrcObj->FirstChildElement("object", false); + for (; button != 0; button = button->NextSiblingElement("object", false)) { + try { + std::string button_class; + button->GetAttribute("class", &button_class); + if (std::string("button") != button_class) { + continue; + } + + ticpp::Element* wxbutton = button->FirstChildElement("object"); + std::string wxbutton_class; + wxbutton->GetAttribute("class", &wxbutton_class); + if (std::string("wxButton") != wxbutton_class) { + continue; + } + + std::string name; + wxbutton->GetAttribute("name", &name); + + if (name == "wxID_OK") { + buttons[_("OK")] = wxT("1"); + } else if (name == "wxID_YES") { + buttons[_("Yes")] = wxT("1"); + } else if (name == "wxID_SAVE") { + buttons[_("Save")] = wxT("1"); + } else if (name == "wxID_APPLY") { + buttons[_("Apply")] = wxT("1"); + } else if (name == "wxID_NO") { + buttons[_("No")] = wxT("1"); + } else if (name == "wxID_CANCEL") { + buttons[_("Cancel")] = wxT("1"); + } else if (name == "wxID_HELP") { + buttons[_("Help")] = wxT("1"); + } else if (name == "wxID_CONTEXT_HELP") { + buttons[_("ContextHelp")] = wxT("1"); + } + } catch (ticpp::Exception&) { + continue; + } + } + + std::map::iterator prop; + for (prop = buttons.begin(); prop != buttons.end(); ++prop) { + filter.AddPropertyValue(prop->first, prop->second); + } + + xrcObj->Clear(); + + return filter.GetXfbObject(); + } }; /////////////////////////////////////////////////////////////////////////////// BEGIN_LIBRARY() -ABSTRACT_COMPONENT("spacer",SpacerComponent) -ABSTRACT_COMPONENT("sizeritem",SizerItemComponent) -ABSTRACT_COMPONENT("gbsizeritem",GBSizerItemComponent) - -SIZER_COMPONENT("wxBoxSizer",BoxSizerComponent) -SIZER_COMPONENT("wxWrapSizer",WrapSizerComponent) -SIZER_COMPONENT("wxStaticBoxSizer",StaticBoxSizerComponent) -SIZER_COMPONENT("wxGridSizer",GridSizerComponent) -SIZER_COMPONENT("wxFlexGridSizer",FlexGridSizerComponent) -SIZER_COMPONENT("wxGridBagSizer",GridBagSizerComponent) -SIZER_COMPONENT("wxStdDialogButtonSizer",StdDialogButtonSizerComponent) +ABSTRACT_COMPONENT("spacer", SpacerComponent) +ABSTRACT_COMPONENT("sizeritem", SizerItemComponent) +ABSTRACT_COMPONENT("gbsizeritem", GBSizerItemComponent) + +SIZER_COMPONENT("wxBoxSizer", BoxSizerComponent) +SIZER_COMPONENT("wxWrapSizer", WrapSizerComponent) +SIZER_COMPONENT("wxStaticBoxSizer", StaticBoxSizerComponent) +SIZER_COMPONENT("wxGridSizer", GridSizerComponent) +SIZER_COMPONENT("wxFlexGridSizer", FlexGridSizerComponent) +SIZER_COMPONENT("wxGridBagSizer", GridBagSizerComponent) +SIZER_COMPONENT("wxStdDialogButtonSizer", StdDialogButtonSizerComponent) // wxBoxSizer MACRO(wxHORIZONTAL) diff --git a/sdk/plugin_interface/component.h b/sdk/plugin_interface/component.h index 84047a23c..860f797bb 100644 --- a/sdk/plugin_interface/component.h +++ b/sdk/plugin_interface/component.h @@ -22,40 +22,34 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef SDK_PLUGIN_INTERFACE_COMPONENT_H #define SDK_PLUGIN_INTERFACE_COMPONENT_H -#include +#include + #include +#include -#include #include "fontcontainer.h" + #define COMPONENT_TYPE_ABSTRACT 0 -#define COMPONENT_TYPE_WINDOW 1 -#define COMPONENT_TYPE_SIZER 2 +#define COMPONENT_TYPE_WINDOW 1 +#define COMPONENT_TYPE_SIZER 2 namespace ticpp { - class Element; +class Element; } class IComponent; // Sections for source code generation -enum -{ - CG_DECLARATION, - CG_CONSTRUCTION, - CG_POST_CONSTRUCTION, - CG_SETTINGS -}; +enum { CG_DECLARATION, CG_CONSTRUCTION, CG_POST_CONSTRUCTION, CG_SETTINGS }; // Programming languages for source code generation -enum -{ - CG_CPP -}; +enum { CG_CPP }; // Plugins interface @@ -63,51 +57,50 @@ enum // from the plugin itself, in a safe way. class IObject { - public: - virtual bool IsNull (const wxString& pname) = 0; - virtual int GetPropertyAsInteger (const wxString& pname) = 0; - virtual wxFontContainer GetPropertyAsFont (const wxString& pname) = 0; - virtual wxColour GetPropertyAsColour (const wxString& pname) = 0; - virtual wxString GetPropertyAsString (const wxString& pname) = 0; - virtual wxPoint GetPropertyAsPoint (const wxString& pname) = 0; - virtual wxSize GetPropertyAsSize (const wxString& pname) = 0; - virtual wxBitmap GetPropertyAsBitmap (const wxString& pname) = 0; - virtual wxArrayInt GetPropertyAsArrayInt(const wxString& pname) = 0; - virtual wxArrayString GetPropertyAsArrayString(const wxString& pname) = 0; - virtual std::vector> GetPropertyAsVectorIntPair(const wxString& pname) = 0; - virtual double GetPropertyAsFloat(const wxString& pname) = 0; - virtual wxString GetChildFromParentProperty( const wxString& parentName, const wxString& childName ) = 0; - virtual wxString GetClassName() = 0; - virtual unsigned int GetChildCount() = 0; - virtual wxString GetObjectTypeName() = 0; - virtual IObject* GetChildPtr (unsigned int idx) = 0; - virtual ~IObject(){} +public: + virtual bool IsNull(const wxString& pname) = 0; + virtual int GetPropertyAsInteger(const wxString& pname) = 0; + virtual wxFontContainer GetPropertyAsFont(const wxString& pname) = 0; + virtual wxColour GetPropertyAsColour(const wxString& pname) = 0; + virtual wxString GetPropertyAsString(const wxString& pname) = 0; + virtual wxPoint GetPropertyAsPoint(const wxString& pname) = 0; + virtual wxSize GetPropertyAsSize(const wxString& pname) = 0; + virtual wxBitmap GetPropertyAsBitmap(const wxString& pname) = 0; + virtual wxArrayInt GetPropertyAsArrayInt(const wxString& pname) = 0; + virtual wxArrayString GetPropertyAsArrayString(const wxString& pname) = 0; + virtual std::vector> GetPropertyAsVectorIntPair(const wxString& pname) = 0; + virtual double GetPropertyAsFloat(const wxString& pname) = 0; + virtual wxString GetChildFromParentProperty(const wxString& parentName, const wxString& childName) = 0; + virtual wxString GetClassName() = 0; + virtual unsigned int GetChildCount() = 0; + virtual wxString GetObjectTypeName() = 0; + virtual IObject* GetChildPtr(unsigned int idx) = 0; + virtual ~IObject() {} }; // Interface which intends to contain all the components for a plugin // This is an abstract class and it'll be the object that the DLL will export. class IComponentLibrary { - public: - - // Used by the plugin for registering components and macros - virtual void RegisterComponent(const wxString &text, IComponent *c) = 0; - virtual void RegisterMacro(const wxString &text, const int value) = 0; - virtual void RegisterMacroSynonymous(const wxString &text, const wxString &name) = 0; - - // Used by wxFormBuilder for recovering components and macros - virtual IComponent* GetComponent(unsigned int idx) = 0; - virtual wxString GetComponentName(unsigned int idx) = 0; - virtual wxString GetMacroName(unsigned int i) = 0; - virtual int GetMacroValue(unsigned int i) = 0; - //virtual wxString GetMacroSynonymous(unsigned int i) = 0; - //virtual wxString GetSynonymousName(unsigned int i) = 0; - virtual bool FindSynonymous(const wxString& syn, wxString& trans) = 0; - - virtual unsigned int GetMacroCount() = 0; - virtual unsigned int GetComponentCount() = 0; - //virtual unsigned int GetSynonymousCount() = 0; - virtual ~IComponentLibrary(){} +public: + // Used by the plugin for registering components and macros + virtual void RegisterComponent(const wxString& text, IComponent* c) = 0; + virtual void RegisterMacro(const wxString& text, const int value) = 0; + virtual void RegisterMacroSynonymous(const wxString& text, const wxString& name) = 0; + + // Used by wxFormBuilder for recovering components and macros + virtual IComponent* GetComponent(unsigned int idx) = 0; + virtual wxString GetComponentName(unsigned int idx) = 0; + virtual wxString GetMacroName(unsigned int i) = 0; + virtual int GetMacroValue(unsigned int i) = 0; + // virtual wxString GetMacroSynonymous(unsigned int i) = 0; + // virtual wxString GetSynonymousName(unsigned int i) = 0; + virtual bool FindSynonymous(const wxString& syn, wxString& trans) = 0; + + virtual unsigned int GetMacroCount() = 0; + virtual unsigned int GetComponentCount() = 0; + // virtual unsigned int GetSynonymousCount() = 0; + virtual ~IComponentLibrary() {} }; /** @@ -115,46 +108,46 @@ class IComponentLibrary */ class IComponent { - public: - /** - * Create an instance of the wxObject and return a pointer - */ - virtual wxObject* Create( IObject* obj, wxObject* parent ) = 0; - - /** - * Cleanup (do the reverse of Create) - */ - virtual void Cleanup( wxObject* obj ) = 0; - - /** - * Allows components to do something after they have been created. - * For example, Abstract components like NotebookPage and SizerItem can - * add the actual widget to the Notebook or sizer. - * - * @param wxobject The object which was just created. - * @param wxparent The wxWidgets parent - the wxObject that the created object was added to. - */ - virtual void OnCreated( wxObject* wxobject, wxWindow* wxparent ) = 0; - - /** - * Allows components to respond when selected in object tree. - * For example, when a wxNotebook's page is selected, it can switch to that page - */ - virtual void OnSelected( wxObject* wxobject ) = 0; - - /** - * Export the object to an XRC node - */ - virtual ticpp::Element* ExportToXrc( IObject* obj ) = 0; - - /** - * Converts from an XRC element to a wxFormBuilder project file XML element - */ - virtual ticpp::Element* ImportFromXrc( ticpp::Element* xrcObj ) = 0; - - - virtual int GetComponentType() = 0; - virtual ~IComponent(){} +public: + /** + * Create an instance of the wxObject and return a pointer + */ + virtual wxObject* Create(IObject* obj, wxObject* parent) = 0; + + /** + * Cleanup (do the reverse of Create) + */ + virtual void Cleanup(wxObject* obj) = 0; + + /** + * Allows components to do something after they have been created. + * For example, Abstract components like NotebookPage and SizerItem can + * add the actual widget to the Notebook or sizer. + * + * @param wxobject The object which was just created. + * @param wxparent The wxWidgets parent - the wxObject that the created object was added to. + */ + virtual void OnCreated(wxObject* wxobject, wxWindow* wxparent) = 0; + + /** + * Allows components to respond when selected in object tree. + * For example, when a wxNotebook's page is selected, it can switch to that page + */ + virtual void OnSelected(wxObject* wxobject) = 0; + + /** + * Export the object to an XRC node + */ + virtual ticpp::Element* ExportToXrc(IObject* obj) = 0; + + /** + * Converts from an XRC element to a wxFormBuilder project file XML element + */ + virtual ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) = 0; + + + virtual int GetComponentType() = 0; + virtual ~IComponent() {} }; // Used to identify wxObject* that must be manually deleted @@ -169,100 +162,93 @@ Essentially a collection of utility functions that take a wxObject* and do somet class IManager { public: - /** - Get the count of the children of this object. - */ - virtual size_t GetChildCount( wxObject* wxobject ) = 0; - - /** - Get a child of the object. - @param childIndex Index of the child to get. - */ - virtual wxObject* GetChild( wxObject* wxobject, size_t childIndex ) = 0; - - /** - Get the parent of the object. - */ - virtual wxObject* GetParent( wxObject* wxobject ) = 0; - - /** - Get the IObject interface to the parent of the object. - */ - virtual IObject* GetIParent( wxObject* wxobject ) = 0; - - /** - Get the corresponding object interface pointer for the object. - This allows easy read only access to properties. - */ - virtual IObject* GetIObject( wxObject* wxobject ) = 0; - - /** - Modify a property of the object. - @param property The name of the property to modify. - @param value The new value for the property. - @param allowUndo If true, the property change will be placed into the undo stack, if false it will be modified silently. - */ - virtual void ModifyProperty( wxObject* wxobject, wxString property, wxString value, bool allowUndo = true ) = 0; - - // used so the wxNoObjects are both created and destroyed in the application - virtual wxNoObject* NewNoObject() = 0; - - /** - Select the object in the object tree - Returns true if selection changed, false if already selected - */ - virtual bool SelectObject( wxObject* wxobject ) = 0; - - virtual ~IManager(){} + /** + Get the count of the children of this object. + */ + virtual size_t GetChildCount(wxObject* wxobject) = 0; + + /** + Get a child of the object. + @param childIndex Index of the child to get. + */ + virtual wxObject* GetChild(wxObject* wxobject, size_t childIndex) = 0; + + /** + Get the parent of the object. + */ + virtual wxObject* GetParent(wxObject* wxobject) = 0; + + /** + Get the IObject interface to the parent of the object. + */ + virtual IObject* GetIParent(wxObject* wxobject) = 0; + + /** + Get the corresponding object interface pointer for the object. + This allows easy read only access to properties. + */ + virtual IObject* GetIObject(wxObject* wxobject) = 0; + + /** + Modify a property of the object. + @param property The name of the property to modify. + @param value The new value for the property. + @param allowUndo If true, the property change will be placed into the undo stack, if false it will be modified + silently. + */ + virtual void ModifyProperty(wxObject* wxobject, wxString property, wxString value, bool allowUndo = true) = 0; + + // used so the wxNoObjects are both created and destroyed in the application + virtual wxNoObject* NewNoObject() = 0; + + /** + Select the object in the object tree + Returns true if selection changed, false if already selected + */ + virtual bool SelectObject(wxObject* wxobject) = 0; + + virtual ~IManager() {} }; #ifdef BUILD_DLL - #define DLL_FUNC extern "C" WXEXPORT + #define DLL_FUNC extern "C" WXEXPORT #else - #define DLL_FUNC extern "C" + #define DLL_FUNC extern "C" #endif // Function that the application calls to get the library -DLL_FUNC IComponentLibrary* GetComponentLibrary( IManager* manager ); +DLL_FUNC IComponentLibrary* GetComponentLibrary(IManager* manager); // Function that the application calls to free the library -DLL_FUNC void FreeComponentLibrary( IComponentLibrary* lib ); +DLL_FUNC void FreeComponentLibrary(IComponentLibrary* lib); -#define BEGIN_LIBRARY() \ +#define BEGIN_LIBRARY() \ \ -extern "C" WXEXPORT IComponentLibrary* GetComponentLibrary( IManager* manager ) \ -{ \ - IComponentLibrary* lib = new ComponentLibrary(); - -#define END_LIBRARY() \ - return lib; \ - } \ - extern "C" WXEXPORT void FreeComponentLibrary( IComponentLibrary* lib ) \ - { \ - delete lib; \ - } - -#define MACRO( name ) \ - lib->RegisterMacro( wxT(#name), name ); - -#define SYNONYMOUS( syn, name ) \ - lib->RegisterMacroSynonymous( wxT(#syn), wxT(#name) ); - -#define _REGISTER_COMPONENT( name, class, type )\ - { \ - ComponentBase* c = new class(); \ - c->__SetComponentType( type ); \ - c->__SetManager( manager ); \ - lib->RegisterComponent( wxT(name), c ); \ - } - -#define WINDOW_COMPONENT( name, class ) \ - _REGISTER_COMPONENT( name, class, COMPONENT_TYPE_WINDOW ) - -#define SIZER_COMPONENT( name,class ) \ - _REGISTER_COMPONENT( name, class, COMPONENT_TYPE_SIZER ) - -#define ABSTRACT_COMPONENT( name, class ) \ - _REGISTER_COMPONENT( name, class, COMPONENT_TYPE_ABSTRACT ) - -#endif // SDK_PLUGIN_INTERFACE_COMPONENT_H + extern "C" WXEXPORT IComponentLibrary* GetComponentLibrary(IManager* manager) \ + { \ + IComponentLibrary* lib = new ComponentLibrary(); + +#define END_LIBRARY() \ + return lib; \ + } \ + extern "C" WXEXPORT void FreeComponentLibrary(IComponentLibrary* lib) { delete lib; } + +#define MACRO(name) lib->RegisterMacro(wxT(#name), name); + +#define SYNONYMOUS(syn, name) lib->RegisterMacroSynonymous(wxT(#syn), wxT(#name)); + +#define _REGISTER_COMPONENT(name, class, type) \ + { \ + ComponentBase* c = new class(); \ + c->__SetComponentType(type); \ + c->__SetManager(manager); \ + lib->RegisterComponent(wxT(name), c); \ + } + +#define WINDOW_COMPONENT(name, class) _REGISTER_COMPONENT(name, class, COMPONENT_TYPE_WINDOW) + +#define SIZER_COMPONENT(name, class) _REGISTER_COMPONENT(name, class, COMPONENT_TYPE_SIZER) + +#define ABSTRACT_COMPONENT(name, class) _REGISTER_COMPONENT(name, class, COMPONENT_TYPE_ABSTRACT) + +#endif // SDK_PLUGIN_INTERFACE_COMPONENT_H diff --git a/sdk/plugin_interface/fontcontainer.h b/sdk/plugin_interface/fontcontainer.h index 0982bdda7..09159dab5 100644 --- a/sdk/plugin_interface/fontcontainer.h +++ b/sdk/plugin_interface/fontcontainer.h @@ -21,87 +21,84 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef SDK_PLUGIN_INTERFACE_FONTCONTAINER_H #define SDK_PLUGIN_INTERFACE_FONTCONTAINER_H #include + /** @class wxFontContainer @brief Because the class wxFont cannot be a container for invalid font data (like default values). */ class wxFontContainer : public wxObject { public: - int m_pointSize; ///< Point Size - wxFontFamily m_family; ///< Family - wxFontStyle m_style; ///< Style - wxFontWeight m_weight; ///< Weight - bool m_underlined; ///< Underlined - wxString m_faceName; ///< Face Name + int m_pointSize; ///< Point Size + wxFontFamily m_family; ///< Family + wxFontStyle m_style; ///< Style + wxFontWeight m_weight; ///< Weight + bool m_underlined; ///< Underlined + wxString m_faceName; ///< Face Name inline void InitDefaults() { - m_pointSize = -1; - m_family = wxFONTFAMILY_DEFAULT; - m_style = wxFONTSTYLE_NORMAL; - m_weight = wxFONTWEIGHT_NORMAL; - m_underlined = false; - m_faceName = wxEmptyString; + m_pointSize = -1; + m_family = wxFONTFAMILY_DEFAULT; + m_style = wxFONTSTYLE_NORMAL; + m_weight = wxFONTWEIGHT_NORMAL; + m_underlined = false; + m_faceName = wxEmptyString; } - wxFontContainer() - { - InitDefaults(); - } + wxFontContainer() { InitDefaults(); } - inline wxFontContainer( const wxFont& font ) + inline wxFontContainer(const wxFont& font) { - if ( !font.IsOk() ) - { - InitDefaults(); - } - else - { - m_pointSize = font.GetPointSize(); - m_family = font.GetFamily(); - m_style = font.GetStyle(); - m_weight = font.GetWeight(); - m_underlined = font.GetUnderlined(); - m_faceName = font.GetFaceName(); + if (!font.IsOk()) { + InitDefaults(); + } else { + m_pointSize = font.GetPointSize(); + m_family = font.GetFamily(); + m_style = font.GetStyle(); + m_weight = font.GetWeight(); + m_underlined = font.GetUnderlined(); + m_faceName = font.GetFaceName(); } } - inline wxFontContainer(int pointSize, wxFontFamily family = wxFONTFAMILY_DEFAULT, - wxFontStyle style = wxFONTSTYLE_NORMAL, - wxFontWeight weight = wxFONTWEIGHT_NORMAL, bool underlined = false, - const wxString& faceName = wxEmptyString) - : m_pointSize(pointSize), m_family(family), m_style(style), m_weight(weight), - m_underlined(underlined), m_faceName(faceName) { - } + inline wxFontContainer( + int pointSize, wxFontFamily family = wxFONTFAMILY_DEFAULT, wxFontStyle style = wxFONTSTYLE_NORMAL, + wxFontWeight weight = wxFONTWEIGHT_NORMAL, bool underlined = false, const wxString& faceName = wxEmptyString) : + m_pointSize(pointSize), + m_family(family), + m_style(style), + m_weight(weight), + m_underlined(underlined), + m_faceName(faceName) + { + } - wxFont GetFont() const - { - int pointSize = m_pointSize <= 0 ? wxNORMAL_FONT->GetPointSize() : m_pointSize; - return wxFont( pointSize, m_family, m_style, m_weight, m_underlined, m_faceName ); - } + wxFont GetFont() const + { + int pointSize = m_pointSize <= 0 ? wxNORMAL_FONT->GetPointSize() : m_pointSize; + return wxFont(pointSize, m_family, m_style, m_weight, m_underlined, m_faceName); + } - // Duplicate wxFont's interface for backward compatiblity - #define MAKE_GET_AND_SET( NAME, TYPE, VARIABLE ) \ - TYPE Get##NAME() const { return VARIABLE; } \ - void Set##NAME( TYPE value ){ VARIABLE = value; } +// Duplicate wxFont's interface for backward compatiblity +#define MAKE_GET_AND_SET(NAME, TYPE, VARIABLE) \ + TYPE Get##NAME() const { return VARIABLE; } \ + void Set##NAME(TYPE value) { VARIABLE = value; } - MAKE_GET_AND_SET( PointSize, int, m_pointSize ) - MAKE_GET_AND_SET(Family, wxFontFamily, m_family) - MAKE_GET_AND_SET(Style, wxFontStyle, m_style) - MAKE_GET_AND_SET(Weight, wxFontWeight, m_weight) - MAKE_GET_AND_SET( Underlined, bool, m_underlined ) - MAKE_GET_AND_SET( FaceName, wxString, m_faceName ) + MAKE_GET_AND_SET(PointSize, int, m_pointSize) + MAKE_GET_AND_SET(Family, wxFontFamily, m_family) + MAKE_GET_AND_SET(Style, wxFontStyle, m_style) + MAKE_GET_AND_SET(Weight, wxFontWeight, m_weight) + MAKE_GET_AND_SET(Underlined, bool, m_underlined) + MAKE_GET_AND_SET(FaceName, wxString, m_faceName) - // Allow implicit cast to wxFont - operator wxFont() const - { - return GetFont(); - } + // Allow implicit cast to wxFont + operator wxFont() const { return GetFont(); } }; -#endif // SDK_PLUGIN_INTERFACE_FONTCONTAINER_H +#endif // SDK_PLUGIN_INTERFACE_FONTCONTAINER_H diff --git a/sdk/plugin_interface/forms/wizard.cpp b/sdk/plugin_interface/forms/wizard.cpp index 182761963..80f9590e5 100644 --- a/sdk/plugin_interface/forms/wizard.cpp +++ b/sdk/plugin_interface/forms/wizard.cpp @@ -22,8 +22,10 @@ // based on original wizard.cpp file in wxWidgets source code // /////////////////////////////////////////////////////////////////////////////// + #include "wizard.h" + wxDEFINE_EVENT(wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEvent); wxDEFINE_EVENT(wxFB_EVT_WIZARD_PAGE_CHANGING, WizardEvent); wxDEFINE_EVENT(wxFB_EVT_WIZARD_CANCEL, WizardEvent); @@ -46,173 +48,161 @@ BEGIN_EVENT_TABLE( Wizard, wxPanel ) EVT_WXFB_WIZARD_HELP( wxID_ANY, Wizard::OnWizEvent ) END_EVENT_TABLE() */ -WizardPageSimple::WizardPageSimple( Wizard *parent ) - : wxPanel( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ) + + +WizardPageSimple::WizardPageSimple(Wizard* parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0) { } WizardPageSimple::~WizardPageSimple() = default; -Wizard::Wizard( wxWindow* parent, wxWindowID id, - const wxPoint& pos, const wxSize& size, long style ) -: wxPanel( parent, id, pos, size, style ) +Wizard::Wizard(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : + wxPanel(parent, id, pos, size, style) { - m_page = nullptr; + m_page = nullptr; m_bitmap = wxNullBitmap; - const auto windowSizer = new wxBoxSizer(wxVERTICAL); - const auto mainColumn = new wxBoxSizer(wxVERTICAL); - const auto buttonRow = new wxBoxSizer(wxHORIZONTAL); - const auto backNextPair = new wxBoxSizer(wxHORIZONTAL); - m_sizerBmpAndPage = new wxBoxSizer( wxHORIZONTAL ); - m_sizerPage = new wxBoxSizer( wxVERTICAL ); + const auto windowSizer = new wxBoxSizer(wxVERTICAL); + const auto mainColumn = new wxBoxSizer(wxVERTICAL); + const auto buttonRow = new wxBoxSizer(wxHORIZONTAL); + const auto backNextPair = new wxBoxSizer(wxHORIZONTAL); + m_sizerBmpAndPage = new wxBoxSizer(wxHORIZONTAL); + m_sizerPage = new wxBoxSizer(wxVERTICAL); - m_statbmp = new wxStaticBitmap( this, wxID_ANY, wxNullBitmap ); + m_statbmp = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap); - m_sizerBmpAndPage->SetMinSize( wxSize( 270, 270 ) ); - m_sizerBmpAndPage->Add( m_statbmp, 0, wxALL, 5 ); - m_sizerBmpAndPage->Add( 5, 0, 0, wxEXPAND, 0 ); - m_sizerBmpAndPage->Add( m_sizerPage, 1, wxEXPAND, 0 ); + m_sizerBmpAndPage->SetMinSize(wxSize(270, 270)); + m_sizerBmpAndPage->Add(m_statbmp, 0, wxALL, 5); + m_sizerBmpAndPage->Add(5, 0, 0, wxEXPAND, 0); + m_sizerBmpAndPage->Add(m_sizerPage, 1, wxEXPAND, 0); - m_btnHelp = new wxButton( this, wxID_HELP, _("&Help") ); - m_btnPrev = new wxButton( this, wxID_BACKWARD, _("< &Back") ); - m_btnNext = new wxButton( this, wxID_FORWARD, _("&Next >") ); - m_btnCancel = new wxButton( this, wxID_CANCEL, _("&Cancel") ); + m_btnHelp = new wxButton(this, wxID_HELP, _("&Help")); + m_btnPrev = new wxButton(this, wxID_BACKWARD, _("< &Back")); + m_btnNext = new wxButton(this, wxID_FORWARD, _("&Next >")); + m_btnCancel = new wxButton(this, wxID_CANCEL, _("&Cancel")); - m_btnPrev->Enable( false ); - m_btnNext->Enable( false ); + m_btnPrev->Enable(false); + m_btnNext->Enable(false); - backNextPair->Add( m_btnPrev, 0, wxBOTTOM|wxLEFT|wxTOP, 0 ); - backNextPair->Add( 10, 0, 0, wxEXPAND, 0 ); - backNextPair->Add( m_btnNext, 0, wxBOTTOM|wxRIGHT|wxTOP, 0 ); + backNextPair->Add(m_btnPrev, 0, wxBOTTOM | wxLEFT | wxTOP, 0); + backNextPair->Add(10, 0, 0, wxEXPAND, 0); + backNextPair->Add(m_btnNext, 0, wxBOTTOM | wxRIGHT | wxTOP, 0); - buttonRow->Add( m_btnHelp, 0, wxALL, 5 ); + buttonRow->Add(m_btnHelp, 0, wxALL, 5); m_btnHelp->Hide(); - buttonRow->Add( backNextPair, 0, wxALL, 5 ); - buttonRow->Add( m_btnCancel, 0, wxALL, 5 ); + buttonRow->Add(backNextPair, 0, wxALL, 5); + buttonRow->Add(m_btnCancel, 0, wxALL, 5); - mainColumn->Add( m_sizerBmpAndPage, 1, wxEXPAND ); - mainColumn->Add( 0, 5, 0, wxEXPAND ); - mainColumn->Add( new wxStaticLine( this ), 0, wxEXPAND | wxALL, 5 ); - mainColumn->Add(0, 5, 0, wxEXPAND); - mainColumn->Add( buttonRow, 0, wxALIGN_RIGHT ); + mainColumn->Add(m_sizerBmpAndPage, 1, wxEXPAND); + mainColumn->Add(0, 5, 0, wxEXPAND); + mainColumn->Add(new wxStaticLine(this), 0, wxEXPAND | wxALL, 5); + mainColumn->Add(0, 5, 0, wxEXPAND); + mainColumn->Add(buttonRow, 0, wxALIGN_RIGHT); - windowSizer->Add( mainColumn, 1, wxALL|wxEXPAND, 5 ); + windowSizer->Add(mainColumn, 1, wxALL | wxEXPAND, 5); - this->SetSizer( windowSizer ); + this->SetSizer(windowSizer); this->Layout(); - windowSizer->Fit( this ); - - m_btnHelp->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnHelp), nullptr, - this); - m_btnPrev->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), - nullptr, this); - m_btnNext->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), - nullptr, this); - m_btnCancel->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnCancel), - nullptr, this); - - this->Connect( wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Connect( wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGING, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Connect( wxID_ANY, wxFB_EVT_WIZARD_CANCEL, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Connect( wxID_ANY, wxFB_EVT_WIZARD_FINISHED, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Connect( wxID_ANY, wxFB_EVT_WIZARD_HELP, WizardEventHandler( Wizard::OnWizEvent ) ); + windowSizer->Fit(this); + + m_btnHelp->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnHelp), nullptr, this); + m_btnPrev->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), nullptr, this); + m_btnNext->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), nullptr, this); + m_btnCancel->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnCancel), nullptr, this); + + this->Connect(wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler(Wizard::OnWizEvent)); + this->Connect(wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGING, WizardEventHandler(Wizard::OnWizEvent)); + this->Connect(wxID_ANY, wxFB_EVT_WIZARD_CANCEL, WizardEventHandler(Wizard::OnWizEvent)); + this->Connect(wxID_ANY, wxFB_EVT_WIZARD_FINISHED, WizardEventHandler(Wizard::OnWizEvent)); + this->Connect(wxID_ANY, wxFB_EVT_WIZARD_HELP, WizardEventHandler(Wizard::OnWizEvent)); } Wizard::~Wizard() { - m_btnHelp->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnHelp), - nullptr, this); - m_btnPrev->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), - nullptr, this); - m_btnNext->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), - nullptr, this); - m_btnCancel->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnCancel), - nullptr, this); - - this->Disconnect( wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Disconnect( wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGING, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Disconnect( wxID_ANY, wxFB_EVT_WIZARD_CANCEL, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Disconnect( wxID_ANY, wxFB_EVT_WIZARD_FINISHED, WizardEventHandler( Wizard::OnWizEvent ) ); - this->Disconnect( wxID_ANY, wxFB_EVT_WIZARD_HELP, WizardEventHandler( Wizard::OnWizEvent ) ); - - m_statbmp->SetBitmap( wxNullBitmap ); + m_btnHelp->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnHelp), nullptr, this); + m_btnPrev->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), nullptr, this); + m_btnNext->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnBackOrNext), nullptr, this); + m_btnCancel->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Wizard::OnCancel), nullptr, this); + + this->Disconnect(wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler(Wizard::OnWizEvent)); + this->Disconnect(wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGING, WizardEventHandler(Wizard::OnWizEvent)); + this->Disconnect(wxID_ANY, wxFB_EVT_WIZARD_CANCEL, WizardEventHandler(Wizard::OnWizEvent)); + this->Disconnect(wxID_ANY, wxFB_EVT_WIZARD_FINISHED, WizardEventHandler(Wizard::OnWizEvent)); + this->Disconnect(wxID_ANY, wxFB_EVT_WIZARD_HELP, WizardEventHandler(Wizard::OnWizEvent)); + + m_statbmp->SetBitmap(wxNullBitmap); m_bitmap = wxNullBitmap; - m_page = nullptr; + m_page = nullptr; m_pages.Clear(); } -void Wizard::OnHelp(wxCommandEvent&) { +void Wizard::OnHelp(wxCommandEvent&) +{ // this function probably can never be called when we don't have an active // page, but a small extra check won't hurt - if (m_page != nullptr) { + if (m_page != nullptr) { // Create and send the help event to the specific page handler // event data contains the active page so that context-sensitive // help is possible - WizardEvent eventHelp( wxFB_EVT_WIZARD_HELP, GetId(), true, m_page ); - ( void )m_page->GetEventHandler()->ProcessEvent( eventHelp ); + WizardEvent eventHelp(wxFB_EVT_WIZARD_HELP, GetId(), true, m_page); + (void)m_page->GetEventHandler()->ProcessEvent(eventHelp); } } -void Wizard::SetSelection( size_t pageIndex ) +void Wizard::SetSelection(size_t pageIndex) { - size_t pageCount = m_pages.GetCount(); // Internal page array count - if (pageIndex < pageCount) { // Is it a valid index? - bool hasPrev = pageIndex > 0; // Has this page a previous one, - bool hasNext = pageIndex < pageCount - 1; // or another after it? + size_t pageCount = m_pages.GetCount(); // Internal page array count + if (pageIndex < pageCount) { // Is it a valid index? + bool hasPrev = pageIndex > 0; // Has this page a previous one, + bool hasNext = pageIndex < pageCount - 1; // or another after it? - m_page = m_pages.Item( pageIndex ); // Yes, update current page and + m_page = m_pages.Item(pageIndex); // Yes, update current page and - m_btnPrev->Enable( hasPrev ); // enable 'back' button if a previous page exists, + m_btnPrev->Enable(hasPrev); // enable 'back' button if a previous page exists, wxString label = hasNext ? _("&Next >") : _("&Finish"); - if (label != m_btnNext->GetLabel()) { // set the correct label on next button - m_btnNext->SetLabel(label); - } + if (label != m_btnNext->GetLabel()) { // set the correct label on next button + m_btnNext->SetLabel(label); + } - m_btnNext->SetDefault(); // and as default one, user needs it ready to go on. + m_btnNext->SetDefault(); // and as default one, user needs it ready to go on. } } -void Wizard::OnBackOrNext( wxCommandEvent& event ) +void Wizard::OnBackOrNext(wxCommandEvent& event) { - int pageIndex = m_pages.Index( m_page ); // Get index of previous selected page + int pageIndex = m_pages.Index(m_page); // Get index of previous selected page bool forward = event.GetEventObject() == m_btnNext; - if ( forward ) - { - pageIndex++; // Update current page index depending - } - else // ( event.GetEventObject() == m_btnPrev ) + if (forward) { + pageIndex++; // Update current page index depending + } else // ( event.GetEventObject() == m_btnPrev ) { - pageIndex--; // on which button was pressed. + pageIndex--; // on which button was pressed. } - SetSelection( pageIndex ); + SetSelection(pageIndex); - WizardEvent eventChanged( wxFB_EVT_WIZARD_PAGE_CHANGED, GetId(), forward, m_page ); - m_page->GetEventHandler()->ProcessEvent( eventChanged ); + WizardEvent eventChanged(wxFB_EVT_WIZARD_PAGE_CHANGED, GetId(), forward, m_page); + m_page->GetEventHandler()->ProcessEvent(eventChanged); } -void Wizard::OnCancel(wxCommandEvent&) { - WizardEvent eventCancel( wxFB_EVT_WIZARD_CANCEL, GetId(), false, m_page ); - GetEventHandler()->ProcessEvent( eventCancel ); +void Wizard::OnCancel(wxCommandEvent&) +{ + WizardEvent eventCancel(wxFB_EVT_WIZARD_CANCEL, GetId(), false, m_page); + GetEventHandler()->ProcessEvent(eventCancel); } -void Wizard::OnWizEvent( WizardEvent& event ) +void Wizard::OnWizEvent(WizardEvent& event) { - if ( event.IsAllowed() ) - { + if (event.IsAllowed()) { wxEventType eventType = event.GetEventType(); - if ( eventType == wxFB_EVT_WIZARD_PAGE_CHANGED ) - { - for (size_t i = 0; i < m_pages.GetCount(); ++i) { - m_pages.Item(i)->Hide(); - } + if (eventType == wxFB_EVT_WIZARD_PAGE_CHANGED) { + for (size_t i = 0; i < m_pages.GetCount(); ++i) { m_pages.Item(i)->Hide(); } event.GetPage()->Show(); Layout(); @@ -230,12 +220,12 @@ void Wizard::OnWizEvent( WizardEvent& event ) { wxLogDebug( wxT("Wizard Help button was pressed.") ); } -#if wxABI_VERSION >= 20811 + #if wxABI_VERSION >= 20811 else if ( eventType == wxFB_EVT_WIZARD_FINISHED ) { wxLogDebug( wxT("Wizard Finish button was pressed.") ); } -#endif + #endif else if ( eventType == wxFB_EVT_WIZARD_PAGE_SHOWN ) { wxLogDebug( wxT("Wizard Page shown.") ); @@ -244,42 +234,38 @@ void Wizard::OnWizEvent( WizardEvent& event ) } } -void Wizard::AddPage( WizardPageSimple* page ) +void Wizard::AddPage(WizardPageSimple* page) { - m_page = page; // Update current page, - m_pages.Add( page ); // add it to internal page array, + m_page = page; // Update current page, + m_pages.Add(page); // add it to internal page array, - size_t pageCount = m_pages.GetCount(); // Internal page array count + size_t pageCount = m_pages.GetCount(); // Internal page array count - for (size_t i = 0; i < pageCount; ++i) { - m_pages.Item(i)->Hide(); - } + for (size_t i = 0; i < pageCount; ++i) { m_pages.Item(i)->Hide(); } page->Show(); - m_sizerPage->Add( page, 1, wxEXPAND, 0 ); // insert it into the page sizer, + m_sizerPage->Add(page, 1, wxEXPAND, 0); // insert it into the page sizer, - Layout(); // update layout, + Layout(); // update layout, - if ( pageCount == 1 ) // First page: no previous, no next + if (pageCount == 1) // First page: no previous, no next { - m_btnNext->Enable( true ); // but enable the next page button - m_btnNext->SetLabel(_("&Finish") ); // because it acts as 'finish' - } - else if ( pageCount == 2 ) // Enable previous page button: - { // from now on everything is done in the - m_btnPrev->Enable( true ); // OnBackOrNext() event when user clicks on - } // 'back' or 'next' buttons. + m_btnNext->Enable(true); // but enable the next page button + m_btnNext->SetLabel(_("&Finish")); // because it acts as 'finish' + } else if (pageCount == 2) // Enable previous page button: + { // from now on everything is done in the + m_btnPrev->Enable(true); // OnBackOrNext() event when user clicks on + } // 'back' or 'next' buttons. } -void Wizard::SetBitmap( const wxBitmap& bitmap ) +void Wizard::SetBitmap(const wxBitmap& bitmap) { m_bitmap = bitmap; - if ( m_statbmp ) - { - m_statbmp->SetBitmap( m_bitmap ); + if (m_statbmp) { + m_statbmp->SetBitmap(m_bitmap); wxSize pageSize = m_sizerBmpAndPage->GetSize(); - pageSize.IncTo( wxSize( 0, m_bitmap.GetHeight() ) ); - m_sizerBmpAndPage->SetMinSize( pageSize ); + pageSize.IncTo(wxSize(0, m_bitmap.GetHeight())); + m_sizerBmpAndPage->SetMinSize(pageSize); } } @@ -287,8 +273,7 @@ void Wizard::SetBitmap( const wxBitmap& bitmap ) // WizardEvent // ---------------------------------------------------------------------------- -WizardEvent::WizardEvent( wxEventType type, int id, bool direction, WizardPageSimple *page ) - : wxNotifyEvent( type, id ) +WizardEvent::WizardEvent(wxEventType type, int id, bool direction, WizardPageSimple* page) : wxNotifyEvent(type, id) { // Modified 10-20-2001 Robert Cavanaugh // add the active page to the event data diff --git a/sdk/plugin_interface/forms/wizard.h b/sdk/plugin_interface/forms/wizard.h index 7cd81f69c..97d8145f9 100644 --- a/sdk/plugin_interface/forms/wizard.h +++ b/sdk/plugin_interface/forms/wizard.h @@ -22,6 +22,7 @@ // based on original wizard.h include in wxWidgets source code // /////////////////////////////////////////////////////////////////////////////// + #ifndef SDK_PLUGIN_INTERFACE_FORMS_WIZARD_H #define SDK_PLUGIN_INTERFACE_FORMS_WIZARD_H @@ -31,59 +32,61 @@ #include #include + class Wizard; class WizardPageSimple; class WizardEvent; -WX_DEFINE_ARRAY_PTR( WizardPageSimple*, WizardPages ); +WX_DEFINE_ARRAY_PTR(WizardPageSimple*, WizardPages); + class WizardPageSimple : public wxPanel { public: - WizardPageSimple( Wizard *parent ); + WizardPageSimple(Wizard* parent); ~WizardPageSimple(); }; class Wizard : public wxPanel { public: - Wizard( wxWindow *parent, wxWindowID id = wxID_ANY, - const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, - long style = wxTAB_TRAVERSAL ); + Wizard( + wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL); ~Wizard(); - wxBoxSizer* GetPageSizer() { return m_sizerPage; } -// WizardPageSimple *GetCurrentPage() { return m_page; } + wxBoxSizer* GetPageSizer() { return m_sizerPage; } + // WizardPageSimple *GetCurrentPage() { return m_page; } // set/get bitmap -// const wxBitmap& GetBitmap() const { return m_bitmap; } - void SetBitmap( const wxBitmap& bitmap ); + // const wxBitmap& GetBitmap() const { return m_bitmap; } + void SetBitmap(const wxBitmap& bitmap); - void AddPage( WizardPageSimple* page ); - WizardPageSimple *GetPage( size_t index ) { return m_pages.Item( index ); } + void AddPage(WizardPageSimple* page); + WizardPageSimple* GetPage(size_t index) { return m_pages.Item(index); } size_t GetPageCount() { return m_pages.GetCount(); } - size_t GetPageIndex( WizardPageSimple *wizpage ) { return m_pages.Index( wizpage ); } - void SetSelection( size_t pageIndex ); - void ShowHelpButton( bool showhelp ) { m_btnHelp->Show( showhelp ); } + size_t GetPageIndex(WizardPageSimple* wizpage) { return m_pages.Index(wizpage); } + void SetSelection(size_t pageIndex); + void ShowHelpButton(bool showhelp) { m_btnHelp->Show(showhelp); } private: - void OnBackOrNext( wxCommandEvent& event ); - void OnHelp( wxCommandEvent& event ); - void OnCancel( wxCommandEvent& event ); - void OnWizEvent( WizardEvent& event ); - - wxBoxSizer *m_sizerBmpAndPage; // Page area sizer will be inserted here with padding - wxBoxSizer *m_sizerPage; // Actual position and size of pages - wxStaticBitmap *m_statbmp; // the control for the bitmap - wxButton *m_btnHelp; - wxButton *m_btnPrev; // the "" or "Finish" button - wxButton *m_btnCancel; - WizardPageSimple *m_page; - wxBitmap m_bitmap; // the default bitmap to show - WizardPages m_pages; - -// DECLARE_EVENT_TABLE() + void OnBackOrNext(wxCommandEvent& event); + void OnHelp(wxCommandEvent& event); + void OnCancel(wxCommandEvent& event); + void OnWizEvent(WizardEvent& event); + + wxBoxSizer* m_sizerBmpAndPage; // Page area sizer will be inserted here with padding + wxBoxSizer* m_sizerPage; // Actual position and size of pages + wxStaticBitmap* m_statbmp; // the control for the bitmap + wxButton* m_btnHelp; + wxButton* m_btnPrev; // the "" or "Finish" button + wxButton* m_btnCancel; + WizardPageSimple* m_page; + wxBitmap m_bitmap; // the default bitmap to show + WizardPages m_pages; + + // DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- @@ -95,8 +98,8 @@ class Wizard : public wxPanel class WizardEvent : public wxNotifyEvent { public: - explicit WizardEvent(wxEventType type = wxEVT_NULL, int id = wxID_ANY, bool direction = true, - WizardPageSimple* page = nullptr); + explicit WizardEvent( + wxEventType type = wxEVT_NULL, int id = wxID_ANY, bool direction = true, WizardPageSimple* page = nullptr); // for EVT_WXFB_WIZARD_PAGE_CHANGING, return true if we're going forward or // false otherwise and for EVT_WXFB_WIZARD_PAGE_CHANGED return true if we came @@ -104,15 +107,13 @@ class WizardEvent : public wxNotifyEvent // (this function doesn't make sense for CANCEL events) bool GetDirection() const { return m_direction; } - WizardPageSimple *GetPage() const { return m_page; } + WizardPageSimple* GetPage() const { return m_page; } - wxEvent* Clone() const override { - return new WizardEvent(*this); - } + wxEvent* Clone() const override { return new WizardEvent(*this); } private: - bool m_direction; - WizardPageSimple *m_page; + bool m_direction; + WizardPageSimple* m_page; }; // ---------------------------------------------------------------------------- @@ -133,27 +134,26 @@ using WizardEventFunction = void (wxEvtHandler::*)(WizardEvent&); #define WizardEventHandler(func) wxEVENT_HANDLER_CAST(WizardEventFunction, func) -#define wxFB__DECLARE_WIZARDEVT( evt, id, fn ) \ - wx__DECLARE_EVT1( wxFB_EVT_WIZARD_ ## evt, id, WizardEventHandler( fn ) ) +#define wxFB__DECLARE_WIZARDEVT(evt, id, fn) wx__DECLARE_EVT1(wxFB_EVT_WIZARD_##evt, id, WizardEventHandler(fn)) // notifies that the page has just been changed (can't be vetoed) -#define EVT_WXFB_WIZARD_PAGE_CHANGED( id, fn ) wxFB__DECLARE_WIZARDEVT( PAGE_CHANGED, id, fn ) +#define EVT_WXFB_WIZARD_PAGE_CHANGED(id, fn) wxFB__DECLARE_WIZARDEVT(PAGE_CHANGED, id, fn) // the user pressed "" button and the page is going to be // changed - unless the event handler vetoes the event -#define EVT_WXFB_WIZARD_PAGE_CHANGING( id, fn ) wxFB__DECLARE_WIZARDEVT( PAGE_CHANGING, id, fn ) +#define EVT_WXFB_WIZARD_PAGE_CHANGING(id, fn) wxFB__DECLARE_WIZARDEVT(PAGE_CHANGING, id, fn) // the user pressed "Cancel" button and the wizard is going to be dismissed - // unless the event handler vetoes the event #define EVT_WXFB_WIZARD_CANCEL(id, fn) wxFB__DECLARE_WIZARDEVT(CANCEL, id, fn) // the user pressed "Finish" button and the wizard is going to be dismissed - -#define EVT_WXFB_WIZARD_FINISHED( id, fn ) wxFB__DECLARE_WIZARDEVT( FINISHED, id, fn ) +#define EVT_WXFB_WIZARD_FINISHED(id, fn) wxFB__DECLARE_WIZARDEVT(FINISHED, id, fn) // the user pressed "Help" button -#define EVT_WXFB_WIZARD_HELP(id, fn) wxFB__DECLARE_WIZARDEVT( HELP, id, fn ) +#define EVT_WXFB_WIZARD_HELP(id, fn) wxFB__DECLARE_WIZARDEVT(HELP, id, fn) // the page was just shown and laid out -#define EVT_WXFB_WIZARD_PAGE_SHOWN( id, fn ) wxFB__DECLARE_WIZARDEVT( PAGE_SHOWN, id, fn ) +#define EVT_WXFB_WIZARD_PAGE_SHOWN(id, fn) wxFB__DECLARE_WIZARDEVT(PAGE_SHOWN, id, fn) -#endif // SDK_PLUGIN_INTERFACE_FORMS_WIZARD_H +#endif // SDK_PLUGIN_INTERFACE_FORMS_WIZARD_H diff --git a/sdk/plugin_interface/plugin.h b/sdk/plugin_interface/plugin.h index 568bcbbae..221425412 100644 --- a/sdk/plugin_interface/plugin.h +++ b/sdk/plugin_interface/plugin.h @@ -22,13 +22,15 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef SDK_PLUGIN_INTERFACE_PLUGIN_H #define SDK_PLUGIN_INTERFACE_PLUGIN_H +#include +#include + #include "component.h" -#include -#include // Library implementation. This module must be implemented inside the library, // instead of linking it as an object for doing the plugin. @@ -37,141 +39,130 @@ class ComponentLibrary : public IComponentLibrary { - private: - typedef struct - { - wxString name; - IComponent *component; - }AComponent; - - typedef struct - { - wxString name; - int value; - } AMacro; - - typedef struct - { - wxString name, syn; - } ASynonymous; - - std::vector m_components; - std::vector m_macros; - typedef std::map SynMap; - SynMap m_synMap; - - public: - ~ComponentLibrary() override - { - std::vector< AComponent >::reverse_iterator component; - for ( component = m_components.rbegin(); component != m_components.rend(); ++component ) - { - delete component->component; - } - } - - void RegisterComponent(const wxString& text, IComponent* c) override - { - AComponent comp; - comp.component = c; - comp.name = text; - - m_components.push_back(comp); - } - - void RegisterMacro(const wxString& text, const int value) override - { - AMacro macro; - macro.name = text; - macro.value = value; - - m_macros.push_back(macro); - } - - void RegisterMacroSynonymous(const wxString& syn, const wxString& name) override - { - /*ASynonymous asyn; - asyn.name = name; - asyn.syn = syn; - - m_synonymous.push_back(asyn);*/ - m_synMap.insert(SynMap::value_type(syn, name)); - } - - IComponent* GetComponent(unsigned int idx) override - { - if (idx < m_components.size()) - return m_components[idx].component; - return NULL; - } - - wxString GetComponentName(unsigned int idx) override - { - if (idx < m_components.size()) - return m_components[idx].name; - - return wxString(); - } - - wxString GetMacroName(unsigned int idx) override - { - if (idx < m_macros.size()) - return m_macros[idx].name; - - return wxString(); - } - - int GetMacroValue(unsigned int idx) override - { - if (idx < m_macros.size()) - return m_macros[idx].value; - - return 0; - } - - /*wxString GetMacroSynonymous(unsigned int idx) override - { - if (idx < m_synonymous.size()) - return m_synonymous[idx].syn; - - return wxString(); - } - - wxString GetSynonymousName(unsigned int idx) override - { - if (idx < m_synonymous.size()) - return m_synonymous[idx].name; - - return wxString(); - }*/ - - bool FindSynonymous(const wxString& syn, wxString& trans) override - { - bool found = false; - SynMap::iterator it = m_synMap.find(syn); - if (it != m_synMap.end()) +private: + typedef struct { + wxString name; + IComponent* component; + } AComponent; + + typedef struct { + wxString name; + int value; + } AMacro; + + typedef struct { + wxString name, syn; + } ASynonymous; + + std::vector m_components; + std::vector m_macros; + typedef std::map SynMap; + SynMap m_synMap; + +public: + ~ComponentLibrary() override + { + std::vector::reverse_iterator component; + for (component = m_components.rbegin(); component != m_components.rend(); ++component) { + delete component->component; + } + } + + void RegisterComponent(const wxString& text, IComponent* c) override + { + AComponent comp; + comp.component = c; + comp.name = text; + + m_components.push_back(comp); + } + + void RegisterMacro(const wxString& text, const int value) override + { + AMacro macro; + macro.name = text; + macro.value = value; + + m_macros.push_back(macro); + } + + void RegisterMacroSynonymous(const wxString& syn, const wxString& name) override + { + /*ASynonymous asyn; + asyn.name = name; + asyn.syn = syn; + + m_synonymous.push_back(asyn);*/ + m_synMap.insert(SynMap::value_type(syn, name)); + } + + IComponent* GetComponent(unsigned int idx) override { - found = true; - trans = it->second; + if (idx < m_components.size()) + return m_components[idx].component; + return NULL; } - return found; - } + wxString GetComponentName(unsigned int idx) override + { + if (idx < m_components.size()) + return m_components[idx].name; + + return wxString(); + } + + wxString GetMacroName(unsigned int idx) override + { + if (idx < m_macros.size()) + return m_macros[idx].name; + + return wxString(); + } - unsigned int GetMacroCount() override - { - return (unsigned int)m_macros.size(); - } + int GetMacroValue(unsigned int idx) override + { + if (idx < m_macros.size()) + return m_macros[idx].value; + + return 0; + } - unsigned int GetComponentCount() override - { - return (unsigned int)m_components.size(); - } + /*wxString GetMacroSynonymous(unsigned int idx) override + { + if (idx < m_synonymous.size()) + return m_synonymous[idx].syn; - /*unsigned int GetSynonymousCount() override - { - return m_synonymous.size(); - }*/ + return wxString(); + } + + wxString GetSynonymousName(unsigned int idx) override + { + if (idx < m_synonymous.size()) + return m_synonymous[idx].name; + + return wxString(); + }*/ + + bool FindSynonymous(const wxString& syn, wxString& trans) override + { + bool found = false; + SynMap::iterator it = m_synMap.find(syn); + if (it != m_synMap.end()) { + found = true; + trans = it->second; + } + + return found; + } + + unsigned int GetMacroCount() override { return (unsigned int)m_macros.size(); } + + unsigned int GetComponentCount() override { return (unsigned int)m_components.size(); } + + /*unsigned int GetSynonymousCount() override + { + return m_synonymous.size(); + }*/ }; /** @@ -180,65 +171,34 @@ class ComponentLibrary : public IComponentLibrary class ComponentBase : public IComponent { private: - int m_type; - IManager* m_manager; + int m_type; + IManager* m_manager; public: - ComponentBase() - : - m_type( 0 ), - m_manager( NULL ) - {} - - void __SetComponentType( int type ) - { - m_type = ( type >= 0 && type <= 2 ? type : COMPONENT_TYPE_ABSTRACT ); - } - - void __SetManager( IManager* manager ) - { - m_manager = manager; - } + ComponentBase() : m_type(0), m_manager(NULL) {} - IManager* GetManager() - { - return m_manager; - } + void __SetComponentType(int type) { m_type = (type >= 0 && type <= 2 ? type : COMPONENT_TYPE_ABSTRACT); } - wxObject* Create(IObject* /*obj*/, wxObject* /*parent*/) override - { - return m_manager->NewNoObject(); /* Even components which are not visible must be unique in the map */ - } + void __SetManager(IManager* manager) { m_manager = manager; } - void Cleanup(wxObject* /*obj*/) override - { + IManager* GetManager() { return m_manager; } - } - - void OnCreated(wxObject* /*wxobject*/, wxWindow* /*wxparent*/) override - { + wxObject* Create(IObject* /*obj*/, wxObject* /*parent*/) override + { + return m_manager->NewNoObject(); /* Even components which are not visible must be unique in the map */ + } - } + void Cleanup(wxObject* /*obj*/) override {} - void OnSelected(wxObject* /*wxobject*/) override - { + void OnCreated(wxObject* /*wxobject*/, wxWindow* /*wxparent*/) override {} - } + void OnSelected(wxObject* /*wxobject*/) override {} - ticpp::Element* ExportToXrc(IObject* /*obj*/) override - { - return NULL; - } + ticpp::Element* ExportToXrc(IObject* /*obj*/) override { return NULL; } - ticpp::Element* ImportFromXrc(ticpp::Element* /*xrcObj*/) override - { - return NULL; - } + ticpp::Element* ImportFromXrc(ticpp::Element* /*xrcObj*/) override { return NULL; } - int GetComponentType() override - { - return m_type; - } + int GetComponentType() override { return m_type; } }; -#endif // SDK_PLUGIN_INTERFACE_PLUGIN_H +#endif // SDK_PLUGIN_INTERFACE_PLUGIN_H diff --git a/sdk/plugin_interface/xrcconv.cpp b/sdk/plugin_interface/xrcconv.cpp index adbbb7109..8763eaad6 100644 --- a/sdk/plugin_interface/xrcconv.cpp +++ b/sdk/plugin_interface/xrcconv.cpp @@ -24,998 +24,897 @@ /////////////////////////////////////////////////////////////////////////////// #include "xrcconv.h" -#include #include #include +#include -static wxString StringToXrcText( const wxString &str ) -{ - wxString result; - for ( unsigned int i = 0 ; i < str.Length() ; i++ ) - { - wxChar c = str[i]; +static wxString StringToXrcText(const wxString& str) +{ + wxString result; + + for (unsigned int i = 0; i < str.Length(); i++) { + wxChar c = str[i]; - switch ( c ) - { - case wxChar( '\n' ): result = result + wxT( "\\n" ); - break; + switch (c) { + case wxChar('\n'): + result = result + wxT("\\n"); + break; - case wxChar( '\t' ): result = result + wxT( "\\t" ); - break; + case wxChar('\t'): + result = result + wxT("\\t"); + break; - case wxChar( '\r' ): result = result + wxT( "\\r" ); - break; + case wxChar('\r'): + result = result + wxT("\\r"); + break; - case wxChar( '\\' ): result = result + wxT( "\\\\" ); - break; + case wxChar('\\'): + result = result + wxT("\\\\"); + break; - case wxChar( '_' ): result = result + wxT( "__" ); - break; + case wxChar('_'): + result = result + wxT("__"); + break; - case wxChar( '&' ): result = result + wxT( "_" ); - break; + case wxChar('&'): + result = result + wxT("_"); + break; - default: - result = result + c; - break; - } - } - return result; + default: + result = result + c; + break; + } + } + return result; } -static wxString XrcTextToString( const wxString &str ) +static wxString XrcTextToString(const wxString& str) { - wxString result; + wxString result; - for ( unsigned int i = 0 ; i < str.Length() ; i++ ) - { - wxChar c = str[i]; - if ( c == wxChar( '\\' ) && i < str.length() - 1 ) - { - wxChar next = str[i+1]; + for (unsigned int i = 0; i < str.Length(); i++) { + wxChar c = str[i]; + if (c == wxChar('\\') && i < str.length() - 1) { + wxChar next = str[i + 1]; - switch ( next ) - { - case wxChar( 'n' ): result = result + wxChar( '\n' ); i++; - break; + switch (next) { + case wxChar('n'): + result = result + wxChar('\n'); + i++; + break; - case wxChar( 't' ): result = result + wxChar( '\t' ); i++; - break; + case wxChar('t'): + result = result + wxChar('\t'); + i++; + break; - case wxChar( 'r' ): result = result + wxChar( '\r' ); i++; - break; + case wxChar('r'): + result = result + wxChar('\r'); + i++; + break; - case wxChar( '\\' ): result = result + wxChar( '\\' ); i++; - break; - } - } - else if ( c == wxChar( '_' ) ) - { - if ( i < str.Length() - 1 && str[i+1] == wxChar( '_' ) ) - { - result = result + wxChar( '_' ); - i++; - } - else - result = result + wxChar( '&' ); - } - else - result = result + c; - } + case wxChar('\\'): + result = result + wxChar('\\'); + i++; + break; + } + } else if (c == wxChar('_')) { + if (i < str.Length() - 1 && str[i + 1] == wxChar('_')) { + result = result + wxChar('_'); + i++; + } else + result = result + wxChar('&'); + } else + result = result + c; + } - return result; + return result; } -static wxString ReplaceSynonymous( const wxString &bitlist ) +static wxString ReplaceSynonymous(const wxString& bitlist) { - IComponentLibrary* lib = GetComponentLibrary( NULL ); - wxString result, translation; - wxStringTokenizer tkz( bitlist, wxT( "|" ) ); - while ( tkz.HasMoreTokens() ) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim( true ); - token.Trim( false ); + IComponentLibrary* lib = GetComponentLibrary(NULL); + wxString result, translation; + wxStringTokenizer tkz(bitlist, wxT("|")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); - if ( result != wxT( "" ) ) - result = result + wxChar( '|' ); + if (result != wxT("")) + result = result + wxChar('|'); - if ( lib->FindSynonymous( token, translation ) ) - result += translation; - else - result += token; + if (lib->FindSynonymous(token, translation)) + result += translation; + else + result += token; + } + delete lib; - } - delete lib; - - return result; + return result; } -ObjectToXrcFilter::ObjectToXrcFilter( IObject *obj, - const wxString &classname, - const wxString &objname, - const wxString &base ) +ObjectToXrcFilter::ObjectToXrcFilter( + IObject* obj, const wxString& classname, const wxString& objname, const wxString& base) { - m_obj = obj; - m_xrcObj = new ticpp::Element( "object" ); + m_obj = obj; + m_xrcObj = new ticpp::Element("object"); - m_xrcObj->SetAttribute( "class", classname.mb_str( wxConvUTF8 ) ); + m_xrcObj->SetAttribute("class", classname.mb_str(wxConvUTF8)); - if ( objname != wxT( "" ) ) - m_xrcObj->SetAttribute( "name", objname.mb_str( wxConvUTF8 ) ); + if (objname != wxT("")) + m_xrcObj->SetAttribute("name", objname.mb_str(wxConvUTF8)); - if ( base != wxT( "" ) ) - m_xrcObj->SetAttribute( "base", base.mb_str( wxConvUTF8 ) ); + if (base != wxT("")) + m_xrcObj->SetAttribute("base", base.mb_str(wxConvUTF8)); } ObjectToXrcFilter::~ObjectToXrcFilter() { - delete m_xrcObj; -} - -void ObjectToXrcFilter::AddProperty( const wxString &objPropName, - const wxString &xrcPropName, - const int &propType ) -{ - std::string name( xrcPropName.mb_str( wxConvUTF8 ) ); - ticpp::Element propElement( name ); - - switch ( propType ) - { - case XRC_TYPE_SIZE: - case XRC_TYPE_POINT: - case XRC_TYPE_BITLIST: - LinkText( m_obj->GetPropertyAsString( objPropName ), &propElement ); - break; - - case XRC_TYPE_TEXT: - // The text must be converted to XRC format - { - wxString text = m_obj->GetPropertyAsString( objPropName ); - LinkText( text, &propElement, true ); - } - break; - - case XRC_TYPE_BOOL: - case XRC_TYPE_INTEGER: - LinkInteger( m_obj->GetPropertyAsInteger( objPropName ), &propElement ); - break; - - case XRC_TYPE_FLOAT: - LinkFloat( m_obj->GetPropertyAsFloat( objPropName ), &propElement ); - break; - - case XRC_TYPE_COLOUR: - LinkColour( m_obj->GetPropertyAsColour( objPropName ), &propElement ); - break; - - case XRC_TYPE_FONT: - LinkFont( m_obj->GetPropertyAsFont( objPropName ), &propElement ); - break; - - case XRC_TYPE_STRINGLIST: - LinkStringList( m_obj->GetPropertyAsArrayString( objPropName ), &propElement ); - break; - - case XRC_TYPE_BITMAP: - { - wxString bitmapProp = m_obj->GetPropertyAsString( objPropName ); - if ( bitmapProp.empty() ) - { - break; - } - - wxString filename = bitmapProp.AfterFirst( wxT(';') ); - if ( filename.empty() ) - { - break; - } - - if ( bitmapProp.size() < ( filename.size() + 2 ) ) - { - break; - } - - if (bitmapProp.StartsWith(_("Load From File")) || bitmapProp.StartsWith(_("Load From Embedded File")) || bitmapProp.StartsWith(_("Load From XRC"))) - { - LinkText( filename.Trim().Trim(false), &propElement ); - } - else if( bitmapProp.StartsWith( _("Load From Art Provider") ) ) - { - propElement.SetAttribute( "stock_id", filename.BeforeFirst( wxT(';') ).Trim().Trim(false).mb_str( wxConvUTF8 ) ); - propElement.SetAttribute( "stock_client", filename.AfterFirst( wxT(';') ).Trim().Trim(false).mb_str( wxConvUTF8 ) ); - - LinkText( wxT("undefined.png"), &propElement ); - } - } - break; - } - - m_xrcObj->LinkEndChild( &propElement ); -} - -void ObjectToXrcFilter::AddPropertyValue ( const wxString &xrcPropName, - const wxString &xrcPropValue, - bool xrcFormat ) -{ - ticpp::Element propElement( xrcPropName.mb_str( wxConvUTF8 ) ); - LinkText( xrcPropValue, &propElement, xrcFormat ); - m_xrcObj->LinkEndChild( &propElement ); -} - -void ObjectToXrcFilter::AddPropertyPair ( const wxString& objPropName1, const wxString& objPropName2, const wxString& xrcPropName ) -{ - AddPropertyValue( xrcPropName, - wxString::Format( _( "%d,%d" ), - m_obj->GetPropertyAsInteger( objPropName1 ), - m_obj->GetPropertyAsInteger( objPropName2 ) - ) - ); + delete m_xrcObj; +} + +void ObjectToXrcFilter::AddProperty(const wxString& objPropName, const wxString& xrcPropName, const int& propType) +{ + std::string name(xrcPropName.mb_str(wxConvUTF8)); + ticpp::Element propElement(name); + + switch (propType) { + case XRC_TYPE_SIZE: + case XRC_TYPE_POINT: + case XRC_TYPE_BITLIST: + LinkText(m_obj->GetPropertyAsString(objPropName), &propElement); + break; + + case XRC_TYPE_TEXT: + // The text must be converted to XRC format + { + wxString text = m_obj->GetPropertyAsString(objPropName); + LinkText(text, &propElement, true); + } + break; + + case XRC_TYPE_BOOL: + case XRC_TYPE_INTEGER: + LinkInteger(m_obj->GetPropertyAsInteger(objPropName), &propElement); + break; + + case XRC_TYPE_FLOAT: + LinkFloat(m_obj->GetPropertyAsFloat(objPropName), &propElement); + break; + + case XRC_TYPE_COLOUR: + LinkColour(m_obj->GetPropertyAsColour(objPropName), &propElement); + break; + + case XRC_TYPE_FONT: + LinkFont(m_obj->GetPropertyAsFont(objPropName), &propElement); + break; + + case XRC_TYPE_STRINGLIST: + LinkStringList(m_obj->GetPropertyAsArrayString(objPropName), &propElement); + break; + + case XRC_TYPE_BITMAP: { + wxString bitmapProp = m_obj->GetPropertyAsString(objPropName); + if (bitmapProp.empty()) { + break; + } + + wxString filename = bitmapProp.AfterFirst(wxT(';')); + if (filename.empty()) { + break; + } + + if (bitmapProp.size() < (filename.size() + 2)) { + break; + } + + if ( + bitmapProp.StartsWith(_("Load From File")) || bitmapProp.StartsWith(_("Load From Embedded File")) || + bitmapProp.StartsWith(_("Load From XRC"))) { + LinkText(filename.Trim().Trim(false), &propElement); + } else if (bitmapProp.StartsWith(_("Load From Art Provider"))) { + propElement.SetAttribute( + "stock_id", filename.BeforeFirst(wxT(';')).Trim().Trim(false).mb_str(wxConvUTF8)); + propElement.SetAttribute( + "stock_client", filename.AfterFirst(wxT(';')).Trim().Trim(false).mb_str(wxConvUTF8)); + + LinkText(wxT("undefined.png"), &propElement); + } + } break; + } + + m_xrcObj->LinkEndChild(&propElement); +} + +void ObjectToXrcFilter::AddPropertyValue(const wxString& xrcPropName, const wxString& xrcPropValue, bool xrcFormat) +{ + ticpp::Element propElement(xrcPropName.mb_str(wxConvUTF8)); + LinkText(xrcPropValue, &propElement, xrcFormat); + m_xrcObj->LinkEndChild(&propElement); +} + +void ObjectToXrcFilter::AddPropertyPair( + const wxString& objPropName1, const wxString& objPropName2, const wxString& xrcPropName) +{ + AddPropertyValue( + xrcPropName, wxString::Format( + _("%d,%d"), m_obj->GetPropertyAsInteger(objPropName1), m_obj->GetPropertyAsInteger(objPropName2))); } ticpp::Element* ObjectToXrcFilter::GetXrcObject() { - return new ticpp::Element( *m_xrcObj ); -} - -void ObjectToXrcFilter::LinkText( const wxString &text, ticpp::Element *propElement, bool xrcFormat ) -{ - wxString value = ( xrcFormat ? StringToXrcText( text ) : text ); - propElement->SetText( value.mb_str( wxConvUTF8 ) ); -} - -void ObjectToXrcFilter::LinkInteger( const int &integer, ticpp::Element *propElement ) -{ - propElement->SetText( integer ); -} - -void ObjectToXrcFilter::LinkFloat( const double& value, ticpp::Element* propElement ) -{ - propElement->SetText( value ); -} - -void ObjectToXrcFilter::LinkColour( const wxColour &colour, ticpp::Element *propElement ) -{ - wxString value = wxString::Format( wxT( "#%02x%02x%02x" ), colour.Red(), colour.Green(), colour.Blue() ); - propElement->SetText( value.mb_str( wxConvUTF8 ) ); -} - -void ObjectToXrcFilter::LinkFont( const wxFontContainer &font, ticpp::Element *propElement ) -{ - if ( font.GetPointSize() > 0 ) - { - wxString aux; - aux.Printf( wxT( "%d" ), font.GetPointSize() ); - - ticpp::Element size( "size" ); - size.SetText( aux.mb_str( wxConvUTF8 ) ); - propElement->LinkEndChild( &size ); - } - - bool skipFamily = false; - ticpp::Element family( "family" ); - switch ( font.GetFamily() ) - { - case wxFONTFAMILY_DECORATIVE: - family.SetText( "decorative" ); - break; - case wxFONTFAMILY_ROMAN: - family.SetText( "roman" ); - break; - case wxFONTFAMILY_SWISS: - family.SetText( "swiss" ); - break; - case wxFONTFAMILY_SCRIPT: - family.SetText( "script" ); - break; - case wxFONTFAMILY_MODERN: - family.SetText( "modern" ); - break; - case wxFONTFAMILY_TELETYPE: - family.SetText( "teletype" ); - break; - default: - // wxWidgets 2.9.0 doesn't define "default" family - skipFamily = true; - break; - } - if( ! skipFamily ) propElement->LinkEndChild( &family ); - - ticpp::Element style( "style" ); - switch ( font.GetStyle() ) - { - case wxFONTSTYLE_SLANT: - style.SetText( "slant" ); - break; - case wxFONTSTYLE_ITALIC: - style.SetText( "italic" ); - break; - default: - style.SetText( "normal" ); - break; - } - propElement->LinkEndChild( &style ); - - ticpp::Element weight( "weight" ); - switch ( font.GetWeight() ) - { - case wxFONTWEIGHT_LIGHT: - weight.SetText( "light" ); - break; - case wxFONTWEIGHT_BOLD: - weight.SetText( "bold" ); - break; - default: - weight.SetText( "normal" ); - break; - } - propElement->LinkEndChild( &weight ); - - ticpp::Element underlined( "underlined" ); - underlined.SetText( font.GetUnderlined() ? "1" : "0" ); - propElement->LinkEndChild( &underlined ); - - if ( !font.GetFaceName().empty() ) - { - ticpp::Element face( "face" ); - face.SetText( font.GetFaceName().mb_str( wxConvUTF8 ) ); - propElement->LinkEndChild( &face ); - } -} - -void ObjectToXrcFilter::LinkStringList( const wxArrayString &array, ticpp::Element *propElement, bool xrcFormat ) -{ - for ( size_t i = 0; i < array.GetCount(); i++ ) - { - wxString value = ( xrcFormat ? StringToXrcText( array[i] ) : array[i] ); - ticpp::Element item( "item" ); - item.SetText( value.mb_str( wxConvUTF8 ) ); - propElement->LinkEndChild( &item ); - } + return new ticpp::Element(*m_xrcObj); +} + +void ObjectToXrcFilter::LinkText(const wxString& text, ticpp::Element* propElement, bool xrcFormat) +{ + wxString value = (xrcFormat ? StringToXrcText(text) : text); + propElement->SetText(value.mb_str(wxConvUTF8)); +} + +void ObjectToXrcFilter::LinkInteger(const int& integer, ticpp::Element* propElement) +{ + propElement->SetText(integer); +} + +void ObjectToXrcFilter::LinkFloat(const double& value, ticpp::Element* propElement) +{ + propElement->SetText(value); +} + +void ObjectToXrcFilter::LinkColour(const wxColour& colour, ticpp::Element* propElement) +{ + wxString value = wxString::Format(wxT("#%02x%02x%02x"), colour.Red(), colour.Green(), colour.Blue()); + propElement->SetText(value.mb_str(wxConvUTF8)); +} + +void ObjectToXrcFilter::LinkFont(const wxFontContainer& font, ticpp::Element* propElement) +{ + if (font.GetPointSize() > 0) { + wxString aux; + aux.Printf(wxT("%d"), font.GetPointSize()); + + ticpp::Element size("size"); + size.SetText(aux.mb_str(wxConvUTF8)); + propElement->LinkEndChild(&size); + } + + bool skipFamily = false; + ticpp::Element family("family"); + switch (font.GetFamily()) { + case wxFONTFAMILY_DECORATIVE: + family.SetText("decorative"); + break; + case wxFONTFAMILY_ROMAN: + family.SetText("roman"); + break; + case wxFONTFAMILY_SWISS: + family.SetText("swiss"); + break; + case wxFONTFAMILY_SCRIPT: + family.SetText("script"); + break; + case wxFONTFAMILY_MODERN: + family.SetText("modern"); + break; + case wxFONTFAMILY_TELETYPE: + family.SetText("teletype"); + break; + default: + // wxWidgets 2.9.0 doesn't define "default" family + skipFamily = true; + break; + } + if (!skipFamily) + propElement->LinkEndChild(&family); + + ticpp::Element style("style"); + switch (font.GetStyle()) { + case wxFONTSTYLE_SLANT: + style.SetText("slant"); + break; + case wxFONTSTYLE_ITALIC: + style.SetText("italic"); + break; + default: + style.SetText("normal"); + break; + } + propElement->LinkEndChild(&style); + + ticpp::Element weight("weight"); + switch (font.GetWeight()) { + case wxFONTWEIGHT_LIGHT: + weight.SetText("light"); + break; + case wxFONTWEIGHT_BOLD: + weight.SetText("bold"); + break; + default: + weight.SetText("normal"); + break; + } + propElement->LinkEndChild(&weight); + + ticpp::Element underlined("underlined"); + underlined.SetText(font.GetUnderlined() ? "1" : "0"); + propElement->LinkEndChild(&underlined); + + if (!font.GetFaceName().empty()) { + ticpp::Element face("face"); + face.SetText(font.GetFaceName().mb_str(wxConvUTF8)); + propElement->LinkEndChild(&face); + } +} + +void ObjectToXrcFilter::LinkStringList(const wxArrayString& array, ticpp::Element* propElement, bool xrcFormat) +{ + for (size_t i = 0; i < array.GetCount(); i++) { + wxString value = (xrcFormat ? StringToXrcText(array[i]) : array[i]); + ticpp::Element item("item"); + item.SetText(value.mb_str(wxConvUTF8)); + propElement->LinkEndChild(&item); + } } void ObjectToXrcFilter::AddWindowProperties() { - wxString style; - if ( !m_obj->IsNull( _( "style" ) ) ) - style = m_obj->GetPropertyAsString( _T( "style" ) ); - if ( !m_obj->IsNull( _( "window_style" ) ) ){ - if ( !style.IsEmpty() ) style += _T( '|' ); - style += m_obj->GetPropertyAsString( _T( "window_style" ) ); - } - if ( !style.IsEmpty() ) AddPropertyValue( _T( "style" ), style ); - - wxString extraStyle; - if ( !m_obj->IsNull( _( "extra_style" ) ) ) - extraStyle = m_obj->GetPropertyAsString( _T( "extra_style" ) ); - if ( !m_obj->IsNull( _( "window_extra_style" ) ) ){ - if ( !extraStyle.IsEmpty() ) extraStyle += _T( '|' ); - extraStyle += m_obj->GetPropertyAsString( _T( "window_extra_style" ) ); - } - if ( !extraStyle.IsEmpty() ) AddPropertyValue( _T( "exstyle" ), extraStyle ); - - if ( !m_obj->IsNull( _( "pos" ) ) ) - AddProperty( _( "pos" ), _( "pos" ), XRC_TYPE_SIZE ); - - if ( !m_obj->IsNull( _( "size" ) ) ) - AddProperty( _( "size" ), _( "size" ), XRC_TYPE_SIZE ); - - if ( !m_obj->IsNull( _( "bg" ) ) ) - AddProperty( _( "bg" ), _( "bg" ), XRC_TYPE_COLOUR ); - - if ( !m_obj->IsNull( _( "fg" ) ) ) - AddProperty( _( "fg" ), _( "fg" ), XRC_TYPE_COLOUR ); - - if (!m_obj->IsNull(_("enabled")) && m_obj->GetPropertyAsInteger(_("enabled")) == 0) { - AddProperty(_("enabled"), _("enabled"), XRC_TYPE_BOOL); - } - if ( !m_obj->IsNull( _( "focused" ) ) ) - AddPropertyValue( _( "focused" ), _( "0" ) ); - - if (!m_obj->IsNull(_("hidden")) && m_obj->GetPropertyAsInteger(_("hidden")) != 0) { - AddProperty(_("hidden"), _("hidden"), XRC_TYPE_BOOL); - } - if ( !m_obj->IsNull( _( "font" ) ) ) - AddProperty( _( "font" ), _( "font" ), XRC_TYPE_FONT ); - - if ( !m_obj->IsNull( _( "tooltip" ) ) ) - AddProperty( _( "tooltip" ), wxT( "tooltip" ), XRC_TYPE_TEXT ); - - if ( !m_obj->IsNull( _( "subclass" ) ) ) - { - wxString subclass = m_obj->GetChildFromParentProperty( _( "subclass" ), wxT( "name" ) ); - if ( !subclass.empty() ) - { - m_xrcObj->SetAttribute( "subclass", subclass.mb_str( wxConvUTF8 ) ); - } - } + wxString style; + if (!m_obj->IsNull(_("style"))) + style = m_obj->GetPropertyAsString(_T( "style" )); + if (!m_obj->IsNull(_("window_style"))) { + if (!style.IsEmpty()) + style += _T('|'); + style += m_obj->GetPropertyAsString(_T( "window_style" )); + } + if (!style.IsEmpty()) + AddPropertyValue(_T( "style" ), style); + + wxString extraStyle; + if (!m_obj->IsNull(_("extra_style"))) + extraStyle = m_obj->GetPropertyAsString(_T( "extra_style" )); + if (!m_obj->IsNull(_("window_extra_style"))) { + if (!extraStyle.IsEmpty()) + extraStyle += _T('|'); + extraStyle += m_obj->GetPropertyAsString(_T( "window_extra_style" )); + } + if (!extraStyle.IsEmpty()) + AddPropertyValue(_T( "exstyle" ), extraStyle); + + if (!m_obj->IsNull(_("pos"))) + AddProperty(_("pos"), _("pos"), XRC_TYPE_SIZE); + + if (!m_obj->IsNull(_("size"))) + AddProperty(_("size"), _("size"), XRC_TYPE_SIZE); + + if (!m_obj->IsNull(_("bg"))) + AddProperty(_("bg"), _("bg"), XRC_TYPE_COLOUR); + + if (!m_obj->IsNull(_("fg"))) + AddProperty(_("fg"), _("fg"), XRC_TYPE_COLOUR); + + if (!m_obj->IsNull(_("enabled")) && m_obj->GetPropertyAsInteger(_("enabled")) == 0) { + AddProperty(_("enabled"), _("enabled"), XRC_TYPE_BOOL); + } + if (!m_obj->IsNull(_("focused"))) + AddPropertyValue(_("focused"), _("0")); + + if (!m_obj->IsNull(_("hidden")) && m_obj->GetPropertyAsInteger(_("hidden")) != 0) { + AddProperty(_("hidden"), _("hidden"), XRC_TYPE_BOOL); + } + if (!m_obj->IsNull(_("font"))) + AddProperty(_("font"), _("font"), XRC_TYPE_FONT); + + if (!m_obj->IsNull(_("tooltip"))) + AddProperty(_("tooltip"), wxT("tooltip"), XRC_TYPE_TEXT); + + if (!m_obj->IsNull(_("subclass"))) { + wxString subclass = m_obj->GetChildFromParentProperty(_("subclass"), wxT("name")); + if (!subclass.empty()) { + m_xrcObj->SetAttribute("subclass", subclass.mb_str(wxConvUTF8)); + } + } } /////////////////////////////////////////////////////////////////////////////// -XrcToXfbFilter::XrcToXfbFilter( ticpp::Element *obj, - const wxString &/*classname*/, - const wxString &objname ) +XrcToXfbFilter::XrcToXfbFilter(ticpp::Element* obj, const wxString& /*classname*/, const wxString& objname) { - m_xrcObj = obj; - m_xfbObj = new ticpp::Element( "object" ); + m_xrcObj = obj; + m_xfbObj = new ticpp::Element("object"); - try - { - std::string name; - obj->GetAttribute( "class", &name ); - m_xfbObj->SetAttribute( "class", name ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } + try { + std::string name; + obj->GetAttribute("class", &name); + m_xfbObj->SetAttribute("class", name); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } - if ( !objname.empty() ) - AddProperty( wxT( "name" ), objname, XRC_TYPE_TEXT ); + if (!objname.empty()) + AddProperty(wxT("name"), objname, XRC_TYPE_TEXT); } -XrcToXfbFilter::XrcToXfbFilter( ticpp::Element *obj, const wxString &classname ) +XrcToXfbFilter::XrcToXfbFilter(ticpp::Element* obj, const wxString& classname) { - m_xrcObj = obj; - m_xfbObj = new ticpp::Element( "object" ); + m_xrcObj = obj; + m_xfbObj = new ticpp::Element("object"); - m_xfbObj->SetAttribute( "class", classname.mb_str( wxConvUTF8 ) ); + m_xfbObj->SetAttribute("class", classname.mb_str(wxConvUTF8)); - try - { - std::string name; - obj->GetAttribute( "name", &name ); - wxString objname( name.c_str(), wxConvUTF8 ); - AddPropertyValue( wxT( "name" ), objname ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } + try { + std::string name; + obj->GetAttribute("name", &name); + wxString objname(name.c_str(), wxConvUTF8); + AddPropertyValue(wxT("name"), objname); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } } XrcToXfbFilter::~XrcToXfbFilter() { - delete m_xfbObj; + delete m_xfbObj; } -ticpp::Element* XrcToXfbFilter::GetXrcProperty( const wxString &name ) +ticpp::Element* XrcToXfbFilter::GetXrcProperty(const wxString& name) { - return m_xrcObj->FirstChildElement( name.mb_str( wxConvUTF8 ) ); + return m_xrcObj->FirstChildElement(name.mb_str(wxConvUTF8)); } -void XrcToXfbFilter::AddProperty( const wxString &xrcPropName, - const wxString &xfbPropName, - const int &propType ) +void XrcToXfbFilter::AddProperty(const wxString& xrcPropName, const wxString& xfbPropName, const int& propType) { - ticpp::Element propElement( "property" ); - propElement.SetAttribute( "name", xfbPropName.mb_str( wxConvUTF8 ) ); - - switch ( propType ) - { - case XRC_TYPE_SIZE: - case XRC_TYPE_POINT: - case XRC_TYPE_BOOL: - ImportTextProperty( xrcPropName, &propElement ); - break; + ticpp::Element propElement("property"); + propElement.SetAttribute("name", xfbPropName.mb_str(wxConvUTF8)); - case XRC_TYPE_TEXT: - ImportTextProperty( xrcPropName, &propElement, true ); - break; + switch (propType) { + case XRC_TYPE_SIZE: + case XRC_TYPE_POINT: + case XRC_TYPE_BOOL: + ImportTextProperty(xrcPropName, &propElement); + break; - case XRC_TYPE_INTEGER: - ImportIntegerProperty( xrcPropName, &propElement ); - break; + case XRC_TYPE_TEXT: + ImportTextProperty(xrcPropName, &propElement, true); + break; - case XRC_TYPE_FLOAT: - ImportFloatProperty( xrcPropName, &propElement ); - break; + case XRC_TYPE_INTEGER: + ImportIntegerProperty(xrcPropName, &propElement); + break; - case XRC_TYPE_BITLIST: - ImportBitlistProperty( xrcPropName, &propElement ); - break; + case XRC_TYPE_FLOAT: + ImportFloatProperty(xrcPropName, &propElement); + break; - case XRC_TYPE_COLOUR: - ImportColourProperty( xrcPropName, &propElement ); - break; + case XRC_TYPE_BITLIST: + ImportBitlistProperty(xrcPropName, &propElement); + break; - case XRC_TYPE_FONT: - ImportFontProperty( xrcPropName, &propElement ); - break; + case XRC_TYPE_COLOUR: + ImportColourProperty(xrcPropName, &propElement); + break; - case XRC_TYPE_STRINGLIST: - ImportStringListProperty( xrcPropName, &propElement, true ); - break; + case XRC_TYPE_FONT: + ImportFontProperty(xrcPropName, &propElement); + break; - case XRC_TYPE_BITMAP: - ImportBitmapProperty( xrcPropName, &propElement ); - break; + case XRC_TYPE_STRINGLIST: + ImportStringListProperty(xrcPropName, &propElement, true); + break; - } + case XRC_TYPE_BITMAP: + ImportBitmapProperty(xrcPropName, &propElement); + break; + } - m_xfbObj->LinkEndChild( &propElement ); + m_xfbObj->LinkEndChild(&propElement); } -void XrcToXfbFilter::AddPropertyValue ( const wxString &xfbPropName, - const wxString &xfbPropValue, - bool parseXrcText ) +void XrcToXfbFilter::AddPropertyValue(const wxString& xfbPropName, const wxString& xfbPropValue, bool parseXrcText) { - ticpp::Element propElement( "property" ); - propElement.SetAttribute( "name", xfbPropName.mb_str( wxConvUTF8 ) ); - wxString value = ( parseXrcText ? XrcTextToString( xfbPropValue ) : xfbPropValue ); - propElement.SetText( value.mb_str( wxConvUTF8 ) ); - m_xfbObj->LinkEndChild( &propElement ); + ticpp::Element propElement("property"); + propElement.SetAttribute("name", xfbPropName.mb_str(wxConvUTF8)); + wxString value = (parseXrcText ? XrcTextToString(xfbPropValue) : xfbPropValue); + propElement.SetText(value.mb_str(wxConvUTF8)); + m_xfbObj->LinkEndChild(&propElement); } void XrcToXfbFilter::AddStyleProperty() { - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( "style" ); - - wxString bitlist = wxString( xrcProperty->GetText().c_str(), wxConvUTF8 ); - bitlist = ReplaceSynonymous( bitlist ); - - // FIXME: We should avoid hardcoding these things - std::set< wxString > windowStyles; - windowStyles.insert(wxT("wxBORDER_DEFAULT")); - windowStyles.insert(wxT("wxBORDER_SIMPLE")); - windowStyles.insert(wxT("wxBORDER_DOUBLE")); - windowStyles.insert(wxT("wxBORDER_SUNKEN")); - windowStyles.insert(wxT("wxBORDER_RAISED")); - windowStyles.insert(wxT("wxBORDER_STATIC")); - windowStyles.insert(wxT("wxBORDER_THEME")); - windowStyles.insert(wxT("wxBORDER_NONE")); - windowStyles.insert( wxT( "wxTRANSPARENT_WINDOW" ) ); - windowStyles.insert( wxT( "wxTAB_TRAVERSAL" ) ); - windowStyles.insert( wxT( "wxWANTS_CHARS" ) ); - windowStyles.insert( wxT( "wxVSCROLL" ) ); - windowStyles.insert( wxT( "wxHSCROLL" ) ); - windowStyles.insert( wxT( "wxALWAYS_SHOW_SB" ) ); - windowStyles.insert( wxT( "wxCLIP_CHILDREN" ) ); - windowStyles.insert( wxT( "wxFULL_REPAINT_ON_RESIZE" ) ); - windowStyles.insert(wxT("wxNO_FULL_REPAINT_ON_RESIZE")); - - wxString style, windowStyle; - wxStringTokenizer tkz( bitlist, wxT( " |" ) ); - while ( tkz.HasMoreTokens() ) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim( true ); - token.Trim( false ); - - if ( windowStyles.find( token ) == windowStyles.end() ) - { - if ( !style.IsEmpty() ) style += _T( "|" ); - style += token; - } - else - { - if ( !windowStyle.IsEmpty() ) windowStyle += _T( "|" ); - windowStyle += token; - } - - } - - if ( !style.empty() ) - { - AddPropertyValue( wxT( "style" ), style ); - } - - AddPropertyValue( wxT( "window_style" ), windowStyle ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement("style"); + + wxString bitlist = wxString(xrcProperty->GetText().c_str(), wxConvUTF8); + bitlist = ReplaceSynonymous(bitlist); + + // FIXME: We should avoid hardcoding these things + std::set windowStyles; + windowStyles.insert(wxT("wxBORDER_DEFAULT")); + windowStyles.insert(wxT("wxBORDER_SIMPLE")); + windowStyles.insert(wxT("wxBORDER_DOUBLE")); + windowStyles.insert(wxT("wxBORDER_SUNKEN")); + windowStyles.insert(wxT("wxBORDER_RAISED")); + windowStyles.insert(wxT("wxBORDER_STATIC")); + windowStyles.insert(wxT("wxBORDER_THEME")); + windowStyles.insert(wxT("wxBORDER_NONE")); + windowStyles.insert(wxT("wxTRANSPARENT_WINDOW")); + windowStyles.insert(wxT("wxTAB_TRAVERSAL")); + windowStyles.insert(wxT("wxWANTS_CHARS")); + windowStyles.insert(wxT("wxVSCROLL")); + windowStyles.insert(wxT("wxHSCROLL")); + windowStyles.insert(wxT("wxALWAYS_SHOW_SB")); + windowStyles.insert(wxT("wxCLIP_CHILDREN")); + windowStyles.insert(wxT("wxFULL_REPAINT_ON_RESIZE")); + windowStyles.insert(wxT("wxNO_FULL_REPAINT_ON_RESIZE")); + + wxString style, windowStyle; + wxStringTokenizer tkz(bitlist, wxT(" |")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + if (windowStyles.find(token) == windowStyles.end()) { + if (!style.IsEmpty()) + style += _T( "|" ); + style += token; + } else { + if (!windowStyle.IsEmpty()) + windowStyle += _T( "|" ); + windowStyle += token; + } + } + + if (!style.empty()) { + AddPropertyValue(wxT("style"), style); + } + + AddPropertyValue(wxT("window_style"), windowStyle); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } } void XrcToXfbFilter::AddExtraStyleProperty() { - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( "exstyle" ); - - wxString bitlist = wxString( xrcProperty->GetText().c_str(), wxConvUTF8 ); - bitlist = ReplaceSynonymous( bitlist ); - - // FIXME: We should avoid hardcoding these things - std::set< wxString > windowStyles; - windowStyles.insert( wxT( "wxWS_EX_VALIDATE_RECURSIVELY" ) ); - windowStyles.insert( wxT( "wxWS_EX_BLOCK_EVENTS" ) ); - windowStyles.insert( wxT( "wxWS_EX_TRANSIENT" ) ); - windowStyles.insert(wxT("wxWS_EX_CONTEXTHELP")); - windowStyles.insert( wxT( "wxWS_EX_PROCESS_IDLE" ) ); - windowStyles.insert( wxT( "wxWS_EX_PROCESS_UI_UPDATES" ) ); - - wxString style, windowStyle; - wxStringTokenizer tkz( bitlist, wxT( " |" ) ); - while ( tkz.HasMoreTokens() ) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim( true ); - token.Trim( false ); - - if ( windowStyles.find( token ) == windowStyles.end() ) - { - if ( !style.IsEmpty() ) style += _T( "|" ); - style += token; - } - else - { - if ( !windowStyle.IsEmpty() ) windowStyle += _T( "|" ); - windowStyle += token; - } - - } - - if ( !style.empty() ) - { - AddPropertyValue( wxT( "extra_style" ), style ); - } - AddPropertyValue( wxT( "window_extra_style" ), windowStyle ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } -} - -void XrcToXfbFilter::AddPropertyPair( const char* xrcPropName, const wxString& xfbPropName1, const wxString& xfbPropName2 ) -{ - try - { - ticpp::Element* pairProp = m_xrcObj->FirstChildElement( xrcPropName ); - - wxString width = wxEmptyString; - wxString height = wxEmptyString; - wxStringTokenizer tkz( wxString( pairProp->GetText().c_str(), wxConvUTF8 ), wxT( "," ) ); - if ( tkz.HasMoreTokens() ) - { - width = tkz.GetNextToken(); - if ( tkz.HasMoreTokens() ) - { - height = tkz.GetNextToken(); - } - } - AddPropertyValue( xfbPropName1, width ); - AddPropertyValue( xfbPropName2, height ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement("exstyle"); + + wxString bitlist = wxString(xrcProperty->GetText().c_str(), wxConvUTF8); + bitlist = ReplaceSynonymous(bitlist); + + // FIXME: We should avoid hardcoding these things + std::set windowStyles; + windowStyles.insert(wxT("wxWS_EX_VALIDATE_RECURSIVELY")); + windowStyles.insert(wxT("wxWS_EX_BLOCK_EVENTS")); + windowStyles.insert(wxT("wxWS_EX_TRANSIENT")); + windowStyles.insert(wxT("wxWS_EX_CONTEXTHELP")); + windowStyles.insert(wxT("wxWS_EX_PROCESS_IDLE")); + windowStyles.insert(wxT("wxWS_EX_PROCESS_UI_UPDATES")); + + wxString style, windowStyle; + wxStringTokenizer tkz(bitlist, wxT(" |")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + if (windowStyles.find(token) == windowStyles.end()) { + if (!style.IsEmpty()) + style += _T( "|" ); + style += token; + } else { + if (!windowStyle.IsEmpty()) + windowStyle += _T( "|" ); + windowStyle += token; + } + } + + if (!style.empty()) { + AddPropertyValue(wxT("extra_style"), style); + } + AddPropertyValue(wxT("window_extra_style"), windowStyle); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } +} + +void XrcToXfbFilter::AddPropertyPair( + const char* xrcPropName, const wxString& xfbPropName1, const wxString& xfbPropName2) +{ + try { + ticpp::Element* pairProp = m_xrcObj->FirstChildElement(xrcPropName); + + wxString width = wxEmptyString; + wxString height = wxEmptyString; + wxStringTokenizer tkz(wxString(pairProp->GetText().c_str(), wxConvUTF8), wxT(",")); + if (tkz.HasMoreTokens()) { + width = tkz.GetNextToken(); + if (tkz.HasMoreTokens()) { + height = tkz.GetNextToken(); + } + } + AddPropertyValue(xfbPropName1, width); + AddPropertyValue(xfbPropName2, height); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } } ticpp::Element* XrcToXfbFilter::GetXfbObject() { - return m_xfbObj->Clone().release()->ToElement(); + return m_xfbObj->Clone().release()->ToElement(); } //----------------------------- -void XrcToXfbFilter::ImportTextProperty( const wxString &xrcPropName, - ticpp::Element *property, - bool parseXrcText ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - - // Convert XRC text to normal text - wxString value( wxString( xrcProperty->GetText().c_str(), wxConvUTF8 ) ); - - if ( parseXrcText ) - value = XrcTextToString( value ); - - property->SetText( value.mb_str( wxConvUTF8 ) ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } -} - -void XrcToXfbFilter::ImportIntegerProperty( const wxString &xrcPropName, ticpp::Element *property ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - property->SetText( xrcProperty->GetText() ); - } - catch( ticpp::Exception& ) - { - property->SetText( "0" ); - } -} - -void XrcToXfbFilter::ImportFloatProperty( const wxString &xrcPropName, ticpp::Element *property ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - property->SetText( xrcProperty->GetText() ); - } - catch( ticpp::Exception& ) - { - property->SetText( "0.0" ); - } -} - -void XrcToXfbFilter::ImportBitlistProperty( const wxString &xrcPropName, ticpp::Element *property ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - - wxString bitlist = wxString( xrcProperty->GetText().c_str(), wxConvUTF8 ); - bitlist = ReplaceSynonymous( bitlist ); - property->SetText( bitlist.mb_str( wxConvUTF8 ) ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } -} - -void XrcToXfbFilter::ImportFontProperty( const wxString &xrcPropName, ticpp::Element *property ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - - ticpp::Element *element; - wxFontContainer font; - - // the size - try - { - element = xrcProperty->FirstChildElement( "size" ); - long size; - element->GetText( &size ); - font.SetPointSize( size ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } - - // the family - try - { - element = xrcProperty->FirstChildElement( "family" ); - wxString family_str( element->GetText().c_str(), wxConvUTF8 ); - - if ( family_str == _( "decorative" ) ) - font.SetFamily(wxFONTFAMILY_DECORATIVE); - else if ( family_str == _( "roman" ) ) - font.SetFamily(wxFONTFAMILY_ROMAN); - else if ( family_str == _( "swiss" ) ) - font.SetFamily(wxFONTFAMILY_SWISS); - else if ( family_str == _( "script" ) ) - font.SetFamily(wxFONTFAMILY_SCRIPT); - else if ( family_str == _( "modern" ) ) - font.SetFamily(wxFONTFAMILY_MODERN); - else if ( family_str == _( "teletype" ) ) - font.SetFamily(wxFONTFAMILY_TELETYPE); - else - font.SetFamily(wxFONTFAMILY_DEFAULT); - } - catch( ticpp::Exception& ) - { - font.SetFamily(wxFONTFAMILY_DEFAULT); - } - - // the style - try - { - element = xrcProperty->FirstChildElement( "style" ); - wxString style_str( element->GetText().c_str(), wxConvUTF8 ); - - if ( style_str == _( "slant" ) ) - font.SetStyle(wxFONTSTYLE_SLANT); - else if ( style_str == _( "italic" ) ) - font.SetStyle(wxFONTSTYLE_ITALIC); - else - font.SetStyle(wxFONTSTYLE_NORMAL); - } - catch( ticpp::Exception& ) - { - font.SetStyle(wxFONTSTYLE_NORMAL); - } - - - // weight - try - { - element = xrcProperty->FirstChildElement( "weight" ); - wxString weight_str( element->GetText().c_str(), wxConvUTF8 ); - - if ( weight_str == _( "light" ) ) - font.SetWeight(wxFONTWEIGHT_LIGHT); - else if ( weight_str == _( "bold" ) ) - font.SetWeight(wxFONTWEIGHT_BOLD); - else - font.SetWeight(wxFONTWEIGHT_NORMAL); - } - catch( ticpp::Exception& ) - { - font.SetWeight(wxFONTWEIGHT_NORMAL); - } - - // underlined - try - { - element = xrcProperty->FirstChildElement( "underlined" ); - wxString underlined_str( element->GetText().c_str(), wxConvUTF8 ); - - if ( underlined_str == wxT( "1" ) ) - font.SetUnderlined( true ); - else - font.SetUnderlined( false ); - } - catch( ticpp::Exception& ) - { - font.SetUnderlined( false ); - } - - // face - try - { - element = xrcProperty->FirstChildElement( "face" ); - wxString face( element->GetText().c_str(), wxConvUTF8 ); - font.SetFaceName( face ); - } - catch( ticpp::Exception& ) - { - font.SetFaceName( wxEmptyString ); - } - - // We already have the font type. So we must now use the wxFB format - wxString font_str = - wxString::Format( wxT("%s,%d,%d,%d,%d,%d"), font.GetFaceName().c_str(), font.GetStyle(), - font.GetWeight(), font.GetPointSize(), - font.GetFamily(), font.GetUnderlined() ); - property->SetText( font_str.mb_str( wxConvUTF8 ) ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } -} - -void XrcToXfbFilter::ImportBitmapProperty( const wxString &xrcPropName, ticpp::Element *property ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - - if( (xrcProperty->GetAttribute( "stock_id" ) != "") && (xrcProperty->GetAttribute( "stock_client" ) != "") ) - { - // read wxArtProvider-based bitmap - wxString res = _("Load From Art Provider"); - res += wxT(";"); - res += wxString( xrcProperty->GetAttribute( "stock_id" ).c_str(), wxConvUTF8 ); - res += wxT(";"); - res += wxString( xrcProperty->GetAttribute( "stock_client" ).c_str(), wxConvUTF8 ); - property->SetText( res.Trim().mb_str( wxConvUTF8 ) ); - } - else - { - // read file-based bitmap - wxString res = _("Load From File"); - res += wxT(";"); - res += wxString( xrcProperty->GetText().c_str(), wxConvUTF8 ); - property->SetText( res.Trim().mb_str( wxConvUTF8 ) ); - } - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } -} - -void XrcToXfbFilter::ImportColourProperty( const wxString &xrcPropName, ticpp::Element *property ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - std::string value = xrcProperty->GetText(); - - // Changing "#rrggbb" format to "rrr,ggg,bbb" - std::string hexColour = "0x" + value.substr( 1, 2 ) + - " 0x" + value.substr( 3, 2 ) + - " 0x" + value.substr( 5, 2 ); - - std::istringstream strIn; - std::ostringstream strOut; - unsigned int red, green, blue; - - strIn.str( hexColour ); - strIn >> std::hex; - - strIn >> red; - strIn >> green; - strIn >> blue; - - strOut << red << "," << green << "," << blue; - - property->SetText( strOut.str() ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); - } -} - -void XrcToXfbFilter::ImportStringListProperty( const wxString &xrcPropName, ticpp::Element *property , bool parseXrcText ) -{ - try - { - ticpp::Element *xrcProperty = m_xrcObj->FirstChildElement( xrcPropName.mb_str( wxConvUTF8 ) ); - - wxString res; - - ticpp::Element *element = xrcProperty->FirstChildElement( "item", false ); - while ( element ) - { - try - { - wxString value( element->GetText().c_str(), wxConvUTF8 ); - if ( parseXrcText ) - value = XrcTextToString( value ); - - res += wxChar( '\"' ) + value + wxT( "\" " ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxT("%s. line: %i"), wxString( ex.m_details.c_str(), wxConvUTF8 ).c_str(), __LINE__ ); - } - - element = element->NextSiblingElement( "item", false ); - } - - res.Trim(); - property->SetText( res.mb_str( wxConvUTF8 ) ); - } - catch( ticpp::Exception& ex ) - { - wxLogDebug( wxT("%s. line: %i"), wxString( ex.m_details.c_str(), wxConvUTF8 ).c_str(), __LINE__ ); - } +void XrcToXfbFilter::ImportTextProperty(const wxString& xrcPropName, ticpp::Element* property, bool parseXrcText) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + + // Convert XRC text to normal text + wxString value(wxString(xrcProperty->GetText().c_str(), wxConvUTF8)); + + if (parseXrcText) + value = XrcTextToString(value); + + property->SetText(value.mb_str(wxConvUTF8)); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } +} + +void XrcToXfbFilter::ImportIntegerProperty(const wxString& xrcPropName, ticpp::Element* property) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + property->SetText(xrcProperty->GetText()); + } catch (ticpp::Exception&) { + property->SetText("0"); + } +} + +void XrcToXfbFilter::ImportFloatProperty(const wxString& xrcPropName, ticpp::Element* property) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + property->SetText(xrcProperty->GetText()); + } catch (ticpp::Exception&) { + property->SetText("0.0"); + } +} + +void XrcToXfbFilter::ImportBitlistProperty(const wxString& xrcPropName, ticpp::Element* property) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + + wxString bitlist = wxString(xrcProperty->GetText().c_str(), wxConvUTF8); + bitlist = ReplaceSynonymous(bitlist); + property->SetText(bitlist.mb_str(wxConvUTF8)); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } +} + +void XrcToXfbFilter::ImportFontProperty(const wxString& xrcPropName, ticpp::Element* property) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + + ticpp::Element* element; + wxFontContainer font; + + // the size + try { + element = xrcProperty->FirstChildElement("size"); + long size; + element->GetText(&size); + font.SetPointSize(size); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } + + // the family + try { + element = xrcProperty->FirstChildElement("family"); + wxString family_str(element->GetText().c_str(), wxConvUTF8); + + if (family_str == _("decorative")) + font.SetFamily(wxFONTFAMILY_DECORATIVE); + else if (family_str == _("roman")) + font.SetFamily(wxFONTFAMILY_ROMAN); + else if (family_str == _("swiss")) + font.SetFamily(wxFONTFAMILY_SWISS); + else if (family_str == _("script")) + font.SetFamily(wxFONTFAMILY_SCRIPT); + else if (family_str == _("modern")) + font.SetFamily(wxFONTFAMILY_MODERN); + else if (family_str == _("teletype")) + font.SetFamily(wxFONTFAMILY_TELETYPE); + else + font.SetFamily(wxFONTFAMILY_DEFAULT); + } catch (ticpp::Exception&) { + font.SetFamily(wxFONTFAMILY_DEFAULT); + } + + // the style + try { + element = xrcProperty->FirstChildElement("style"); + wxString style_str(element->GetText().c_str(), wxConvUTF8); + + if (style_str == _("slant")) + font.SetStyle(wxFONTSTYLE_SLANT); + else if (style_str == _("italic")) + font.SetStyle(wxFONTSTYLE_ITALIC); + else + font.SetStyle(wxFONTSTYLE_NORMAL); + } catch (ticpp::Exception&) { + font.SetStyle(wxFONTSTYLE_NORMAL); + } + + + // weight + try { + element = xrcProperty->FirstChildElement("weight"); + wxString weight_str(element->GetText().c_str(), wxConvUTF8); + + if (weight_str == _("light")) + font.SetWeight(wxFONTWEIGHT_LIGHT); + else if (weight_str == _("bold")) + font.SetWeight(wxFONTWEIGHT_BOLD); + else + font.SetWeight(wxFONTWEIGHT_NORMAL); + } catch (ticpp::Exception&) { + font.SetWeight(wxFONTWEIGHT_NORMAL); + } + + // underlined + try { + element = xrcProperty->FirstChildElement("underlined"); + wxString underlined_str(element->GetText().c_str(), wxConvUTF8); + + if (underlined_str == wxT("1")) + font.SetUnderlined(true); + else + font.SetUnderlined(false); + } catch (ticpp::Exception&) { + font.SetUnderlined(false); + } + + // face + try { + element = xrcProperty->FirstChildElement("face"); + wxString face(element->GetText().c_str(), wxConvUTF8); + font.SetFaceName(face); + } catch (ticpp::Exception&) { + font.SetFaceName(wxEmptyString); + } + + // We already have the font type. So we must now use the wxFB format + wxString font_str = wxString::Format( + wxT("%s,%d,%d,%d,%d,%d"), font.GetFaceName().c_str(), font.GetStyle(), font.GetWeight(), font.GetPointSize(), + font.GetFamily(), font.GetUnderlined()); + property->SetText(font_str.mb_str(wxConvUTF8)); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } +} + +void XrcToXfbFilter::ImportBitmapProperty(const wxString& xrcPropName, ticpp::Element* property) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + + if ((xrcProperty->GetAttribute("stock_id") != "") && (xrcProperty->GetAttribute("stock_client") != "")) { + // read wxArtProvider-based bitmap + wxString res = _("Load From Art Provider"); + res += wxT(";"); + res += wxString(xrcProperty->GetAttribute("stock_id").c_str(), wxConvUTF8); + res += wxT(";"); + res += wxString(xrcProperty->GetAttribute("stock_client").c_str(), wxConvUTF8); + property->SetText(res.Trim().mb_str(wxConvUTF8)); + } else { + // read file-based bitmap + wxString res = _("Load From File"); + res += wxT(";"); + res += wxString(xrcProperty->GetText().c_str(), wxConvUTF8); + property->SetText(res.Trim().mb_str(wxConvUTF8)); + } + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } +} + +void XrcToXfbFilter::ImportColourProperty(const wxString& xrcPropName, ticpp::Element* property) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + std::string value = xrcProperty->GetText(); + + // Changing "#rrggbb" format to "rrr,ggg,bbb" + std::string hexColour = "0x" + value.substr(1, 2) + " 0x" + value.substr(3, 2) + " 0x" + value.substr(5, 2); + + std::istringstream strIn; + std::ostringstream strOut; + unsigned int red, green, blue; + + strIn.str(hexColour); + strIn >> std::hex; + + strIn >> red; + strIn >> green; + strIn >> blue; + + strOut << red << "," << green << "," << blue; + + property->SetText(strOut.str()); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxString(ex.m_details.c_str(), wxConvUTF8)); + } +} + +void XrcToXfbFilter::ImportStringListProperty(const wxString& xrcPropName, ticpp::Element* property, bool parseXrcText) +{ + try { + ticpp::Element* xrcProperty = m_xrcObj->FirstChildElement(xrcPropName.mb_str(wxConvUTF8)); + + wxString res; + + ticpp::Element* element = xrcProperty->FirstChildElement("item", false); + while (element) { + try { + wxString value(element->GetText().c_str(), wxConvUTF8); + if (parseXrcText) + value = XrcTextToString(value); + + res += wxChar('\"') + value + wxT("\" "); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxT("%s. line: %i"), wxString(ex.m_details.c_str(), wxConvUTF8).c_str(), __LINE__); + } + + element = element->NextSiblingElement("item", false); + } + + res.Trim(); + property->SetText(res.mb_str(wxConvUTF8)); + } catch (ticpp::Exception& ex) { + wxLogDebug(wxT("%s. line: %i"), wxString(ex.m_details.c_str(), wxConvUTF8).c_str(), __LINE__); + } } void XrcToXfbFilter::AddWindowProperties() { - AddProperty( _( "pos" ), _( "pos" ), XRC_TYPE_POINT ); - AddProperty( _( "size" ), _( "size" ), XRC_TYPE_SIZE ); - AddProperty( _( "bg" ), _( "bg" ), XRC_TYPE_COLOUR ); - AddProperty( _( "fg" ), _( "fg" ), XRC_TYPE_COLOUR ); - AddProperty( _( "font" ), _( "font" ), XRC_TYPE_FONT ); - if ( m_xrcObj->FirstChildElement( "enabled", false ) ) - { - AddProperty( _( "enabled"), _("enabled"), XRC_TYPE_BOOL ); - } - AddProperty( _( "hidden"), _("hidden"), XRC_TYPE_BOOL ); - AddProperty( _( "tooltip"), _("tooltip"), XRC_TYPE_TEXT ); - AddStyleProperty(); - AddExtraStyleProperty(); - - // Subclass - std::string subclass; - m_xrcObj->GetAttribute( "subclass", &subclass, false ); - if ( !subclass.empty() ) - { - ticpp::Element propElement( "property" ); - propElement.SetAttribute( "name", "subclass" ); - propElement.SetText( subclass ); - m_xfbObj->LinkEndChild( &propElement ); - } + AddProperty(_("pos"), _("pos"), XRC_TYPE_POINT); + AddProperty(_("size"), _("size"), XRC_TYPE_SIZE); + AddProperty(_("bg"), _("bg"), XRC_TYPE_COLOUR); + AddProperty(_("fg"), _("fg"), XRC_TYPE_COLOUR); + AddProperty(_("font"), _("font"), XRC_TYPE_FONT); + if (m_xrcObj->FirstChildElement("enabled", false)) { + AddProperty(_("enabled"), _("enabled"), XRC_TYPE_BOOL); + } + AddProperty(_("hidden"), _("hidden"), XRC_TYPE_BOOL); + AddProperty(_("tooltip"), _("tooltip"), XRC_TYPE_TEXT); + AddStyleProperty(); + AddExtraStyleProperty(); + + // Subclass + std::string subclass; + m_xrcObj->GetAttribute("subclass", &subclass, false); + if (!subclass.empty()) { + ticpp::Element propElement("property"); + propElement.SetAttribute("name", "subclass"); + propElement.SetText(subclass); + m_xfbObj->LinkEndChild(&propElement); + } } diff --git a/sdk/plugin_interface/xrcconv.h b/sdk/plugin_interface/xrcconv.h index da35f2269..4c9183f2b 100644 --- a/sdk/plugin_interface/xrcconv.h +++ b/sdk/plugin_interface/xrcconv.h @@ -22,26 +22,28 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef SDK_PLUGIN_INTERFACE_XRCCONV_H #define SDK_PLUGIN_INTERFACE_XRCCONV_H #include "component.h" -#define XRC_TYPE_TEXT 0 + +#define XRC_TYPE_TEXT 0 #define XRC_TYPE_INTEGER 1 -#define XRC_TYPE_BOOL 2 -#define XRC_TYPE_COLOUR 3 -#define XRC_TYPE_FONT 4 +#define XRC_TYPE_BOOL 2 +#define XRC_TYPE_COLOUR 3 +#define XRC_TYPE_FONT 4 #define XRC_TYPE_BITLIST 5 -#define XRC_TYPE_SIZE 6 -#define XRC_TYPE_POINT 7 +#define XRC_TYPE_SIZE 6 +#define XRC_TYPE_POINT 7 #define XRC_TYPE_STRINGLIST 8 -#define XRC_TYPE_BITMAP 9 +#define XRC_TYPE_BITMAP 9 #define XRC_TYPE_FLOAT 10 namespace ticpp { - class Element; +class Element; } /** @@ -64,38 +66,32 @@ namespace ticpp */ class ObjectToXrcFilter { - public: - ObjectToXrcFilter(IObject *obj, - const wxString &classname, - const wxString &objname = wxT(""), - const wxString &base = wxT("")); +public: + ObjectToXrcFilter( + IObject* obj, const wxString& classname, const wxString& objname = wxT(""), const wxString& base = wxT("")); - ~ObjectToXrcFilter(); + ~ObjectToXrcFilter(); - void AddProperty (const wxString &objPropName, - const wxString &xrcPropName, - const int &propType); + void AddProperty(const wxString& objPropName, const wxString& xrcPropName, const int& propType); - void AddPropertyValue (const wxString &xrcPropName, - const wxString &xrcPropValue, - bool xrcFormat = false); + void AddPropertyValue(const wxString& xrcPropName, const wxString& xrcPropValue, bool xrcFormat = false); - void AddPropertyPair ( const wxString& objPropName1, const wxString& objPropName2, const wxString& xrcPropName ); + void AddPropertyPair(const wxString& objPropName1, const wxString& objPropName2, const wxString& xrcPropName); - void AddWindowProperties(); + void AddWindowProperties(); - ticpp::Element* GetXrcObject(); + ticpp::Element* GetXrcObject(); - private: - ticpp::Element* m_xrcObj; - IObject *m_obj; +private: + ticpp::Element* m_xrcObj; + IObject* m_obj; - void LinkText(const wxString &text, ticpp::Element *propElement, bool xrcFormat = false); - void LinkColour(const wxColour &colour, ticpp::Element *propElement); - void LinkFont(const wxFontContainer &font, ticpp::Element *propElement); - void LinkInteger(const int &integer, ticpp::Element *propElement); - void LinkFloat( const double& value, ticpp::Element* propElement ); - void LinkStringList(const wxArrayString &array, ticpp::Element *propElement, bool xrcFormat = false); + void LinkText(const wxString& text, ticpp::Element* propElement, bool xrcFormat = false); + void LinkColour(const wxColour& colour, ticpp::Element* propElement); + void LinkFont(const wxFontContainer& font, ticpp::Element* propElement); + void LinkInteger(const int& integer, ticpp::Element* propElement); + void LinkFloat(const double& value, ticpp::Element* propElement); + void LinkStringList(const wxArrayString& array, ticpp::Element* propElement, bool xrcFormat = false); }; /** @@ -107,46 +103,39 @@ class ObjectToXrcFilter */ class XrcToXfbFilter { - public: - - XrcToXfbFilter(ticpp::Element *obj, - const wxString &classname); +public: + XrcToXfbFilter(ticpp::Element* obj, const wxString& classname); - XrcToXfbFilter(ticpp::Element *obj, - const wxString &classname, - const wxString &objname); - ~XrcToXfbFilter(); + XrcToXfbFilter(ticpp::Element* obj, const wxString& classname, const wxString& objname); + ~XrcToXfbFilter(); - void AddProperty (const wxString &xrcPropName, - const wxString &xfbPropName, const int &propType); + void AddProperty(const wxString& xrcPropName, const wxString& xfbPropName, const int& propType); - void AddPropertyValue (const wxString &xfbPropName, - const wxString &xfbPropValue, - bool parseXrcText = false); + void AddPropertyValue(const wxString& xfbPropName, const wxString& xfbPropValue, bool parseXrcText = false); - void AddWindowProperties(); + void AddWindowProperties(); - void AddPropertyPair( const char* xrcPropName, const wxString& xfbPropName1, const wxString& xfbPropName2 ); + void AddPropertyPair(const char* xrcPropName, const wxString& xfbPropName1, const wxString& xfbPropName2); - ticpp::Element* GetXfbObject(); + ticpp::Element* GetXfbObject(); - private: - ticpp::Element *m_xfbObj; - ticpp::Element *m_xrcObj; +private: + ticpp::Element* m_xfbObj; + ticpp::Element* m_xrcObj; - void ImportTextProperty(const wxString &xrcPropName, ticpp::Element *property, bool parseXrcText = false); - void ImportIntegerProperty(const wxString &xrcPropName, ticpp::Element *property); - void ImportFloatProperty(const wxString &xrcPropName, ticpp::Element *property); - void ImportBitlistProperty(const wxString &xrcPropName, ticpp::Element *property); - void ImportBitmapProperty(const wxString &xrcPropName, ticpp::Element *property); - void ImportColourProperty(const wxString &xrcPropName, ticpp::Element *property); - void ImportFontProperty(const wxString &xrcPropName, ticpp::Element *property); - void ImportStringListProperty(const wxString &xrcPropName, ticpp::Element *property, bool parseXrcText = false); + void ImportTextProperty(const wxString& xrcPropName, ticpp::Element* property, bool parseXrcText = false); + void ImportIntegerProperty(const wxString& xrcPropName, ticpp::Element* property); + void ImportFloatProperty(const wxString& xrcPropName, ticpp::Element* property); + void ImportBitlistProperty(const wxString& xrcPropName, ticpp::Element* property); + void ImportBitmapProperty(const wxString& xrcPropName, ticpp::Element* property); + void ImportColourProperty(const wxString& xrcPropName, ticpp::Element* property); + void ImportFontProperty(const wxString& xrcPropName, ticpp::Element* property); + void ImportStringListProperty(const wxString& xrcPropName, ticpp::Element* property, bool parseXrcText = false); - void AddStyleProperty(); - void AddExtraStyleProperty(); + void AddStyleProperty(); + void AddExtraStyleProperty(); - ticpp::Element *GetXrcProperty(const wxString &name); + ticpp::Element* GetXrcProperty(const wxString& name); }; -#endif // SDK_PLUGIN_INTERFACE_XRCCONV_H +#endif // SDK_PLUGIN_INTERFACE_XRCCONV_H diff --git a/src/codegen/codegen.cpp b/src/codegen/codegen.cpp index 91b4f8771..ae8279101 100644 --- a/src/codegen/codegen.cpp +++ b/src/codegen/codegen.cpp @@ -25,63 +25,54 @@ #include "codegen.h" +#include + #include "model/objectbase.h" #include "rad/appdata.h" #include "utils/wxfbexception.h" -#include - -BufferedTextInputStream::BufferedTextInputStream(wxTextInputStream& text) : m_text(text), m_buffer(static_cast(wxEOF)) +BufferedTextInputStream::BufferedTextInputStream(wxTextInputStream& text) : + m_text(text), m_buffer(static_cast(wxEOF)) { - readChar(); + readChar(); } bool BufferedTextInputStream::Eof() const { - return (m_buffer == static_cast(wxEOF)); + return (m_buffer == static_cast(wxEOF)); } wxChar BufferedTextInputStream::Peek() { - return m_buffer; + return m_buffer; } wxChar BufferedTextInputStream::GetC() { - auto result = m_buffer; + auto result = m_buffer; + + readChar(); - readChar(); - - return result; + return result; } void BufferedTextInputStream::readChar() { - m_buffer = m_text.GetChar(); - if (m_buffer == 0) { - m_buffer = static_cast(wxEOF); - } + m_buffer = m_text.GetChar(); + if (m_buffer == 0) { + m_buffer = static_cast(wxEOF); + } } -TemplateParser::TemplateParser(PObjectBase obj, wxString _template) -: -m_obj( obj ), -m_stream(_template), -m_text(m_stream, wxT(" \t"), wxConvUTF8), -m_in(m_text), -m_indent( 0 ) +TemplateParser::TemplateParser(PObjectBase obj, wxString _template) : + m_obj(obj), m_stream(_template), m_text(m_stream, wxT(" \t"), wxConvUTF8), m_in(m_text), m_indent(0) { } -TemplateParser::TemplateParser( const TemplateParser & that, wxString _template ) -: -m_obj( that.m_obj ), -m_stream(_template), -m_text(m_stream, wxT(" \t"), wxConvUTF8), -m_in(m_text), -m_indent( 0 ) +TemplateParser::TemplateParser(const TemplateParser& that, wxString _template) : + m_obj(that.m_obj), m_stream(_template), m_text(m_stream, wxT(" \t"), wxConvUTF8), m_in(m_text), m_indent(0) { } @@ -90,755 +81,662 @@ TemplateParser::~TemplateParser() = default; TemplateParser::Token TemplateParser::GetNextToken() { - // There are 3 special characters - // #xxxx -> command - // $xxxx -> property - // %xxxx -> local variable - // @x -> Escape a special character. Example: @# is the character #. - - Token result = TOK_ERROR; - - if (!m_in.Eof()) - { - wxChar c = m_in.Peek(); - if ( c == wxT('#') ) - result = TOK_MACRO; - else if (c == wxT('$') ) - result = TOK_PROPERTY; - else - result = TOK_TEXT; - } - - return result; + // There are 3 special characters + // #xxxx -> command + // $xxxx -> property + // %xxxx -> local variable + // @x -> Escape a special character. Example: @# is the character #. + + Token result = TOK_ERROR; + + if (!m_in.Eof()) { + wxChar c = m_in.Peek(); + if (c == wxT('#')) + result = TOK_MACRO; + else if (c == wxT('$')) + result = TOK_PROPERTY; + else + result = TOK_TEXT; + } + + return result; } bool TemplateParser::ParseMacro() { - Ident ident; - - ident = ParseIdent(); - switch (ident) - { - case ID_WXPARENT: - return ParseWxParent(); - break; - case ID_PARENT: - return ParseParent(); - break; - case ID_FORM: - return ParseForm(); - break; - case ID_IFNOTNULL: - return ParseIfNotNull(); - break; - case ID_IFNULL: - return ParseIfNull(); - break; - case ID_FOREACH: - return ParseForEach(); - break; - case ID_PREDEFINED: - return ParsePred(); - break; - case ID_PREDEFINED_INDEX: - return ParseNPred(); - break; - case ID_CHILD: - return ParseChild(); - break; - case ID_NEWLINE: - return ParseNewLine(); - break; - case ID_IFEQUAL: - ParseIfEqual(); - break; - case ID_IFNOTEQUAL: - ParseIfNotEqual(); - break; - case ID_IFPARENTTYPEEQUAL: - ParseIfParentTypeEqual(); - break; - case ID_IFPARENTCLASSEQUAL: - ParseIfParentClassEqual(); - break; - case ID_IFPARENTTYPENOTEQUAL: - ParseIfParentTypeNotEqual(); - break; - case ID_IFPARENTCLASSNOTEQUAL: - ParseIfParentClassNotEqual(); - break; - case ID_APPEND: - ParseAppend(); - break; - case ID_CLASS: - ParseClass(); - break; - case ID_INDENT: - ParseIndent(); - break; - case ID_UNINDENT: - ParseUnindent(); - break; - case ID_IFTYPEEQUAL: - ParseIfTypeEqual(); - break; - case ID_IFTYPENOTEQUAL: - ParseIfTypeNotEqual(); - break; - case ID_UTBL: - ParseLuaTable(); - break; - default: - THROW_WXFBEX( wxT("Invalid Macro Type") ); - break; - } - - return true; + Ident ident; + + ident = ParseIdent(); + switch (ident) { + case ID_WXPARENT: + return ParseWxParent(); + break; + case ID_PARENT: + return ParseParent(); + break; + case ID_FORM: + return ParseForm(); + break; + case ID_IFNOTNULL: + return ParseIfNotNull(); + break; + case ID_IFNULL: + return ParseIfNull(); + break; + case ID_FOREACH: + return ParseForEach(); + break; + case ID_PREDEFINED: + return ParsePred(); + break; + case ID_PREDEFINED_INDEX: + return ParseNPred(); + break; + case ID_CHILD: + return ParseChild(); + break; + case ID_NEWLINE: + return ParseNewLine(); + break; + case ID_IFEQUAL: + ParseIfEqual(); + break; + case ID_IFNOTEQUAL: + ParseIfNotEqual(); + break; + case ID_IFPARENTTYPEEQUAL: + ParseIfParentTypeEqual(); + break; + case ID_IFPARENTCLASSEQUAL: + ParseIfParentClassEqual(); + break; + case ID_IFPARENTTYPENOTEQUAL: + ParseIfParentTypeNotEqual(); + break; + case ID_IFPARENTCLASSNOTEQUAL: + ParseIfParentClassNotEqual(); + break; + case ID_APPEND: + ParseAppend(); + break; + case ID_CLASS: + ParseClass(); + break; + case ID_INDENT: + ParseIndent(); + break; + case ID_UNINDENT: + ParseUnindent(); + break; + case ID_IFTYPEEQUAL: + ParseIfTypeEqual(); + break; + case ID_IFTYPENOTEQUAL: + ParseIfTypeNotEqual(); + break; + case ID_UTBL: + ParseLuaTable(); + break; + default: + THROW_WXFBEX(wxT("Invalid Macro Type")); + break; + } + + return true; } TemplateParser::Ident TemplateParser::ParseIdent() { - Ident ident = ID_ERROR; - - if (!m_in.Eof()) - { - wxString macro; - m_in.GetC(); - - wxChar peek( m_in.Peek() ); - while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT('#') && peek != wxT('$') - && ( (peek >= wxT('a') && peek <= wxT('z') ) || - (peek >= wxT('A') && peek <= wxT('Z') ) || - (peek >= wxT('0') && peek <= wxT('9') ) )) - { - macro += wxChar( m_in.GetC() ); - peek = wxChar( m_in.Peek() ); - } - - // Searching the identifier - ident = SearchIdent( macro ); - } - return ident; + Ident ident = ID_ERROR; + + if (!m_in.Eof()) { + wxString macro; + m_in.GetC(); + + wxChar peek(m_in.Peek()); + while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT('#') && peek != wxT('$') && + ((peek >= wxT('a') && peek <= wxT('z')) || (peek >= wxT('A') && peek <= wxT('Z')) || + (peek >= wxT('0') && peek <= wxT('9')))) { + macro += wxChar(m_in.GetC()); + peek = wxChar(m_in.Peek()); + } + + // Searching the identifier + ident = SearchIdent(macro); + } + return ident; } -wxString TemplateParser::ParsePropertyName( wxString* child ) +wxString TemplateParser::ParsePropertyName(wxString* child) { - wxString propname; + wxString propname; - // children of parent properties can be referred to with a '/' like "$parent/child" - bool foundSlash = false; - // property names used in templates may be encapsulated by curly brackets (e.g. ${name}) so they + // children of parent properties can be referred to with a '/' like "$parent/child" + bool foundSlash = false; + // property names used in templates may be encapsulated by curly brackets (e.g. ${name}) so they // can be surrounded by the template content without any white spaces now. - bool foundLeftCurlyBracket = false; - bool saveChild = (child != nullptr); - - if (!m_in.Eof()) - { - m_in.GetC(); - - wxChar peek( m_in.Peek() ); - while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT('#') && peek != wxT('$') - && ( (peek >= wxT('a') && peek <= wxT('z') ) || - (peek >= wxT('A') && peek <= wxT('Z') ) || - (peek >= wxT('0') && peek <= wxT('9') ) || - (peek >= wxT('{') && peek <= wxT('}') ) || - peek == wxT('_') || peek == wxT('/') ) ) - { - if ( foundSlash ) - { - if ( saveChild ) - { - (*child) << wxChar( m_in.GetC() ); - } - } - else - { - wxChar next = wxChar( m_in.GetC() ); - if ( wxT('{') == next ) - { - foundLeftCurlyBracket = true; - } - else if ( ( wxT('}') == next) && (foundLeftCurlyBracket == true) ) - { - break; - } - else if ( wxT('/') == next ) - { - foundSlash = true; - } - else - { - propname << next; - } - } - peek = wxChar( m_in.Peek() ); - } - } - return propname; + bool foundLeftCurlyBracket = false; + bool saveChild = (child != nullptr); + + if (!m_in.Eof()) { + m_in.GetC(); + + wxChar peek(m_in.Peek()); + while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT('#') && peek != wxT('$') && + ((peek >= wxT('a') && peek <= wxT('z')) || (peek >= wxT('A') && peek <= wxT('Z')) || + (peek >= wxT('0') && peek <= wxT('9')) || (peek >= wxT('{') && peek <= wxT('}')) || peek == wxT('_') || + peek == wxT('/'))) { + if (foundSlash) { + if (saveChild) { + (*child) << wxChar(m_in.GetC()); + } + } else { + wxChar next = wxChar(m_in.GetC()); + if (wxT('{') == next) { + foundLeftCurlyBracket = true; + } else if ((wxT('}') == next) && (foundLeftCurlyBracket == true)) { + break; + } else if (wxT('/') == next) { + foundSlash = true; + } else { + propname << next; + } + } + peek = wxChar(m_in.Peek()); + } + } + return propname; } bool TemplateParser::ParseProperty() { - wxString childName; - wxString propname = ParsePropertyName( &childName ); - - PProperty property = m_obj->GetProperty(propname); - if (!property) - { - wxLogError( wxT("The property '%s' does not exist for objects of class '%s'"), propname, m_obj->GetClassName() ); - return true; - } - - if ( childName.empty() ) - { - wxString code = PropertyToCode(property); - m_out << code; - } - else - { - m_out << property->GetChildFromParent( childName ); - } - - // LogDebug("parsing property %s",propname); - - return true; + wxString childName; + wxString propname = ParsePropertyName(&childName); + + PProperty property = m_obj->GetProperty(propname); + if (!property) { + wxLogError(wxT("The property '%s' does not exist for objects of class '%s'"), propname, m_obj->GetClassName()); + return true; + } + + if (childName.empty()) { + wxString code = PropertyToCode(property); + m_out << code; + } else { + m_out << property->GetChildFromParent(childName); + } + + // LogDebug("parsing property %s",propname); + + return true; } bool TemplateParser::ParseText() { - wxString text; - int sspace = 0; - - if ( !m_in.Eof() ) - { - wxChar peek( m_in.Peek() ); - - while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT('#') && peek != wxT('$') ) - { - wxChar c( m_in.GetC() ); - if (c == wxT('@') ) - { - c = wxChar(m_in.GetC()); - if(c == wxT(' '))sspace++; - } - - text << c; - peek = wxChar( m_in.Peek() ); - } - - if ( text.find_first_not_of( wxT("\r\n\t ") ) != text.npos ) - { - // If text is all whitespace, ignore it - m_out << text; - } - else - { - // ... but allow all '@ ' instances - wxString spaces(wxT(' '), sspace); - m_out << spaces; - } - } - - //LogDebug(wxT("Parsed Text: %s"),text); - return true; + wxString text; + int sspace = 0; + + if (!m_in.Eof()) { + wxChar peek(m_in.Peek()); + + while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT('#') && peek != wxT('$')) { + wxChar c(m_in.GetC()); + if (c == wxT('@')) { + c = wxChar(m_in.GetC()); + if (c == wxT(' ')) + sspace++; + } + + text << c; + peek = wxChar(m_in.Peek()); + } + + if (text.find_first_not_of(wxT("\r\n\t ")) != text.npos) { + // If text is all whitespace, ignore it + m_out << text; + } else { + // ... but allow all '@ ' instances + wxString spaces(wxT(' '), sspace); + m_out << spaces; + } + } + + // LogDebug(wxT("Parsed Text: %s"),text); + return true; } bool TemplateParser::ParseInnerTemplate() { - return true; + return true; } PObjectBase TemplateParser::GetWxParent() { - PObjectBase wxparent, prev_wxparent; - - std::vector< PObjectBase > candidates; - candidates.push_back( m_obj->FindNearAncestor( wxT("container") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("notebook") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("splitter") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("flatnotebook") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("listbook") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("choicebook") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("simplebook") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("auinotebook") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("toolbar") ) ); - candidates.push_back( m_obj->FindNearAncestor( wxT("wizardpagesimple") ) ); - candidates.push_back( m_obj->FindNearAncestorByBaseClass( wxT("wxStaticBoxSizer") ) ); - - for ( size_t i = 0; i < candidates.size(); i++ ) - { - if ( !wxparent ) - { - wxparent = candidates[i]; - } - else - { - if ( candidates[i] && candidates[i]->Deep() > wxparent->Deep() ) - { - wxparent = candidates[i]; - } - } - - if (wxparent && wxparent->GetClassName() == wxT("wxStaticBoxSizer") && - wxparent->GetProperty("parent")->GetValueAsInteger() == 0) { - wxparent = prev_wxparent; - } - prev_wxparent = wxparent; - } - - return wxparent; + PObjectBase wxparent, prev_wxparent; + + std::vector candidates; + candidates.push_back(m_obj->FindNearAncestor(wxT("container"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("notebook"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("splitter"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("flatnotebook"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("listbook"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("choicebook"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("simplebook"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("auinotebook"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("toolbar"))); + candidates.push_back(m_obj->FindNearAncestor(wxT("wizardpagesimple"))); + candidates.push_back(m_obj->FindNearAncestorByBaseClass(wxT("wxStaticBoxSizer"))); + + for (size_t i = 0; i < candidates.size(); i++) { + if (!wxparent) { + wxparent = candidates[i]; + } else { + if (candidates[i] && candidates[i]->Deep() > wxparent->Deep()) { + wxparent = candidates[i]; + } + } + + if ( + wxparent && wxparent->GetClassName() == wxT("wxStaticBoxSizer") && + wxparent->GetProperty("parent")->GetValueAsInteger() == 0) { + wxparent = prev_wxparent; + } + prev_wxparent = wxparent; + } + + return wxparent; } bool TemplateParser::ParseWxParent() { - PObjectBase wxparent( GetWxParent() ); - - if ( wxparent ) - { - PProperty property = GetRelatedProperty( wxparent ); - //m_out << PropertyToCode(property); - const auto& classname = wxparent->GetClassName(); - if (classname == wxT("wxStaticBoxSizer")) - { - // We got a wxStaticBoxSizer as parent, use the special PT_WXPARENT_SB type to - // generate code to get its static box + PObjectBase wxparent(GetWxParent()); + + if (wxparent) { + PProperty property = GetRelatedProperty(wxparent); + // m_out << PropertyToCode(property); + const auto& classname = wxparent->GetClassName(); + if (classname == wxT("wxStaticBoxSizer")) { + // We got a wxStaticBoxSizer as parent, use the special PT_WXPARENT_SB type to + // generate code to get its static box m_out << ValueToCode(PT_WXPARENT_SB, property->GetValue()); - } - else if (classname == wxT("wxCollapsiblePane")) - { - // We got a wxCollapsiblePane as parent, use the special PT_WXPARENT_CP type to - // generate code to get its pane - m_out << ValueToCode(PT_WXPARENT_CP, property->GetValue()); - } - else - { - m_out << ValueToCode(PT_WXPARENT, property->GetValue()); - } - } - else - { - ignore_whitespaces(); - ParsePropertyName(); - m_out << RootWxParentToCode(); - } - - return true; + } else if (classname == wxT("wxCollapsiblePane")) { + // We got a wxCollapsiblePane as parent, use the special PT_WXPARENT_CP type to + // generate code to get its pane + m_out << ValueToCode(PT_WXPARENT_CP, property->GetValue()); + } else { + m_out << ValueToCode(PT_WXPARENT, property->GetValue()); + } + } else { + ignore_whitespaces(); + ParsePropertyName(); + m_out << RootWxParentToCode(); + } + + return true; } bool TemplateParser::ParseForm() { - PObjectBase form (m_obj); - PObjectBase parent(form->GetParent()); - - if ( !parent ) - { - return false; - } - - // form is a form when grandparent is null - PObjectBase grandparent = parent->GetParent(); - while ( grandparent ) - { - form = parent; - parent = grandparent; - grandparent = grandparent->GetParent(); - } - - PProperty property = GetRelatedProperty( form ); - m_out << PropertyToCode( property ); - - return true; + PObjectBase form(m_obj); + PObjectBase parent(form->GetParent()); + + if (!parent) { + return false; + } + + // form is a form when grandparent is null + PObjectBase grandparent = parent->GetParent(); + while (grandparent) { + form = parent; + parent = grandparent; + grandparent = grandparent->GetParent(); + } + + PProperty property = GetRelatedProperty(form); + m_out << PropertyToCode(property); + + return true; } void TemplateParser::ParseLuaTable() { - const auto& project = AppData()->GetProjectData(); - const auto& table = project->GetProperty(wxT("ui_table")); - if (table) - { - auto strTableName = table->GetValueAsString(); - if (strTableName.empty()) - { - strTableName = wxT("UI"); - } - m_out << strTableName << wxT("."); - } + const auto& project = AppData()->GetProjectData(); + const auto& table = project->GetProperty(wxT("ui_table")); + if (table) { + auto strTableName = table->GetValueAsString(); + if (strTableName.empty()) { + strTableName = wxT("UI"); + } + m_out << strTableName << wxT("."); + } } bool TemplateParser::ParseParent() { - PObjectBase parent(m_obj->GetParent()); - if (parent) - { - PProperty property = GetRelatedProperty( parent ); - m_out << PropertyToCode(property); - } - else - { - m_out << wxT("ERROR"); - } - - return true; + PObjectBase parent(m_obj->GetParent()); + if (parent) { + PProperty property = GetRelatedProperty(parent); + m_out << PropertyToCode(property); + } else { + m_out << wxT("ERROR"); + } + + return true; } bool TemplateParser::ParseChild() { - // Get the first child - PObjectBase child(m_obj->GetChild(0)); - - if (child) - { - PProperty property = GetRelatedProperty( child ); - m_out << PropertyToCode(property); - } - else - m_out << RootWxParentToCode(); - - return true; + // Get the first child + PObjectBase child(m_obj->GetChild(0)); + + if (child) { + PProperty property = GetRelatedProperty(child); + m_out << PropertyToCode(property); + } else + m_out << RootWxParentToCode(); + + return true; } -PProperty TemplateParser::GetRelatedProperty( PObjectBase relative ) +PProperty TemplateParser::GetRelatedProperty(PObjectBase relative) { - ignore_whitespaces(); - wxString propname = ParsePropertyName(); - return relative->GetProperty( propname ); + ignore_whitespaces(); + wxString propname = ParsePropertyName(); + return relative->GetProperty(propname); } bool TemplateParser::ParseForEach() { - // Whitespaces at the very start are ignored - ignore_whitespaces(); - - // parsing the property - if (GetNextToken() == TOK_PROPERTY) - { - wxString propname = ParsePropertyName(); - wxString inner_template = ExtractInnerTemplate(); - - PProperty property = m_obj->GetProperty(propname); - wxString propvalue = property->GetValue(); - - // Property value must be an string using ',' as separator. - // The template will be generated nesting as many times as - // tokens were found in the property value. - - if (property->GetType() == PT_INTLIST || property->GetType() == PT_UINTLIST || property->GetType() == PT_INTPAIRLIST || property->GetType() == PT_UINTPAIRLIST) - { - // For doing that we will use wxStringTokenizer class from wxWidgets - wxStringTokenizer tkz( propvalue, wxT(",")); - int i = 0; - while (tkz.HasMoreTokens()) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim(true); - token.Trim(false); - // Pair values get interpreted as adjacent parameters, all supported languages use comma as parameter separator - token.Replace(wxT(":"), wxT(", ")); - - // Parsing the internal template - { - wxString code; - PTemplateParser parser = CreateParser( this, inner_template ); - parser->SetPredefined( token, wxString::Format( wxT("%i"), i++ ) ); - code = parser->ParseTemplate(); - m_out << wxT("\n") << code; - } - } - } - else if (property->GetType() == PT_STRINGLIST) - { - wxArrayString array = property->GetValueAsArrayString(); - for ( unsigned int i = 0 ; i < array.Count(); i++ ) - { - wxString code; - PTemplateParser parser = CreateParser(this,inner_template); - parser->SetPredefined( ValueToCode( PT_WXSTRING_I18N, array[i] ), wxString::Format( wxT("%i"), i ) ); - code = parser->ParseTemplate(); - m_out << wxT("\n") << code; - } - } - else - wxLogError(wxT("Property type not compatible with \"foreach\" macro")); - } - - return true; + // Whitespaces at the very start are ignored + ignore_whitespaces(); + + // parsing the property + if (GetNextToken() == TOK_PROPERTY) { + wxString propname = ParsePropertyName(); + wxString inner_template = ExtractInnerTemplate(); + + PProperty property = m_obj->GetProperty(propname); + wxString propvalue = property->GetValue(); + + // Property value must be an string using ',' as separator. + // The template will be generated nesting as many times as + // tokens were found in the property value. + + if ( + property->GetType() == PT_INTLIST || property->GetType() == PT_UINTLIST || + property->GetType() == PT_INTPAIRLIST || property->GetType() == PT_UINTPAIRLIST) { + // For doing that we will use wxStringTokenizer class from wxWidgets + wxStringTokenizer tkz(propvalue, wxT(",")); + int i = 0; + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + // Pair values get interpreted as adjacent parameters, all supported languages use comma as parameter + // separator + token.Replace(wxT(":"), wxT(", ")); + + // Parsing the internal template + { + wxString code; + PTemplateParser parser = CreateParser(this, inner_template); + parser->SetPredefined(token, wxString::Format(wxT("%i"), i++)); + code = parser->ParseTemplate(); + m_out << wxT("\n") << code; + } + } + } else if (property->GetType() == PT_STRINGLIST) { + wxArrayString array = property->GetValueAsArrayString(); + for (unsigned int i = 0; i < array.Count(); i++) { + wxString code; + PTemplateParser parser = CreateParser(this, inner_template); + parser->SetPredefined(ValueToCode(PT_WXSTRING_I18N, array[i]), wxString::Format(wxT("%i"), i)); + code = parser->ParseTemplate(); + m_out << wxT("\n") << code; + } + } else + wxLogError(wxT("Property type not compatible with \"foreach\" macro")); + } + + return true; } -PProperty TemplateParser::GetProperty( wxString* childName ) +PProperty TemplateParser::GetProperty(wxString* childName) { - PProperty property; + PProperty property; - // Check for #wxparent, #parent, or #child - if ( GetNextToken() == TOK_MACRO ) - { - try - { + // Check for #wxparent, #parent, or #child + if (GetNextToken() == TOK_MACRO) { + try { Ident ident = ParseIdent(); - switch (ident) - { - case ID_WXPARENT: - { - PObjectBase wxparent( GetWxParent() ); - if ( wxparent ) - { - property = GetRelatedProperty( wxparent ); + switch (ident) { + case ID_WXPARENT: { + PObjectBase wxparent(GetWxParent()); + if (wxparent) { + property = GetRelatedProperty(wxparent); } break; } - case ID_PARENT: - { - PObjectBase parent( m_obj->GetParent() ); - if ( parent ) - { - property = GetRelatedProperty( parent ); + case ID_PARENT: { + PObjectBase parent(m_obj->GetParent()); + if (parent) { + property = GetRelatedProperty(parent); } break; } - case ID_CHILD: - { - PObjectBase child( m_obj->GetChild( 0 ) ); - if ( child ) - { - property = GetRelatedProperty( child ); + case ID_CHILD: { + PObjectBase child(m_obj->GetChild(0)); + if (child) { + property = GetRelatedProperty(child); } break; } default: break; } - } - catch( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } - - if ( !property ) - { - if ( GetNextToken() == TOK_PROPERTY ) - { - wxString propname = ParsePropertyName( childName ); - property = m_obj->GetProperty( propname ); - } - } - - return property; + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } + + if (!property) { + if (GetNextToken() == TOK_PROPERTY) { + wxString propname = ParsePropertyName(childName); + property = m_obj->GetProperty(propname); + } + } + + return property; } void TemplateParser::ignore_whitespaces() { - wxChar peek( m_in.Peek() ); - while ( peek != static_cast(wxEOF) && !m_in.Eof() && peek == wxT(' ') ) - { - m_in.GetC(); - peek = wxChar( m_in.Peek() ); - } + wxChar peek(m_in.Peek()); + while (peek != static_cast(wxEOF) && !m_in.Eof() && peek == wxT(' ')) { + m_in.GetC(); + peek = wxChar(m_in.Peek()); + } } bool TemplateParser::ParseIfNotNull() { - ignore_whitespaces(); - - // Get the property - wxString childName; - PProperty property( GetProperty( &childName ) ); - if ( !property ) - { - return false; - } - - wxString inner_template = ExtractInnerTemplate(); - - if ( !property->IsNull() ) - { - if ( !childName.empty() ) - { - if ( property->GetChildFromParent( childName ).empty() ) - { - return true; - } - } - - // Generate the code from the block - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - } - - return true; + ignore_whitespaces(); + + // Get the property + wxString childName; + PProperty property(GetProperty(&childName)); + if (!property) { + return false; + } + + wxString inner_template = ExtractInnerTemplate(); + + if (!property->IsNull()) { + if (!childName.empty()) { + if (property->GetChildFromParent(childName).empty()) { + return true; + } + } + + // Generate the code from the block + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + } + + return true; } bool TemplateParser::ParseIfNull() { - ignore_whitespaces(); - - // Get the property - wxString childName; - PProperty property( GetProperty( &childName ) ); - if ( !property ) - { - return false; - } - - wxString inner_template = ExtractInnerTemplate(); - - if ( property->IsNull() ) - { - // Generate the code from the block - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - } - else - { - if ( !childName.empty() ) - { - if ( property->GetChildFromParent( childName ).empty() ) - { - // Generate the code from the block - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - } - } - } - - return true; + ignore_whitespaces(); + + // Get the property + wxString childName; + PProperty property(GetProperty(&childName)); + if (!property) { + return false; + } + + wxString inner_template = ExtractInnerTemplate(); + + if (property->IsNull()) { + // Generate the code from the block + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + } else { + if (!childName.empty()) { + if (property->GetChildFromParent(childName).empty()) { + // Generate the code from the block + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + } + } + } + + return true; } wxString TemplateParser::ExtractLiteral() { - wxString os; - - wxChar c; - - // Whitespaces at the very start are ignored - ignore_whitespaces(); - - c = wxChar(m_in.GetC()); // Initial quotation mark - - if ( c == wxT('"') ) - { - bool end = false; - // Beginning the template extraction - while (!end && !m_in.Eof() && m_in.Peek() != static_cast(wxEOF) ) - { - c = wxChar(m_in.GetC()); // obtaining one char - - // Checking for a possible closing quotation mark - if ( c == wxT('"') ) - { - if ( m_in.Peek() == wxT('"') ) // Char (") denoted as ("") - { - m_in.GetC(); // Second quotation mark is ignored - os << wxT('"'); - } - else // Closing - { - end = true; - - // All the following chars are ignored up to an space char, - // so we can avoid errors like "hello"world" -> "hello" - wxChar peek( m_in.Peek() ); - while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT(' ') ) - { - m_in.GetC(); - peek = wxChar( m_in.Peek() ); - } - } - } - else // one char from literal (N.B. ??) - os << c; - } - } - - return os; + wxString os; + + wxChar c; + + // Whitespaces at the very start are ignored + ignore_whitespaces(); + + c = wxChar(m_in.GetC()); // Initial quotation mark + + if (c == wxT('"')) { + bool end = false; + // Beginning the template extraction + while (!end && !m_in.Eof() && m_in.Peek() != static_cast(wxEOF)) { + c = wxChar(m_in.GetC()); // obtaining one char + + // Checking for a possible closing quotation mark + if (c == wxT('"')) { + if (m_in.Peek() == wxT('"')) // Char (") denoted as ("") + { + m_in.GetC(); // Second quotation mark is ignored + os << wxT('"'); + } else // Closing + { + end = true; + + // All the following chars are ignored up to an space char, + // so we can avoid errors like "hello"world" -> "hello" + wxChar peek(m_in.Peek()); + while (peek != static_cast(wxEOF) && !m_in.Eof() && peek != wxT(' ')) { + m_in.GetC(); + peek = wxChar(m_in.Peek()); + } + } + } else // one char from literal (N.B. ??) + os << c; + } + } + + return os; } bool TemplateParser::ParseIfEqual() { - // ignore leading whitespace - ignore_whitespaces(); - - // Get the property - wxString childName; - PProperty property( GetProperty( &childName ) ); - if ( property ) - { - // Get the value to compare to - wxString value = ExtractLiteral(); - - // Get the template to generate if comparison is true - wxString inner_template = ExtractInnerTemplate(); - - // Get the value of the property - wxString propValue; - if ( childName.empty() ) - { - propValue = property->GetValue(); - } - else - { - propValue = property->GetChildFromParent( childName ); - } - - // Compare - //if ( propValue == value ) - if ( IsEqual( propValue, value ) ) - { - // Generate the code - PTemplateParser parser = CreateParser(this,inner_template); - m_out << parser->ParseTemplate(); - return true; - } - } - return false; + // ignore leading whitespace + ignore_whitespaces(); + + // Get the property + wxString childName; + PProperty property(GetProperty(&childName)); + if (property) { + // Get the value to compare to + wxString value = ExtractLiteral(); + + // Get the template to generate if comparison is true + wxString inner_template = ExtractInnerTemplate(); + + // Get the value of the property + wxString propValue; + if (childName.empty()) { + propValue = property->GetValue(); + } else { + propValue = property->GetChildFromParent(childName); + } + + // Compare + // if ( propValue == value ) + if (IsEqual(propValue, value)) { + // Generate the code + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; + } + } + return false; } bool TemplateParser::ParseIfNotEqual() { - // ignore leading whitespace - ignore_whitespaces(); - - // Get the property - wxString childName; - PProperty property( GetProperty( &childName ) ); - if ( property ) - { - // Get the value to compare to - wxString value = ExtractLiteral(); - - // Get the template to generate if comparison is false - wxString inner_template = ExtractInnerTemplate(); - - // Get the value of the property - wxString propValue; - if ( childName.empty() ) - { - propValue = property->GetValue(); - } - else - { - propValue = property->GetChildFromParent( childName ); - } - - // Compare - if ( propValue != value ) - { - // Generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate();; - return true; - } - } - - return false; + // ignore leading whitespace + ignore_whitespaces(); + + // Get the property + wxString childName; + PProperty property(GetProperty(&childName)); + if (property) { + // Get the value to compare to + wxString value = ExtractLiteral(); + + // Get the template to generate if comparison is false + wxString inner_template = ExtractInnerTemplate(); + + // Get the value of the property + wxString propValue; + if (childName.empty()) { + propValue = property->GetValue(); + } else { + propValue = property->GetChildFromParent(childName); + } + + // Compare + if (propValue != value) { + // Generate the code + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + ; + return true; + } + } + + return false; } bool TemplateParser::ParseIfParentTypeEqual() { - PObjectBase parent( m_obj->GetParent() ); + PObjectBase parent(m_obj->GetParent()); // get examined type name wxString type = ExtractLiteral(); @@ -847,12 +745,11 @@ bool TemplateParser::ParseIfParentTypeEqual() wxString inner_template = ExtractInnerTemplate(); // compare give type name with type of the wx parent object - if( parent && IsEqual( parent->GetObjectTypeName(), type) ) - { - // generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - return true; + if (parent && IsEqual(parent->GetObjectTypeName(), type)) { + // generate the code + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; } return false; @@ -860,7 +757,7 @@ bool TemplateParser::ParseIfParentTypeEqual() bool TemplateParser::ParseIfParentTypeNotEqual() { - PObjectBase parent( m_obj->GetParent() ); + PObjectBase parent(m_obj->GetParent()); // get examined type name wxString type = ExtractLiteral(); @@ -869,12 +766,11 @@ bool TemplateParser::ParseIfParentTypeNotEqual() wxString inner_template = ExtractInnerTemplate(); // compare give type name with type of the wx parent object - if( parent && ! IsEqual( parent->GetObjectTypeName(), type) ) - { - // generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - return true; + if (parent && !IsEqual(parent->GetObjectTypeName(), type)) { + // generate the code + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; } return false; @@ -882,7 +778,7 @@ bool TemplateParser::ParseIfParentTypeNotEqual() bool TemplateParser::ParseIfParentClassEqual() { - PObjectBase parent( m_obj->GetParent() ); + PObjectBase parent(m_obj->GetParent()); // get examined type name wxString type = ExtractLiteral(); @@ -891,12 +787,11 @@ bool TemplateParser::ParseIfParentClassEqual() wxString inner_template = ExtractInnerTemplate(); // compare give type name with type of the wx parent object - if( parent && IsEqual( parent->GetClassName(), type) ) - { - // generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - return true; + if (parent && IsEqual(parent->GetClassName(), type)) { + // generate the code + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; } return false; @@ -904,7 +799,7 @@ bool TemplateParser::ParseIfParentClassEqual() bool TemplateParser::ParseIfParentClassNotEqual() { - PObjectBase parent( m_obj->GetParent() ); + PObjectBase parent(m_obj->GetParent()); // get examined type name wxString type = ExtractLiteral(); @@ -913,12 +808,11 @@ bool TemplateParser::ParseIfParentClassNotEqual() wxString inner_template = ExtractInnerTemplate(); // compare give type name with type of the wx parent object - if( parent && ! IsEqual( parent->GetClassName(), type) ) - { - // generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - return true; + if (parent && !IsEqual(parent->GetClassName(), type)) { + // generate the code + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; } return false; @@ -933,13 +827,12 @@ bool TemplateParser::ParseIfTypeEqual() wxString inner_template = ExtractInnerTemplate(); // compare give type name with type of the wx parent object - if( IsEqual( m_obj->GetObjectTypeName(), type) ) - { + if (IsEqual(m_obj->GetObjectTypeName(), type)) { // generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - return true; - } + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; + } return false; } @@ -953,284 +846,256 @@ bool TemplateParser::ParseIfTypeNotEqual() wxString inner_template = ExtractInnerTemplate(); // compare give type name with type of the wx parent object - if( !IsEqual( m_obj->GetObjectTypeName(), type) ) - { + if (!IsEqual(m_obj->GetObjectTypeName(), type)) { // generate the code - PTemplateParser parser = CreateParser( this, inner_template ); - m_out << parser->ParseTemplate(); - return true; - } + PTemplateParser parser = CreateParser(this, inner_template); + m_out << parser->ParseTemplate(); + return true; + } return false; } TemplateParser::Ident TemplateParser::SearchIdent(wxString ident) { - // LogDebug("Parsing command %s",ident); - - if (ident == wxT("wxparent") ) - return ID_WXPARENT; - else if (ident == wxT("ifnotnull") ) - return ID_IFNOTNULL; - else if (ident == wxT("ifnull") ) - return ID_IFNULL; - else if (ident == wxT("foreach") ) - return ID_FOREACH; - else if (ident == wxT("pred") ) - return ID_PREDEFINED; - else if (ident == wxT("npred") ) - return ID_PREDEFINED_INDEX; - else if (ident == wxT("child") ) - return ID_CHILD; - else if (ident == wxT("parent") ) - return ID_PARENT; - else if (ident == wxT("nl") ) - return ID_NEWLINE; - else if (ident == wxT("ifequal") ) - return ID_IFEQUAL; - else if (ident == wxT("ifnotequal") ) - return ID_IFNOTEQUAL; - else if (ident == wxT("ifparenttypeequal") ) - return ID_IFPARENTTYPEEQUAL; - else if (ident == wxT("ifparentclassequal") ) - return ID_IFPARENTCLASSEQUAL; - else if (ident == wxT("ifparenttypenotequal") ) - return ID_IFPARENTTYPENOTEQUAL; - else if (ident == wxT("ifparentclassnotequal") ) - return ID_IFPARENTCLASSNOTEQUAL; - else if (ident == wxT("append") ) - return ID_APPEND; - else if (ident == wxT("class") ) - return ID_CLASS; - else if (ident == wxT("form") || ident == wxT("wizard")) - return ID_FORM; - else if (ident == wxT("indent") ) - return ID_INDENT; - else if (ident == wxT("unindent") ) - return ID_UNINDENT; - else if (ident == wxT("iftypeequal") ) - return ID_IFTYPEEQUAL; - else if (ident == wxT("iftypenotequal") ) - return ID_IFTYPENOTEQUAL; - else if(ident == wxT("utbl")) - return ID_UTBL; - else - THROW_WXFBEX( wxString::Format( wxT("Unknown macro: \"%s\""), ident ) ); + // LogDebug("Parsing command %s",ident); + + if (ident == wxT("wxparent")) + return ID_WXPARENT; + else if (ident == wxT("ifnotnull")) + return ID_IFNOTNULL; + else if (ident == wxT("ifnull")) + return ID_IFNULL; + else if (ident == wxT("foreach")) + return ID_FOREACH; + else if (ident == wxT("pred")) + return ID_PREDEFINED; + else if (ident == wxT("npred")) + return ID_PREDEFINED_INDEX; + else if (ident == wxT("child")) + return ID_CHILD; + else if (ident == wxT("parent")) + return ID_PARENT; + else if (ident == wxT("nl")) + return ID_NEWLINE; + else if (ident == wxT("ifequal")) + return ID_IFEQUAL; + else if (ident == wxT("ifnotequal")) + return ID_IFNOTEQUAL; + else if (ident == wxT("ifparenttypeequal")) + return ID_IFPARENTTYPEEQUAL; + else if (ident == wxT("ifparentclassequal")) + return ID_IFPARENTCLASSEQUAL; + else if (ident == wxT("ifparenttypenotequal")) + return ID_IFPARENTTYPENOTEQUAL; + else if (ident == wxT("ifparentclassnotequal")) + return ID_IFPARENTCLASSNOTEQUAL; + else if (ident == wxT("append")) + return ID_APPEND; + else if (ident == wxT("class")) + return ID_CLASS; + else if (ident == wxT("form") || ident == wxT("wizard")) + return ID_FORM; + else if (ident == wxT("indent")) + return ID_INDENT; + else if (ident == wxT("unindent")) + return ID_UNINDENT; + else if (ident == wxT("iftypeequal")) + return ID_IFTYPEEQUAL; + else if (ident == wxT("iftypenotequal")) + return ID_IFTYPENOTEQUAL; + else if (ident == wxT("utbl")) + return ID_UTBL; + else + THROW_WXFBEX(wxString::Format(wxT("Unknown macro: \"%s\""), ident)); } wxString TemplateParser::ParseTemplate() { - try - { - while (!m_in.Eof()) - { + try { + while (!m_in.Eof()) { Token token = GetNextToken(); - switch (token) - { - case TOK_MACRO: - ParseMacro(); - break; - case TOK_PROPERTY: - ParseProperty(); - break; - case TOK_TEXT: - ParseText(); - break; - default: - return wxEmptyString; + switch (token) { + case TOK_MACRO: + ParseMacro(); + break; + case TOK_PROPERTY: + ParseProperty(); + break; + case TOK_TEXT: + ParseText(); + break; + default: + return wxEmptyString; } } - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); + } catch (wxFBException& ex) { + wxLogError(ex.what()); } - return m_out; + return m_out; } /** -* Obtaining the template enclosed between '@{' y '@}'. -* Note: whitespaces at the very start will be ignored. -*/ + * Obtaining the template enclosed between '@{' y '@}'. + * Note: whitespaces at the very start will be ignored. + */ wxString TemplateParser::ExtractInnerTemplate() { - // bool error = false; - wxString os; - - wxChar c1, c2; - - // Initial whitespaces are ignored - ignore_whitespaces(); - - // The two following characters must be '@{' - c1 = wxChar(m_in.GetC()); - c2 = wxChar(m_in.GetC()); - - if (c1 == wxT('@') && c2 == wxT('{') ) - { - ignore_whitespaces(); - - int level = 1; - bool end = false; - // Beginning with the template extraction - while ( !end && !m_in.Eof() && m_in.Peek() != static_cast(wxEOF) ) - { - c1 = wxChar(m_in.GetC()); - - // Checking if there are initial or closing braces - if (c1 == wxT('@') ) - { - c2 = wxChar(m_in.GetC()); - - if (c2 == wxT('}') ) - { - level--; - if (level == 0) - end = true; - else - { - // There isn't a final closing brace, so that we put in - // the chars and continue - os << c1; - os << c2; - } - } - else - { - os << c1; - os << c2; - - if (c2 == wxT('{') ) - level++; - } - } - else - os << c1; - } - } - - return os; + // bool error = false; + wxString os; + + wxChar c1, c2; + + // Initial whitespaces are ignored + ignore_whitespaces(); + + // The two following characters must be '@{' + c1 = wxChar(m_in.GetC()); + c2 = wxChar(m_in.GetC()); + + if (c1 == wxT('@') && c2 == wxT('{')) { + ignore_whitespaces(); + + int level = 1; + bool end = false; + // Beginning with the template extraction + while (!end && !m_in.Eof() && m_in.Peek() != static_cast(wxEOF)) { + c1 = wxChar(m_in.GetC()); + + // Checking if there are initial or closing braces + if (c1 == wxT('@')) { + c2 = wxChar(m_in.GetC()); + + if (c2 == wxT('}')) { + level--; + if (level == 0) + end = true; + else { + // There isn't a final closing brace, so that we put in + // the chars and continue + os << c1; + os << c2; + } + } else { + os << c1; + os << c2; + + if (c2 == wxT('{')) + level++; + } + } else + os << c1; + } + } + + return os; } bool TemplateParser::ParsePred() { - if (!m_pred.empty()) - { - m_out << m_pred; - } + if (!m_pred.empty()) { + m_out << m_pred; + } - return true; + return true; } bool TemplateParser::ParseNPred() { - if (!m_npred.empty()) - { - m_out << m_npred; - } + if (!m_npred.empty()) { + m_out << m_npred; + } - return true; + return true; } bool TemplateParser::ParseNewLine() { - m_out << wxT('\n'); - // append custom indentation define in code templates (will be replace by '\t' in code writer) - for( int i = 0; i < m_indent; i++ ) m_out << wxT("%TAB%"); + m_out << wxT('\n'); + // append custom indentation define in code templates (will be replace by '\t' in code writer) + for (int i = 0; i < m_indent; i++) m_out << wxT("%TAB%"); - return true; + return true; } void TemplateParser::ParseAppend() { - ignore_whitespaces(); - //NOTE: This macro is usually used to attach some postfix to a name to create another unique name. - // If the name contains array brackets the resulting name is not a valid identifier. - // You cannot simply replace all brackets, depending on how many times #append is used in a template - // there might be preceding brackets that need to be preserved. Here we assume #append is used directly - // after an array name to attach something to it, we have to search for the last delimiter or start of line - // and replace all brackets after this one, not before. - if (!m_out.empty() && m_out.GetChar(m_out.size() - 1) == wxT(']')) - { - auto pos = m_out.find_last_of(wxT(" \t\r\n.>")); - if (pos == wxString::npos) - { - pos = 0; - } - else - { - ++pos; - } - for (pos = m_out.find_first_of(wxT("[]"), pos); pos != wxString::npos; pos = m_out.find_first_of(wxT("[]"), pos + 1)) - { - m_out[pos] = wxT('_'); - } - } + ignore_whitespaces(); + // NOTE: This macro is usually used to attach some postfix to a name to create another unique name. + // If the name contains array brackets the resulting name is not a valid identifier. + // You cannot simply replace all brackets, depending on how many times #append is used in a template + // there might be preceding brackets that need to be preserved. Here we assume #append is used directly + // after an array name to attach something to it, we have to search for the last delimiter or start of line + // and replace all brackets after this one, not before. + if (!m_out.empty() && m_out.GetChar(m_out.size() - 1) == wxT(']')) { + auto pos = m_out.find_last_of(wxT(" \t\r\n.>")); + if (pos == wxString::npos) { + pos = 0; + } else { + ++pos; + } + for (pos = m_out.find_first_of(wxT("[]"), pos); pos != wxString::npos; + pos = m_out.find_first_of(wxT("[]"), pos + 1)) { + m_out[pos] = wxT('_'); + } + } } void TemplateParser::ParseClass() { - PProperty subclass_prop = m_obj->GetProperty( wxT("subclass") ); - if ( subclass_prop ) - { - wxString subclass = subclass_prop->GetChildFromParent( wxT("name") ); - if ( !subclass.empty() ) - { - m_out << subclass; - return; - } - } - - m_out << ValueToCode( PT_CLASS, m_obj->GetClassName() ); + PProperty subclass_prop = m_obj->GetProperty(wxT("subclass")); + if (subclass_prop) { + wxString subclass = subclass_prop->GetChildFromParent(wxT("name")); + if (!subclass.empty()) { + m_out << subclass; + return; + } + } + + m_out << ValueToCode(PT_CLASS, m_obj->GetClassName()); } void TemplateParser::ParseIndent() { - m_indent++; + m_indent++; } void TemplateParser::ParseUnindent() { - m_indent--; + m_indent--; - if( m_indent < 0 ) m_indent = 0; + if (m_indent < 0) + m_indent = 0; } wxString TemplateParser::PropertyToCode(PProperty property) { - if ( property ) - { - return ValueToCode(property->GetType(), property->GetValue()); - } - else - { - return wxEmptyString; - } + if (property) { + return ValueToCode(property->GetType(), property->GetValue()); + } else { + return wxEmptyString; + } } bool TemplateParser::IsEqual(const wxString& value, const wxString& set) { - bool contains = false; - - wxStringTokenizer tokens( set, wxT("||") ); - while ( tokens.HasMoreTokens() ) - { - wxString token = tokens.GetNextToken(); - token.Trim().Trim(false); - - if( token == value ) - { - contains = true; - break; - } - } - - return contains; -} + bool contains = false; + wxStringTokenizer tokens(set, wxT("||")); + while (tokens.HasMoreTokens()) { + wxString token = tokens.GetNextToken(); + token.Trim().Trim(false); + if (token == value) { + contains = true; + break; + } + } + + return contains; +} CodeGenerator::~CodeGenerator() = default; @@ -1238,71 +1103,56 @@ CodeGenerator::~CodeGenerator() = default; void CodeGenerator::FindArrayObjects(PObjectBase obj, ArrayItems& arrays, bool skipRoot) { - if (!skipRoot) - { - const auto& propName = obj->GetProperty(wxT("name")); - if (propName) - { - const auto& name = propName->GetValue(); - wxString baseName; - ArrayItem item; - if (ParseArrayName(name, baseName, item)) - { - auto& baseItem = arrays[baseName]; - for (size_t i = 0; i < item.maxIndex.size(); ++i) - { - if (i < baseItem.maxIndex.size()) - { - if (baseItem.maxIndex[i] < item.maxIndex[i]) - { - baseItem.maxIndex[i] = item.maxIndex[i]; - } - } - else - { - baseItem.maxIndex.push_back(item.maxIndex[i]); - } - } - } - } - } - - for (unsigned int i = 0; i < obj->GetChildCount(); ++i) - { - FindArrayObjects(obj->GetChild(i), arrays, false); - } + if (!skipRoot) { + const auto& propName = obj->GetProperty(wxT("name")); + if (propName) { + const auto& name = propName->GetValue(); + wxString baseName; + ArrayItem item; + if (ParseArrayName(name, baseName, item)) { + auto& baseItem = arrays[baseName]; + for (size_t i = 0; i < item.maxIndex.size(); ++i) { + if (i < baseItem.maxIndex.size()) { + if (baseItem.maxIndex[i] < item.maxIndex[i]) { + baseItem.maxIndex[i] = item.maxIndex[i]; + } + } else { + baseItem.maxIndex.push_back(item.maxIndex[i]); + } + } + } + } + } + + for (unsigned int i = 0; i < obj->GetChildCount(); ++i) { FindArrayObjects(obj->GetChild(i), arrays, false); } } bool CodeGenerator::ParseArrayName(const wxString& name, wxString& baseName, ArrayItem& item) { - bool isArray = false; - - auto indexStart = name.find_first_of(wxT('[')); - while (indexStart != wxString::npos) - { - const auto indexEnd = name.find_first_of(wxT(']'), indexStart + 1); - if (indexEnd == wxString::npos) - { - break; - } - - unsigned long indexValue; - if (!name.substr(indexStart + 1, indexEnd - indexStart - 1).ToULong(&indexValue)) - { - return false; - } - - if (!isArray) - { - baseName = name.substr(0, indexStart); - item.maxIndex.clear(); - - isArray = true; - } - item.maxIndex.push_back(indexValue); - - indexStart = name.find_first_of(wxT('['), indexEnd + 1); - } - - return isArray; + bool isArray = false; + + auto indexStart = name.find_first_of(wxT('[')); + while (indexStart != wxString::npos) { + const auto indexEnd = name.find_first_of(wxT(']'), indexStart + 1); + if (indexEnd == wxString::npos) { + break; + } + + unsigned long indexValue; + if (!name.substr(indexStart + 1, indexEnd - indexStart - 1).ToULong(&indexValue)) { + return false; + } + + if (!isArray) { + baseName = name.substr(0, indexStart); + item.maxIndex.clear(); + + isArray = true; + } + item.maxIndex.push_back(indexValue); + + indexStart = name.find_first_of(wxT('['), indexEnd + 1); + } + + return isArray; } diff --git a/src/codegen/codegen.h b/src/codegen/codegen.h index 430b8cb0a..c04cc4b45 100644 --- a/src/codegen/codegen.h +++ b/src/codegen/codegen.h @@ -32,335 +32,330 @@ #ifndef CODEGEN_CODEGEN_H #define CODEGEN_CODEGEN_H -#include "model/types.h" -#include "utils/wxfbdefs.h" - #include #include #include #include +#include "model/types.h" +#include "utils/wxfbdefs.h" + /** * @brief Simple adapter class to provide a wxInputStream interface for TemplateParser - * + * * TemplateParser reads single characters from a wxInputStream and makes heavy use of Peek(). * Single characters can not be read correctly from a wxInputStream if the underlying encoding * uses a variable length or multibyte encoding (e.g. UTF-8). This adapter adds a simple buffer * that allows to Peek() from a wxTextInputStream that correctly processes such encodings. */ -class BufferedTextInputStream { +class BufferedTextInputStream +{ public: - BufferedTextInputStream(wxTextInputStream& text); - - /** - * @return Returns true after an attempt has been made to read past the end of the stream - */ - bool Eof() const; - /** - * @brief Returns the next character of the stream without removing it - * - * @return The next character of the stream or wxEOF - */ - wxChar Peek(); - /** - * @brief Returns the next character of the stream and removes it - * - * @return The next character of the stream or wxEOF - */ - wxChar GetC(); + BufferedTextInputStream(wxTextInputStream& text); + + /** + * @return Returns true after an attempt has been made to read past the end of the stream + */ + bool Eof() const; + /** + * @brief Returns the next character of the stream without removing it + * + * @return The next character of the stream or wxEOF + */ + wxChar Peek(); + /** + * @brief Returns the next character of the stream and removes it + * + * @return The next character of the stream or wxEOF + */ + wxChar GetC(); private: - void readChar(); + void readChar(); private: - wxTextInputStream& m_text; - wxChar m_buffer; + wxTextInputStream& m_text; + wxChar m_buffer; }; /** -* Template notes -* -* The preprocessor macros begin with the character '#'. -* Example: #wxparent $name -* -* The object properties begin with the character '$'. -* Example: $name -* -* The creation of a local variable begins with the character '%' -* Example: int %var = $style; -* -* The '@' character is used to escape the special characters to treat them as text -* Example: @# @$ @@ @% -* -*/ + * Template notes + * + * The preprocessor macros begin with the character '#'. + * Example: #wxparent $name + * + * The object properties begin with the character '$'. + * Example: $name + * + * The creation of a local variable begins with the character '%' + * Example: int %var = $style; + * + * The '@' character is used to escape the special characters to treat them as text + * Example: @# @$ @@ @% + * + */ /** -* Preprocessor directives: -* -* - #wxparent $property -* Used to get the property of the parent of the current object. -* This directive is necessary to generate the parameter "wxWindow* parent" in the constructors of each widget. -* Example: -* $name = new wxButton( #wxparent $name, .... -* -* - #wxchild $property -* Used to get a property of the first child of the current object. -* Used by "sizeritem" in order to add a sizer object. -* -* - #ifnotnull $property @{ .... @} -* Used to generate code as long as the property is not null -* -* - #foreach $property @{ ..... @} -* Used to repeat code for each subproperty of $property, where $property is a comma delimited list. -* The code is contained between '@{' and '@}'. The code will be generated as many times as there are subexpressions -* in the value of the property. Within the brace, access to the subexpression is obtained with the #pred directive, and -* access to index of the subexpression is obtained with #npred. -* Example: -* #foreach $growable_cols -* @{ -* $name->AddGrowableCol(#pred); -* @} -* -* - #pred (see #foreach) -* - #npred (see #foreach) -* -*/ + * Preprocessor directives: + * + * - #wxparent $property + * Used to get the property of the parent of the current object. + * This directive is necessary to generate the parameter "wxWindow* parent" in the constructors of each widget. + * Example: + * $name = new wxButton( #wxparent $name, .... + * + * - #wxchild $property + * Used to get a property of the first child of the current object. + * Used by "sizeritem" in order to add a sizer object. + * + * - #ifnotnull $property @{ .... @} + * Used to generate code as long as the property is not null + * + * - #foreach $property @{ ..... @} + * Used to repeat code for each subproperty of $property, where $property is a comma delimited list. + * The code is contained between '@{' and '@}'. The code will be generated as many times as there are subexpressions + * in the value of the property. Within the brace, access to the subexpression is obtained with the #pred directive, + *and access to index of the subexpression is obtained with #npred. Example: #foreach $growable_cols + * @{ + * $name->AddGrowableCol(#pred); + * @} + * + * - #pred (see #foreach) + * - #npred (see #foreach) + * + */ /** -* Template Parser -*/ + * Template Parser + */ class TemplateParser { private: - PObjectBase m_obj; - wxStringInputStream m_stream; - wxTextInputStream m_text; - BufferedTextInputStream m_in; - wxString m_out; - wxString m_pred; - wxString m_npred; - void ignore_whitespaces(); - - // Current indentation level in the file - int m_indent; - - typedef enum { - TOK_ERROR, - TOK_MACRO, - TOK_TEXT, - TOK_PROPERTY - } Token; - - typedef enum { - ID_ERROR, - ID_WXPARENT, - ID_PARENT, - ID_FORM, - ID_CHILD, - ID_IFNOTNULL, - ID_IFNULL, - ID_FOREACH, - ID_PREDEFINED, // predefined symbol '#pred' - ID_PREDEFINED_INDEX, // #npred - ID_NEWLINE, - ID_IFEQUAL, - ID_IFNOTEQUAL, - ID_IFPARENTTYPEEQUAL, - ID_IFPARENTTYPENOTEQUAL, - ID_IFPARENTCLASSEQUAL, - ID_IFPARENTCLASSNOTEQUAL, - ID_APPEND, - ID_CLASS, - ID_INDENT, - ID_UNINDENT, - ID_IFTYPEEQUAL, - ID_IFTYPENOTEQUAL, - ID_UTBL - } Ident; - - bool IsEqual(const wxString& value, const wxString& set); - - Ident SearchIdent(wxString ident); - Ident ParseIdent(); - - wxString ParsePropertyName(wxString* child = nullptr); - /** - * This routine extracts the source code from a template enclosed between - * the #begin and #end macros, having in mind that they can be nested - */ - wxString ExtractInnerTemplate(); - - /** - * A literal value is an string enclosed between '"' (e.g. "xxx"), - * The " character is represented with "". - */ - wxString ExtractLiteral(); - - /** - * Look up for the following symbol from input and returns the token. - * @return TOK_MACRO when it's followed by a command. - * TOK_PROPERTY when it's followed by a property. - * TOK_TEXT when it's followed by normal text. - */ - Token GetNextToken(); - - - bool ParseInnerTemplate(); - bool ParseWxParent(); - bool ParseParent(); - bool ParseForm(); - bool ParseChild(); - bool ParseForEach(); - bool ParseIfNotNull(); - bool ParseIfNull(); - bool ParseNewLine(); - bool ParseIfEqual(); - bool ParseIfNotEqual(); - bool ParseIfParentTypeEqual(); - bool ParseIfParentTypeNotEqual(); - bool ParseIfParentClassEqual(); - bool ParseIfParentClassNotEqual(); - void ParseAppend(); - void ParseClass(); - void ParseIndent(); - void ParseUnindent(); - bool ParseIfTypeEqual(); - bool ParseIfTypeNotEqual(); - void ParseLuaTable(); - - PProperty GetProperty(wxString* childName = nullptr); - PObjectBase GetWxParent(); - PProperty GetRelatedProperty( PObjectBase relative ); - - /** - * Parse a macro. - */ - bool ParseMacro(); - - /** - * Parse a property. - */ - bool ParseProperty(); - - - /** - * Parse text. - */ - bool ParseText(); - - bool ParsePred(); - bool ParseNPred(); + PObjectBase m_obj; + wxStringInputStream m_stream; + wxTextInputStream m_text; + BufferedTextInputStream m_in; + wxString m_out; + wxString m_pred; + wxString m_npred; + void ignore_whitespaces(); + + // Current indentation level in the file + int m_indent; + + typedef enum { TOK_ERROR, TOK_MACRO, TOK_TEXT, TOK_PROPERTY } Token; + + typedef enum { + ID_ERROR, + ID_WXPARENT, + ID_PARENT, + ID_FORM, + ID_CHILD, + ID_IFNOTNULL, + ID_IFNULL, + ID_FOREACH, + ID_PREDEFINED, // predefined symbol '#pred' + ID_PREDEFINED_INDEX, // #npred + ID_NEWLINE, + ID_IFEQUAL, + ID_IFNOTEQUAL, + ID_IFPARENTTYPEEQUAL, + ID_IFPARENTTYPENOTEQUAL, + ID_IFPARENTCLASSEQUAL, + ID_IFPARENTCLASSNOTEQUAL, + ID_APPEND, + ID_CLASS, + ID_INDENT, + ID_UNINDENT, + ID_IFTYPEEQUAL, + ID_IFTYPENOTEQUAL, + ID_UTBL + } Ident; + + bool IsEqual(const wxString& value, const wxString& set); + + Ident SearchIdent(wxString ident); + Ident ParseIdent(); + + wxString ParsePropertyName(wxString* child = nullptr); + /** + * This routine extracts the source code from a template enclosed between + * the #begin and #end macros, having in mind that they can be nested + */ + wxString ExtractInnerTemplate(); + + /** + * A literal value is an string enclosed between '"' (e.g. "xxx"), + * The " character is represented with "". + */ + wxString ExtractLiteral(); + + /** + * Look up for the following symbol from input and returns the token. + * @return TOK_MACRO when it's followed by a command. + * TOK_PROPERTY when it's followed by a property. + * TOK_TEXT when it's followed by normal text. + */ + Token GetNextToken(); + + + bool ParseInnerTemplate(); + bool ParseWxParent(); + bool ParseParent(); + bool ParseForm(); + bool ParseChild(); + bool ParseForEach(); + bool ParseIfNotNull(); + bool ParseIfNull(); + bool ParseNewLine(); + bool ParseIfEqual(); + bool ParseIfNotEqual(); + bool ParseIfParentTypeEqual(); + bool ParseIfParentTypeNotEqual(); + bool ParseIfParentClassEqual(); + bool ParseIfParentClassNotEqual(); + void ParseAppend(); + void ParseClass(); + void ParseIndent(); + void ParseUnindent(); + bool ParseIfTypeEqual(); + bool ParseIfTypeNotEqual(); + void ParseLuaTable(); + + PProperty GetProperty(wxString* childName = nullptr); + PObjectBase GetWxParent(); + PProperty GetRelatedProperty(PObjectBase relative); + + /** + * Parse a macro. + */ + bool ParseMacro(); + + /** + * Parse a property. + */ + bool ParseProperty(); + + + /** + * Parse text. + */ + bool ParseText(); + + bool ParsePred(); + bool ParseNPred(); public: - TemplateParser( PObjectBase obj, wxString _template); - TemplateParser( const TemplateParser & that, wxString _template ); - /** - * Returns the code for a property value in the language format. - * @note use ValueToCode - */ - wxString PropertyToCode( PProperty property ); - - /** - * This method creates a new parser with the same type that the object - * calling such method. - */ - virtual PTemplateParser CreateParser( const TemplateParser* oldparser, wxString _template ) = 0; - - virtual ~TemplateParser(); - - /** - * Returns the code for a "wxWindow *parent" root attribute' name. - * In C++ it will be the "this" pointer, but in other languages it - * could be named differently. - */ - virtual wxString RootWxParentToCode() = 0; - - /** - * Generates the code from a property value. - */ - virtual wxString ValueToCode(PropertyType type, wxString value) = 0; - - /** - * The "star" function for this class. Analyzes a template, returning the code. - */ - wxString ParseTemplate(); - - /** - * Set the string for the #pred and #npred macros - */ - void SetPredefined( wxString pred, wxString npred ) { m_pred = pred; m_npred = npred; } + TemplateParser(PObjectBase obj, wxString _template); + TemplateParser(const TemplateParser& that, wxString _template); + /** + * Returns the code for a property value in the language format. + * @note use ValueToCode + */ + wxString PropertyToCode(PProperty property); + + /** + * This method creates a new parser with the same type that the object + * calling such method. + */ + virtual PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) = 0; + + virtual ~TemplateParser(); + + /** + * Returns the code for a "wxWindow *parent" root attribute' name. + * In C++ it will be the "this" pointer, but in other languages it + * could be named differently. + */ + virtual wxString RootWxParentToCode() = 0; + + /** + * Generates the code from a property value. + */ + virtual wxString ValueToCode(PropertyType type, wxString value) = 0; + + /** + * The "star" function for this class. Analyzes a template, returning the code. + */ + wxString ParseTemplate(); + + /** + * Set the string for the #pred and #npred macros + */ + void SetPredefined(wxString pred, wxString npred) + { + m_pred = pred; + m_npred = npred; + } }; /** -* Code Generator -* -* This class defines an interface to execute the code generation. -* The algorithms to generate the code are similar from one language to another. -* Examples: -* -* - In C++, we generate the class declarations and then its implementation, -* besides the related #define and #include. -* - In java, it has a similar syntax, but declaration and implementation are -* together in the same file, and it's required one file per class. -* - In XRC format (XML), it's a different way, it's more likely to the -* data model from the application itself. -* -* Given that doesn't exist an "universal" algorithm for generating code, there -* is no choice but to make a different implementation for each language. It's -* possible to reuse the whole code templates system, although, simplifying a lot -* the implementation task for a new language. -*/ + * Code Generator + * + * This class defines an interface to execute the code generation. + * The algorithms to generate the code are similar from one language to another. + * Examples: + * + * - In C++, we generate the class declarations and then its implementation, + * besides the related #define and #include. + * - In java, it has a similar syntax, but declaration and implementation are + * together in the same file, and it's required one file per class. + * - In XRC format (XML), it's a different way, it's more likely to the + * data model from the application itself. + * + * Given that doesn't exist an "universal" algorithm for generating code, there + * is no choice but to make a different implementation for each language. It's + * possible to reuse the whole code templates system, although, simplifying a lot + * the implementation task for a new language. + */ class CodeGenerator { protected: - public: - /** - * Describes the properties and state of an array item - */ - struct ArrayItem - { - /** - * Maximum used index for each array dimension - */ - std::vector maxIndex; - /** - * State if the code generator has already declared this array - */ - bool isDeclared = false; - }; - /** - * Lookup map of array items - * - * key = basename of the array - * value = properties and state of the array - */ - typedef std::map ArrayItems; - - /** - * Virtual destructor. - */ - virtual ~CodeGenerator(); - /** - * Generate the code of the project - */ - virtual bool GenerateCode( PObjectBase project ) = 0; - - /** - * Stores all discovered arrays for the given object and its child objects. - */ - void FindArrayObjects(PObjectBase obj, ArrayItems& arrays, bool skipRoot = false); - - /** - * Parses a name and determines if it is an array. - * - * Returns true if it is an array and extracts the basename and the indexes of the dimensions. - * Returns false if it is not. - */ - bool ParseArrayName(const wxString& name, wxString& baseName, ArrayItem& item); + /** + * Describes the properties and state of an array item + */ + struct ArrayItem { + /** + * Maximum used index for each array dimension + */ + std::vector maxIndex; + /** + * State if the code generator has already declared this array + */ + bool isDeclared = false; + }; + /** + * Lookup map of array items + * + * key = basename of the array + * value = properties and state of the array + */ + typedef std::map ArrayItems; + + /** + * Virtual destructor. + */ + virtual ~CodeGenerator(); + /** + * Generate the code of the project + */ + virtual bool GenerateCode(PObjectBase project) = 0; + + /** + * Stores all discovered arrays for the given object and its child objects. + */ + void FindArrayObjects(PObjectBase obj, ArrayItems& arrays, bool skipRoot = false); + + /** + * Parses a name and determines if it is an array. + * + * Returns true if it is an array and extracts the basename and the indexes of the dimensions. + * Returns false if it is not. + */ + bool ParseArrayName(const wxString& name, wxString& baseName, ArrayItem& item); }; - -#endif // CODEGEN_CODEGEN_H +#endif // CODEGEN_CODEGEN_H diff --git a/src/codegen/codeparser.cpp b/src/codegen/codeparser.cpp index 2cc98e774..9574816b1 100644 --- a/src/codegen/codeparser.cpp +++ b/src/codegen/codeparser.cpp @@ -1,272 +1,287 @@ #include "codeparser.h" -wxString RemoveWhiteSpace(wxString str) { - size_t index = 0; - while (index < str.Len()) { - if (str.GetChar(index) == ' ' || str.GetChar(index) == '\t' || str.GetChar(index) == '\n') { - str.Remove(index, 1); - } else { - index++; - } - } - return str; + +wxString RemoveWhiteSpace(wxString str) +{ + size_t index = 0; + while (index < str.Len()) { + if (str.GetChar(index) == ' ' || str.GetChar(index) == '\t' || str.GetChar(index) == '\n') { + str.Remove(index, 1); + } else { + index++; + } + } + return str; } -void Function::SetHeading(wxString heading) { - m_functionHeading = heading; +void Function::SetHeading(wxString heading) +{ + m_functionHeading = heading; } -void Function::SetContents(wxString contents) { - if (contents.Left(1) == '\n') { - contents.Remove(0, 1); - } - if (contents.Right(1) == '\n') { - contents.Remove(contents.Len() - 1, 1); - } - m_functionContents = contents; +void Function::SetContents(wxString contents) +{ + if (contents.Left(1) == '\n') { + contents.Remove(0, 1); + } + if (contents.Right(1) == '\n') { + contents.Remove(contents.Len() - 1, 1); + } + m_functionContents = contents; } -wxString Function::GetFunction() { - wxString Str; +wxString Function::GetFunction() +{ + wxString Str; - Str << wxT("\n"); - Str << m_documentation; - Str << wxT("\n"); - Str << m_functionHeading; - Str << wxT("\n{\n"); - Str << m_functionContents; - Str << wxT("\n}"); + Str << wxT("\n"); + Str << m_documentation; + Str << wxT("\n"); + Str << m_functionHeading; + Str << wxT("\n{\n"); + Str << m_functionContents; + Str << wxT("\n}"); - return Str; + return Str; } //--------------------------------------------------- // CodeParser //--------------------------------------------------- -void CCodeParser::ParseCFiles(wxString className) { - m_className = className; - wxTextFile headerFile(m_hFile); - wxTextFile sourceFile(m_cFile); - - wxString header; - wxString source; - - // start opening files - if (headerFile.Open()) { - wxString Str; - - Str = headerFile.GetFirstLine(); - while (!(headerFile.Eof())) { - header << Str; - header << wxT('\n'); - Str = headerFile.GetNextLine(); - } - headerFile.Close(); - } else { - header = wxT(""); - } - if (sourceFile.Open()) { - wxString Str; - - source = sourceFile.GetFirstLine(); - while (!(sourceFile.Eof())) { - source << Str; - source << wxT('\n'); - Str = sourceFile.GetNextLine(); - } - sourceFile.Close(); - } else { - source = wxT(""); - } - - // parse the file contents - ParseCCode(header, source); +void CCodeParser::ParseCFiles(wxString className) +{ + m_className = className; + wxTextFile headerFile(m_hFile); + wxTextFile sourceFile(m_cFile); + + wxString header; + wxString source; + + // start opening files + if (headerFile.Open()) { + wxString Str; + + Str = headerFile.GetFirstLine(); + while (!(headerFile.Eof())) { + header << Str; + header << wxT('\n'); + Str = headerFile.GetNextLine(); + } + headerFile.Close(); + } else { + header = wxT(""); + } + if (sourceFile.Open()) { + wxString Str; + + source = sourceFile.GetFirstLine(); + while (!(sourceFile.Eof())) { + source << Str; + source << wxT('\n'); + Str = sourceFile.GetNextLine(); + } + sourceFile.Close(); + } else { + source = wxT(""); + } + + // parse the file contents + ParseCCode(header, source); } -void CCodeParser::ParseCCode(wxString header, wxString source) { - ParseCInclude(header); - ParseCClass(header); +void CCodeParser::ParseCCode(wxString header, wxString source) +{ + ParseCInclude(header); + ParseCClass(header); - ParseSourceFunctions(source); + ParseSourceFunctions(source); } -void CCodeParser::ParseCInclude(wxString code) { - int userIncludeEnd; - m_userInclude = wxT(""); - - // find the beginning of the user include - int userIncludeStart = code.Find(wxT("//// end generated include")); - if (userIncludeStart != wxNOT_FOUND) { - userIncludeStart = code.find(wxT('\n'), userIncludeStart); - if (userIncludeStart != wxNOT_FOUND) { - // find the end of the user include - userIncludeEnd = code.find(wxT("\n/** Implementing "), userIncludeStart); - - if (userIncludeEnd != wxNOT_FOUND) { - userIncludeStart++; - m_userInclude = code.substr(userIncludeStart, userIncludeEnd - userIncludeStart); - } - } - } +void CCodeParser::ParseCInclude(wxString code) +{ + int userIncludeEnd; + m_userInclude = wxT(""); + + // find the beginning of the user include + int userIncludeStart = code.Find(wxT("//// end generated include")); + if (userIncludeStart != wxNOT_FOUND) { + userIncludeStart = code.find(wxT('\n'), userIncludeStart); + if (userIncludeStart != wxNOT_FOUND) { + // find the end of the user include + userIncludeEnd = code.find(wxT("\n/** Implementing "), userIncludeStart); + + if (userIncludeEnd != wxNOT_FOUND) { + userIncludeStart++; + m_userInclude = code.substr(userIncludeStart, userIncludeEnd - userIncludeStart); + } + } + } } -void CCodeParser::ParseCClass(wxString code) { - int startClass = code.Find(wxT("class ") + m_className); - if (startClass != wxNOT_FOUND) { - code = ParseBrackets(code, startClass); - if (startClass != wxNOT_FOUND) { - ParseCUserMembers(code); - } - } +void CCodeParser::ParseCClass(wxString code) +{ + int startClass = code.Find(wxT("class ") + m_className); + if (startClass != wxNOT_FOUND) { + code = ParseBrackets(code, startClass); + if (startClass != wxNOT_FOUND) { + ParseCUserMembers(code); + } + } } -void CCodeParser::ParseCUserMembers(wxString code) { - m_userMemebers = wxT(""); - int userMembersStart = code.Find(wxT("//// end generated class members")); - if (userMembersStart != wxNOT_FOUND) { - userMembersStart = code.find('\n', userMembersStart); - if (userMembersStart == wxNOT_FOUND) { - m_userMemebers = wxT(""); - } else { - userMembersStart++; - if (userMembersStart < (int)code.Len()) { - m_userMemebers = code.Mid(userMembersStart); - } - } - } +void CCodeParser::ParseCUserMembers(wxString code) +{ + m_userMemebers = wxT(""); + int userMembersStart = code.Find(wxT("//// end generated class members")); + if (userMembersStart != wxNOT_FOUND) { + userMembersStart = code.find('\n', userMembersStart); + if (userMembersStart == wxNOT_FOUND) { + m_userMemebers = wxT(""); + } else { + userMembersStart++; + if (userMembersStart < (int)code.Len()) { + m_userMemebers = code.Mid(userMembersStart); + } + } + } } -void CCodeParser::ParseSourceFunctions(wxString code) { - int functionStart = 0; - int functionEnd = 0; - int previousFunctionEnd = 0; - wxString funcName, funcArg; - Function* func; - wxString Str, R; - - int loop = 0; - while (1) { - // find the beginning of the function name - Str = m_className + wxT("::"); - functionStart = code.find(Str, previousFunctionEnd); - if (functionStart == wxNOT_FOUND) { - // Get the last bit of remaining code after the last function in the file - m_trailingCode = code.Mid(previousFunctionEnd); - m_trailingCode.RemoveLast(); - return; - } - // found a function now create a new function class - func = new Function(); - - // find the beginning of the line on which the function name resides - functionStart = code.rfind('\n', functionStart); - func->SetDocumentation(code.Mid(previousFunctionEnd, functionStart - previousFunctionEnd)); - functionStart++; - - functionEnd = code.find('{', functionStart); - wxString heading = code.Mid(functionStart, functionEnd - functionStart); - if (heading.Right(1) == '\n') { - heading.RemoveLast(); - } - func->SetHeading(heading); - - m_functions[std::string(RemoveWhiteSpace(heading).ToUTF8())] = func; - - // find the opening brackets of the function - func->SetContents(ParseBrackets(code, functionStart)); - if (functionStart != wxNOT_FOUND) { - functionEnd = functionStart; - } else { - wxMessageBox(wxT("Brackets Missing in Source File!")); - code.insert(functionEnd + 1, - wxT("//The Following Block is missing a closing bracket\n//and has been " - "set aside by wxFormbuilder\n")); - func->SetContents(wxT("")); - } - - previousFunctionEnd = functionEnd; - if (loop == 100) { - return; - } - loop++; - } +void CCodeParser::ParseSourceFunctions(wxString code) +{ + int functionStart = 0; + int functionEnd = 0; + int previousFunctionEnd = 0; + wxString funcName, funcArg; + Function* func; + wxString Str, R; + + int loop = 0; + while (1) { + // find the beginning of the function name + Str = m_className + wxT("::"); + functionStart = code.find(Str, previousFunctionEnd); + if (functionStart == wxNOT_FOUND) { + // Get the last bit of remaining code after the last function in the file + m_trailingCode = code.Mid(previousFunctionEnd); + m_trailingCode.RemoveLast(); + return; + } + // found a function now create a new function class + func = new Function(); + + // find the beginning of the line on which the function name resides + functionStart = code.rfind('\n', functionStart); + func->SetDocumentation(code.Mid(previousFunctionEnd, functionStart - previousFunctionEnd)); + functionStart++; + + functionEnd = code.find('{', functionStart); + wxString heading = code.Mid(functionStart, functionEnd - functionStart); + if (heading.Right(1) == '\n') { + heading.RemoveLast(); + } + func->SetHeading(heading); + + m_functions[std::string(RemoveWhiteSpace(heading).ToUTF8())] = func; + + // find the opening brackets of the function + func->SetContents(ParseBrackets(code, functionStart)); + if (functionStart != wxNOT_FOUND) { + functionEnd = functionStart; + } else { + wxMessageBox(wxT("Brackets Missing in Source File!")); + code.insert( + functionEnd + 1, wxT("//The Following Block is missing a closing bracket\n//and has been " + "set aside by wxFormbuilder\n")); + func->SetContents(wxT("")); + } + + previousFunctionEnd = functionEnd; + if (loop == 100) { + return; + } + loop++; + } } -wxString CCodeParser::ParseBrackets(wxString code, int& functionStart) { - int openingBrackets = 0; - int closingBrackets = 0; - int index = 0; - wxString Str; - - int functionLength = 0; - index = code.find('{', functionStart); - if (index != wxNOT_FOUND) { - openingBrackets++; - index++; - functionStart = index; - int loop = 0; - while (openingBrackets > closingBrackets) { - index = code.find_first_of(wxT("{}"), index); - if (index == wxNOT_FOUND) { - Str = code.Mid(functionStart, index); - functionStart = index; - return Str; - } - if (code.GetChar(index) == '{') { - index++; - openingBrackets++; - } else { - index++; - closingBrackets++; - } - if (loop == 100) { - return wxT(""); - } - loop++; - } - index--; - functionLength = index - functionStart; - } else { - wxMessageBox(wxT("no brackets found")); - } - Str = code.Mid(functionStart, functionLength); - functionStart = functionStart + functionLength + 1; - return Str; +wxString CCodeParser::ParseBrackets(wxString code, int& functionStart) +{ + int openingBrackets = 0; + int closingBrackets = 0; + int index = 0; + wxString Str; + + int functionLength = 0; + index = code.find('{', functionStart); + if (index != wxNOT_FOUND) { + openingBrackets++; + index++; + functionStart = index; + int loop = 0; + while (openingBrackets > closingBrackets) { + index = code.find_first_of(wxT("{}"), index); + if (index == wxNOT_FOUND) { + Str = code.Mid(functionStart, index); + functionStart = index; + return Str; + } + if (code.GetChar(index) == '{') { + index++; + openingBrackets++; + } else { + index++; + closingBrackets++; + } + if (loop == 100) { + return wxT(""); + } + loop++; + } + index--; + functionLength = index - functionStart; + } else { + wxMessageBox(wxT("no brackets found")); + } + Str = code.Mid(functionStart, functionLength); + functionStart = functionStart + functionLength + 1; + return Str; } -wxString CodeParser::GetFunctionDocumentation(wxString function) { - wxString contents = wxT(""); - Function* func; - - m_functionIter = m_functions.find(std::string(function.ToUTF8())); - if (m_functionIter != m_functions.end()) { - func = m_functionIter->second; - contents = func->GetDocumentation(); - } - return contents; +wxString CodeParser::GetFunctionDocumentation(wxString function) +{ + wxString contents = wxT(""); + Function* func; + + m_functionIter = m_functions.find(std::string(function.ToUTF8())); + if (m_functionIter != m_functions.end()) { + func = m_functionIter->second; + contents = func->GetDocumentation(); + } + return contents; } -wxString CodeParser::GetFunctionContents(wxString function) { - wxString contents = wxT(""); - Function* func; - - m_functionIter = m_functions.find(std::string(RemoveWhiteSpace(function).ToUTF8())); - if (m_functionIter != m_functions.end()) { - func = m_functionIter->second; - contents = func->GetContents(); - m_functions.erase(m_functionIter); - delete func; - } - return contents; +wxString CodeParser::GetFunctionContents(wxString function) +{ + wxString contents = wxT(""); + Function* func; + + m_functionIter = m_functions.find(std::string(RemoveWhiteSpace(function).ToUTF8())); + if (m_functionIter != m_functions.end()) { + func = m_functionIter->second; + contents = func->GetContents(); + m_functions.erase(m_functionIter); + delete func; + } + return contents; } -wxString CodeParser::GetRemainingFunctions() { - wxString functions; - m_functionIter = m_functions.begin(); - while (m_functionIter != m_functions.end()) { - functions += m_functionIter->second->GetFunction(); - m_functionIter++; - } - return functions; +wxString CodeParser::GetRemainingFunctions() +{ + wxString functions; + m_functionIter = m_functions.begin(); + while (m_functionIter != m_functions.end()) { + functions += m_functionIter->second->GetFunction(); + m_functionIter++; + } + return functions; } diff --git a/src/codegen/codeparser.h b/src/codegen/codeparser.h index c4589c071..d75a76aba 100644 --- a/src/codegen/codeparser.h +++ b/src/codegen/codeparser.h @@ -1,62 +1,58 @@ #ifndef CODEGEN_CODEPARSER_H #define CODEGEN_CODEPARSER_H -#include "utils/debug.h" - #include -#include + #include +#include + +#include "utils/debug.h" + wxString RemoveWhiteSpace(wxString str); /** Stores all of the information for all of the parsed functions */ -class Function { +class Function +{ public: - Function() { - } - ~Function() { - } - - /** stores the code contained in the body of the function */ - void SetContents(wxString contents); - - /** stores the whole first line of the function as a single string ex: "void - * fubar::DoSomething(int number)" */ - void SetHeading(wxString heading); - - /** stores any code/documentation located between the previous function and the current function - */ - void SetDocumentation(wxString documentation) { - if (documentation.Left(1) == '\n') { - documentation.Remove(0, 1); - } - if (documentation.Right(1) == '\n') { - documentation.Remove(documentation.Len() - 1, 1); - } - m_documentation = documentation; - } - - /** retrieves the body code */ - wxString GetHeading() { - return m_functionHeading; - } - - /** retrieves the body code */ - wxString GetContents() { - return m_functionContents; - } - - /** retrieves the documentation */ - wxString GetDocumentation() { - return m_documentation; - } - /** retrieves everything including documentation */ - wxString GetFunction(); + Function() {} + ~Function() {} + + /** stores the code contained in the body of the function */ + void SetContents(wxString contents); + + /** stores the whole first line of the function as a single string ex: "void + * fubar::DoSomething(int number)" */ + void SetHeading(wxString heading); + + /** stores any code/documentation located between the previous function and the current function + */ + void SetDocumentation(wxString documentation) + { + if (documentation.Left(1) == '\n') { + documentation.Remove(0, 1); + } + if (documentation.Right(1) == '\n') { + documentation.Remove(documentation.Len() - 1, 1); + } + m_documentation = documentation; + } + + /** retrieves the body code */ + wxString GetHeading() { return m_functionHeading; } + + /** retrieves the body code */ + wxString GetContents() { return m_functionContents; } + + /** retrieves the documentation */ + wxString GetDocumentation() { return m_documentation; } + /** retrieves everything including documentation */ + wxString GetFunction(); protected: - wxString m_functionContents; - wxString m_functionHeading; - wxString m_documentation; + wxString m_functionContents; + wxString m_functionHeading; + wxString m_documentation; }; /** map class mapping Function* to function name */ @@ -64,95 +60,88 @@ using FunctionMap = std::unordered_map; #define funcIterator FunctionMap::iterator /** parses the source and header files for all code added to the generated */ -class CodeParser { +class CodeParser +{ public: - /** constructor */ - CodeParser() { - } + /** constructor */ + CodeParser() {} - ~CodeParser() { - } + ~CodeParser() {} - /////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////// - /** returns all user header include code before the class declaration */ - wxString GetUserIncludes() { - return m_userInclude; - } + /** returns all user header include code before the class declaration */ + wxString GetUserIncludes() { return m_userInclude; } - /** returns user class members */ - wxString GetUserMembers() { - return m_userMemebers; - } + /** returns user class members */ + wxString GetUserMembers() { return m_userMemebers; } - /** returns the Documentation of a function by name */ - wxString GetFunctionDocumentation(wxString function); + /** returns the Documentation of a function by name */ + wxString GetFunctionDocumentation(wxString function); - /** returns the contents of a function by name and then removes it from the list of remaining - * functions */ - wxString GetFunctionContents(wxString function); + /** returns the contents of a function by name and then removes it from the list of remaining + * functions */ + wxString GetFunctionContents(wxString function); - /** returns all ramaining functions including documentation as one string. - this may rearange functions, but should keep them intact */ - wxString GetRemainingFunctions(); + /** returns all ramaining functions including documentation as one string. + this may rearange functions, but should keep them intact */ + wxString GetRemainingFunctions(); - wxString GetTrailingCode() { - return m_trailingCode; - } + wxString GetTrailingCode() { return m_trailingCode; } protected: - wxString m_userInclude; - wxString m_className; - wxString m_userMemebers; - wxString m_trailingCode; + wxString m_userInclude; + wxString m_className; + wxString m_userMemebers; + wxString m_trailingCode; - FunctionMap m_functions; - funcIterator m_functionIter; + FunctionMap m_functions; + funcIterator m_functionIter; }; /** parses the source and header files for all code added to the generated */ -class CCodeParser : public CodeParser { +class CCodeParser : public CodeParser +{ private: - wxString m_hFile; - wxString m_cFile; + wxString m_hFile; + wxString m_cFile; public: - /** constructor */ - CCodeParser() { - } + /** constructor */ + CCodeParser() {} - CCodeParser(wxString headerFileName, wxString sourceFileName) { - m_hFile = headerFileName; - m_cFile = sourceFileName; - } + CCodeParser(wxString headerFileName, wxString sourceFileName) + { + m_hFile = headerFileName; + m_cFile = sourceFileName; + } - ~CCodeParser() { - } + ~CCodeParser() {} - /** c++ Parser */ + /** c++ Parser */ - /** opens the header and source, 'className' is the Inherited class */ - void ParseCFiles(wxString className); + /** opens the header and source, 'className' is the Inherited class */ + void ParseCFiles(wxString className); - /** extracts the contents of the files. take the the entire contents of both files in string - * form */ - void ParseCCode(wxString header, wxString source); + /** extracts the contents of the files. take the the entire contents of both files in string + * form */ + void ParseCCode(wxString header, wxString source); - /** extracts all user header include code before the class declaration */ - void ParseCInclude(wxString code); + /** extracts all user header include code before the class declaration */ + void ParseCInclude(wxString code); - /** extracts the contents of the generated class declaration */ - void ParseCClass(wxString code); + /** extracts the contents of the generated class declaration */ + void ParseCClass(wxString code); - void ParseSourceFunctions(wxString code); + void ParseSourceFunctions(wxString code); - wxString ParseBrackets(wxString code, int& functionStart); + wxString ParseBrackets(wxString code, int& functionStart); - void ParseCUserMembers(wxString code); + void ParseCUserMembers(wxString code); - /***************/ + /***************/ }; /**class PCodeParser : public CodeParser */ -#endif // CODEGEN_CODEPARSER_H +#endif // CODEGEN_CODEPARSER_H diff --git a/src/codegen/codewriter.cpp b/src/codegen/codewriter.cpp index 928602265..b176629c3 100644 --- a/src/codegen/codewriter.cpp +++ b/src/codegen/codewriter.cpp @@ -26,148 +26,127 @@ #include "codewriter.h" -#include "utils/typeconv.h" -#include "utils/wxfbexception.h" +#include +#include #include - #include #include -#include #include +#include -#include -#include +#include "utils/typeconv.h" +#include "utils/wxfbexception.h" -CodeWriter::CodeWriter() -: -m_indent(0), -m_isLineWriting(false), -m_indent_with_spaces(false) +CodeWriter::CodeWriter() : m_indent(0), m_isLineWriting(false), m_indent_with_spaces(false) { } int CodeWriter::GetIndentSize() const { - return 1; + return 1; } void CodeWriter::Indent() { - m_indent += GetIndentSize(); + m_indent += GetIndentSize(); } void CodeWriter::Unindent() { - m_indent -= GetIndentSize(); + m_indent -= GetIndentSize(); - if ( m_indent < 0 ) - { - m_indent = 0; - } + if (m_indent < 0) { + m_indent = 0; + } } bool CodeWriter::IsSingleLine(const wxString& code) const { - return (code.find(wxT("\n")) == wxString::npos); + return (code.find(wxT("\n")) == wxString::npos); } void CodeWriter::ProcessLine(wxString line, bool rawIndents) { - static const wxRegEx reIndent = wxRegEx(wxT("%TAB%\\s*"), wxRE_ADVANCED); - - // Cleanup whitespace - if (!rawIndents) - { - line.Trim(false); - } - line.Trim(); - // Remove and count indentations defined in code templates by #indent and #unindent macros to use own indentation mode - auto templateIndents = reIndent.Replace(&line, wxT("")); - if (templateIndents < 0) - { - templateIndents = 0; - } - - m_indent += templateIndents; - Write(line, rawIndents); - m_indent -= templateIndents; - // To prevent trailing whitespace in case the line was empty write the newline as-is - Write(wxT("\n"), true); - m_isLineWriting = false; + static const wxRegEx reIndent = wxRegEx(wxT("%TAB%\\s*"), wxRE_ADVANCED); + + // Cleanup whitespace + if (!rawIndents) { + line.Trim(false); + } + line.Trim(); + // Remove and count indentations defined in code templates by #indent and #unindent macros to use own indentation + // mode + auto templateIndents = reIndent.Replace(&line, wxT("")); + if (templateIndents < 0) { + templateIndents = 0; + } + + m_indent += templateIndents; + Write(line, rawIndents); + m_indent -= templateIndents; + // To prevent trailing whitespace in case the line was empty write the newline as-is + Write(wxT("\n"), true); + m_isLineWriting = false; } void CodeWriter::WriteLn(const wxString& code, bool rawIndents) { - if (!IsSingleLine(code)) - { - wxStringTokenizer tkz(code, wxT("\n"), wxTOKEN_RET_EMPTY_ALL); - while (tkz.HasMoreTokens()) - { - ProcessLine(tkz.GetNextToken(), rawIndents); - } - } - else - { - ProcessLine(code, rawIndents); - } + if (!IsSingleLine(code)) { + wxStringTokenizer tkz(code, wxT("\n"), wxTOKEN_RET_EMPTY_ALL); + while (tkz.HasMoreTokens()) { ProcessLine(tkz.GetNextToken(), rawIndents); } + } else { + ProcessLine(code, rawIndents); + } } void CodeWriter::Write(const wxString& code, bool rawIndents) { - // Early abort to not produce lines with trailing whitespace - if (code.empty()) - { - return; - } - - if (!m_isLineWriting) - { - if (!rawIndents) - { - for (int i = 0; i < m_indent; ++i) - { - DoWrite(m_indent_with_spaces ? wxT(" ") : wxT("\t")); - } - } - m_isLineWriting = true; - } - - DoWrite(code); + // Early abort to not produce lines with trailing whitespace + if (code.empty()) { + return; + } + + if (!m_isLineWriting) { + if (!rawIndents) { + for (int i = 0; i < m_indent; ++i) { DoWrite(m_indent_with_spaces ? wxT(" ") : wxT("\t")); } + } + m_isLineWriting = true; + } + + DoWrite(code); } -void CodeWriter::SetIndentWithSpaces( bool on ) +void CodeWriter::SetIndentWithSpaces(bool on) { - m_indent_with_spaces = on; + m_indent_with_spaces = on; } -TCCodeWriter::TCCodeWriter() -: -m_tc( 0 ) +TCCodeWriter::TCCodeWriter() : m_tc(0) { } TCCodeWriter::TCCodeWriter(wxStyledTextCtrl* tc) { - SetTextCtrl(tc); + SetTextCtrl(tc); } void TCCodeWriter::SetTextCtrl(wxStyledTextCtrl* tc) { - m_tc = tc; + m_tc = tc; } void TCCodeWriter::DoWrite(const wxString& code) { - if (m_tc) - m_tc->AddText(code); + if (m_tc) + m_tc->AddText(code); } void TCCodeWriter::Clear() { - if ( m_tc ) - m_tc->ClearAll(); //*!* + if (m_tc) + m_tc->ClearAll(); //*!* } StringCodeWriter::StringCodeWriter() @@ -176,99 +155,86 @@ StringCodeWriter::StringCodeWriter() void StringCodeWriter::DoWrite(const wxString& code) { - m_buffer += code; + m_buffer += code; } void StringCodeWriter::Clear() { - m_buffer.clear(); + m_buffer.clear(); } const wxString& StringCodeWriter::GetString() const { - return m_buffer; + return m_buffer; } -FileCodeWriter::FileCodeWriter(const wxString& file, bool useMicrosoftBOM, bool useUtf8) -: -m_filename(file), -m_useMicrosoftBOM(useMicrosoftBOM), -m_useUtf8(useUtf8) +FileCodeWriter::FileCodeWriter(const wxString& file, bool useMicrosoftBOM, bool useUtf8) : + m_filename(file), m_useMicrosoftBOM(useMicrosoftBOM), m_useUtf8(useUtf8) { - Clear(); + Clear(); } FileCodeWriter::~FileCodeWriter() { - WriteBuffer(); + WriteBuffer(); } void FileCodeWriter::WriteBuffer() { - static const unsigned char MICROSOFT_BOM[3] = { 0xEF, 0xBB, 0xBF }; - - const std::string& data = (m_useUtf8 ? _STDSTR(m_buffer) : _ANSISTR(m_buffer)); - - // Compare buffer with existing file (if any) to determine if - // writing the file is necessary - bool shouldWrite = true; - std::ifstream fileIn(m_filename.mb_str(wxConvFile), std::ios::binary | std::ios::in); - - if (fileIn) - { - MD5 diskHash(fileIn); - unsigned char* diskDigest = diskHash.raw_digest(); - - MD5 bufferHash; - if (m_useUtf8 && m_useMicrosoftBOM) - { - bufferHash.update(MICROSOFT_BOM, 3); - } - bufferHash.update(reinterpret_cast(data.c_str()), data.size()); - bufferHash.finalize(); - unsigned char* bufferDigest = bufferHash.raw_digest(); - - shouldWrite = (0 != std::memcmp(diskDigest, bufferDigest, 16)); - - delete[] diskDigest; - delete[] bufferDigest; - } - - if (shouldWrite) - { - wxFile fileOut; - if (!fileOut.Create(m_filename, true)) - { - wxLogError( _("Unable to create file: %s"), m_filename ); - return; - } - - if (m_useUtf8 && m_useMicrosoftBOM) - { - fileOut.Write(MICROSOFT_BOM, 3); - } - fileOut.Write(data.c_str(), data.length()); - } + static const unsigned char MICROSOFT_BOM[3] = {0xEF, 0xBB, 0xBF}; + + const std::string& data = (m_useUtf8 ? _STDSTR(m_buffer) : _ANSISTR(m_buffer)); + + // Compare buffer with existing file (if any) to determine if + // writing the file is necessary + bool shouldWrite = true; + std::ifstream fileIn(m_filename.mb_str(wxConvFile), std::ios::binary | std::ios::in); + + if (fileIn) { + MD5 diskHash(fileIn); + unsigned char* diskDigest = diskHash.raw_digest(); + + MD5 bufferHash; + if (m_useUtf8 && m_useMicrosoftBOM) { + bufferHash.update(MICROSOFT_BOM, 3); + } + bufferHash.update(reinterpret_cast(data.c_str()), data.size()); + bufferHash.finalize(); + unsigned char* bufferDigest = bufferHash.raw_digest(); + + shouldWrite = (0 != std::memcmp(diskDigest, bufferDigest, 16)); + + delete[] diskDigest; + delete[] bufferDigest; + } + + if (shouldWrite) { + wxFile fileOut; + if (!fileOut.Create(m_filename, true)) { + wxLogError(_("Unable to create file: %s"), m_filename); + return; + } + + if (m_useUtf8 && m_useMicrosoftBOM) { + fileOut.Write(MICROSOFT_BOM, 3); + } + fileOut.Write(data.c_str(), data.length()); + } } void FileCodeWriter::Clear() { - StringCodeWriter::Clear(); - - if ( ::wxFileExists( m_filename ) ) - { - // check for write access to the target file - if ( !wxFile::Access( m_filename, wxFile::write ) ) - { - THROW_WXFBEX( _("Unable to write file: ") << m_filename ); - } - } - else - { - wxFile file; - if ( !file.Create( m_filename, true ) ) - { - THROW_WXFBEX( _("Unable to create file: ") << m_filename ); - } - } + StringCodeWriter::Clear(); + + if (::wxFileExists(m_filename)) { + // check for write access to the target file + if (!wxFile::Access(m_filename, wxFile::write)) { + THROW_WXFBEX(_("Unable to write file: ") << m_filename); + } + } else { + wxFile file; + if (!file.Create(m_filename, true)) { + THROW_WXFBEX(_("Unable to create file: ") << m_filename); + } + } } diff --git a/src/codegen/codewriter.h b/src/codegen/codewriter.h index 5e58313f7..1974e13d8 100644 --- a/src/codegen/codewriter.h +++ b/src/codegen/codewriter.h @@ -22,89 +22,91 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef CODEGEN_CODEWRITER_H #define CODEGEN_CODEWRITER_H #include + /** Abstracts the code generation from the target. Because, in some cases the target is a file, sometimes a TextCtrl, and sometimes both. */ class CodeWriter { private: - /// Current indentation level in the file - int m_indent; - /// Flag if line writing is in progress - bool m_isLineWriting; - bool m_indent_with_spaces; + /// Current indentation level in the file + int m_indent; + /// Flag if line writing is in progress + bool m_isLineWriting; + bool m_indent_with_spaces; protected: - /// Write a wxString. - virtual void DoWrite(const wxString& code) = 0; - - /// Returns the size of the indentation - was useful when using spaces, now it is 1 because using tabs. - virtual int GetIndentSize() const; - - /** - * @param code Code fragment - * - * @return True, if code doesn't contain any newline character - */ - bool IsSingleLine(const wxString& code) const; - - /** - * Outputs a single line - * - * Performs whitespace cleanup and indentation processing - * including the special markers of the TemplateParser. - * - * @param line Single line, must not contain newlines - * @param rawIndents If true, keep leading indenting whitespace and don't apply own indenting - */ - void ProcessLine(wxString line, bool rawIndents); + /// Write a wxString. + virtual void DoWrite(const wxString& code) = 0; + + /// Returns the size of the indentation - was useful when using spaces, now it is 1 because using tabs. + virtual int GetIndentSize() const; + + /** + * @param code Code fragment + * + * @return True, if code doesn't contain any newline character + */ + bool IsSingleLine(const wxString& code) const; + + /** + * Outputs a single line + * + * Performs whitespace cleanup and indentation processing + * including the special markers of the TemplateParser. + * + * @param line Single line, must not contain newlines + * @param rawIndents If true, keep leading indenting whitespace and don't apply own indenting + */ + void ProcessLine(wxString line, bool rawIndents); public: - /// Constructor. - CodeWriter(); - virtual ~CodeWriter() = default; - - /// Increment the indent. - void Indent(); - - /// Decrement the indent. - void Unindent(); - - /** - * Write a block of code with trailing newline - * - * This is a general purpose method to output the input properly formatted. - * Cleans up whitespace and applies template indentation processing. - * - * @param code Block of code - * @param rawIndents If true, keep leading indenting whitespace and don't apply own indenting - */ - void WriteLn(const wxString& code = wxEmptyString, bool rawIndents = false); - - /** - * Write a fragment of code without trailing newline - * - * This method is not intended for general purpose output but only to output preformatted input. - * No whitespace cleanup and no template indentation processing is performed! - * - * The initial call of this method initiates the output process, it can be called multiple times - * to continue the output process, but it must be terminated with a call to WriteLn(const wxString&, bool). - * - * @param code Block of code - * @param rawIndents If true, keep leading indenting whitespace and don't apply own indenting - */ - void Write(const wxString& code, bool rawIndents = false); - - // Sets the option to indent with spaces - void SetIndentWithSpaces( bool on ); - - /// Deletes all the code previously written. - virtual void Clear() = 0; + /// Constructor. + CodeWriter(); + virtual ~CodeWriter() = default; + + /// Increment the indent. + void Indent(); + + /// Decrement the indent. + void Unindent(); + + /** + * Write a block of code with trailing newline + * + * This is a general purpose method to output the input properly formatted. + * Cleans up whitespace and applies template indentation processing. + * + * @param code Block of code + * @param rawIndents If true, keep leading indenting whitespace and don't apply own indenting + */ + void WriteLn(const wxString& code = wxEmptyString, bool rawIndents = false); + + /** + * Write a fragment of code without trailing newline + * + * This method is not intended for general purpose output but only to output preformatted input. + * No whitespace cleanup and no template indentation processing is performed! + * + * The initial call of this method initiates the output process, it can be called multiple times + * to continue the output process, but it must be terminated with a call to WriteLn(const wxString&, bool). + * + * @param code Block of code + * @param rawIndents If true, keep leading indenting whitespace and don't apply own indenting + */ + void Write(const wxString& code, bool rawIndents = false); + + // Sets the option to indent with spaces + void SetIndentWithSpaces(bool on); + + /// Deletes all the code previously written. + virtual void Clear() = 0; }; class wxStyledTextCtrl; @@ -112,49 +114,49 @@ class wxStyledTextCtrl; class TCCodeWriter : public CodeWriter { private: - wxStyledTextCtrl* m_tc; + wxStyledTextCtrl* m_tc; protected: - void DoWrite(const wxString& code) override; + void DoWrite(const wxString& code) override; public: - TCCodeWriter(); - TCCodeWriter(wxStyledTextCtrl* tc); + TCCodeWriter(); + TCCodeWriter(wxStyledTextCtrl* tc); - void SetTextCtrl(wxStyledTextCtrl* tc); - void Clear() override; + void SetTextCtrl(wxStyledTextCtrl* tc); + void Clear() override; }; class StringCodeWriter : public CodeWriter { protected: - wxString m_buffer; + wxString m_buffer; protected: - void DoWrite(const wxString& code) override; + void DoWrite(const wxString& code) override; public: - StringCodeWriter(); + StringCodeWriter(); - void Clear() override; - const wxString& GetString() const; + void Clear() override; + const wxString& GetString() const; }; class FileCodeWriter : public StringCodeWriter { private: - wxString m_filename; - bool m_useMicrosoftBOM; - bool m_useUtf8; + wxString m_filename; + bool m_useMicrosoftBOM; + bool m_useUtf8; protected: - void WriteBuffer(); + void WriteBuffer(); public: - FileCodeWriter(const wxString& file, bool useMicrosoftBOM = false, bool useUtf8 = true); - ~FileCodeWriter() override; + FileCodeWriter(const wxString& file, bool useMicrosoftBOM = false, bool useUtf8 = true); + ~FileCodeWriter() override; - void Clear() final; + void Clear() final; }; -#endif // CODEGEN_CODEWRITER_H +#endif // CODEGEN_CODEWRITER_H diff --git a/src/codegen/cppcg.cpp b/src/codegen/cppcg.cpp index 8515235e5..e664d44db 100644 --- a/src/codegen/cppcg.cpp +++ b/src/codegen/cppcg.cpp @@ -25,6 +25,12 @@ #include "cppcg.h" +#include + +#include +#include + +#include "codegen/codewriter.h" #include "model/objectbase.h" #include "rad/appdata.h" #include "rad/revision.h" @@ -32,2113 +38,1809 @@ #include "utils/filetocarray.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "codegen/codewriter.h" - -#include -#include -#include -CppTemplateParser::CppTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath ) - : - TemplateParser( obj, _template ), - m_i18n( useI18N ), - m_useRelativePath( useRelativePath ), - m_basePath( basePath ) +CppTemplateParser::CppTemplateParser( + PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath) : + TemplateParser(obj, _template), m_i18n(useI18N), m_useRelativePath(useRelativePath), m_basePath(basePath) { - if ( !wxFileName::DirExists( m_basePath ) ) - { - m_basePath.clear(); - } + if (!wxFileName::DirExists(m_basePath)) { + m_basePath.clear(); + } } -CppTemplateParser::CppTemplateParser( const CppTemplateParser & that, wxString _template ) - : - TemplateParser( that, _template ), - m_i18n( that.m_i18n ), - m_useRelativePath( that.m_useRelativePath ), - m_basePath( that.m_basePath ) +CppTemplateParser::CppTemplateParser(const CppTemplateParser& that, wxString _template) : + TemplateParser(that, _template), + m_i18n(that.m_i18n), + m_useRelativePath(that.m_useRelativePath), + m_basePath(that.m_basePath) { } wxString CppTemplateParser::RootWxParentToCode() { - return wxT( "this" ); + return wxT("this"); } -PTemplateParser CppTemplateParser::CreateParser( const TemplateParser* oldparser, wxString _template ) +PTemplateParser CppTemplateParser::CreateParser(const TemplateParser* oldparser, wxString _template) { - const CppTemplateParser* cppOldParser = dynamic_cast< const CppTemplateParser* >( oldparser ); - if (cppOldParser) - { - PTemplateParser newparser( new CppTemplateParser( *cppOldParser, _template ) ); - return newparser; - } - return PTemplateParser(); + const CppTemplateParser* cppOldParser = dynamic_cast(oldparser); + if (cppOldParser) { + PTemplateParser newparser(new CppTemplateParser(*cppOldParser, _template)); + return newparser; + } + return PTemplateParser(); } /** -* Convert the value of the property to C++ code -*/ -wxString CppTemplateParser::ValueToCode( PropertyType type, wxString value ) + * Convert the value of the property to C++ code + */ +wxString CppTemplateParser::ValueToCode(PropertyType type, wxString value) { - wxString result; - - switch ( type ) - { - case PT_WXPARENT: - { - result = value; - break; - } - case PT_WXPARENT_SB: - { - result = value + wxT("->GetStaticBox()"); - break; - } - case PT_WXPARENT_CP: - { - result = value + wxT("->GetPane()"); - break; - } - case PT_WXSTRING: - case PT_FILE: - case PT_PATH: - { - if ( value.empty() ) - { - result << wxT( "wxEmptyString" ); - } - else - { - result << wxT( "wxT(\"" ) << CppCodeGenerator::ConvertCppString( value ) << wxT( "\")" ); - } - break; - } - case PT_WXSTRING_I18N: - { - if ( value.empty() ) - { - result << wxT( "wxEmptyString" ); - } - else - { - if ( m_i18n ) - { - result << wxT( "_(\"" ) << CppCodeGenerator::ConvertCppString( value ) << wxT( "\")" ); - } - else - { - result << wxT( "wxT(\"" ) << CppCodeGenerator::ConvertCppString( value ) << wxT( "\")" ); - } - } - break; - } - case PT_CLASS: - case PT_MACRO: - case PT_TEXT: - case PT_OPTION: - case PT_EDIT_OPTION: - case PT_FLOAT: - case PT_INT: - case PT_UINT: - { - result = value; - break; - } - case PT_BITLIST: - { - result = ( value.empty() ? wxT( "0" ) : value ); - break; - } - case PT_WXPOINT: - { - if ( value.empty() ) - { - result = wxT( "wxDefaultPosition" ); - } - else - { - result << wxT( "wxPoint( " ) << value << wxT( " )" ); - } - break; - } - case PT_WXSIZE: - { - if ( value.empty() ) - { - result = wxT( "wxDefaultSize" ); - } - else - { - result << wxT( "wxSize( " ) << value << wxT( " )" ); - } - break; - } - case PT_BOOL: - { - result = ( value == wxT( "0" ) ? wxT( "false" ) : wxT( "true" ) ); - break; - } - case PT_WXFONT: - { - if ( !value.empty() ) - { - wxFontContainer fontContainer = TypeConv::StringToFont( value ); - wxFont font = fontContainer.GetFont(); - - const int pointSize = fontContainer.GetPointSize(); - - result = wxString::Format( "wxFont( %s, %s, %s, %s, %s, %s )", - ((pointSize <= 0) ? "wxNORMAL_FONT->GetPointSize()" : (wxString() << pointSize)), - TypeConv::FontFamilyToString( fontContainer.GetFamily() ), - font.GetStyleString(), - font.GetWeightString(), - ( fontContainer.GetUnderlined() ? "true" : "false" ), - ( fontContainer.m_faceName.empty() ? "wxEmptyString" : ("wxT(\"" + fontContainer.m_faceName + "\")") ) - ); - } - else - { - result = wxT("*wxNORMAL_FONT"); - } - break; - } - case PT_WXCOLOUR: - { - if ( !value.empty() ) - { - if ( value.find_first_of( wxT( "wx" ) ) == 0 ) - { - // System Colour - result << wxT( "wxSystemSettings::GetColour( " ) << value << wxT( " )" ); - } - else - { - wxColour colour = TypeConv::StringToColour( value ); - result = wxString::Format( wxT( "wxColour( %i, %i, %i )" ), colour.Red(), colour.Green(), colour.Blue() ); - } - } - else - { - result = wxT( "wxColour()" ); - } - break; - } - case PT_BITMAP: - { - wxString path; - wxString source; - wxSize icoSize; - TypeConv::ParseBitmapWithResource( value, &path, &source, &icoSize ); - - if ( path.empty() ) - { - // Empty path, generate Null Bitmap - result = wxT( "wxNullBitmap" ); - break; - } - - if ( path.StartsWith( wxT( "file:" ) ) ) - { - wxLogWarning( wxT( "C++ code generation does not support using URLs for bitmap properties:\n%s" ), path ); - result = wxT( "wxNullBitmap" ); - break; - } - - if ( source == _("Load From File") ) - { - wxString absPath; - try - { - absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - result = wxT( "wxNullBitmap" ); - break; - } - - wxString file = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath ); - - wxFileName bmpFileName( path ); - if ( bmpFileName.GetExt().Upper() == wxT( "XPM" ) ) - { - // If the bitmap is an XPM we will embed it in the code, otherwise it will be loaded from the file at run time. - result << wxT( "wxBitmap( " ) << CppCodeGenerator::ConvertEmbeddedBitmapName( path ) << wxT( " )" ); - } - else - { - result << wxT( "wxBitmap( wxT(\"" ) << CppCodeGenerator::ConvertCppString( file ) << wxT( "\"), wxBITMAP_TYPE_ANY )" ); - } - } - else if ( source == _("Load From Embedded File") ) - { - wxString absPath; - try - { - absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - result = wxT( "wxNullBitmap" ); - break; - } - - wxFileName bmpFileName( path ); - if ( bmpFileName.GetExt().Upper() == wxT( "XPM" ) ) - { - // If the bitmap is an XPM we will embed it as is, otherwise we'll generate a header - result << wxT( "wxBitmap( " ) << CppCodeGenerator::ConvertEmbeddedBitmapName( path ) << wxT( " )" ); - } - else - { - result << CppCodeGenerator::ConvertEmbeddedBitmapName( path ) << wxT("_to_wx_bitmap()"); - } - } - else if ( source == _("Load From Resource") ) - { - result << wxT( "wxBitmap( wxT(\"" ) << path << wxT( "\"), wxBITMAP_TYPE_RESOURCE )" ); - } - else if ( source == _("Load From Icon Resource") ) - { - if ( wxDefaultSize == icoSize ) - { - result << wxT( "wxICON( " ) << path << wxT( " )" ); - } - else - { - result.Printf( wxT( "wxIcon( wxT(\"%s\"), wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )" ), path, icoSize.GetWidth(), icoSize.GetHeight() ); - } - } - else if (source == _("Load From XRC")) - { - result << wxT("wxXmlResource::Get()->LoadBitmap( wxT(\"") << path << wxT("\") )"); - } - else if ( source == _("Load From Art Provider") ) - { - wxString rid = path.BeforeFirst( wxT(':') ); - if( rid.StartsWith( wxT("gtk-") ) ) rid = wxT("wxT(\"") + rid + wxT("\")"); - - result = wxT("wxArtProvider::GetBitmap( ") + rid + wxT(", ") + path.AfterFirst( wxT(':') ) + wxT(" )"); - } - break; - } - case PT_STRINGLIST: - { - // Stringlists are generated like a sequence of wxString separated by ', '. - wxArrayString array = TypeConv::StringToArrayString( value ); - if ( array.Count() > 0 ) - { - result = ValueToCode( PT_WXSTRING_I18N, array[0] ); - } - - for ( size_t i = 1; i < array.Count(); i++ ) - { - result << wxT( ", " ) << ValueToCode( PT_WXSTRING_I18N, array[i] ); - } - break; - } - default: - break; - } - - return result; + wxString result; + + switch (type) { + case PT_WXPARENT: { + result = value; + break; + } + case PT_WXPARENT_SB: { + result = value + wxT("->GetStaticBox()"); + break; + } + case PT_WXPARENT_CP: { + result = value + wxT("->GetPane()"); + break; + } + case PT_WXSTRING: + case PT_FILE: + case PT_PATH: { + if (value.empty()) { + result << wxT("wxEmptyString"); + } else { + result << wxT("wxT(\"") << CppCodeGenerator::ConvertCppString(value) << wxT("\")"); + } + break; + } + case PT_WXSTRING_I18N: { + if (value.empty()) { + result << wxT("wxEmptyString"); + } else { + if (m_i18n) { + result << wxT("_(\"") << CppCodeGenerator::ConvertCppString(value) << wxT("\")"); + } else { + result << wxT("wxT(\"") << CppCodeGenerator::ConvertCppString(value) << wxT("\")"); + } + } + break; + } + case PT_CLASS: + case PT_MACRO: + case PT_TEXT: + case PT_OPTION: + case PT_EDIT_OPTION: + case PT_FLOAT: + case PT_INT: + case PT_UINT: { + result = value; + break; + } + case PT_BITLIST: { + result = (value.empty() ? wxT("0") : value); + break; + } + case PT_WXPOINT: { + if (value.empty()) { + result = wxT("wxDefaultPosition"); + } else { + result << wxT("wxPoint( ") << value << wxT(" )"); + } + break; + } + case PT_WXSIZE: { + if (value.empty()) { + result = wxT("wxDefaultSize"); + } else { + result << wxT("wxSize( ") << value << wxT(" )"); + } + break; + } + case PT_BOOL: { + result = (value == wxT("0") ? wxT("false") : wxT("true")); + break; + } + case PT_WXFONT: { + if (!value.empty()) { + wxFontContainer fontContainer = TypeConv::StringToFont(value); + wxFont font = fontContainer.GetFont(); + + const int pointSize = fontContainer.GetPointSize(); + + result = wxString::Format( + "wxFont( %s, %s, %s, %s, %s, %s )", + ((pointSize <= 0) ? "wxNORMAL_FONT->GetPointSize()" : (wxString() << pointSize)), + TypeConv::FontFamilyToString(fontContainer.GetFamily()), font.GetStyleString(), + font.GetWeightString(), (fontContainer.GetUnderlined() ? "true" : "false"), + (fontContainer.m_faceName.empty() ? "wxEmptyString" : ("wxT(\"" + fontContainer.m_faceName + "\")"))); + } else { + result = wxT("*wxNORMAL_FONT"); + } + break; + } + case PT_WXCOLOUR: { + if (!value.empty()) { + if (value.find_first_of(wxT("wx")) == 0) { + // System Colour + result << wxT("wxSystemSettings::GetColour( ") << value << wxT(" )"); + } else { + wxColour colour = TypeConv::StringToColour(value); + result = + wxString::Format(wxT("wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue()); + } + } else { + result = wxT("wxColour()"); + } + break; + } + case PT_BITMAP: { + wxString path; + wxString source; + wxSize icoSize; + TypeConv::ParseBitmapWithResource(value, &path, &source, &icoSize); + + if (path.empty()) { + // Empty path, generate Null Bitmap + result = wxT("wxNullBitmap"); + break; + } + + if (path.StartsWith(wxT("file:"))) { + wxLogWarning(wxT("C++ code generation does not support using URLs for bitmap properties:\n%s"), path); + result = wxT("wxNullBitmap"); + break; + } + + if (source == _("Load From File")) { + wxString absPath; + try { + absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + result = wxT("wxNullBitmap"); + break; + } + + wxString file = (m_useRelativePath ? TypeConv::MakeRelativePath(absPath, m_basePath) : absPath); + + wxFileName bmpFileName(path); + if (bmpFileName.GetExt().Upper() == wxT("XPM")) { + // If the bitmap is an XPM we will embed it in the code, otherwise it will be loaded from the file + // at run time. + result << wxT("wxBitmap( ") << CppCodeGenerator::ConvertEmbeddedBitmapName(path) << wxT(" )"); + } else { + result << wxT("wxBitmap( wxT(\"") << CppCodeGenerator::ConvertCppString(file) + << wxT("\"), wxBITMAP_TYPE_ANY )"); + } + } else if (source == _("Load From Embedded File")) { + wxString absPath; + try { + absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + result = wxT("wxNullBitmap"); + break; + } + + wxFileName bmpFileName(path); + if (bmpFileName.GetExt().Upper() == wxT("XPM")) { + // If the bitmap is an XPM we will embed it as is, otherwise we'll generate a header + result << wxT("wxBitmap( ") << CppCodeGenerator::ConvertEmbeddedBitmapName(path) << wxT(" )"); + } else { + result << CppCodeGenerator::ConvertEmbeddedBitmapName(path) << wxT("_to_wx_bitmap()"); + } + } else if (source == _("Load From Resource")) { + result << wxT("wxBitmap( wxT(\"") << path << wxT("\"), wxBITMAP_TYPE_RESOURCE )"); + } else if (source == _("Load From Icon Resource")) { + if (wxDefaultSize == icoSize) { + result << wxT("wxICON( ") << path << wxT(" )"); + } else { + result.Printf( + wxT("wxIcon( wxT(\"%s\"), wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, icoSize.GetWidth(), + icoSize.GetHeight()); + } + } else if (source == _("Load From XRC")) { + result << wxT("wxXmlResource::Get()->LoadBitmap( wxT(\"") << path << wxT("\") )"); + } else if (source == _("Load From Art Provider")) { + wxString rid = path.BeforeFirst(wxT(':')); + if (rid.StartsWith(wxT("gtk-"))) + rid = wxT("wxT(\"") + rid + wxT("\")"); + + result = wxT("wxArtProvider::GetBitmap( ") + rid + wxT(", ") + path.AfterFirst(wxT(':')) + wxT(" )"); + } + break; + } + case PT_STRINGLIST: { + // Stringlists are generated like a sequence of wxString separated by ', '. + wxArrayString array = TypeConv::StringToArrayString(value); + if (array.Count() > 0) { + result = ValueToCode(PT_WXSTRING_I18N, array[0]); + } + + for (size_t i = 1; i < array.Count(); i++) { + result << wxT(", ") << ValueToCode(PT_WXSTRING_I18N, array[i]); + } + break; + } + default: + break; + } + + return result; } /////////////////////////////////////////////////////////////////////////////// CppCodeGenerator::CppCodeGenerator() { - SetupPredefinedMacros(); - m_useRelativePath = false; - m_i18n = false; - m_firstID = 1000; + SetupPredefinedMacros(); + m_useRelativePath = false; + m_i18n = false; + m_firstID = 1000; } -wxString CppCodeGenerator::ConvertCppString( wxString text ) +wxString CppCodeGenerator::ConvertCppString(wxString text) { - wxString result; - - for ( size_t i = 0; i < text.length(); i++ ) - { - wxChar c = text[i]; - - switch ( c ) - { - case wxT( '"' ): - result += wxT( "\\\"" ); - break; - - case wxT( '\\' ): - result += wxT( "\\\\" ); - break; - - case wxT( '\t' ): - result += wxT( "\\t" ); - break; - - case wxT( '\n' ): - result += wxT( "\\n" ); - break; - - case wxT( '\r' ): - result += wxT( "\\r" ); - break; - - default: - result += c; - break; - } - } - return result; + wxString result; + + for (size_t i = 0; i < text.length(); i++) { + wxChar c = text[i]; + + switch (c) { + case wxT('"'): + result += wxT("\\\""); + break; + + case wxT('\\'): + result += wxT("\\\\"); + break; + + case wxT('\t'): + result += wxT("\\t"); + break; + + case wxT('\n'): + result += wxT("\\n"); + break; + + case wxT('\r'): + result += wxT("\\r"); + break; + + default: + result += c; + break; + } + } + return result; } -wxString CppCodeGenerator::ConvertEmbeddedBitmapName( const wxString& text ) +wxString CppCodeGenerator::ConvertEmbeddedBitmapName(const wxString& text) { - wxString name = text; - // the name consists of extracting the name of the file (without the directory) - // and replacing the character '.' by ' _ '. + wxString name = text; + // the name consists of extracting the name of the file (without the directory) + // and replacing the character '.' by ' _ '. - size_t last_slash = name.find_last_of( wxT("\\/") ); - if ( last_slash != name.npos ) - { - name = name.substr( last_slash + 1 ); - } + size_t last_slash = name.find_last_of(wxT("\\/")); + if (last_slash != name.npos) { + name = name.substr(last_slash + 1); + } - name.Replace( wxT("."), wxT("_") ); + name.Replace(wxT("."), wxT("_")); - return name; + return name; } -void CppCodeGenerator::GenerateInheritedClass( PObjectBase userClasses, PObjectBase form ) +void CppCodeGenerator::GenerateInheritedClass(PObjectBase userClasses, PObjectBase form) { - if (!userClasses) - { - wxLogError(wxT("There is no object to generate inherited class")); - return; - } - - if ( wxT("UserClasses") != userClasses->GetClassName() ) - { - wxLogError(wxT("This not a UserClasses object")); - return; - } - - m_inheritedCodeParser.ParseCFiles(userClasses->GetPropertyAsString( _("name") )); - - //(FileCodeWriter*)m_header-> - wxString type = userClasses->GetPropertyAsString( wxT("type") ); - wxString userCode; - - // Start header file - wxString code = GetCode( userClasses, wxT("guard_macro_open") ); - m_header->WriteLn( code ); - m_header->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, wxT("header_comment") ); - m_header->WriteLn( code ); - m_header->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, wxT("header_include") ); - m_header->WriteLn( code ); - m_header->WriteLn( wxEmptyString ); - m_header->WriteLn( wxT("//// end generated include") ); - - m_header->WriteLn( m_inheritedCodeParser.GetUserIncludes() ); - if ( !userCode.IsEmpty() ) - { - m_header->WriteLn( userCode ); - } - - code = GetCode( userClasses, wxT("class_decl") ); - m_header->WriteLn( code ); - m_header->WriteLn( wxT("{") ); - m_header->Indent(); - - // Start source file - code = GetCode( userClasses, wxT("source_include") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, type + wxT("_cons_def") ); - LogDebug(code + "<"); - m_source->WriteLn( code ); - m_source->WriteLn( wxT("{") ); - userCode = m_inheritedCodeParser.GetFunctionContents( code ); - if ( !userCode.IsEmpty() ) - { - m_source->WriteLn( userCode, true ); - } - else - { - m_source->WriteLn( wxEmptyString ); - } - m_source->WriteLn( wxT("}") ); - - // Do events in both files - EventVector events; - FindEventHandlers( form, events ); - - if ( events.size() > 0 ) - { - m_header->WriteLn( wxT("protected:") ); - m_header->Indent(); - code = GetCode( userClasses, wxT("event_handler_comment") ); - m_header->WriteLn( code ); - - wxString className = userClasses->GetPropertyAsString( _( "name") ); - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString prototype; - if ( generatedHandlers.find( event->GetValue() ) == generatedHandlers.end() ) - { - prototype = wxString::Format( wxT("%s( %s& event )"), event->GetValue(), event->GetEventInfo()->GetEventClassName() ); - m_header->WriteLn( wxString::Format( wxT("void %s;"), prototype ) ); - userCode = m_inheritedCodeParser.GetFunctionDocumentation( event->GetValue() ); - if ( !userCode.IsEmpty() ) - { - m_source->Write( userCode ); - } - else - { - m_source->WriteLn(); - } - m_source->WriteLn( wxString::Format( wxT("void %s::%s"), className, prototype ) ); - m_source->WriteLn( wxT("{") ); - userCode = m_inheritedCodeParser.GetFunctionContents( wxString::Format( wxT("void %s::%s"), className, prototype ) ); - LogDebug(wxString::Format( wxT("void %s::%s"), className, prototype ) + "<"); - if ( !userCode.IsEmpty() ) - { - m_source->WriteLn( userCode); - } - else - { - m_source->Indent(); - m_source->WriteLn( wxString::Format( wxT("// TODO: Implement %s"), event->GetValue() ), true ); - m_source->Unindent(); - } - m_source->WriteLn( wxT("}") ); - generatedHandlers.insert( event->GetValue() ); - } - } - - m_header->Unindent(); - } - - // Finish header file - - m_header->WriteLn( wxT("public:") ); - - m_header->Indent(); - code = GetCode( userClasses, type + wxT("_cons_decl") ); - m_header->WriteLn( code ); - m_header->Unindent(); - m_header->WriteLn( wxT("//// end generated class members") ); - userCode = m_inheritedCodeParser.GetUserMembers(); - if ( !userCode.IsEmpty() ) - { - m_header->WriteLn( userCode, true); - } - else - { - m_header->WriteLn(wxEmptyString); - } - - m_header->Unindent(); - - m_header->WriteLn( wxT("};") ); - m_header->WriteLn( wxEmptyString ); - code = GetCode( userClasses, wxT( "guard_macro_close" ) ); - m_header->WriteLn( code ); - - userCode = m_inheritedCodeParser.GetRemainingFunctions(); - if ( !userCode.IsEmpty() ) - { - m_source->Write( userCode ); - } - userCode = m_inheritedCodeParser.GetTrailingCode(); - if ( !userCode.IsEmpty() ) - { - m_source->WriteLn( userCode, true ); - } + if (!userClasses) { + wxLogError(wxT("There is no object to generate inherited class")); + return; + } + + if (wxT("UserClasses") != userClasses->GetClassName()) { + wxLogError(wxT("This not a UserClasses object")); + return; + } + + m_inheritedCodeParser.ParseCFiles(userClasses->GetPropertyAsString(_("name"))); + + //(FileCodeWriter*)m_header-> + wxString type = userClasses->GetPropertyAsString(wxT("type")); + wxString userCode; + + // Start header file + wxString code = GetCode(userClasses, wxT("guard_macro_open")); + m_header->WriteLn(code); + m_header->WriteLn(wxEmptyString); + + code = GetCode(userClasses, wxT("header_comment")); + m_header->WriteLn(code); + m_header->WriteLn(wxEmptyString); + + code = GetCode(userClasses, wxT("header_include")); + m_header->WriteLn(code); + m_header->WriteLn(wxEmptyString); + m_header->WriteLn(wxT("//// end generated include")); + + m_header->WriteLn(m_inheritedCodeParser.GetUserIncludes()); + if (!userCode.IsEmpty()) { + m_header->WriteLn(userCode); + } + + code = GetCode(userClasses, wxT("class_decl")); + m_header->WriteLn(code); + m_header->WriteLn(wxT("{")); + m_header->Indent(); + + // Start source file + code = GetCode(userClasses, wxT("source_include")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + code = GetCode(userClasses, type + wxT("_cons_def")); + LogDebug(code + "<"); + m_source->WriteLn(code); + m_source->WriteLn(wxT("{")); + userCode = m_inheritedCodeParser.GetFunctionContents(code); + if (!userCode.IsEmpty()) { + m_source->WriteLn(userCode, true); + } else { + m_source->WriteLn(wxEmptyString); + } + m_source->WriteLn(wxT("}")); + + // Do events in both files + EventVector events; + FindEventHandlers(form, events); + + if (events.size() > 0) { + m_header->WriteLn(wxT("protected:")); + m_header->Indent(); + code = GetCode(userClasses, wxT("event_handler_comment")); + m_header->WriteLn(code); + + wxString className = userClasses->GetPropertyAsString(_("name")); + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString prototype; + if (generatedHandlers.find(event->GetValue()) == generatedHandlers.end()) { + prototype = wxString::Format( + wxT("%s( %s& event )"), event->GetValue(), event->GetEventInfo()->GetEventClassName()); + m_header->WriteLn(wxString::Format(wxT("void %s;"), prototype)); + userCode = m_inheritedCodeParser.GetFunctionDocumentation(event->GetValue()); + if (!userCode.IsEmpty()) { + m_source->Write(userCode); + } else { + m_source->WriteLn(); + } + m_source->WriteLn(wxString::Format(wxT("void %s::%s"), className, prototype)); + m_source->WriteLn(wxT("{")); + userCode = + m_inheritedCodeParser.GetFunctionContents(wxString::Format(wxT("void %s::%s"), className, prototype)); + LogDebug(wxString::Format(wxT("void %s::%s"), className, prototype) + "<"); + if (!userCode.IsEmpty()) { + m_source->WriteLn(userCode); + } else { + m_source->Indent(); + m_source->WriteLn(wxString::Format(wxT("// TODO: Implement %s"), event->GetValue()), true); + m_source->Unindent(); + } + m_source->WriteLn(wxT("}")); + generatedHandlers.insert(event->GetValue()); + } + } + + m_header->Unindent(); + } + + // Finish header file + + m_header->WriteLn(wxT("public:")); + + m_header->Indent(); + code = GetCode(userClasses, type + wxT("_cons_decl")); + m_header->WriteLn(code); + m_header->Unindent(); + m_header->WriteLn(wxT("//// end generated class members")); + userCode = m_inheritedCodeParser.GetUserMembers(); + if (!userCode.IsEmpty()) { + m_header->WriteLn(userCode, true); + } else { + m_header->WriteLn(wxEmptyString); + } + + m_header->Unindent(); + + m_header->WriteLn(wxT("};")); + m_header->WriteLn(wxEmptyString); + code = GetCode(userClasses, wxT("guard_macro_close")); + m_header->WriteLn(code); + + userCode = m_inheritedCodeParser.GetRemainingFunctions(); + if (!userCode.IsEmpty()) { + m_source->Write(userCode); + } + userCode = m_inheritedCodeParser.GetTrailingCode(); + if (!userCode.IsEmpty()) { + m_source->WriteLn(userCode, true); + } } -bool CppCodeGenerator::GenerateCode( PObjectBase project ) +bool CppCodeGenerator::GenerateCode(PObjectBase project) { - if ( !project ) - { - wxLogError( wxT( "There is no project to generate code" ) ); - return false; - } - - bool useEnum = false; - - PProperty useEnumProperty = project->GetProperty( wxT( "use_enum" ) ); - if ( useEnumProperty && useEnumProperty->GetValueAsInteger() ) - useEnum = true; - - m_useArrayEnum = false; - const auto& useArrayEnumProperty = project->GetProperty(wxT("use_array_enum")); - if (useArrayEnumProperty && useArrayEnumProperty->GetValueAsInteger()) - { - m_useArrayEnum = true; - } - - m_i18n = false; - PProperty i18nProperty = project->GetProperty( wxT( "internationalize" ) ); - if ( i18nProperty && i18nProperty->GetValueAsInteger() ) - m_i18n = true; - - m_useConnect = !( _( "table" ) == project->GetPropertyAsString( _( "event_generation" ) ) ); - m_disconnectEvents = ( project->GetPropertyAsInteger( _( "disconnect_events" ) ) != 0 ); - - m_header->Clear(); - m_source->Clear(); - wxString code = wxString::Format( - wxT("///////////////////////////////////////////////////////////////////////////\n") - wxT("// C++ code generated with wxFormBuilder (version %s%s)\n") - wxT("// http://www.wxformbuilder.org/\n") - wxT("//\n") - wxT("// PLEASE DO *NOT* EDIT THIS FILE!\n") - wxT("///////////////////////////////////////////////////////////////////////////\n"), - getVersion(), getPostfixRevision(getVersion()).c_str() - ); - - m_header->WriteLn( code ); - m_source->WriteLn( code ); - - PProperty propFile = project->GetProperty( wxT( "file" ) ); - if ( !propFile ) - { - wxLogError( wxT( "Missing \"file\" property on Project Object" ) ); - return false; - } - - wxString file = propFile->GetValue(); - if ( file.empty() ) - { - file = wxT( "noname" ); - } - - m_header->WriteLn(wxT("#pragma once")); - m_header->WriteLn(wxEmptyString); - - code = GetCode( project, wxT( "header_preamble" ) ); - if ( !code.empty() ) - { - m_header->WriteLn( code ); - } - - // Generate the subclass sets - std::set< wxString > subclasses; - std::set< wxString > subclassSourceIncludes; - std::vector< wxString > headerIncludes; - - GenSubclassSets( project, &subclasses, &subclassSourceIncludes, &headerIncludes ); - - // Write the forward declaration lines - std::set< wxString >::iterator subclass_it; - for ( subclass_it = subclasses.begin(); subclass_it != subclasses.end(); ++subclass_it ) - { - m_header->WriteLn( *subclass_it ); - } - if ( !subclasses.empty() ) - { - m_header->WriteLn(wxEmptyString); - } - - // Generating in the .h header file those include from components dependencies. - std::set< wxString > templates; - GenIncludes( project, &headerIncludes, &templates ); - - // Write the include lines - std::vector::iterator include_it; - for ( include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it ) - { - m_header->WriteLn( *include_it ); - } - if ( !headerIncludes.empty() ) - { - m_header->WriteLn(wxEmptyString); - } - - // class decoration - PProperty propClassDecoration = project->GetProperty( wxT( "class_decoration" ) ); - wxString classDecoration; - if ( propClassDecoration ) - { - // get the decoration to be used by GenClassDeclaration - std::map< wxString, wxString > children; - propClassDecoration->SplitParentProperty( &children ); - - std::map< wxString, wxString >::iterator decoration; - decoration = children.find( wxT( "decoration" ) ); - - if ( decoration != children.end() ) - { - classDecoration = decoration->second; - if ( !classDecoration.empty() ) - { - classDecoration += wxT( " " ); - } - } - - // Now get the header - std::map< wxString, wxString >::iterator header; - header = children.find( wxT( "header" ) ); - - if ( header != children.end() ) - { - wxString headerVal = header->second; - if ( !headerVal.empty() ) - { - wxString include = wxT( "#include \"" ) + headerVal + wxT( "\"" ); - std::vector< wxString >::iterator findInclude = std::find( headerIncludes.begin(), headerIncludes.end(), include ); - if ( findInclude == headerIncludes.end() ) - { - m_header->WriteLn( include ); - m_header->WriteLn( wxEmptyString ); - } - } - } - } - - code = GetCode( project, wxT( "header_epilogue" ) ); - m_header->WriteLn( code ); - m_header->WriteLn( wxEmptyString ); - - // Inserting in the .cpp source file the include corresponding to the - // generated .h header file and the related xpm includes - code = GetCode( project, wxT( "cpp_preamble" ) ); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - } - - // Write include lines for subclasses - for ( subclass_it = subclassSourceIncludes.begin(); subclass_it != subclassSourceIncludes.end(); ++subclass_it ) - { - m_source->WriteLn( *subclass_it ); - } - if ( !subclassSourceIncludes.empty() ) - { - m_source->WriteLn( wxEmptyString ); - } - - // Generated header - m_source->WriteLn( wxT( "#include \"" ) + file + wxT( ".h\"" ) ); - - m_source->WriteLn( wxEmptyString ); - GenEmbeddedBitmapIncludes( project ); - - code = GetCode( project, wxT( "cpp_epilogue" ) ); - m_source->WriteLn( code ); - - // namespace - PProperty propNamespace = project->GetProperty( wxT( "namespace" ) ); - wxArrayString namespaceArray; - if ( propNamespace ) - { - namespaceArray = propNamespace->GetValueAsArrayString(); - wxString usingNamespaceStr; - for ( unsigned int i = 0; i < namespaceArray.Count(); ++i ) - { - m_header->WriteLn( wxT( "namespace " ) + namespaceArray[i] ); - m_header->WriteLn( wxT( "{" ) ); - m_header->Indent(); - - if ( usingNamespaceStr.empty() ) - { - usingNamespaceStr = wxT( "using namespace " ); - } - else - { - usingNamespaceStr += wxT( "::" ); - } - usingNamespaceStr += namespaceArray[i]; - } - - if ( namespaceArray.Count() && !usingNamespaceStr.empty() ) - { - usingNamespaceStr += wxT( ";" ); - m_source->WriteLn( usingNamespaceStr ); - } - } - - // Generating "defines" for macros - if ( !useEnum ) - { - GenDefines( project ); - } - - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - PObjectBase child = project->GetChild( i ); - - // Preprocess to find arrays - ArrayItems arrays; - FindArrayObjects(child, arrays, true); - - EventVector events; - FindEventHandlers( child, events ); - GenClassDeclaration(child, useEnum, classDecoration, events, arrays); - if ( !m_useConnect ) - { - GenEvents( child, events ); - } - GenConstructor(child, events, arrays); - GenDestructor( child, events ); - } - - // namespace - if ( namespaceArray.Count() > 0 ) - { - for ( size_t i = namespaceArray.Count(); i > 0; --i ) - { - m_header->Unindent(); - m_header->WriteLn( wxT( "} // namespace " ) + namespaceArray[ i - 1 ] ); - } - m_header->WriteLn( wxEmptyString ); - } - - return true; + if (!project) { + wxLogError(wxT("There is no project to generate code")); + return false; + } + + bool useEnum = false; + + PProperty useEnumProperty = project->GetProperty(wxT("use_enum")); + if (useEnumProperty && useEnumProperty->GetValueAsInteger()) + useEnum = true; + + m_useArrayEnum = false; + const auto& useArrayEnumProperty = project->GetProperty(wxT("use_array_enum")); + if (useArrayEnumProperty && useArrayEnumProperty->GetValueAsInteger()) { + m_useArrayEnum = true; + } + + m_i18n = false; + PProperty i18nProperty = project->GetProperty(wxT("internationalize")); + if (i18nProperty && i18nProperty->GetValueAsInteger()) + m_i18n = true; + + m_useConnect = !(_("table") == project->GetPropertyAsString(_("event_generation"))); + m_disconnectEvents = (project->GetPropertyAsInteger(_("disconnect_events")) != 0); + + m_header->Clear(); + m_source->Clear(); + wxString code = wxString::Format( + wxT("///////////////////////////////////////////////////////////////////////////\n") + wxT("// C++ code generated with wxFormBuilder (version %s%s)\n") wxT("// http://www.wxformbuilder.org/\n") + wxT("//\n") wxT("// PLEASE DO *NOT* EDIT THIS FILE!\n") + wxT("///////////////////////////////////////////////////////////////////////////\n"), + getVersion(), getPostfixRevision(getVersion()).c_str()); + + m_header->WriteLn(code); + m_source->WriteLn(code); + + PProperty propFile = project->GetProperty(wxT("file")); + if (!propFile) { + wxLogError(wxT("Missing \"file\" property on Project Object")); + return false; + } + + wxString file = propFile->GetValue(); + if (file.empty()) { + file = wxT("noname"); + } + + m_header->WriteLn(wxT("#pragma once")); + m_header->WriteLn(wxEmptyString); + + code = GetCode(project, wxT("header_preamble")); + if (!code.empty()) { + m_header->WriteLn(code); + } + + // Generate the subclass sets + std::set subclasses; + std::set subclassSourceIncludes; + std::vector headerIncludes; + + GenSubclassSets(project, &subclasses, &subclassSourceIncludes, &headerIncludes); + + // Write the forward declaration lines + std::set::iterator subclass_it; + for (subclass_it = subclasses.begin(); subclass_it != subclasses.end(); ++subclass_it) { + m_header->WriteLn(*subclass_it); + } + if (!subclasses.empty()) { + m_header->WriteLn(wxEmptyString); + } + + // Generating in the .h header file those include from components dependencies. + std::set templates; + GenIncludes(project, &headerIncludes, &templates); + + // Write the include lines + std::vector::iterator include_it; + for (include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it) { + m_header->WriteLn(*include_it); + } + if (!headerIncludes.empty()) { + m_header->WriteLn(wxEmptyString); + } + + // class decoration + PProperty propClassDecoration = project->GetProperty(wxT("class_decoration")); + wxString classDecoration; + if (propClassDecoration) { + // get the decoration to be used by GenClassDeclaration + std::map children; + propClassDecoration->SplitParentProperty(&children); + + std::map::iterator decoration; + decoration = children.find(wxT("decoration")); + + if (decoration != children.end()) { + classDecoration = decoration->second; + if (!classDecoration.empty()) { + classDecoration += wxT(" "); + } + } + + // Now get the header + std::map::iterator header; + header = children.find(wxT("header")); + + if (header != children.end()) { + wxString headerVal = header->second; + if (!headerVal.empty()) { + wxString include = wxT("#include \"") + headerVal + wxT("\""); + std::vector::iterator findInclude = + std::find(headerIncludes.begin(), headerIncludes.end(), include); + if (findInclude == headerIncludes.end()) { + m_header->WriteLn(include); + m_header->WriteLn(wxEmptyString); + } + } + } + } + + code = GetCode(project, wxT("header_epilogue")); + m_header->WriteLn(code); + m_header->WriteLn(wxEmptyString); + + // Inserting in the .cpp source file the include corresponding to the + // generated .h header file and the related xpm includes + code = GetCode(project, wxT("cpp_preamble")); + if (!code.empty()) { + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + } + + // Write include lines for subclasses + for (subclass_it = subclassSourceIncludes.begin(); subclass_it != subclassSourceIncludes.end(); ++subclass_it) { + m_source->WriteLn(*subclass_it); + } + if (!subclassSourceIncludes.empty()) { + m_source->WriteLn(wxEmptyString); + } + + // Generated header + m_source->WriteLn(wxT("#include \"") + file + wxT(".h\"")); + + m_source->WriteLn(wxEmptyString); + GenEmbeddedBitmapIncludes(project); + + code = GetCode(project, wxT("cpp_epilogue")); + m_source->WriteLn(code); + + // namespace + PProperty propNamespace = project->GetProperty(wxT("namespace")); + wxArrayString namespaceArray; + if (propNamespace) { + namespaceArray = propNamespace->GetValueAsArrayString(); + wxString usingNamespaceStr; + for (unsigned int i = 0; i < namespaceArray.Count(); ++i) { + m_header->WriteLn(wxT("namespace ") + namespaceArray[i]); + m_header->WriteLn(wxT("{")); + m_header->Indent(); + + if (usingNamespaceStr.empty()) { + usingNamespaceStr = wxT("using namespace "); + } else { + usingNamespaceStr += wxT("::"); + } + usingNamespaceStr += namespaceArray[i]; + } + + if (namespaceArray.Count() && !usingNamespaceStr.empty()) { + usingNamespaceStr += wxT(";"); + m_source->WriteLn(usingNamespaceStr); + } + } + + // Generating "defines" for macros + if (!useEnum) { + GenDefines(project); + } + + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + PObjectBase child = project->GetChild(i); + + // Preprocess to find arrays + ArrayItems arrays; + FindArrayObjects(child, arrays, true); + + EventVector events; + FindEventHandlers(child, events); + GenClassDeclaration(child, useEnum, classDecoration, events, arrays); + if (!m_useConnect) { + GenEvents(child, events); + } + GenConstructor(child, events, arrays); + GenDestructor(child, events); + } + + // namespace + if (namespaceArray.Count() > 0) { + for (size_t i = namespaceArray.Count(); i > 0; --i) { + m_header->Unindent(); + m_header->WriteLn(wxT("} // namespace ") + namespaceArray[i - 1]); + } + m_header->WriteLn(wxEmptyString); + } + + return true; } -void CppCodeGenerator::GenEvents( PObjectBase class_obj, const EventVector &events, bool disconnect ) +void CppCodeGenerator::GenEvents(PObjectBase class_obj, const EventVector& events, bool disconnect) { - if ( events.empty() ) - { - return; - } - - PProperty propName = class_obj->GetProperty( wxT( "name" ) ); - if ( !propName ) - { - wxLogError( wxT( "Missing \"name\" property on \"%s\" class. Review your XML object description" ), - class_obj->GetClassName() ); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT( "Object name cannot be null" ) ); - return; - } - - wxString base_class; - PProperty propSubclass = class_obj->GetProperty( wxT( "subclass" ) ); - if ( propSubclass ) - { - wxString subclass = propSubclass->GetChildFromParent( wxT( "name" ) ); - if ( !subclass.empty() ) - { - base_class = subclass; - } - } - - if ( base_class.empty() ) - base_class = wxT( "wx" ) + class_obj->GetClassName(); - - if ( events.size() > 0 ) - { - if ( !m_useConnect ) - { - m_source->WriteLn(); - m_source->WriteLn( wxT( "BEGIN_EVENT_TABLE( " ) + class_name + wxT( ", " ) + base_class + wxT( " )" ) ); - m_source->Indent(); - } - - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString handlerName; - if ( m_useConnect ) - { - handlerName.Printf( wxT( "%sHandler( %s::%s )" ), event->GetEventInfo()->GetEventClassName(), class_name, event->GetValue() ); - } - else - { - handlerName.Printf( wxT( "%s::_wxFB_%s" ), class_name, event->GetValue() ); - } - wxString templateName = wxString::Format( wxT( "%s_%s" ), m_useConnect ? wxT( "connect" ) : wxT( "entry" ), event->GetName() ); - - PObjectBase obj = event->GetObject(); - if (!GenEventEntry(obj, obj->GetObjectInfo(), templateName, handlerName, disconnect) && - (!disconnect || event->GetName() != "OnMenuSelection")) { - // We don't bother with disconnecting OnMenuSelection events, that's why we skip the - // error message in that case. - wxLogError( wxT( "Missing \"evt_%s\" template for \"%s\" class. Review your XML object description" ), - templateName, class_name ); - } - } - - if ( !m_useConnect ) - { - m_source->Unindent(); - m_source->WriteLn( wxT( "END_EVENT_TABLE()" ) ); - } - } + if (events.empty()) { + return; + } + + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name cannot be null")); + return; + } + + wxString base_class; + PProperty propSubclass = class_obj->GetProperty(wxT("subclass")); + if (propSubclass) { + wxString subclass = propSubclass->GetChildFromParent(wxT("name")); + if (!subclass.empty()) { + base_class = subclass; + } + } + + if (base_class.empty()) + base_class = wxT("wx") + class_obj->GetClassName(); + + if (events.size() > 0) { + if (!m_useConnect) { + m_source->WriteLn(); + m_source->WriteLn(wxT("BEGIN_EVENT_TABLE( ") + class_name + wxT(", ") + base_class + wxT(" )")); + m_source->Indent(); + } + + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString handlerName; + if (m_useConnect) { + handlerName.Printf( + wxT("%sHandler( %s::%s )"), event->GetEventInfo()->GetEventClassName(), class_name, + event->GetValue()); + } else { + handlerName.Printf(wxT("%s::_wxFB_%s"), class_name, event->GetValue()); + } + wxString templateName = + wxString::Format(wxT("%s_%s"), m_useConnect ? wxT("connect") : wxT("entry"), event->GetName()); + + PObjectBase obj = event->GetObject(); + if ( + !GenEventEntry(obj, obj->GetObjectInfo(), templateName, handlerName, disconnect) && + (!disconnect || event->GetName() != "OnMenuSelection")) { + // We don't bother with disconnecting OnMenuSelection events, that's why we skip the + // error message in that case. + wxLogError( + wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), templateName, + class_name); + } + } + + if (!m_useConnect) { + m_source->Unindent(); + m_source->WriteLn(wxT("END_EVENT_TABLE()")); + } + } } -bool CppCodeGenerator::GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect ) +bool CppCodeGenerator::GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect) { - wxString _template; - PCodeInfo code_info = obj_info->GetCodeInfo( wxT( "C++" ) ); - if ( code_info ) - { - _template = code_info->GetTemplate(wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); - if ( disconnect && _template.empty() ) - { - _template = code_info->GetTemplate( wxT( "evt_" ) + templateName ); - if (_template.Replace(wxT("Connect"), wxT("Disconnect"), true) == 0) { - _template.clear(); // "Connect" wasn't found, skip this entry - } - } - - if ( !_template.empty() ) - { - _template.Replace( wxT( "#handler" ), handlerName ); // Ugly patch! - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn( parser.ParseTemplate() ); - return true; - } - } - - for ( unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = obj_info->GetBaseClass( i, false ); - if ( GenEventEntry( obj, base_info, templateName, handlerName, disconnect ) ) - { - return true; - } - } - - return false; + wxString _template; + PCodeInfo code_info = obj_info->GetCodeInfo(wxT("C++")); + if (code_info) { + _template = code_info->GetTemplate( + wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); + if (disconnect && _template.empty()) { + _template = code_info->GetTemplate(wxT("evt_") + templateName); + if (_template.Replace(wxT("Connect"), wxT("Disconnect"), true) == 0) { + _template.clear(); // "Connect" wasn't found, skip this entry + } + } + + if (!_template.empty()) { + _template.Replace(wxT("#handler"), handlerName); // Ugly patch! + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + return true; + } + } + + for (unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = obj_info->GetBaseClass(i, false); + if (GenEventEntry(obj, base_info, templateName, handlerName, disconnect)) { + return true; + } + } + + return false; } -void CppCodeGenerator::GenPrivateEventHandlers( const EventVector& events ) +void CppCodeGenerator::GenPrivateEventHandlers(const EventVector& events) { - if ( events.size() > 0 ) - { - m_header->WriteLn( wxEmptyString ); - m_header->WriteLn( wxT( "// Private event handlers" ) ); - - std::set generatedHandlers; - - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString aux; - - if ( generatedHandlers.find( event->GetValue() ) == generatedHandlers.end() ) - { - aux = wxT( "void _wxFB_" ) + event->GetValue() + wxT( "( " ) + - event->GetEventInfo()->GetEventClassName() + wxT( "& event ){ " ) + - event->GetValue() + wxT( "( event ); }" ); - - m_header->WriteLn( aux ); - generatedHandlers.insert( event->GetValue() ); - } - } - m_header->WriteLn( wxEmptyString ); - } + if (events.size() > 0) { + m_header->WriteLn(wxEmptyString); + m_header->WriteLn(wxT("// Private event handlers")); + + std::set generatedHandlers; + + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString aux; + + if (generatedHandlers.find(event->GetValue()) == generatedHandlers.end()) { + aux = wxT("void _wxFB_") + event->GetValue() + wxT("( ") + event->GetEventInfo()->GetEventClassName() + + wxT("& event ){ ") + event->GetValue() + wxT("( event ); }"); + + m_header->WriteLn(aux); + generatedHandlers.insert(event->GetValue()); + } + } + m_header->WriteLn(wxEmptyString); + } } -void CppCodeGenerator::GenVirtualEventHandlers( const EventVector& events, const wxString& eventHandlerPrefix, const wxString& eventHandlerPostfix ) +void CppCodeGenerator::GenVirtualEventHandlers( + const EventVector& events, const wxString& eventHandlerPrefix, const wxString& eventHandlerPostfix) { - if ( events.size() > 0 ) - { - // There are problems if we create "pure" virtual handlers, because some - // events could be triggered in the constructor in which virtual methods are - // execute properly. - // So we create a default handler which will skip the event. - m_header->WriteLn( wxEmptyString ); - m_header->WriteLn( wxT( "// Virtual event handlers, override them in your derived class" ) ); - - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString aux = eventHandlerPrefix + wxT( "void " ) + event->GetValue() + wxT( "( " ) + - event->GetEventInfo()->GetEventClassName() + wxT( "& event )" ) + eventHandlerPostfix; - - if ( generatedHandlers.find( aux ) == generatedHandlers.end() ) - { - m_header->WriteLn( aux ); - generatedHandlers.insert( aux ); - } - } - m_header->WriteLn( wxEmptyString ); - } + if (events.size() > 0) { + // There are problems if we create "pure" virtual handlers, because some + // events could be triggered in the constructor in which virtual methods are + // execute properly. + // So we create a default handler which will skip the event. + m_header->WriteLn(wxEmptyString); + m_header->WriteLn(wxT("// Virtual event handlers, override them in your derived class")); + + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString aux = eventHandlerPrefix + wxT("void ") + event->GetValue() + wxT("( ") + + event->GetEventInfo()->GetEventClassName() + wxT("& event )") + eventHandlerPostfix; + + if (generatedHandlers.find(aux) == generatedHandlers.end()) { + m_header->WriteLn(aux); + generatedHandlers.insert(aux); + } + } + m_header->WriteLn(wxEmptyString); + } } void CppCodeGenerator::GenAttributeDeclaration(PObjectBase obj, Permission perm, ArrayItems& arrays) { - wxString typeName = obj->GetObjectTypeName(); - if ( ObjectDatabase::HasCppProperties( typeName ) ) - { - wxString perm_str = obj->GetProperty( wxT( "permission" ) )->GetValue(); - - if ( ( perm == P_PUBLIC && perm_str == wxT( "public" ) ) || - ( perm == P_PROTECTED && perm_str == wxT( "protected" ) ) || - ( perm == P_PRIVATE && perm_str == wxT( "private" ) ) ) - { - const auto& code = GetDeclaration(obj, arrays, perm != P_PRIVATE && m_useArrayEnum); - if ( !code.empty() ) - m_header->WriteLn( code ); - } - } - - // Generate recursively the rest of the attributes - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - - GenAttributeDeclaration(child, perm, arrays); - } + wxString typeName = obj->GetObjectTypeName(); + if (ObjectDatabase::HasCppProperties(typeName)) { + wxString perm_str = obj->GetProperty(wxT("permission"))->GetValue(); + + if ( + (perm == P_PUBLIC && perm_str == wxT("public")) || (perm == P_PROTECTED && perm_str == wxT("protected")) || + (perm == P_PRIVATE && perm_str == wxT("private"))) { + const auto& code = GetDeclaration(obj, arrays, perm != P_PRIVATE && m_useArrayEnum); + if (!code.empty()) + m_header->WriteLn(code); + } + } + + // Generate recursively the rest of the attributes + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + + GenAttributeDeclaration(child, perm, arrays); + } } -void CppCodeGenerator::GenValidatorVariables( PObjectBase obj ) +void CppCodeGenerator::GenValidatorVariables(PObjectBase obj) { - GenValVarsBase( obj->GetObjectInfo(), obj ); - - // Proceeding recursively with the children - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenValidatorVariables( child ); - } + GenValVarsBase(obj->GetObjectInfo(), obj); + + // Proceeding recursively with the children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenValidatorVariables(child); + } } -void CppCodeGenerator::GenValVarsBase( PObjectInfo info, PObjectBase obj ) +void CppCodeGenerator::GenValVarsBase(PObjectInfo info, PObjectBase obj) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT( "C++" ) ); - - if ( !code_info ) - { - return; - } - - _template = code_info->GetTemplate( wxT( "valvar_declaration" ) ); - - if ( !_template.empty() ) - { - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_header->WriteLn( code ); - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenValVarsBase( base_info, obj ); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("C++")); + + if (!code_info) { + return; + } + + _template = code_info->GetTemplate(wxT("valvar_declaration")); + + if (!_template.empty()) { + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_header->WriteLn(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenValVarsBase(base_info, obj); + } } -void CppCodeGenerator::GetGenEventHandlers( PObjectBase obj ) +void CppCodeGenerator::GetGenEventHandlers(PObjectBase obj) { - GenDefinedEventHandlers( obj->GetObjectInfo(), obj ); - - // Process child widgets - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - GetGenEventHandlers( child ); - } + GenDefinedEventHandlers(obj->GetObjectInfo(), obj); + + // Process child widgets + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GetGenEventHandlers(child); + } } -void CppCodeGenerator::GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ) +void CppCodeGenerator::GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj) { - PCodeInfo code_info = info->GetCodeInfo( wxT( "C++" ) ); - if ( code_info ) - { - wxString _template = code_info->GetTemplate( wxT( "generated_event_handlers" ) ); - if ( !_template.empty() ) - { - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - - if ( !code.empty() ) - { - m_header->WriteLn( code ); - } - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenDefinedEventHandlers( base_info, obj ); - } + PCodeInfo code_info = info->GetCodeInfo(wxT("C++")); + if (code_info) { + wxString _template = code_info->GetTemplate(wxT("generated_event_handlers")); + if (!_template.empty()) { + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + + if (!code.empty()) { + m_header->WriteLn(code); + } + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenDefinedEventHandlers(base_info, obj); + } } -wxString CppCodeGenerator::GetCode( PObjectBase obj, wxString name ) +wxString CppCodeGenerator::GetCode(PObjectBase obj, wxString name) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT( "C++" ) ); + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("C++")); - if ( !code_info ) - { - wxString msg( wxString::Format( wxT( "Missing \"%s\" template for \"%s\" class. Review your XML object description" ), - name, obj->GetClassName() ) ); - wxLogError( msg ); - return wxEmptyString; - } + if (!code_info) { + wxString msg(wxString::Format( + wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), name, + obj->GetClassName())); + wxLogError(msg); + return wxEmptyString; + } - _template = code_info->GetTemplate( name ); + _template = code_info->GetTemplate(name); - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); - return code; + return code; } wxString CppCodeGenerator::GetDeclaration(PObjectBase obj, ArrayItems& arrays, bool useEnum) { - // Get the name - const auto& propName = obj->GetProperty(wxT("name")); - if (!propName) - { - // Object has no name, just get its code - return GetCode(obj, wxT("declaration")); - } - - // Object has a name, check if its an array - const auto& name = propName->GetValue(); - wxString baseName; - ArrayItem unused; - if (!ParseArrayName(name, baseName, unused)) - { - // Object is not an array, just get its code - return GetCode(obj, wxT("declaration")); - } - - // Object is an array, check if it needs to be declared - auto& item = arrays[baseName]; - if (item.isDeclared) - { - // Object is already declared, return empty result - return wxEmptyString; - } - - // Array needs to be declared - wxString code; - - if (useEnum) - { - // Generate enum value with element count of the array dimensions - const auto enumBaseName = baseName.Upper(); - if (item.maxIndex.size() == 1) - { - // Without dimension index - code.append(wxString::Format(wxT("enum { %s_SIZE = %u };\n"), enumBaseName, static_cast(item.maxIndex[0] + 1))); - } - else - { - // With dimension index - code.append(wxT("enum { ")); - for (size_t i = 0; i < item.maxIndex.size(); ++i) - { - if (i > 0) - { - code.append(wxT(", ")); - } - code.append(wxString::Format(wxT("%s_%u_SIZE = %u"), enumBaseName, static_cast(i), static_cast(item.maxIndex[i] + 1))); - } - code.append(wxT(" };\n")); - } - } - - // Construct proper name for declaration - auto targetName = baseName; - for (const auto& index : item.maxIndex) - { - targetName.append(wxString::Format(wxT("[%u]"), static_cast(index + 1))); - } - - // Set declaration name - propName->SetValue(targetName); - // Get the Code - code.append(GetCode(obj, wxT("declaration"))); - // Restore the name - propName->SetValue(name); - - // Mark the array as declared - item.isDeclared = true; - - return code; + // Get the name + const auto& propName = obj->GetProperty(wxT("name")); + if (!propName) { + // Object has no name, just get its code + return GetCode(obj, wxT("declaration")); + } + + // Object has a name, check if its an array + const auto& name = propName->GetValue(); + wxString baseName; + ArrayItem unused; + if (!ParseArrayName(name, baseName, unused)) { + // Object is not an array, just get its code + return GetCode(obj, wxT("declaration")); + } + + // Object is an array, check if it needs to be declared + auto& item = arrays[baseName]; + if (item.isDeclared) { + // Object is already declared, return empty result + return wxEmptyString; + } + + // Array needs to be declared + wxString code; + + if (useEnum) { + // Generate enum value with element count of the array dimensions + const auto enumBaseName = baseName.Upper(); + if (item.maxIndex.size() == 1) { + // Without dimension index + code.append(wxString::Format( + wxT("enum { %s_SIZE = %u };\n"), enumBaseName, static_cast(item.maxIndex[0] + 1))); + } else { + // With dimension index + code.append(wxT("enum { ")); + for (size_t i = 0; i < item.maxIndex.size(); ++i) { + if (i > 0) { + code.append(wxT(", ")); + } + code.append(wxString::Format( + wxT("%s_%u_SIZE = %u"), enumBaseName, static_cast(i), + static_cast(item.maxIndex[i] + 1))); + } + code.append(wxT(" };\n")); + } + } + + // Construct proper name for declaration + auto targetName = baseName; + for (const auto& index : item.maxIndex) { + targetName.append(wxString::Format(wxT("[%u]"), static_cast(index + 1))); + } + + // Set declaration name + propName->SetValue(targetName); + // Get the Code + code.append(GetCode(obj, wxT("declaration"))); + // Restore the name + propName->SetValue(name); + + // Mark the array as declared + item.isDeclared = true; + + return code; } -void CppCodeGenerator::GenClassDeclaration(PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector &events, ArrayItems& arrays) +void CppCodeGenerator::GenClassDeclaration( + PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, ArrayItems& arrays) { - PProperty propName = class_obj->GetProperty( wxT( "name" ) ); - if ( !propName ) - { - wxLogError( wxT( "Missing \"name\" property on \"%s\" class. Review your XML object description" ), - class_obj->GetClassName() ); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT( "Object name can not be null" ) ); - return; - } - - m_header->WriteLn( wxT( "///////////////////////////////////////////////////////////////////////////////" ) ); - m_header->WriteLn( wxT( "/// Class " ) + class_name ); - m_header->WriteLn( wxT( "///////////////////////////////////////////////////////////////////////////////" ) ); - - m_header->WriteLn( wxT( "class " ) + classDecoration + class_name + wxT( " : " ) + GetCode( class_obj, wxT( "base" ) ) ); - m_header->WriteLn( wxT( "{" ) ); - m_header->Indent(); - - // are there event handlers? - if ( !m_useConnect && events.size() > 0 ) - { - m_header->WriteLn( wxT( "DECLARE_EVENT_TABLE()" ) ); - } - - // private - m_header->WriteLn( wxT( "private:" ) ); - m_header->Indent(); - GenAttributeDeclaration(class_obj, P_PRIVATE, arrays); - - if ( !m_useConnect ) - { - GenPrivateEventHandlers( events ); - } - - m_header->Unindent(); - m_header->WriteLn(wxEmptyString); - - // protected - m_header->WriteLn( wxT( "protected:" ) ); - m_header->Indent(); - - if ( use_enum ) - GenEnumIds( class_obj ); - - GenAttributeDeclaration(class_obj, P_PROTECTED, arrays); - - wxString eventHandlerKind; - wxString eventHandlerPrefix; - wxString eventHandlerPostfix; - - PProperty eventHandlerKindProp = class_obj->GetProperty( wxT( "event_handler" ) ); - if ( eventHandlerKindProp ) - { - eventHandlerKind = eventHandlerKindProp->GetValueAsString(); - } - - if ( 0 == eventHandlerKind.compare( wxT( "decl_pure_virtual" ) ) ) - { - eventHandlerPrefix = wxT( "virtual " ); - eventHandlerPostfix = wxT( " = 0;" ); - } - else if ( 0 == eventHandlerKind.compare( wxT( "decl" ) ) ) - { - eventHandlerPrefix = wxEmptyString; - eventHandlerPostfix = wxT( ";" ); - } - else // Default: impl_virtual - { - eventHandlerPrefix = wxT( "virtual " ); - eventHandlerPostfix = wxT( " { event.Skip(); }" ); - } - - GenVirtualEventHandlers( events, eventHandlerPrefix, eventHandlerPostfix ); - - m_header->Unindent(); - m_header->WriteLn(wxEmptyString); - - // public - m_header->WriteLn( wxT( "public:" ) ); - m_header->Indent(); - GenAttributeDeclaration(class_obj, P_PUBLIC, arrays); - - // Validators' variables - GenValidatorVariables( class_obj ); - m_header->WriteLn(wxEmptyString); - - // The constructor is also included within public - m_header->WriteLn( GetCode( class_obj, wxT( "cons_decl" ) ) ); - - // Destructor - m_header->WriteLn( wxString::Format( wxT( "~%s();" ), class_name ) ); - - GetGenEventHandlers( class_obj ); - m_header->Unindent(); - m_header->WriteLn(wxEmptyString); - - m_header->Unindent(); - m_header->WriteLn( wxT( "};" ) ); - m_header->WriteLn(wxEmptyString); + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name can not be null")); + return; + } + + m_header->WriteLn(wxT("///////////////////////////////////////////////////////////////////////////////")); + m_header->WriteLn(wxT("/// Class ") + class_name); + m_header->WriteLn(wxT("///////////////////////////////////////////////////////////////////////////////")); + + m_header->WriteLn(wxT("class ") + classDecoration + class_name + wxT(" : ") + GetCode(class_obj, wxT("base"))); + m_header->WriteLn(wxT("{")); + m_header->Indent(); + + // are there event handlers? + if (!m_useConnect && events.size() > 0) { + m_header->WriteLn(wxT("DECLARE_EVENT_TABLE()")); + } + + // private + m_header->WriteLn(wxT("private:")); + m_header->Indent(); + GenAttributeDeclaration(class_obj, P_PRIVATE, arrays); + + if (!m_useConnect) { + GenPrivateEventHandlers(events); + } + + m_header->Unindent(); + m_header->WriteLn(wxEmptyString); + + // protected + m_header->WriteLn(wxT("protected:")); + m_header->Indent(); + + if (use_enum) + GenEnumIds(class_obj); + + GenAttributeDeclaration(class_obj, P_PROTECTED, arrays); + + wxString eventHandlerKind; + wxString eventHandlerPrefix; + wxString eventHandlerPostfix; + + PProperty eventHandlerKindProp = class_obj->GetProperty(wxT("event_handler")); + if (eventHandlerKindProp) { + eventHandlerKind = eventHandlerKindProp->GetValueAsString(); + } + + if (0 == eventHandlerKind.compare(wxT("decl_pure_virtual"))) { + eventHandlerPrefix = wxT("virtual "); + eventHandlerPostfix = wxT(" = 0;"); + } else if (0 == eventHandlerKind.compare(wxT("decl"))) { + eventHandlerPrefix = wxEmptyString; + eventHandlerPostfix = wxT(";"); + } else // Default: impl_virtual + { + eventHandlerPrefix = wxT("virtual "); + eventHandlerPostfix = wxT(" { event.Skip(); }"); + } + + GenVirtualEventHandlers(events, eventHandlerPrefix, eventHandlerPostfix); + + m_header->Unindent(); + m_header->WriteLn(wxEmptyString); + + // public + m_header->WriteLn(wxT("public:")); + m_header->Indent(); + GenAttributeDeclaration(class_obj, P_PUBLIC, arrays); + + // Validators' variables + GenValidatorVariables(class_obj); + m_header->WriteLn(wxEmptyString); + + // The constructor is also included within public + m_header->WriteLn(GetCode(class_obj, wxT("cons_decl"))); + + // Destructor + m_header->WriteLn(wxString::Format(wxT("~%s();"), class_name)); + + GetGenEventHandlers(class_obj); + m_header->Unindent(); + m_header->WriteLn(wxEmptyString); + + m_header->Unindent(); + m_header->WriteLn(wxT("};")); + m_header->WriteLn(wxEmptyString); } -void CppCodeGenerator::GenEnumIds( PObjectBase class_obj ) +void CppCodeGenerator::GenEnumIds(PObjectBase class_obj) { - std::vector< wxString > macros; - FindMacros( class_obj, ¯os ); - - std::vector< wxString >::iterator it = macros.begin(); - if ( it != macros.end() ) - { - m_header->WriteLn( wxT( "enum" ) ); - m_header->WriteLn( wxT( "{" ) ); - m_header->Indent(); - - // Remove the default macro from the set, for backward compatibility - it = std::find( macros.begin(), macros.end(), wxT( "ID_DEFAULT" ) ); - if ( it != macros.end() ) - { - // The default macro is defined to wxID_ANY - m_header->WriteLn( wxT( "ID_DEFAULT = wxID_ANY, // Default" ) ); - macros.erase( it ); - } - - size_t idx; - size_t count = macros.size(); - wxString sId; - - for ( idx = 0; idx < count; idx++ ) - { - sId = macros.at( idx ); - - if ( idx == 0 ) - sId = wxString::Format( wxT("%s = %i"), sId, m_firstID ); - - if ( idx < (count-1) ) - sId << wxT(","); - - m_header->WriteLn( sId ); - } - - //m_header->WriteLn(id); - m_header->Unindent(); - m_header->WriteLn( wxT( "};" ) ); - m_header->WriteLn( wxEmptyString ); - } + std::vector macros; + FindMacros(class_obj, ¯os); + + std::vector::iterator it = macros.begin(); + if (it != macros.end()) { + m_header->WriteLn(wxT("enum")); + m_header->WriteLn(wxT("{")); + m_header->Indent(); + + // Remove the default macro from the set, for backward compatibility + it = std::find(macros.begin(), macros.end(), wxT("ID_DEFAULT")); + if (it != macros.end()) { + // The default macro is defined to wxID_ANY + m_header->WriteLn(wxT("ID_DEFAULT = wxID_ANY, // Default")); + macros.erase(it); + } + + size_t idx; + size_t count = macros.size(); + wxString sId; + + for (idx = 0; idx < count; idx++) { + sId = macros.at(idx); + + if (idx == 0) + sId = wxString::Format(wxT("%s = %i"), sId, m_firstID); + + if (idx < (count - 1)) + sId << wxT(","); + + m_header->WriteLn(sId); + } + + // m_header->WriteLn(id); + m_header->Unindent(); + m_header->WriteLn(wxT("};")); + m_header->WriteLn(wxEmptyString); + } } -void CppCodeGenerator::GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::set< wxString >* sourceIncludes, std::vector< wxString >* headerIncludes ) +void CppCodeGenerator::GenSubclassSets( + PObjectBase obj, std::set* subclasses, std::set* sourceIncludes, + std::vector* headerIncludes) { - // Call GenSubclassForwardDeclarations on all children as well - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenSubclassSets( obj->GetChild( i ), subclasses, sourceIncludes, headerIncludes ); - } - - // Fill the set - PProperty subclass = obj->GetProperty( wxT( "subclass" ) ); - if ( subclass ) - { - std::map< wxString, wxString > children; - subclass->SplitParentProperty( &children ); - - std::map< wxString, wxString >::iterator name; - name = children.find( wxT( "name" ) ); - - if ( children.end() == name ) - { - // No name, so do nothing - return; - } - - wxString nameVal = name->second; - if ( nameVal.empty() ) - { - // No name, so do nothing - return; - } - - //check if user wants to include the header or forward declare - bool forward_declare = true; - std::map< wxString, wxString >::iterator forward_declare_it = children.find( wxT( "forward_declare" ) ); - if ( children.end() != forward_declare_it ) - { - // The value needs to be tested like ObjectInspector does - forward_declare = (forward_declare_it->second == forward_declare_it->first); - } - - //get namespaces - wxString originalValue = nameVal; - int delimiter = nameVal.Find( wxT( "::" ) ) ; - wxString forwardDecl = wxT( "class " ) + nameVal + wxT( ";" ); - if ( wxNOT_FOUND != delimiter ) - { - wxString subClassPrefix, subClassSuffix; - do - { - wxString namespaceStr; - namespaceStr = nameVal.Mid( 0, delimiter ); - if ( namespaceStr.empty() ) - { - break; - } - subClassPrefix += wxT( "namespace " ) + namespaceStr + wxT( "{ " ); - subClassSuffix += wxT( " }" ); - - nameVal = nameVal.Mid( delimiter + 2 ); - delimiter = nameVal.Find( wxT( "::" ) ); - - } while ( delimiter != wxNOT_FOUND ); - - if ( delimiter != wxNOT_FOUND || nameVal.empty() ) - { - wxLogError ( _( "Invalid Value for Property\n\tObject: %s\n\tProperty: %s\n\tValue: %s" ), - obj->GetPropertyAsString( _( "name" ) ), - _( "subclass" ), - originalValue - ); - return; - } - - forwardDecl = subClassPrefix + wxT( "class " ) + nameVal + wxT( ";" ) + subClassSuffix; - } - - // Now get the header - wxString headerVal; - auto header = children.find(wxT("header")); - if (children.end() != header) - { - headerVal = header->second; - } - - if (headerVal.empty()) - { - // No header, do a forward declare if requested, otherwise do nothing - if (forward_declare) - { - subclasses->insert(forwardDecl); - } - - return; - } - - // Got a header - PObjectInfo info = obj->GetObjectInfo(); - if ( !info ) - { - return; - } - - PObjectPackage pkg = info->GetPackage(); - if ( !pkg ) - { - return; - } - - wxString include = wxT( "#include \"" ) + headerVal + wxT( "\"" ); - if ( pkg->GetPackageName() == wxT( "Forms" ) || - obj->GetChild( 1, wxT("menu") ) || - !forward_declare ) - { - std::vector< wxString >::iterator it = std::find( headerIncludes->begin(), headerIncludes->end(), include ); - if ( headerIncludes->end() == it ) - { - headerIncludes->push_back( include ); - } - } - else - { - subclasses->insert( forwardDecl ); - sourceIncludes->insert( include ); - } - } + // Call GenSubclassForwardDeclarations on all children as well + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + GenSubclassSets(obj->GetChild(i), subclasses, sourceIncludes, headerIncludes); + } + + // Fill the set + PProperty subclass = obj->GetProperty(wxT("subclass")); + if (subclass) { + std::map children; + subclass->SplitParentProperty(&children); + + std::map::iterator name; + name = children.find(wxT("name")); + + if (children.end() == name) { + // No name, so do nothing + return; + } + + wxString nameVal = name->second; + if (nameVal.empty()) { + // No name, so do nothing + return; + } + + // check if user wants to include the header or forward declare + bool forward_declare = true; + std::map::iterator forward_declare_it = children.find(wxT("forward_declare")); + if (children.end() != forward_declare_it) { + // The value needs to be tested like ObjectInspector does + forward_declare = (forward_declare_it->second == forward_declare_it->first); + } + + // get namespaces + wxString originalValue = nameVal; + int delimiter = nameVal.Find(wxT("::")); + wxString forwardDecl = wxT("class ") + nameVal + wxT(";"); + if (wxNOT_FOUND != delimiter) { + wxString subClassPrefix, subClassSuffix; + do { + wxString namespaceStr; + namespaceStr = nameVal.Mid(0, delimiter); + if (namespaceStr.empty()) { + break; + } + subClassPrefix += wxT("namespace ") + namespaceStr + wxT("{ "); + subClassSuffix += wxT(" }"); + + nameVal = nameVal.Mid(delimiter + 2); + delimiter = nameVal.Find(wxT("::")); + + } while (delimiter != wxNOT_FOUND); + + if (delimiter != wxNOT_FOUND || nameVal.empty()) { + wxLogError( + _("Invalid Value for Property\n\tObject: %s\n\tProperty: %s\n\tValue: %s"), + obj->GetPropertyAsString(_("name")), _("subclass"), originalValue); + return; + } + + forwardDecl = subClassPrefix + wxT("class ") + nameVal + wxT(";") + subClassSuffix; + } + + // Now get the header + wxString headerVal; + auto header = children.find(wxT("header")); + if (children.end() != header) { + headerVal = header->second; + } + + if (headerVal.empty()) { + // No header, do a forward declare if requested, otherwise do nothing + if (forward_declare) { + subclasses->insert(forwardDecl); + } + + return; + } + + // Got a header + PObjectInfo info = obj->GetObjectInfo(); + if (!info) { + return; + } + + PObjectPackage pkg = info->GetPackage(); + if (!pkg) { + return; + } + + wxString include = wxT("#include \"") + headerVal + wxT("\""); + if (pkg->GetPackageName() == wxT("Forms") || obj->GetChild(1, wxT("menu")) || !forward_declare) { + std::vector::iterator it = std::find(headerIncludes->begin(), headerIncludes->end(), include); + if (headerIncludes->end() == it) { + headerIncludes->push_back(include); + } + } else { + subclasses->insert(forwardDecl); + sourceIncludes->insert(include); + } + } } -void CppCodeGenerator::GenIncludes( PObjectBase project, std::vector* includes, std::set< wxString >* templates ) +void CppCodeGenerator::GenIncludes(PObjectBase project, std::vector* includes, std::set* templates) { - GenObjectIncludes( project, includes, templates ); + GenObjectIncludes(project, includes, templates); } -void CppCodeGenerator::GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ) +void CppCodeGenerator::GenObjectIncludes( + PObjectBase project, std::vector* includes, std::set* templates) { - // Call GenIncludes on all children as well - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - GenObjectIncludes( project->GetChild( i ), includes, templates ); - } - - // Fill the set - PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo( wxT( "C++" ) ); - if ( code_info ) - { - CppTemplateParser parser( project, code_info->GetTemplate( wxT( "include" ) ), m_i18n, m_useRelativePath, m_basePath ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } - - // Generate includes for base classes - GenBaseIncludes( project->GetObjectInfo(), project, includes, templates ); + // Call GenIncludes on all children as well + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + GenObjectIncludes(project->GetChild(i), includes, templates); + } + + // Fill the set + PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo(wxT("C++")); + if (code_info) { + CppTemplateParser parser( + project, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } + + // Generate includes for base classes + GenBaseIncludes(project->GetObjectInfo(), project, includes, templates); } -void CppCodeGenerator::GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ) +void CppCodeGenerator::GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates) { - if ( !info ) - { - return; - } - - // Process all the base classes recursively - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenBaseIncludes( base_info, obj, includes, templates ); - } - - PCodeInfo code_info = info->GetCodeInfo( wxT( "C++" ) ); - if ( code_info ) - { - CppTemplateParser parser( obj, code_info->GetTemplate( wxT( "include" ) ), m_i18n, m_useRelativePath, m_basePath ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } + if (!info) { + return; + } + + // Process all the base classes recursively + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenBaseIncludes(base_info, obj, includes, templates); + } + + PCodeInfo code_info = info->GetCodeInfo(wxT("C++")); + if (code_info) { + CppTemplateParser parser(obj, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } } -void CppCodeGenerator::AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ) +void CppCodeGenerator::AddUniqueIncludes(const wxString& include, std::vector* includes) { - // Split on newlines to only generate unique include lines - // This strips blank lines and trims - wxStringTokenizer tkz( include, wxT( "\n" ), wxTOKEN_STRTOK ); - - bool inPreproc = false; - - while ( tkz.HasMoreTokens() ) - { - wxString line = tkz.GetNextToken(); - line.Trim( false ); - line.Trim( true ); - - // Anything within a #if preprocessor block will be written - if ( line.StartsWith( wxT( "#if" ) ) ) - { - inPreproc = true; - } - else if ( line.StartsWith( wxT( "#endif" ) ) ) - { - inPreproc = false; - } - - if ( inPreproc ) - { - includes->push_back( line ); - continue; - } - - // If it is not an include line, it will be written - if ( !line.StartsWith( wxT( "#include" ) ) ) - { - includes->push_back( line ); - continue; - } - - // If it is an include, it must be unique to be written - std::vector< wxString >::iterator it = std::find( includes->begin(), includes->end(), line ); - if ( includes->end() == it ) - { - includes->push_back( line ); - } - } + // Split on newlines to only generate unique include lines + // This strips blank lines and trims + wxStringTokenizer tkz(include, wxT("\n"), wxTOKEN_STRTOK); + + bool inPreproc = false; + + while (tkz.HasMoreTokens()) { + wxString line = tkz.GetNextToken(); + line.Trim(false); + line.Trim(true); + + // Anything within a #if preprocessor block will be written + if (line.StartsWith(wxT("#if"))) { + inPreproc = true; + } else if (line.StartsWith(wxT("#endif"))) { + inPreproc = false; + } + + if (inPreproc) { + includes->push_back(line); + continue; + } + + // If it is not an include line, it will be written + if (!line.StartsWith(wxT("#include"))) { + includes->push_back(line); + continue; + } + + // If it is an include, it must be unique to be written + std::vector::iterator it = std::find(includes->begin(), includes->end(), line); + if (includes->end() == it) { + includes->push_back(line); + } + } } -void CppCodeGenerator::FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ) +void CppCodeGenerator::FindDependencies(PObjectBase obj, std::set& info_set) { - unsigned int ch_count = obj->GetChildCount(); - if ( ch_count > 0 ) - { - unsigned int i; - for ( i = 0; i < ch_count; i++ ) - { - PObjectBase child = obj->GetChild( i ); - info_set.insert( child->GetObjectInfo() ); - FindDependencies( child, info_set ); - } - } + unsigned int ch_count = obj->GetChildCount(); + if (ch_count > 0) { + unsigned int i; + for (i = 0; i < ch_count; i++) { + PObjectBase child = obj->GetChild(i); + info_set.insert(child->GetObjectInfo()); + FindDependencies(child, info_set); + } + } } -void CppCodeGenerator::GenConstructor(PObjectBase class_obj, const EventVector &events, ArrayItems& arrays) +void CppCodeGenerator::GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays) { - m_source->WriteLn(); - m_source->WriteLn( GetCode( class_obj, wxT( "cons_def" ) ) ); - m_source->WriteLn( wxT( "{" ) ); - m_source->Indent(); - - wxString settings = GetCode( class_obj, wxT( "settings" ) ); - if ( !settings.empty() ) - { - m_source->WriteLn( settings ); - } - - for ( unsigned int i = 0; i < class_obj->GetChildCount(); i++ ) - { - GenConstruction(class_obj->GetChild(i), true, arrays); - } - - wxString afterAddChild = GetCode( class_obj, wxT( "after_addchild" ) ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - if ( class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0 ) - { - m_source->WriteLn( wxT("for ( unsigned int i = 1; i < m_pages.GetCount(); i++ )") ); - m_source->WriteLn( wxT("{") ); - m_source->Indent(); - m_source->WriteLn( wxT("m_pages.Item( i )->SetPrev( m_pages.Item( i - 1 ) );") ); - m_source->WriteLn( wxT("m_pages.Item( i - 1 )->SetNext( m_pages.Item( i ) );") ); - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); - } - } - - if ( m_useConnect && !events.empty() ) - { - m_source->WriteLn(); - m_source->WriteLn( wxT( "// Connect Events" ) ); - GenEvents( class_obj, events ); - } - - auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); - if (!afterConnectEvents.empty()) - { - m_source->WriteLn(); - m_source->WriteLn(afterConnectEvents); - } - - m_source->Unindent(); - m_source->WriteLn( wxT( "}" ) ); + m_source->WriteLn(); + m_source->WriteLn(GetCode(class_obj, wxT("cons_def"))); + m_source->WriteLn(wxT("{")); + m_source->Indent(); + + wxString settings = GetCode(class_obj, wxT("settings")); + if (!settings.empty()) { + m_source->WriteLn(settings); + } + + for (unsigned int i = 0; i < class_obj->GetChildCount(); i++) { + GenConstruction(class_obj->GetChild(i), true, arrays); + } + + wxString afterAddChild = GetCode(class_obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + if (class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0) { + m_source->WriteLn(wxT("for ( unsigned int i = 1; i < m_pages.GetCount(); i++ )")); + m_source->WriteLn(wxT("{")); + m_source->Indent(); + m_source->WriteLn(wxT("m_pages.Item( i )->SetPrev( m_pages.Item( i - 1 ) );")); + m_source->WriteLn(wxT("m_pages.Item( i - 1 )->SetNext( m_pages.Item( i ) );")); + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + } + } + + if (m_useConnect && !events.empty()) { + m_source->WriteLn(); + m_source->WriteLn(wxT("// Connect Events")); + GenEvents(class_obj, events); + } + + auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); + if (!afterConnectEvents.empty()) { + m_source->WriteLn(); + m_source->WriteLn(afterConnectEvents); + } + + m_source->Unindent(); + m_source->WriteLn(wxT("}")); } -void CppCodeGenerator::GenDestructor( PObjectBase class_obj, const EventVector &events ) +void CppCodeGenerator::GenDestructor(PObjectBase class_obj, const EventVector& events) { - m_source->WriteLn(); - wxString className = class_obj->GetPropertyAsString( wxT( "name" ) ); - m_source->WriteLn( wxString::Format( wxT( "%s::~%s()" ), className, className ) ); - m_source->WriteLn( wxT( "{" ) ); - m_source->Indent(); - - if ( m_disconnectEvents && m_useConnect && !events.empty() ) - { - m_source->WriteLn( wxT( "// Disconnect Events" ) ); - GenEvents( class_obj, events, true ); - m_source->WriteLn(); - } - - // destruct objects - GenDestruction( class_obj ); - - m_source->Unindent(); - m_source->WriteLn( wxT( "}" ) ); + m_source->WriteLn(); + wxString className = class_obj->GetPropertyAsString(wxT("name")); + m_source->WriteLn(wxString::Format(wxT("%s::~%s()"), className, className)); + m_source->WriteLn(wxT("{")); + m_source->Indent(); + + if (m_disconnectEvents && m_useConnect && !events.empty()) { + m_source->WriteLn(wxT("// Disconnect Events")); + GenEvents(class_obj, events, true); + m_source->WriteLn(); + } + + // destruct objects + GenDestruction(class_obj); + + m_source->Unindent(); + m_source->WriteLn(wxT("}")); } void CppCodeGenerator::GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays) { - wxString type = obj->GetObjectTypeName(); - PObjectInfo info = obj->GetObjectInfo(); - - if ( ObjectDatabase::HasCppProperties( type ) ) - { - // Checking if it has not been declared as class attribute - // so that, we will declare it inside the constructor - - wxString perm_str = obj->GetProperty( wxT( "permission" ) )->GetValue(); - if ( perm_str == wxT( "none" ) ) - { - const auto& decl = GetDeclaration(obj, arrays, false); - if ( !decl.empty() ) - { - m_source->WriteLn( decl ); - } - } - - m_source->WriteLn( GetCode( obj, wxT( "construction" ) ) ); - - GenSettings( obj->GetObjectInfo(), obj ); - - bool isWidget = !info->IsSubclassOf( wxT( "sizer" ) ); - - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenConstruction(child, isWidget, arrays); - - if ( type == wxT( "toolbar" ) ) - { - GenAddToolbar( child->GetObjectInfo(), child ); - } - } - - if ( !isWidget ) // sizers - { - wxString afterAddChild = GetCode( obj, wxT( "after_addchild" ) ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - - if ( is_widget ) - { - // the parent object is not a sizer. There is no template for - // this so we'll make it manually. - // It's not a good practice to embed templates into the source code, - // because you will need to recompile... - - wxString _template = wxT("#wxparent $name->SetSizer( $name ); #nl") - wxT("#wxparent $name->Layout();") - wxT("#ifnull #parent $size") - wxT("@{ #nl $name->Fit( #wxparent $name ); @}"); - - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn( parser.ParseTemplate() ); - } - } - else if ( type == wxT( "splitter" ) ) - { - // Generating the split - switch ( obj->GetChildCount() ) - { - case 1: - { - PObjectBase sub1 = obj->GetChild( 0 )->GetChild( 0 ); - wxString _template = wxT( "$name->Initialize( " ); - _template = _template + sub1->GetProperty( wxT( "name" ) )->GetValue() + wxT( " );" ); - - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn( parser.ParseTemplate() ); - break; - } - case 2: - { - PObjectBase sub1, sub2; - sub1 = obj->GetChild( 0 )->GetChild( 0 ); - sub2 = obj->GetChild( 1 )->GetChild( 0 ); - - wxString _template; - if ( obj->GetProperty( wxT( "splitmode" ) )->GetValue() == wxT( "wxSPLIT_VERTICAL" ) ) - { - _template = wxT( "$name->SplitVertically( " ); - } - else - { - _template = wxT( "$name->SplitHorizontally( " ); - } - - _template = _template + sub1->GetProperty( wxT( "name" ) )->GetValue() + - wxT( ", " ) + sub2->GetProperty( wxT( "name" ) )->GetValue() + wxT( ", $sashpos );" ); - - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn( parser.ParseTemplate() ); - break; - } - default: - wxLogError( wxT( "Missing subwindows for wxSplitterWindow widget." ) ); - break; - } - } - else if ( type == wxT( "menubar" ) || - type == wxT( "menu" ) || - type == wxT( "submenu" ) || - type == wxT( "ribbonbar" ) || - type == wxT( "toolbar" ) || - type == wxT( "tool" ) || - type == wxT( "listbook" ) || - type == wxT( "simplebook" ) || - type == wxT( "notebook" ) || - type == wxT( "auinotebook" ) || - type == wxT( "treelistctrl" ) || - type == wxT( "flatnotebook" ) - ) - { - wxString afterAddChild = GetCode( obj, wxT( "after_addchild" ) ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - } - } - else if ( info->IsSubclassOf( wxT( "sizeritembase" ) ) ) - { - // The child must be added to the sizer having in mind the - // child object type (there are 3 different routines) - GenConstruction(obj->GetChild(0), false, arrays); - - PObjectInfo childInfo = obj->GetChild( 0 )->GetObjectInfo(); - wxString temp_name; - if ( childInfo->IsSubclassOf( wxT( "wxWindow" ) ) || wxT( "CustomControl" ) == childInfo->GetClassName() ) - { - temp_name = wxT( "window_add" ); - } - else if ( childInfo->IsSubclassOf( wxT( "sizer" ) ) ) - { - temp_name = wxT( "sizer_add" ); - } - else if ( childInfo->GetClassName() == wxT( "spacer" ) ) - { - temp_name = wxT( "spacer_add" ); - } - else - { - LogDebug( wxT( "SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer." ) ); - return; - } - - m_source->WriteLn( GetCode( obj, temp_name ) ); - } - else if ( type == wxT( "notebookpage" ) || - type == wxT( "flatnotebookpage" ) || - type == wxT( "listbookpage" ) || - type == wxT( "choicebookpage" ) || - type == wxT( "simplebookpage" ) || - type == wxT( "auinotebookpage" ) || - type == wxT(" wizardpagesimple" ) - ) - { - GenConstruction(obj->GetChild(0), false, arrays); - m_source->WriteLn( GetCode( obj, wxT( "page_add" ) ) ); - GenSettings( obj->GetObjectInfo(), obj ); - } - else if ( type == wxT( "treelistctrlcolumn" ) ) - { - m_source->WriteLn( GetCode( obj, wxT( "column_add" ) ) ); - GenSettings( obj->GetObjectInfo(), obj ); - } - else if ( type == wxT( "tool" ) ) - { - // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize - // So hacky, yet so useful ... - wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize( _( "bitmapsize" ) ); - if ( wxDefaultSize != toolbarsize ) - { - PProperty prop = obj->GetProperty( _( "bitmap" ) ); - if ( prop ) - { - wxString oldVal = prop->GetValueAsString(); - wxString path, source; - wxSize toolsize; - TypeConv::ParseBitmapWithResource( oldVal, &path, &source, &toolsize ); - if ( _("Load From Icon Resource") == source && wxDefaultSize == toolsize ) - { - prop->SetValue( wxString::Format( wxT( "%s; %s [%i; %i]" ), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight() ) ); - m_source->WriteLn( GetCode( obj, wxT( "construction" ) ) ); - prop->SetValue( oldVal ); - return; - } - } - } - m_source->WriteLn( GetCode( obj, wxT( "construction" ) ) ); - } - else - { - // Generate the children - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenConstruction(obj->GetChild(i), false, arrays); - } - } + wxString type = obj->GetObjectTypeName(); + PObjectInfo info = obj->GetObjectInfo(); + + if (ObjectDatabase::HasCppProperties(type)) { + // Checking if it has not been declared as class attribute + // so that, we will declare it inside the constructor + + wxString perm_str = obj->GetProperty(wxT("permission"))->GetValue(); + if (perm_str == wxT("none")) { + const auto& decl = GetDeclaration(obj, arrays, false); + if (!decl.empty()) { + m_source->WriteLn(decl); + } + } + + m_source->WriteLn(GetCode(obj, wxT("construction"))); + + GenSettings(obj->GetObjectInfo(), obj); + + bool isWidget = !info->IsSubclassOf(wxT("sizer")); + + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenConstruction(child, isWidget, arrays); + + if (type == wxT("toolbar")) { + GenAddToolbar(child->GetObjectInfo(), child); + } + } + + if (!isWidget) // sizers + { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + + if (is_widget) { + // the parent object is not a sizer. There is no template for + // this so we'll make it manually. + // It's not a good practice to embed templates into the source code, + // because you will need to recompile... + + wxString _template = wxT("#wxparent $name->SetSizer( $name ); #nl") wxT("#wxparent $name->Layout();") + wxT("#ifnull #parent $size") wxT("@{ #nl $name->Fit( #wxparent $name ); @}"); + + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + } + } else if (type == wxT("splitter")) { + // Generating the split + switch (obj->GetChildCount()) { + case 1: { + PObjectBase sub1 = obj->GetChild(0)->GetChild(0); + wxString _template = wxT("$name->Initialize( "); + _template = _template + sub1->GetProperty(wxT("name"))->GetValue() + wxT(" );"); + + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + case 2: { + PObjectBase sub1, sub2; + sub1 = obj->GetChild(0)->GetChild(0); + sub2 = obj->GetChild(1)->GetChild(0); + + wxString _template; + if (obj->GetProperty(wxT("splitmode"))->GetValue() == wxT("wxSPLIT_VERTICAL")) { + _template = wxT("$name->SplitVertically( "); + } else { + _template = wxT("$name->SplitHorizontally( "); + } + + _template = _template + sub1->GetProperty(wxT("name"))->GetValue() + wxT(", ") + + sub2->GetProperty(wxT("name"))->GetValue() + wxT(", $sashpos );"); + + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + default: + wxLogError(wxT("Missing subwindows for wxSplitterWindow widget.")); + break; + } + } else if ( + type == wxT("menubar") || type == wxT("menu") || type == wxT("submenu") || type == wxT("ribbonbar") || + type == wxT("toolbar") || type == wxT("tool") || type == wxT("listbook") || type == wxT("simplebook") || + type == wxT("notebook") || type == wxT("auinotebook") || type == wxT("treelistctrl") || + type == wxT("flatnotebook")) { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + } + } else if (info->IsSubclassOf(wxT("sizeritembase"))) { + // The child must be added to the sizer having in mind the + // child object type (there are 3 different routines) + GenConstruction(obj->GetChild(0), false, arrays); + + PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); + wxString temp_name; + if (childInfo->IsSubclassOf(wxT("wxWindow")) || wxT("CustomControl") == childInfo->GetClassName()) { + temp_name = wxT("window_add"); + } else if (childInfo->IsSubclassOf(wxT("sizer"))) { + temp_name = wxT("sizer_add"); + } else if (childInfo->GetClassName() == wxT("spacer")) { + temp_name = wxT("spacer_add"); + } else { + LogDebug(wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.")); + return; + } + + m_source->WriteLn(GetCode(obj, temp_name)); + } else if ( + type == wxT("notebookpage") || type == wxT("flatnotebookpage") || type == wxT("listbookpage") || + type == wxT("choicebookpage") || type == wxT("simplebookpage") || type == wxT("auinotebookpage") || + type == wxT(" wizardpagesimple")) { + GenConstruction(obj->GetChild(0), false, arrays); + m_source->WriteLn(GetCode(obj, wxT("page_add"))); + GenSettings(obj->GetObjectInfo(), obj); + } else if (type == wxT("treelistctrlcolumn")) { + m_source->WriteLn(GetCode(obj, wxT("column_add"))); + GenSettings(obj->GetObjectInfo(), obj); + } else if (type == wxT("tool")) { + // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize + // So hacky, yet so useful ... + wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize(_("bitmapsize")); + if (wxDefaultSize != toolbarsize) { + PProperty prop = obj->GetProperty(_("bitmap")); + if (prop) { + wxString oldVal = prop->GetValueAsString(); + wxString path, source; + wxSize toolsize; + TypeConv::ParseBitmapWithResource(oldVal, &path, &source, &toolsize); + if (_("Load From Icon Resource") == source && wxDefaultSize == toolsize) { + prop->SetValue(wxString::Format( + wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight())); + m_source->WriteLn(GetCode(obj, wxT("construction"))); + prop->SetValue(oldVal); + return; + } + } + } + m_source->WriteLn(GetCode(obj, wxT("construction"))); + } else { + // Generate the children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { GenConstruction(obj->GetChild(i), false, arrays); } + } } -void CppCodeGenerator::FindMacros( PObjectBase obj, std::vector* macros ) +void CppCodeGenerator::FindMacros(PObjectBase obj, std::vector* macros) { - // iterate through all of the properties of all objects, add the macros - // to the vector - unsigned int i; - - for ( i = 0; i < obj->GetPropertyCount(); i++ ) - { - PProperty prop = obj->GetProperty( i ); - if ( prop->GetType() == PT_MACRO ) - { - wxString value = prop->GetValue(); - // Skip wx IDs - if ( ( ! value.Contains( wxT("XRCID" ) ) ) && - ( m_predMacros.end() == m_predMacros.find( value ) ) ) - { - if ( macros->end() == std::find( macros->begin(), macros->end(), value ) ) - { - macros->push_back( value ); - } - } - } - } - - for ( i = 0; i < obj->GetChildCount(); i++ ) - { - FindMacros( obj->GetChild( i ), macros ); - } + // iterate through all of the properties of all objects, add the macros + // to the vector + unsigned int i; + + for (i = 0; i < obj->GetPropertyCount(); i++) { + PProperty prop = obj->GetProperty(i); + if (prop->GetType() == PT_MACRO) { + wxString value = prop->GetValue(); + // Skip wx IDs + if ((!value.Contains(wxT("XRCID"))) && (m_predMacros.end() == m_predMacros.find(value))) { + if (macros->end() == std::find(macros->begin(), macros->end(), value)) { + macros->push_back(value); + } + } + } + } + + for (i = 0; i < obj->GetChildCount(); i++) { FindMacros(obj->GetChild(i), macros); } } -void CppCodeGenerator::FindEventHandlers( PObjectBase obj, EventVector &events ) +void CppCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector& events) { - unsigned int i; - for ( i = 0; i < obj->GetEventCount(); i++ ) - { - PEvent event = obj->GetEvent( i ); - if ( !event->GetValue().IsEmpty() ) - events.push_back( event ); - } - - for ( i = 0; i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); - FindEventHandlers( child, events ); - } + unsigned int i; + for (i = 0; i < obj->GetEventCount(); i++) { + PEvent event = obj->GetEvent(i); + if (!event->GetValue().IsEmpty()) + events.push_back(event); + } + + for (i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + FindEventHandlers(child, events); + } } -void CppCodeGenerator::GenDefines( PObjectBase project ) +void CppCodeGenerator::GenDefines(PObjectBase project) { - std::vector< wxString > macros; - FindMacros( project, ¯os ); - - // Remove the default macro from the set, for backward compatibility - std::vector< wxString >::iterator it; - it = std::find( macros.begin(), macros.end(), wxT( "ID_DEFAULT" ) ); - if ( it != macros.end() ) - { - // The default macro is defined to wxID_ANY - m_header->WriteLn( wxT( "#define ID_DEFAULT wxID_ANY // Default" ) ); - macros.erase( it ); - } - - unsigned int id = m_firstID; - if ( id < 1000 ) - { - wxLogWarning( wxT( "First ID is Less than 1000" ) ); - } - for ( it = macros.begin() ; it != macros.end(); it++ ) - { - // Don't redefine wx IDs - m_header->WriteLn( wxString::Format( wxT( "#define %s %i" ), it->c_str(), id ) ); - id++; - } - - m_header->WriteLn(wxEmptyString); + std::vector macros; + FindMacros(project, ¯os); + + // Remove the default macro from the set, for backward compatibility + std::vector::iterator it; + it = std::find(macros.begin(), macros.end(), wxT("ID_DEFAULT")); + if (it != macros.end()) { + // The default macro is defined to wxID_ANY + m_header->WriteLn(wxT("#define ID_DEFAULT wxID_ANY // Default")); + macros.erase(it); + } + + unsigned int id = m_firstID; + if (id < 1000) { + wxLogWarning(wxT("First ID is Less than 1000")); + } + for (it = macros.begin(); it != macros.end(); it++) { + // Don't redefine wx IDs + m_header->WriteLn(wxString::Format(wxT("#define %s %i"), it->c_str(), id)); + id++; + } + + m_header->WriteLn(wxEmptyString); } -void CppCodeGenerator::GenSettings( PObjectInfo info, PObjectBase obj ) +void CppCodeGenerator::GenSettings(PObjectInfo info, PObjectBase obj) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT( "C++" ) ); - - if ( !code_info ) - { - return; - } - - _template = code_info->GetTemplate( wxT( "settings" ) ); - - if ( !_template.empty() ) - { - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenSettings( base_info, obj ); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("C++")); + + if (!code_info) { + return; + } + + _template = code_info->GetTemplate(wxT("settings")); + + if (!_template.empty()) { + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenSettings(base_info, obj); + } } -void CppCodeGenerator::GenDestruction( PObjectBase obj ) +void CppCodeGenerator::GenDestruction(PObjectBase obj) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT( "C++" ) ); - - if ( code_info ) - { - _template = code_info->GetTemplate( wxT( "destruction" ) ); - - if ( !_template.empty() ) - { - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - } - } - } - - // Process child widgets - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenDestruction( child ); - } + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("C++")); + + if (code_info) { + _template = code_info->GetTemplate(wxT("destruction")); + + if (!_template.empty()) { + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Process child widgets + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenDestruction(child); + } } -void CppCodeGenerator::GenAddToolbar( PObjectInfo info, PObjectBase obj ) +void CppCodeGenerator::GenAddToolbar(PObjectInfo info, PObjectBase obj) { - wxArrayString arrCode; + wxArrayString arrCode; - GetAddToolbarCode( info, obj, arrCode ); + GetAddToolbarCode(info, obj, arrCode); - for( size_t i = 0; i < arrCode.GetCount(); i++ ) m_source->WriteLn( arrCode[i] ); + for (size_t i = 0; i < arrCode.GetCount(); i++) m_source->WriteLn(arrCode[i]); } -void CppCodeGenerator::GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ) +void CppCodeGenerator::GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT( "C++" ) ); - - if ( !code_info ) - return; - - _template = code_info->GetTemplate( wxT( "toolbar_add" ) ); - - if ( !_template.empty() ) - { - CppTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - if( codelines.Index( code ) == wxNOT_FOUND ) codelines.Add( code ); - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GetAddToolbarCode( base_info, obj, codelines ); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("C++")); + + if (!code_info) + return; + + _template = code_info->GetTemplate(wxT("toolbar_add")); + + if (!_template.empty()) { + CppTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + if (codelines.Index(code) == wxNOT_FOUND) + codelines.Add(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GetAddToolbarCode(base_info, obj, codelines); + } } /////////////////////////////////////////////////////////////////////// -void CppCodeGenerator::GenEmbeddedBitmapIncludes( PObjectBase project ) +void CppCodeGenerator::GenEmbeddedBitmapIncludes(PObjectBase project) { - std::set< wxString > include_set; - - // We begin obtaining the "include" list - FindEmbeddedBitmapProperties( project, include_set ); - - if ( include_set.empty() ) - { - return; - } - - // and then, we generate them - std::set::iterator it; - for ( it = include_set.begin() ; it != include_set.end(); it++ ) - { - if ( !it->empty() ) - { - m_source->WriteLn( *it ); - } - } - - m_source->WriteLn(); + std::set include_set; + + // We begin obtaining the "include" list + FindEmbeddedBitmapProperties(project, include_set); + + if (include_set.empty()) { + return; + } + + // and then, we generate them + std::set::iterator it; + for (it = include_set.begin(); it != include_set.end(); it++) { + if (!it->empty()) { + m_source->WriteLn(*it); + } + } + + m_source->WriteLn(); } -void CppCodeGenerator::FindEmbeddedBitmapProperties( PObjectBase obj, std::set& embedset ) +void CppCodeGenerator::FindEmbeddedBitmapProperties(PObjectBase obj, std::set& embedset) { - // We go through (browse) for each property in "obj" object. If any of the - // PT_BITMAP type is found, then the proper "include" string is added - // in "set". After that, we recursively do it the same with the child objects. - unsigned int i, count; - - count = obj->GetPropertyCount(); - - for ( i = 0; i < count; i++ ) - { - PProperty property = obj->GetProperty( i ); - if ( property->GetType() == PT_BITMAP ) - { - wxString propValue = property->GetValue(); - - wxString path; - wxString source; - wxSize icoSize; - TypeConv::ParseBitmapWithResource( propValue, &path, &source, &icoSize ); - - wxFileName bmpFileName( path ); - if ( bmpFileName.GetExt().Upper() == wxT( "XPM" ) ) - { - wxString absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - - // It's supposed that "path" contains an absolute path to the file - // and not a relative one. - wxString relPath = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath ); - - wxString inc; - inc << wxT( "#include \"" ) << relPath << wxT( "\"" ); - embedset.insert( inc ); - } - else if ( source == _("Load From Embedded File") ) - { - wxString absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - wxString includePath = FileToCArray::Generate( absPath ); - wxString inc; - inc << wxT( "#include \"" ) << includePath << wxT( "\"" ); - embedset.insert( inc ); - } - // NOTE: This is currently not necessary because the default code already contains this header. - // Because the unique include filtering is not global this cannot be enabled without creating a duplicate entry. - //else if (source == _("Load From XRC")) - //{ - // embedset.insert(wxT("#include ")); - //} - } - } - - count = obj->GetChildCount(); - for ( i = 0; i < count; i++ ) - { - PObjectBase child = obj->GetChild( i ); - FindEmbeddedBitmapProperties( child, embedset ); - } + // We go through (browse) for each property in "obj" object. If any of the + // PT_BITMAP type is found, then the proper "include" string is added + // in "set". After that, we recursively do it the same with the child objects. + unsigned int i, count; + + count = obj->GetPropertyCount(); + + for (i = 0; i < count; i++) { + PProperty property = obj->GetProperty(i); + if (property->GetType() == PT_BITMAP) { + wxString propValue = property->GetValue(); + + wxString path; + wxString source; + wxSize icoSize; + TypeConv::ParseBitmapWithResource(propValue, &path, &source, &icoSize); + + wxFileName bmpFileName(path); + if (bmpFileName.GetExt().Upper() == wxT("XPM")) { + wxString absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + + // It's supposed that "path" contains an absolute path to the file + // and not a relative one. + wxString relPath = (m_useRelativePath ? TypeConv::MakeRelativePath(absPath, m_basePath) : absPath); + + wxString inc; + inc << wxT("#include \"") << relPath << wxT("\""); + embedset.insert(inc); + } else if (source == _("Load From Embedded File")) { + wxString absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + wxString includePath = FileToCArray::Generate(absPath); + wxString inc; + inc << wxT("#include \"") << includePath << wxT("\""); + embedset.insert(inc); + } + // NOTE: This is currently not necessary because the default code already contains this header. + // Because the unique include filtering is not global this cannot be enabled without creating a + // duplicate entry. + // else if (source == _("Load From XRC")) + //{ + // embedset.insert(wxT("#include ")); + //} + } + } + + count = obj->GetChildCount(); + for (i = 0; i < count; i++) { + PObjectBase child = obj->GetChild(i); + FindEmbeddedBitmapProperties(child, embedset); + } } -void CppCodeGenerator::UseRelativePath( bool relative, wxString basePath ) +void CppCodeGenerator::UseRelativePath(bool relative, wxString basePath) { - m_useRelativePath = relative; - - if (m_useRelativePath) - { - if (wxFileName::DirExists(basePath)) - { - m_basePath = basePath; - } - else - { - m_basePath = wxEmptyString; - } - } + m_useRelativePath = relative; + + if (m_useRelativePath) { + if (wxFileName::DirExists(basePath)) { + m_basePath = basePath; + } else { + m_basePath = wxEmptyString; + } + } } /* wxString CppCodeGenerator::ConvertToRelativePath(wxString path, wxString basePath) @@ -2153,137 +1855,136 @@ auxPath = _STDSTR(filename.GetFullPath()); return auxPath; }*/ -#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert( wxT(#x) ) +#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert(wxT(#x)) void CppCodeGenerator::SetupPredefinedMacros() { - /* no id matches this one when compared to it */ - ADD_PREDEFINED_MACRO( wxID_NONE ); - - /* id for a separator line in the menu (invalid for normal item) */ - ADD_PREDEFINED_MACRO( wxID_SEPARATOR ); - - ADD_PREDEFINED_MACRO( wxID_ANY ); - - ADD_PREDEFINED_MACRO( wxID_LOWEST ); - - ADD_PREDEFINED_MACRO( wxID_OPEN ); - ADD_PREDEFINED_MACRO( wxID_CLOSE ); - ADD_PREDEFINED_MACRO( wxID_NEW ); - ADD_PREDEFINED_MACRO( wxID_SAVE ); - ADD_PREDEFINED_MACRO( wxID_SAVEAS ); - ADD_PREDEFINED_MACRO( wxID_REVERT ); - ADD_PREDEFINED_MACRO( wxID_EXIT ); - ADD_PREDEFINED_MACRO( wxID_UNDO ); - ADD_PREDEFINED_MACRO( wxID_REDO ); - ADD_PREDEFINED_MACRO( wxID_HELP ); - ADD_PREDEFINED_MACRO( wxID_PRINT ); - ADD_PREDEFINED_MACRO( wxID_PRINT_SETUP ); - ADD_PREDEFINED_MACRO( wxID_PREVIEW ); - ADD_PREDEFINED_MACRO( wxID_ABOUT ); - ADD_PREDEFINED_MACRO( wxID_HELP_CONTENTS ); - ADD_PREDEFINED_MACRO( wxID_HELP_COMMANDS ); - ADD_PREDEFINED_MACRO( wxID_HELP_PROCEDURES ); - ADD_PREDEFINED_MACRO( wxID_HELP_CONTEXT ); - ADD_PREDEFINED_MACRO( wxID_CLOSE_ALL ); - ADD_PREDEFINED_MACRO( wxID_PAGE_SETUP ); - ADD_PREDEFINED_MACRO( wxID_HELP_INDEX ); - ADD_PREDEFINED_MACRO( wxID_HELP_SEARCH ); - ADD_PREDEFINED_MACRO( wxID_PREFERENCES ); - - ADD_PREDEFINED_MACRO( wxID_EDIT ); - ADD_PREDEFINED_MACRO( wxID_CUT ); - ADD_PREDEFINED_MACRO( wxID_COPY ); - ADD_PREDEFINED_MACRO( wxID_PASTE ); - ADD_PREDEFINED_MACRO( wxID_CLEAR ); - ADD_PREDEFINED_MACRO( wxID_FIND ); - - ADD_PREDEFINED_MACRO( wxID_DUPLICATE ); - ADD_PREDEFINED_MACRO( wxID_SELECTALL ); - ADD_PREDEFINED_MACRO( wxID_DELETE ); - ADD_PREDEFINED_MACRO( wxID_REPLACE ); - ADD_PREDEFINED_MACRO( wxID_REPLACE_ALL ); - ADD_PREDEFINED_MACRO( wxID_PROPERTIES ); - - ADD_PREDEFINED_MACRO( wxID_VIEW_DETAILS ); - ADD_PREDEFINED_MACRO( wxID_VIEW_LARGEICONS ); - ADD_PREDEFINED_MACRO( wxID_VIEW_SMALLICONS ); - ADD_PREDEFINED_MACRO( wxID_VIEW_LIST ); - ADD_PREDEFINED_MACRO( wxID_VIEW_SORTDATE ); - ADD_PREDEFINED_MACRO( wxID_VIEW_SORTNAME ); - ADD_PREDEFINED_MACRO( wxID_VIEW_SORTSIZE ); - ADD_PREDEFINED_MACRO( wxID_VIEW_SORTTYPE ); - - ADD_PREDEFINED_MACRO( wxID_FILE ); - ADD_PREDEFINED_MACRO( wxID_FILE1 ); - ADD_PREDEFINED_MACRO( wxID_FILE2 ); - ADD_PREDEFINED_MACRO( wxID_FILE3 ); - ADD_PREDEFINED_MACRO( wxID_FILE4 ); - ADD_PREDEFINED_MACRO( wxID_FILE5 ); - ADD_PREDEFINED_MACRO( wxID_FILE6 ); - ADD_PREDEFINED_MACRO( wxID_FILE7 ); - ADD_PREDEFINED_MACRO( wxID_FILE8 ); - ADD_PREDEFINED_MACRO( wxID_FILE9 ); - - /* Standard button and menu IDs */ - - ADD_PREDEFINED_MACRO( wxID_OK ); - ADD_PREDEFINED_MACRO( wxID_CANCEL ); - - ADD_PREDEFINED_MACRO( wxID_APPLY ); - ADD_PREDEFINED_MACRO( wxID_YES ); - ADD_PREDEFINED_MACRO( wxID_NO ); - ADD_PREDEFINED_MACRO( wxID_STATIC ); - ADD_PREDEFINED_MACRO( wxID_FORWARD ); - ADD_PREDEFINED_MACRO( wxID_BACKWARD ); - ADD_PREDEFINED_MACRO( wxID_DEFAULT ); - ADD_PREDEFINED_MACRO( wxID_MORE ); - ADD_PREDEFINED_MACRO( wxID_SETUP ); - ADD_PREDEFINED_MACRO( wxID_RESET ); - ADD_PREDEFINED_MACRO( wxID_CONTEXT_HELP ); - ADD_PREDEFINED_MACRO( wxID_YESTOALL ); - ADD_PREDEFINED_MACRO( wxID_NOTOALL ); - ADD_PREDEFINED_MACRO( wxID_ABORT ); - ADD_PREDEFINED_MACRO( wxID_RETRY ); - ADD_PREDEFINED_MACRO( wxID_IGNORE ); - ADD_PREDEFINED_MACRO( wxID_ADD ); - ADD_PREDEFINED_MACRO( wxID_REMOVE ); - - ADD_PREDEFINED_MACRO( wxID_UP ); - ADD_PREDEFINED_MACRO( wxID_DOWN ); - ADD_PREDEFINED_MACRO( wxID_HOME ); - ADD_PREDEFINED_MACRO( wxID_REFRESH ); - ADD_PREDEFINED_MACRO( wxID_STOP ); - ADD_PREDEFINED_MACRO( wxID_INDEX ); - - ADD_PREDEFINED_MACRO( wxID_BOLD ); - ADD_PREDEFINED_MACRO( wxID_ITALIC ); - ADD_PREDEFINED_MACRO( wxID_JUSTIFY_CENTER ); - ADD_PREDEFINED_MACRO( wxID_JUSTIFY_FILL ); - ADD_PREDEFINED_MACRO( wxID_JUSTIFY_RIGHT ); - - ADD_PREDEFINED_MACRO( wxID_JUSTIFY_LEFT ); - ADD_PREDEFINED_MACRO( wxID_UNDERLINE ); - ADD_PREDEFINED_MACRO( wxID_INDENT ); - ADD_PREDEFINED_MACRO( wxID_UNINDENT ); - ADD_PREDEFINED_MACRO( wxID_ZOOM_100 ); - ADD_PREDEFINED_MACRO( wxID_ZOOM_FIT ); - ADD_PREDEFINED_MACRO( wxID_ZOOM_IN ); - ADD_PREDEFINED_MACRO( wxID_ZOOM_OUT ); - ADD_PREDEFINED_MACRO( wxID_UNDELETE ); - ADD_PREDEFINED_MACRO( wxID_REVERT_TO_SAVED ); - - /* System menu IDs (used by wxUniv): */ - ADD_PREDEFINED_MACRO( wxID_SYSTEM_MENU ); - ADD_PREDEFINED_MACRO( wxID_CLOSE_FRAME ); - ADD_PREDEFINED_MACRO( wxID_MOVE_FRAME ); - ADD_PREDEFINED_MACRO( wxID_RESIZE_FRAME ); - ADD_PREDEFINED_MACRO( wxID_MAXIMIZE_FRAME ); - ADD_PREDEFINED_MACRO( wxID_ICONIZE_FRAME ); - ADD_PREDEFINED_MACRO( wxID_RESTORE_FRAME ); - - /* IDs used by generic file dialog (13 consecutive starting from this value) */ - ADD_PREDEFINED_MACRO( wxID_FILEDLGG ); - - ADD_PREDEFINED_MACRO( wxID_HIGHEST ); - + /* no id matches this one when compared to it */ + ADD_PREDEFINED_MACRO(wxID_NONE); + + /* id for a separator line in the menu (invalid for normal item) */ + ADD_PREDEFINED_MACRO(wxID_SEPARATOR); + + ADD_PREDEFINED_MACRO(wxID_ANY); + + ADD_PREDEFINED_MACRO(wxID_LOWEST); + + ADD_PREDEFINED_MACRO(wxID_OPEN); + ADD_PREDEFINED_MACRO(wxID_CLOSE); + ADD_PREDEFINED_MACRO(wxID_NEW); + ADD_PREDEFINED_MACRO(wxID_SAVE); + ADD_PREDEFINED_MACRO(wxID_SAVEAS); + ADD_PREDEFINED_MACRO(wxID_REVERT); + ADD_PREDEFINED_MACRO(wxID_EXIT); + ADD_PREDEFINED_MACRO(wxID_UNDO); + ADD_PREDEFINED_MACRO(wxID_REDO); + ADD_PREDEFINED_MACRO(wxID_HELP); + ADD_PREDEFINED_MACRO(wxID_PRINT); + ADD_PREDEFINED_MACRO(wxID_PRINT_SETUP); + ADD_PREDEFINED_MACRO(wxID_PREVIEW); + ADD_PREDEFINED_MACRO(wxID_ABOUT); + ADD_PREDEFINED_MACRO(wxID_HELP_CONTENTS); + ADD_PREDEFINED_MACRO(wxID_HELP_COMMANDS); + ADD_PREDEFINED_MACRO(wxID_HELP_PROCEDURES); + ADD_PREDEFINED_MACRO(wxID_HELP_CONTEXT); + ADD_PREDEFINED_MACRO(wxID_CLOSE_ALL); + ADD_PREDEFINED_MACRO(wxID_PAGE_SETUP); + ADD_PREDEFINED_MACRO(wxID_HELP_INDEX); + ADD_PREDEFINED_MACRO(wxID_HELP_SEARCH); + ADD_PREDEFINED_MACRO(wxID_PREFERENCES); + + ADD_PREDEFINED_MACRO(wxID_EDIT); + ADD_PREDEFINED_MACRO(wxID_CUT); + ADD_PREDEFINED_MACRO(wxID_COPY); + ADD_PREDEFINED_MACRO(wxID_PASTE); + ADD_PREDEFINED_MACRO(wxID_CLEAR); + ADD_PREDEFINED_MACRO(wxID_FIND); + + ADD_PREDEFINED_MACRO(wxID_DUPLICATE); + ADD_PREDEFINED_MACRO(wxID_SELECTALL); + ADD_PREDEFINED_MACRO(wxID_DELETE); + ADD_PREDEFINED_MACRO(wxID_REPLACE); + ADD_PREDEFINED_MACRO(wxID_REPLACE_ALL); + ADD_PREDEFINED_MACRO(wxID_PROPERTIES); + + ADD_PREDEFINED_MACRO(wxID_VIEW_DETAILS); + ADD_PREDEFINED_MACRO(wxID_VIEW_LARGEICONS); + ADD_PREDEFINED_MACRO(wxID_VIEW_SMALLICONS); + ADD_PREDEFINED_MACRO(wxID_VIEW_LIST); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTDATE); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTNAME); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTSIZE); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTTYPE); + + ADD_PREDEFINED_MACRO(wxID_FILE); + ADD_PREDEFINED_MACRO(wxID_FILE1); + ADD_PREDEFINED_MACRO(wxID_FILE2); + ADD_PREDEFINED_MACRO(wxID_FILE3); + ADD_PREDEFINED_MACRO(wxID_FILE4); + ADD_PREDEFINED_MACRO(wxID_FILE5); + ADD_PREDEFINED_MACRO(wxID_FILE6); + ADD_PREDEFINED_MACRO(wxID_FILE7); + ADD_PREDEFINED_MACRO(wxID_FILE8); + ADD_PREDEFINED_MACRO(wxID_FILE9); + + /* Standard button and menu IDs */ + + ADD_PREDEFINED_MACRO(wxID_OK); + ADD_PREDEFINED_MACRO(wxID_CANCEL); + + ADD_PREDEFINED_MACRO(wxID_APPLY); + ADD_PREDEFINED_MACRO(wxID_YES); + ADD_PREDEFINED_MACRO(wxID_NO); + ADD_PREDEFINED_MACRO(wxID_STATIC); + ADD_PREDEFINED_MACRO(wxID_FORWARD); + ADD_PREDEFINED_MACRO(wxID_BACKWARD); + ADD_PREDEFINED_MACRO(wxID_DEFAULT); + ADD_PREDEFINED_MACRO(wxID_MORE); + ADD_PREDEFINED_MACRO(wxID_SETUP); + ADD_PREDEFINED_MACRO(wxID_RESET); + ADD_PREDEFINED_MACRO(wxID_CONTEXT_HELP); + ADD_PREDEFINED_MACRO(wxID_YESTOALL); + ADD_PREDEFINED_MACRO(wxID_NOTOALL); + ADD_PREDEFINED_MACRO(wxID_ABORT); + ADD_PREDEFINED_MACRO(wxID_RETRY); + ADD_PREDEFINED_MACRO(wxID_IGNORE); + ADD_PREDEFINED_MACRO(wxID_ADD); + ADD_PREDEFINED_MACRO(wxID_REMOVE); + + ADD_PREDEFINED_MACRO(wxID_UP); + ADD_PREDEFINED_MACRO(wxID_DOWN); + ADD_PREDEFINED_MACRO(wxID_HOME); + ADD_PREDEFINED_MACRO(wxID_REFRESH); + ADD_PREDEFINED_MACRO(wxID_STOP); + ADD_PREDEFINED_MACRO(wxID_INDEX); + + ADD_PREDEFINED_MACRO(wxID_BOLD); + ADD_PREDEFINED_MACRO(wxID_ITALIC); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_CENTER); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_FILL); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_RIGHT); + + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_LEFT); + ADD_PREDEFINED_MACRO(wxID_UNDERLINE); + ADD_PREDEFINED_MACRO(wxID_INDENT); + ADD_PREDEFINED_MACRO(wxID_UNINDENT); + ADD_PREDEFINED_MACRO(wxID_ZOOM_100); + ADD_PREDEFINED_MACRO(wxID_ZOOM_FIT); + ADD_PREDEFINED_MACRO(wxID_ZOOM_IN); + ADD_PREDEFINED_MACRO(wxID_ZOOM_OUT); + ADD_PREDEFINED_MACRO(wxID_UNDELETE); + ADD_PREDEFINED_MACRO(wxID_REVERT_TO_SAVED); + + /* System menu IDs (used by wxUniv): */ + ADD_PREDEFINED_MACRO(wxID_SYSTEM_MENU); + ADD_PREDEFINED_MACRO(wxID_CLOSE_FRAME); + ADD_PREDEFINED_MACRO(wxID_MOVE_FRAME); + ADD_PREDEFINED_MACRO(wxID_RESIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_MAXIMIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_ICONIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_RESTORE_FRAME); + + /* IDs used by generic file dialog (13 consecutive starting from this value) */ + ADD_PREDEFINED_MACRO(wxID_FILEDLGG); + + ADD_PREDEFINED_MACRO(wxID_HIGHEST); } diff --git a/src/codegen/cppcg.h b/src/codegen/cppcg.h index 1e984d632..74e96774f 100644 --- a/src/codegen/cppcg.h +++ b/src/codegen/cppcg.h @@ -29,277 +29,275 @@ @author Juan Antonio Ortega - jortegalalmolda@gmail.com @note The implementation of the generation of relative paths is a little hacky, and not a solution. -The value of all properties that are file or a directory paths must be absolute, otherwise the code generation will not work. +The value of all properties that are file or a directory paths must be absolute, otherwise the code generation will not +work. */ #ifndef CODEGEN_CPPCG_H #define CODEGEN_CPPCG_H +#include +#include + #include "codegen/codegen.h" #include "codegen/codeparser.h" -#include -#include /** -* Parse the C++ templates. -*/ + * Parse the C++ templates. + */ class CppTemplateParser : public TemplateParser { private: - bool m_i18n; - bool m_useRelativePath; - wxString m_basePath; + bool m_i18n; + bool m_useRelativePath; + wxString m_basePath; public: - CppTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath ); - CppTemplateParser( const CppTemplateParser & that, wxString _template ); + CppTemplateParser(PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath); + CppTemplateParser(const CppTemplateParser& that, wxString _template); - // overrides for C++ - PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; - wxString RootWxParentToCode() override; - wxString ValueToCode(PropertyType type, wxString value) override; + // overrides for C++ + PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; + wxString RootWxParentToCode() override; + wxString ValueToCode(PropertyType type, wxString value) override; }; /** -* Generate the C++ code -*/ + * Generate the C++ code + */ class CppCodeGenerator : public CodeGenerator { private: - typedef enum - { - P_PRIVATE, - P_PROTECTED, - P_PUBLIC - } Permission; - - CCodeParser m_inheritedCodeParser; - - PCodeWriter m_header; - PCodeWriter m_source; - - bool m_useRelativePath; - bool m_useArrayEnum; - bool m_i18n; - wxString m_basePath; - unsigned int m_firstID; - bool m_useConnect; - bool m_disconnectEvents; - - /** - * Predefined macros won't generate defines. - */ - std::set m_predMacros; - - void SetupPredefinedMacros(); - - /** - * Given an object and the name for a template, obtains the code. - */ - wxString GetCode( PObjectBase obj, wxString name); - - /** - * Gets the declaration fragment for the specified object. - * - * This method encapsulates the adjustments that need to be made for array declarations. - */ - wxString GetDeclaration(PObjectBase obj, ArrayItems& arrays, bool useEnum); - - /** - * Stores the project's objects classes set, for generating the includes. - */ - void FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ); - - /** - * Stores the needed "includes" set for the PT_BITMAP properties. - */ - void FindEmbeddedBitmapProperties( PObjectBase obj, std::set< wxString >& embedset); - - /** - * Stores all the properties for "macro" type objects, so that their - * related '#define' can be generated subsequently. - */ - void FindMacros( PObjectBase obj, std::vector< wxString >* macros ); - - /** - * Looks for "non-null" event handlers (PEvent) and collects it into a vector. - */ - void FindEventHandlers(PObjectBase obj, EventVector &events); - - /** - * Generates classes declarations inside the header file. - */ - void GenClassDeclaration(PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector &events, ArrayItems& arrays); - - /** - * Generates the event table. - */ - void GenEvents( PObjectBase class_obj, const EventVector &events, bool disconnect = false ); - - /** - * helper function to find the event table entry template in the class or its base classes - */ - bool GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect = false ); - - /** - * Recursive function for the attributes declaration, used inside GenClassDeclaration. - */ - void GenAttributeDeclaration(PObjectBase obj, Permission perm, ArrayItems& arrays); - - /** - * Recursive function for the validators' variables declaration, used inside GenClassDeclaration. - */ - void GenValidatorVariables( PObjectBase obj); - /** - * Recursive function for the validators' variables declaration, used inside GenClassDeclaration. - */ - void GenValVarsBase( PObjectInfo info, PObjectBase obj); - - /** - * Generates the generated_event_handlers template - */ - void GetGenEventHandlers( PObjectBase obj ); - /** - * Generates the generated_event_handlers template - */ - void GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ); - - /** - * Generates the '#include' section for files. - */ - void GenIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ); - void AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ); - - /** - * Generate a set of all subclasses to forward declare in the generated header file. - * Also generate sets of header files to be include in either the source or header file. - */ - void GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::set< wxString >* sourceIncludes, std::vector< wxString >* headerIncludes ); - - /** - * Generates the '#include' section for the embedded bitmap properties. - */ - void GenEmbeddedBitmapIncludes( PObjectBase project); - - /** - * Generates the '#define' section for macros. - */ - void GenDefines( PObjectBase project); - - /** - * Generates an enum with wxWindow identifiers. - */ - void GenEnumIds( PObjectBase class_obj); - - /** - * Generates the constructor for a class - */ - void GenConstructor(PObjectBase class_obj, const EventVector &events, ArrayItems& arrays); - - /** - * Generates the destructor for a class - */ - void GenDestructor( PObjectBase class_obj, const EventVector &events ); - - /** - * Makes the objects construction, setting up the objects' and Layout properties. - * The algorithm is similar to that used in the designer preview generation. - */ - void GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays); - - /** - * Makes the objects destructions. - */ - void GenDestruction( PObjectBase obj); - - /** - * Configures the object properties, both own and inherited ones. - * Information for the class is given, because it will recursively make the - * configuration in the "super-classes". - */ - void GenSettings( PObjectInfo info, PObjectBase obj); - - /** - * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where - * the template is found, and the objectbase for the control. - */ - void GenAddToolbar( PObjectInfo info, PObjectBase obj ); - void GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ); - - void GenPrivateEventHandlers(const EventVector &events); - - void GenVirtualEventHandlers( const EventVector &events, const wxString& eventHandlerPrefix, const wxString& eventHandlerPostfix ); + typedef enum { P_PRIVATE, P_PROTECTED, P_PUBLIC } Permission; + + CCodeParser m_inheritedCodeParser; + + PCodeWriter m_header; + PCodeWriter m_source; + + bool m_useRelativePath; + bool m_useArrayEnum; + bool m_i18n; + wxString m_basePath; + unsigned int m_firstID; + bool m_useConnect; + bool m_disconnectEvents; + + /** + * Predefined macros won't generate defines. + */ + std::set m_predMacros; + + void SetupPredefinedMacros(); + + /** + * Given an object and the name for a template, obtains the code. + */ + wxString GetCode(PObjectBase obj, wxString name); + + /** + * Gets the declaration fragment for the specified object. + * + * This method encapsulates the adjustments that need to be made for array declarations. + */ + wxString GetDeclaration(PObjectBase obj, ArrayItems& arrays, bool useEnum); + + /** + * Stores the project's objects classes set, for generating the includes. + */ + void FindDependencies(PObjectBase obj, std::set& info_set); + + /** + * Stores the needed "includes" set for the PT_BITMAP properties. + */ + void FindEmbeddedBitmapProperties(PObjectBase obj, std::set& embedset); + + /** + * Stores all the properties for "macro" type objects, so that their + * related '#define' can be generated subsequently. + */ + void FindMacros(PObjectBase obj, std::vector* macros); + + /** + * Looks for "non-null" event handlers (PEvent) and collects it into a vector. + */ + void FindEventHandlers(PObjectBase obj, EventVector& events); + + /** + * Generates classes declarations inside the header file. + */ + void GenClassDeclaration( + PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, + ArrayItems& arrays); + + /** + * Generates the event table. + */ + void GenEvents(PObjectBase class_obj, const EventVector& events, bool disconnect = false); + + /** + * helper function to find the event table entry template in the class or its base classes + */ + bool GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + bool disconnect = false); + + /** + * Recursive function for the attributes declaration, used inside GenClassDeclaration. + */ + void GenAttributeDeclaration(PObjectBase obj, Permission perm, ArrayItems& arrays); + + /** + * Recursive function for the validators' variables declaration, used inside GenClassDeclaration. + */ + void GenValidatorVariables(PObjectBase obj); + /** + * Recursive function for the validators' variables declaration, used inside GenClassDeclaration. + */ + void GenValVarsBase(PObjectInfo info, PObjectBase obj); + + /** + * Generates the generated_event_handlers template + */ + void GetGenEventHandlers(PObjectBase obj); + /** + * Generates the generated_event_handlers template + */ + void GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj); + + /** + * Generates the '#include' section for files. + */ + void GenIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenObjectIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates); + void AddUniqueIncludes(const wxString& include, std::vector* includes); + + /** + * Generate a set of all subclasses to forward declare in the generated header file. + * Also generate sets of header files to be include in either the source or header file. + */ + void GenSubclassSets( + PObjectBase obj, std::set* subclasses, std::set* sourceIncludes, + std::vector* headerIncludes); + + /** + * Generates the '#include' section for the embedded bitmap properties. + */ + void GenEmbeddedBitmapIncludes(PObjectBase project); + + /** + * Generates the '#define' section for macros. + */ + void GenDefines(PObjectBase project); + + /** + * Generates an enum with wxWindow identifiers. + */ + void GenEnumIds(PObjectBase class_obj); + + /** + * Generates the constructor for a class + */ + void GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays); + + /** + * Generates the destructor for a class + */ + void GenDestructor(PObjectBase class_obj, const EventVector& events); + + /** + * Makes the objects construction, setting up the objects' and Layout properties. + * The algorithm is similar to that used in the designer preview generation. + */ + void GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays); + + /** + * Makes the objects destructions. + */ + void GenDestruction(PObjectBase obj); + + /** + * Configures the object properties, both own and inherited ones. + * Information for the class is given, because it will recursively make the + * configuration in the "super-classes". + */ + void GenSettings(PObjectInfo info, PObjectBase obj); + + /** + * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where + * the template is found, and the objectbase for the control. + */ + void GenAddToolbar(PObjectInfo info, PObjectBase obj); + void GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines); + + void GenPrivateEventHandlers(const EventVector& events); + + void GenVirtualEventHandlers( + const EventVector& events, const wxString& eventHandlerPrefix, const wxString& eventHandlerPostfix); public: - /** - * Convert a wxString to the "C/C++" format. - */ - static wxString ConvertCppString( wxString text); - - /** - * Convert a path to a relative path. - */ - //static wxString ConvertToRelativePath( wxString path, wxString basePath); - - /** - * Convert an Embedded Bitmap filename to the name of the character array. - */ - static wxString ConvertEmbeddedBitmapName( const wxString& text ); - - CppCodeGenerator(); - - /** - * Set the codewriter for the header file - */ - void SetHeaderWriter( PCodeWriter cw ) - { - m_header = cw; - } - - /** - * Set the codewriter for the source file - */ - void SetSourceWriter( PCodeWriter cw ) - { - m_source = cw; - } - - - /** - * Parse existing source/header files - */ - void ParseFiles(wxString headerFile, wxString sourceFile) - { - m_inheritedCodeParser = CCodeParser(headerFile, sourceFile); - } - - /** - * Configures the reference path for generating relative paths to - * that passed as parameter. - * - * @note path is generated with the separators, '/', since on Windows - * the compilers interpret path correctly. - */ - void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); - - /** - * Set the First ID used during Code Generation. - */ - void SetFirstID( const unsigned int id ){ m_firstID = id; } - - /** - * Generate the project's code - */ - bool GenerateCode(PObjectBase project) override; - - /** - * Generate an inherited class - */ - void GenerateInheritedClass( PObjectBase userClasses, PObjectBase form ); + /** + * Convert a wxString to the "C/C++" format. + */ + static wxString ConvertCppString(wxString text); + + /** + * Convert a path to a relative path. + */ + // static wxString ConvertToRelativePath( wxString path, wxString basePath); + + /** + * Convert an Embedded Bitmap filename to the name of the character array. + */ + static wxString ConvertEmbeddedBitmapName(const wxString& text); + + CppCodeGenerator(); + + /** + * Set the codewriter for the header file + */ + void SetHeaderWriter(PCodeWriter cw) { m_header = cw; } + + /** + * Set the codewriter for the source file + */ + void SetSourceWriter(PCodeWriter cw) { m_source = cw; } + + + /** + * Parse existing source/header files + */ + void ParseFiles(wxString headerFile, wxString sourceFile) + { + m_inheritedCodeParser = CCodeParser(headerFile, sourceFile); + } + + /** + * Configures the reference path for generating relative paths to + * that passed as parameter. + * + * @note path is generated with the separators, '/', since on Windows + * the compilers interpret path correctly. + */ + void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); + + /** + * Set the First ID used during Code Generation. + */ + void SetFirstID(const unsigned int id) { m_firstID = id; } + + /** + * Generate the project's code + */ + bool GenerateCode(PObjectBase project) override; + + /** + * Generate an inherited class + */ + void GenerateInheritedClass(PObjectBase userClasses, PObjectBase form); }; - -#endif // CODEGEN_CPPCG_H +#endif // CODEGEN_CPPCG_H diff --git a/src/codegen/luacg.cpp b/src/codegen/luacg.cpp index e71ca025d..ead957766 100644 --- a/src/codegen/luacg.cpp +++ b/src/codegen/luacg.cpp @@ -28,6 +28,12 @@ #include "luacg.h" +#include + +#include +#include + +#include "codegen/codewriter.h" #include "model/objectbase.h" #include "rad/appdata.h" #include "rad/revision.h" @@ -35,1872 +41,1669 @@ #include "utils/debug.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "codegen/codewriter.h" -#include -#include -#include - -LuaTemplateParser::LuaTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, std::vector strUserIDsVec ) -: -TemplateParser(obj,_template), -m_i18n( useI18N ), -m_useRelativePath( useRelativePath ), -m_basePath( basePath ), -m_strUserIDsVec(strUserIDsVec) +LuaTemplateParser::LuaTemplateParser( + PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, + std::vector strUserIDsVec) : + TemplateParser(obj, _template), + m_i18n(useI18N), + m_useRelativePath(useRelativePath), + m_basePath(basePath), + m_strUserIDsVec(strUserIDsVec) { - if ( !wxFileName::DirExists( m_basePath ) ) - { - m_basePath.clear(); - } + if (!wxFileName::DirExists(m_basePath)) { + m_basePath.clear(); + } - SetupModulePrefixes(); + SetupModulePrefixes(); } -LuaTemplateParser::LuaTemplateParser( const LuaTemplateParser & that, wxString _template, std::vector strUserIDsVec ) -: -TemplateParser( that, _template ), -m_i18n( that.m_i18n ), -m_useRelativePath( that.m_useRelativePath ), -m_basePath( that.m_basePath ), -m_strUserIDsVec(strUserIDsVec) +LuaTemplateParser::LuaTemplateParser( + const LuaTemplateParser& that, wxString _template, std::vector strUserIDsVec) : + TemplateParser(that, _template), + m_i18n(that.m_i18n), + m_useRelativePath(that.m_useRelativePath), + m_basePath(that.m_basePath), + m_strUserIDsVec(strUserIDsVec) { - SetupModulePrefixes(); + SetupModulePrefixes(); } wxString LuaTemplateParser::RootWxParentToCode() { - return wxT("NS."); + return wxT("NS."); } -PTemplateParser LuaTemplateParser::CreateParser( const TemplateParser* oldparser, wxString _template ) +PTemplateParser LuaTemplateParser::CreateParser(const TemplateParser* oldparser, wxString _template) { - const LuaTemplateParser* luaOldParser = dynamic_cast< const LuaTemplateParser* >( oldparser ); - if (luaOldParser) - { - std::vector empty; - PTemplateParser newparser( new LuaTemplateParser( *luaOldParser, _template, empty)); - return newparser; - } - return PTemplateParser(); + const LuaTemplateParser* luaOldParser = dynamic_cast(oldparser); + if (luaOldParser) { + std::vector empty; + PTemplateParser newparser(new LuaTemplateParser(*luaOldParser, _template, empty)); + return newparser; + } + return PTemplateParser(); } /** -* Convert the value of the property to Lua code -*/ -wxString LuaTemplateParser::ValueToCode( PropertyType type, wxString value ) + * Convert the value of the property to Lua code + */ +wxString LuaTemplateParser::ValueToCode(PropertyType type, wxString value) { - wxString result; - - switch ( type ) - { - case PT_WXPARENT: - { - result = wxT("NS.") + value; - break; - } - case PT_WXPARENT_SB: - { - result = value + wxT(":GetStaticBox()"); - break; - } - case PT_WXPARENT_CP: - { - result = wxT("NS.") + value + wxT(":GetPane()"); - break; - } - case PT_WXSTRING: - case PT_FILE: - case PT_PATH: - { - if ( value.empty() ) - { - result << wxT("\"\""); - } - else - { - result << wxT("\"") << LuaCodeGenerator::ConvertLuaString( value ) << wxT("\""); - } - break; - } - case PT_WXSTRING_I18N: - { - if ( value.empty() ) - { - result << wxT("\"\""); - } - else - { - if ( m_i18n ) - { - result << wxT("\"") << LuaCodeGenerator::ConvertLuaString(value) << wxT("\""); - } - else - { - result << wxT("\"") << LuaCodeGenerator::ConvertLuaString(value) << wxT("\""); - } - } - break; - } - case PT_CLASS: - case PT_MACRO: - case PT_OPTION: - case PT_EDIT_OPTION: - { - result = value; - wxString pred = m_predModulePrefix[value]; - - if( !pred.empty() ) - result.Replace( wxT("wx"), pred ); - else - { - //prepend "wx." if value isn't UserID and contains "wx" prefix - if(m_strUserIDsVec.end() == std::find(m_strUserIDsVec.begin(),m_strUserIDsVec.end(),value) && wxNOT_FOUND != result.Find(wxT("wx"))){ - result.Prepend(wxT("wx.")); - } - } - - break; - } - case PT_TEXT: - case PT_FLOAT: - case PT_INT: - case PT_UINT: - { - result = value; - break; - } - case PT_BITLIST: - { - if(value.empty() ){ - result = wxT("0"); - break; - }else{ - result = value; - } - wxString pred, bit, res, pref; - wxStringTokenizer bits( result, wxT("|"), wxTOKEN_STRTOK ); - - while( bits.HasMoreTokens() ) - { - bit = bits.GetNextToken(); - pred = m_predModulePrefix[bit]; - - if(pred.empty() ) - { - res += pref + wxT("wx.") + bit; - }else{ - res += pref + pred + bit; - } - pref = wxT(" + "); - } - result = res; - break; - } - case PT_WXPOINT: - { - if ( value.empty() ) - { - result = wxT("wx.wxDefaultPosition"); - } - else - { - result << wxT("wx.wxPoint( ") << value << wxT(" )"); - } - break; - } - case PT_WXSIZE: - { - if ( value.empty() ) - { - result = wxT("wx.wxDefaultSize"); - } - else - { - result << wxT("wx.wxSize( ") << value << wxT(" )"); - } - break; - } - case PT_BOOL: - { - result = ( value == wxT("0") ? wxT("False") : wxT("True") ); - break; - } - case PT_WXFONT: - { - if ( !value.empty() ) - { - wxFontContainer fontContainer = TypeConv::StringToFont( value ); - wxFont font = fontContainer.GetFont(); - - const int pointSize = fontContainer.GetPointSize(); - - result = wxString::Format( "wx.wxFont( %s, %s, %s, %s, %s, %s )", - ((pointSize <= 0) ? "wx.wxNORMAL_FONT:GetPointSize()" : (wxString() << pointSize)), - "wx." + TypeConv::FontFamilyToString( fontContainer.GetFamily() ), - "wx." + font.GetStyleString(), - "wx." + font.GetWeightString(), - ( fontContainer.GetUnderlined() ? "True" : "False" ), - ( fontContainer.m_faceName.empty() ? "\"\"" : ("\"" + fontContainer.m_faceName + "\"") ) - ); - } - else - { - result = wxT("wx.wxNORMAL_FONT"); - } - break; - } - case PT_WXCOLOUR: - { - if ( !value.empty() ) - { - if ( value.find_first_of( wxT("wx") ) == 0 ) - { - // System Colour - result << wxT("wx.wxSystemSettings.GetColour( ") << ValueToCode( PT_OPTION, value ) << wxT(" )"); - } - else - { - wxColour colour = TypeConv::StringToColour( value ); - result = wxString::Format( wxT("wx.wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue() ); - } - } - else - { - result = wxT("wx.wxColour()"); - } - break; - } - case PT_BITMAP: - { - wxString path; - wxString source; - wxSize icoSize; - TypeConv::ParseBitmapWithResource( value, &path, &source, &icoSize ); - - if ( path.empty() ) - { - // Empty path, generate Null Bitmap - result = wxT("wx.wxNullBitmap"); - break; - } - - if ( path.StartsWith( wxT("file:") ) ) - { - wxLogWarning( wxT("Lua code generation does not support using URLs for bitmap properties:\n%s"), path ); - result = wxT("wx.wxNullBitmap"); - break; - } - - if ( source == _("Load From File") || source == _("Load From Embedded File")) - { - wxString absPath; - try - { - absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - } - catch( wxFBException& ex ) - { - wxLogError( ex.what() ); - result = wxT( "wx.wxNullBitmap" ); - break; - } - - wxString file = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath ); - - result << wxT("wx.wxBitmap( \"") << LuaCodeGenerator::ConvertLuaString( file ) << wxT("\", wx.wxBITMAP_TYPE_ANY )"); - } - else if ( source == _("Load From Resource") ) - { - result << wxT("wx.wxBitmap( \"") << path << wxT("\", wx.wxBITMAP_TYPE_RESOURCE )"); - } - else if ( source == _("Load From Icon Resource") ) - { - result << wxT("wx.wxBitmap( \"") << path << wxT("\")"); - //load from icon isn't supported by wxLua - //wxStaticBitmap(wxWindow* parent, wxWindowID id, const wxBitmap& label = wxNullBitmap, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = "wxStaticBitmap") - /* - if ( wxDefaultSize == icoSize ) - { - result << wxT("wx.wxICON( ") << path << wxT(" )"); - } - else - { - result.Printf( wxT("wx.Icon( u\"%s\", wx.wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, icoSize.GetWidth(), icoSize.GetHeight() ); - }*/ - } - else if (source == _("Load From XRC")) - { - // This requires that the global wxXmlResource object is set - result << wxT("wx.wxXmlResource.Get():LoadBitmap( \"") << path << wxT("\" )"); - } - else if ( source == _("Load From Art Provider") ) - { - wxString rid = path.BeforeFirst( wxT(':') ); - - if( rid.StartsWith( wxT("gtk-") ) ) - { - rid = wxT("\"") + rid + wxT("\""); - } - else - rid.Replace( wxT("wx"), wxT("wx.wx") ); - - wxString cid = path.AfterFirst( wxT(':') ); - cid.Replace( wxT("wx"), wxT("wx.wx") ); - - result = wxT("wx.wxArtProvider.GetBitmap( ") + rid + wxT(", ") + cid + wxT(" )"); - } - break; - } - case PT_STRINGLIST: - { - // Stringlists are generated like a sequence of wxString separated by ', '. - wxArrayString array = TypeConv::StringToArrayString( value ); - if ( array.Count() > 0 ) - { - result = ValueToCode( PT_WXSTRING_I18N, array[0] ); - } - - for ( size_t i = 1; i < array.Count(); i++ ) - { - result << wxT(", ") << ValueToCode( PT_WXSTRING_I18N, array[i] ); - } - break; - } - default: - break; - } - - return result; + wxString result; + + switch (type) { + case PT_WXPARENT: { + result = wxT("NS.") + value; + break; + } + case PT_WXPARENT_SB: { + result = value + wxT(":GetStaticBox()"); + break; + } + case PT_WXPARENT_CP: { + result = wxT("NS.") + value + wxT(":GetPane()"); + break; + } + case PT_WXSTRING: + case PT_FILE: + case PT_PATH: { + if (value.empty()) { + result << wxT("\"\""); + } else { + result << wxT("\"") << LuaCodeGenerator::ConvertLuaString(value) << wxT("\""); + } + break; + } + case PT_WXSTRING_I18N: { + if (value.empty()) { + result << wxT("\"\""); + } else { + if (m_i18n) { + result << wxT("\"") << LuaCodeGenerator::ConvertLuaString(value) << wxT("\""); + } else { + result << wxT("\"") << LuaCodeGenerator::ConvertLuaString(value) << wxT("\""); + } + } + break; + } + case PT_CLASS: + case PT_MACRO: + case PT_OPTION: + case PT_EDIT_OPTION: { + result = value; + wxString pred = m_predModulePrefix[value]; + + if (!pred.empty()) + result.Replace(wxT("wx"), pred); + else { + // prepend "wx." if value isn't UserID and contains "wx" prefix + if ( + m_strUserIDsVec.end() == std::find(m_strUserIDsVec.begin(), m_strUserIDsVec.end(), value) && + wxNOT_FOUND != result.Find(wxT("wx"))) { + result.Prepend(wxT("wx.")); + } + } + + break; + } + case PT_TEXT: + case PT_FLOAT: + case PT_INT: + case PT_UINT: { + result = value; + break; + } + case PT_BITLIST: { + if (value.empty()) { + result = wxT("0"); + break; + } else { + result = value; + } + wxString pred, bit, res, pref; + wxStringTokenizer bits(result, wxT("|"), wxTOKEN_STRTOK); + + while (bits.HasMoreTokens()) { + bit = bits.GetNextToken(); + pred = m_predModulePrefix[bit]; + + if (pred.empty()) { + res += pref + wxT("wx.") + bit; + } else { + res += pref + pred + bit; + } + pref = wxT(" + "); + } + result = res; + break; + } + case PT_WXPOINT: { + if (value.empty()) { + result = wxT("wx.wxDefaultPosition"); + } else { + result << wxT("wx.wxPoint( ") << value << wxT(" )"); + } + break; + } + case PT_WXSIZE: { + if (value.empty()) { + result = wxT("wx.wxDefaultSize"); + } else { + result << wxT("wx.wxSize( ") << value << wxT(" )"); + } + break; + } + case PT_BOOL: { + result = (value == wxT("0") ? wxT("False") : wxT("True")); + break; + } + case PT_WXFONT: { + if (!value.empty()) { + wxFontContainer fontContainer = TypeConv::StringToFont(value); + wxFont font = fontContainer.GetFont(); + + const int pointSize = fontContainer.GetPointSize(); + + result = wxString::Format( + "wx.wxFont( %s, %s, %s, %s, %s, %s )", + ((pointSize <= 0) ? "wx.wxNORMAL_FONT:GetPointSize()" : (wxString() << pointSize)), + "wx." + TypeConv::FontFamilyToString(fontContainer.GetFamily()), "wx." + font.GetStyleString(), + "wx." + font.GetWeightString(), (fontContainer.GetUnderlined() ? "True" : "False"), + (fontContainer.m_faceName.empty() ? "\"\"" : ("\"" + fontContainer.m_faceName + "\""))); + } else { + result = wxT("wx.wxNORMAL_FONT"); + } + break; + } + case PT_WXCOLOUR: { + if (!value.empty()) { + if (value.find_first_of(wxT("wx")) == 0) { + // System Colour + result << wxT("wx.wxSystemSettings.GetColour( ") << ValueToCode(PT_OPTION, value) << wxT(" )"); + } else { + wxColour colour = TypeConv::StringToColour(value); + result = + wxString::Format(wxT("wx.wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue()); + } + } else { + result = wxT("wx.wxColour()"); + } + break; + } + case PT_BITMAP: { + wxString path; + wxString source; + wxSize icoSize; + TypeConv::ParseBitmapWithResource(value, &path, &source, &icoSize); + + if (path.empty()) { + // Empty path, generate Null Bitmap + result = wxT("wx.wxNullBitmap"); + break; + } + + if (path.StartsWith(wxT("file:"))) { + wxLogWarning(wxT("Lua code generation does not support using URLs for bitmap properties:\n%s"), path); + result = wxT("wx.wxNullBitmap"); + break; + } + + if (source == _("Load From File") || source == _("Load From Embedded File")) { + wxString absPath; + try { + absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + result = wxT("wx.wxNullBitmap"); + break; + } + + wxString file = (m_useRelativePath ? TypeConv::MakeRelativePath(absPath, m_basePath) : absPath); + + result << wxT("wx.wxBitmap( \"") << LuaCodeGenerator::ConvertLuaString(file) + << wxT("\", wx.wxBITMAP_TYPE_ANY )"); + } else if (source == _("Load From Resource")) { + result << wxT("wx.wxBitmap( \"") << path << wxT("\", wx.wxBITMAP_TYPE_RESOURCE )"); + } else if (source == _("Load From Icon Resource")) { + result << wxT("wx.wxBitmap( \"") << path << wxT("\")"); + // load from icon isn't supported by wxLua + // wxStaticBitmap(wxWindow* parent, wxWindowID id, const wxBitmap& label = wxNullBitmap, const wxPoint& + // pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = + // "wxStaticBitmap") + /* + if ( wxDefaultSize == icoSize ) + { + result << wxT("wx.wxICON( ") << path << wxT(" )"); + } + else + { + result.Printf( wxT("wx.Icon( u\"%s\", wx.wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, + icoSize.GetWidth(), icoSize.GetHeight() ); + }*/ + } else if (source == _("Load From XRC")) { + // This requires that the global wxXmlResource object is set + result << wxT("wx.wxXmlResource.Get():LoadBitmap( \"") << path << wxT("\" )"); + } else if (source == _("Load From Art Provider")) { + wxString rid = path.BeforeFirst(wxT(':')); + + if (rid.StartsWith(wxT("gtk-"))) { + rid = wxT("\"") + rid + wxT("\""); + } else + rid.Replace(wxT("wx"), wxT("wx.wx")); + + wxString cid = path.AfterFirst(wxT(':')); + cid.Replace(wxT("wx"), wxT("wx.wx")); + + result = wxT("wx.wxArtProvider.GetBitmap( ") + rid + wxT(", ") + cid + wxT(" )"); + } + break; + } + case PT_STRINGLIST: { + // Stringlists are generated like a sequence of wxString separated by ', '. + wxArrayString array = TypeConv::StringToArrayString(value); + if (array.Count() > 0) { + result = ValueToCode(PT_WXSTRING_I18N, array[0]); + } + + for (size_t i = 1; i < array.Count(); i++) { + result << wxT(", ") << ValueToCode(PT_WXSTRING_I18N, array[i]); + } + break; + } + default: + break; + } + + return result; } /////////////////////////////////////////////////////////////////////////////// LuaCodeGenerator::LuaCodeGenerator() { - SetupPredefinedMacros(); - m_useRelativePath = false; - m_i18n = false; - m_firstID = 1000; - - //this classes aren't wrapped by wxLua - make exception - m_strUnsupportedClasses.push_back(wxT("wxRichTextCtrl")); - m_strUnsupportedClasses.push_back(wxT("wxSearchCtrl")); - m_strUnsupportedClasses.push_back(wxT("wxAuiToolBar")); - m_strUnsupportedClasses.push_back(wxT("wxRibbonBar")); - m_strUnsupportedClasses.push_back(wxT("wxDataViewCtrl")); - m_strUnsupportedClasses.push_back(wxT("wxDataViewListCtrl")); - m_strUnsupportedClasses.push_back(wxT("wxDataViewTreeCtrl")); + SetupPredefinedMacros(); + m_useRelativePath = false; + m_i18n = false; + m_firstID = 1000; + + // this classes aren't wrapped by wxLua - make exception + m_strUnsupportedClasses.push_back(wxT("wxRichTextCtrl")); + m_strUnsupportedClasses.push_back(wxT("wxSearchCtrl")); + m_strUnsupportedClasses.push_back(wxT("wxAuiToolBar")); + m_strUnsupportedClasses.push_back(wxT("wxRibbonBar")); + m_strUnsupportedClasses.push_back(wxT("wxDataViewCtrl")); + m_strUnsupportedClasses.push_back(wxT("wxDataViewListCtrl")); + m_strUnsupportedClasses.push_back(wxT("wxDataViewTreeCtrl")); } -wxString LuaCodeGenerator::ConvertLuaString( wxString text ) +wxString LuaCodeGenerator::ConvertLuaString(wxString text) { - wxString result; - - for ( size_t i = 0; i < text.length(); i++ ) - { - wxChar c = text[i]; - - switch ( c ) - { - case wxT('"'): - result += wxT("\\\""); - break; - - case wxT('\\'): - result += wxT("\\\\"); - break; - - case wxT('\t'): - result += wxT("\\t"); - break; - - case wxT('\n'): - result += wxT("\\n"); - break; - - case wxT('\r'): - result += wxT("\\r"); - break; - - default: - result += c; - break; - } - } - return result; + wxString result; + + for (size_t i = 0; i < text.length(); i++) { + wxChar c = text[i]; + + switch (c) { + case wxT('"'): + result += wxT("\\\""); + break; + + case wxT('\\'): + result += wxT("\\\\"); + break; + + case wxT('\t'): + result += wxT("\\t"); + break; + + case wxT('\n'): + result += wxT("\\n"); + break; + + case wxT('\r'): + result += wxT("\\r"); + break; + + default: + result += c; + break; + } + } + return result; } -void LuaCodeGenerator::GenerateInheritedClass( PObjectBase userClasses, PObjectBase form,const wxString & genFileFullPath) +void LuaCodeGenerator::GenerateInheritedClass( + PObjectBase userClasses, PObjectBase form, const wxString& genFileFullPath) { - if (!userClasses) - { - wxLogError(wxT("There is no object to generate inherited class")); - return; - } - - if ( wxT("UserClasses") != userClasses->GetClassName() ) - { - wxLogError(wxT("This not a UserClasses object")); - return; - } - - // Start file - wxString code = GetCode( userClasses, wxT("file_comment") ); - m_source->WriteLn( code ); - - wxString fullGenPath = genFileFullPath; - fullGenPath.Replace(wxT("\\"), wxT("\\\\")); - - code = wxT("package.path = \"") + fullGenPath + wxT(".lua\""); - m_source->WriteLn( code ); - - code = GetCode( userClasses, wxT("source_include") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - - EventVector events; - FindEventHandlers( form, events ); - - - if ( events.size() > 0 ) - { - code = GetCode( userClasses, wxT("event_handler_comment") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - std::set generatedHandlers; - wxString eventsGroupID ; - wxString strPrevClassName; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - - wxString handlerName = event->GetValue(); - wxString templateName = wxString::Format( wxT("connect_%s"), event->GetName() ); - - PObjectBase obj = event->GetObject(); - PObjectInfo obj_info = obj->GetObjectInfo(); - - wxString strClassName; - code = GenEventEntryForInheritedClass(obj, obj_info, templateName, handlerName, strClassName); - - bool bAddCaption = false; - PProperty propName = obj->GetProperty( wxT("name") ); - if (propName) - { - strClassName = propName->GetValue(); - if(strPrevClassName != strClassName){ - strPrevClassName = strClassName; - bAddCaption = true; - eventsGroupID = wxString::Format( wxT("-- %s (%s) event handlers: "), strClassName, obj->GetClassName()); - } - } - - if(code.length() > 0){ - if(bAddCaption) - m_source->WriteLn(eventsGroupID); - - m_source->WriteLn( code); - m_source->WriteLn(); - } - } - m_source->WriteLn( wxEmptyString ); - m_source->WriteLn( wxEmptyString ); - } - - m_source->Unindent(); + if (!userClasses) { + wxLogError(wxT("There is no object to generate inherited class")); + return; + } + + if (wxT("UserClasses") != userClasses->GetClassName()) { + wxLogError(wxT("This not a UserClasses object")); + return; + } + + // Start file + wxString code = GetCode(userClasses, wxT("file_comment")); + m_source->WriteLn(code); + + wxString fullGenPath = genFileFullPath; + fullGenPath.Replace(wxT("\\"), wxT("\\\\")); + + code = wxT("package.path = \"") + fullGenPath + wxT(".lua\""); + m_source->WriteLn(code); + + code = GetCode(userClasses, wxT("source_include")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + + EventVector events; + FindEventHandlers(form, events); + + + if (events.size() > 0) { + code = GetCode(userClasses, wxT("event_handler_comment")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + std::set generatedHandlers; + wxString eventsGroupID; + wxString strPrevClassName; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + + wxString handlerName = event->GetValue(); + wxString templateName = wxString::Format(wxT("connect_%s"), event->GetName()); + + PObjectBase obj = event->GetObject(); + PObjectInfo obj_info = obj->GetObjectInfo(); + + wxString strClassName; + code = GenEventEntryForInheritedClass(obj, obj_info, templateName, handlerName, strClassName); + + bool bAddCaption = false; + PProperty propName = obj->GetProperty(wxT("name")); + if (propName) { + strClassName = propName->GetValue(); + if (strPrevClassName != strClassName) { + strPrevClassName = strClassName; + bAddCaption = true; + eventsGroupID = + wxString::Format(wxT("-- %s (%s) event handlers: "), strClassName, obj->GetClassName()); + } + } + + if (code.length() > 0) { + if (bAddCaption) + m_source->WriteLn(eventsGroupID); + + m_source->WriteLn(code); + m_source->WriteLn(); + } + } + m_source->WriteLn(wxEmptyString); + m_source->WriteLn(wxEmptyString); + } + + m_source->Unindent(); } -wxString LuaCodeGenerator::GenEventEntryForInheritedClass( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, wxString &strClassName ) +wxString LuaCodeGenerator::GenEventEntryForInheritedClass( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + wxString& strClassName) { - wxString code; - PCodeInfo code_info = obj_info->GetCodeInfo( wxT("Lua") ); - if ( code_info ) - { - wxString _template; - _template = code_info->GetTemplate( wxString::Format( wxT("evt_%s"), templateName ) ); - if ( !_template.empty() ) - { - _template.Replace( wxT("#handler"),handlerName ); - _template.Replace( wxT("#skip"),wxT("\n") + m_strEventHandlerPostfix ); - } - - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - code = parser.ParseTemplate(); - if(code.length() > 0) return code; - - for ( unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = obj_info->GetBaseClass( i, false ); - if ( (code = GenEventEntryForInheritedClass( obj, base_info, templateName, handlerName, strClassName )).length() > 0 ) - { - return code; - } - } - } - return code; + wxString code; + PCodeInfo code_info = obj_info->GetCodeInfo(wxT("Lua")); + if (code_info) { + wxString _template; + _template = code_info->GetTemplate(wxString::Format(wxT("evt_%s"), templateName)); + if (!_template.empty()) { + _template.Replace(wxT("#handler"), handlerName); + _template.Replace(wxT("#skip"), wxT("\n") + m_strEventHandlerPostfix); + } + + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + code = parser.ParseTemplate(); + if (code.length() > 0) + return code; + + for (unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = obj_info->GetBaseClass(i, false); + if ( + (code = GenEventEntryForInheritedClass(obj, base_info, templateName, handlerName, strClassName)) + .length() > 0) { + return code; + } + } + } + return code; } -bool LuaCodeGenerator::GenerateCode( PObjectBase project ) +bool LuaCodeGenerator::GenerateCode(PObjectBase project) { - if (!project) - { - wxLogError(wxT("There is no project to generate code")); - return false; - } - - m_i18n = false; - PProperty i18nProperty = project->GetProperty( wxT("internationalize") ); - if (i18nProperty && i18nProperty->GetValueAsInteger()) - m_i18n = true; - - m_disconnectEvents = ( project->GetPropertyAsInteger( wxT("disconnect_lua_events") ) != 0 ); - - m_source->Clear(); - - // Insert Lua preamble - - wxString code = GetCode( project, wxT("lua_preamble") ); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - } - - code = wxString::Format( - wxT("----------------------------------------------------------------------------\n") - wxT("-- Lua code generated with wxFormBuilder (version %s%s)\n") - wxT("-- http://www.wxformbuilder.org/\n") - wxT("----------------------------------------------------------------------------\n"), - getVersion(), getPostfixRevision(getVersion()).c_str() - ); - - m_source->WriteLn( code ); - - PProperty propFile = project->GetProperty( wxT("file") ); - if (!propFile) - { - wxLogError( wxT("Missing \"file\" property on Project Object") ); - return false; - } - - wxString file = propFile->GetValue(); - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Generate the subclass sets - std::set< wxString > subclasses; - std::vector< wxString > headerIncludes; - - GenSubclassSets( project, &subclasses, &headerIncludes ); - - // Generating includes - std::set< wxString > templates; - GenIncludes(project, &headerIncludes, &templates ); - - // Write the include lines - std::vector::iterator include_it; - for ( include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it ) - { - m_source->WriteLn( *include_it ); - } - if ( !headerIncludes.empty() ) - { - m_source->WriteLn(wxEmptyString); - } - - // Generating "defines" for macros - GenDefines( project ); - - PProperty propNamespace = project->GetProperty( wxT( "ui_table" ) ); - if ( propNamespace ) - { - m_strUITable = propNamespace->GetValueAsString(); - if(m_strUITable.length() <= 0){ - m_strUITable = wxT("UI");//default value ... m_strUITable shouldn't be empty - } - code = m_strUITable + wxT(" = {} \n"); - m_source->WriteLn( code ); - } - - - PProperty eventKindProp = project->GetProperty( wxT("skip_lua_events") ); - if( eventKindProp->GetValueAsInteger() ){ - m_strEventHandlerPostfix = wxT("event:Skip()"); - } - else - { - m_strEventHandlerPostfix = wxEmptyString; - } - - - PProperty disconnectMode = project->GetProperty( wxT("disconnect_mode") ); - m_disconnecMode = disconnectMode->GetValueAsString(); - - unsigned int dProjChildCount = project->GetChildCount(); - for ( unsigned int i = 0; i < dProjChildCount; i++ ) - { - PObjectBase child = project->GetChild( i ); - - // Preprocess to find arrays - ArrayItems arrays; - FindArrayObjects(child, arrays, true); - - EventVector events; - FindEventHandlers( child, events ); - GenClassDeclaration(child, false, wxEmptyString, events, m_strEventHandlerPostfix, arrays); - } - - code = GetCode( project, wxT("lua_epilogue") ); - if( !code.empty() ) - m_source->WriteLn( code ); - - return true; + if (!project) { + wxLogError(wxT("There is no project to generate code")); + return false; + } + + m_i18n = false; + PProperty i18nProperty = project->GetProperty(wxT("internationalize")); + if (i18nProperty && i18nProperty->GetValueAsInteger()) + m_i18n = true; + + m_disconnectEvents = (project->GetPropertyAsInteger(wxT("disconnect_lua_events")) != 0); + + m_source->Clear(); + + // Insert Lua preamble + + wxString code = GetCode(project, wxT("lua_preamble")); + if (!code.empty()) { + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + } + + code = wxString::Format( + wxT("----------------------------------------------------------------------------\n") + wxT("-- Lua code generated with wxFormBuilder (version %s%s)\n") wxT("-- http://www.wxformbuilder.org/\n") + wxT("----------------------------------------------------------------------------\n"), + getVersion(), getPostfixRevision(getVersion()).c_str()); + + m_source->WriteLn(code); + + PProperty propFile = project->GetProperty(wxT("file")); + if (!propFile) { + wxLogError(wxT("Missing \"file\" property on Project Object")); + return false; + } + + wxString file = propFile->GetValue(); + if (file.empty()) { + file = wxT("noname"); + } + + // Generate the subclass sets + std::set subclasses; + std::vector headerIncludes; + + GenSubclassSets(project, &subclasses, &headerIncludes); + + // Generating includes + std::set templates; + GenIncludes(project, &headerIncludes, &templates); + + // Write the include lines + std::vector::iterator include_it; + for (include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it) { + m_source->WriteLn(*include_it); + } + if (!headerIncludes.empty()) { + m_source->WriteLn(wxEmptyString); + } + + // Generating "defines" for macros + GenDefines(project); + + PProperty propNamespace = project->GetProperty(wxT("ui_table")); + if (propNamespace) { + m_strUITable = propNamespace->GetValueAsString(); + if (m_strUITable.length() <= 0) { + m_strUITable = wxT("UI"); // default value ... m_strUITable shouldn't be empty + } + code = m_strUITable + wxT(" = {} \n"); + m_source->WriteLn(code); + } + + + PProperty eventKindProp = project->GetProperty(wxT("skip_lua_events")); + if (eventKindProp->GetValueAsInteger()) { + m_strEventHandlerPostfix = wxT("event:Skip()"); + } else { + m_strEventHandlerPostfix = wxEmptyString; + } + + + PProperty disconnectMode = project->GetProperty(wxT("disconnect_mode")); + m_disconnecMode = disconnectMode->GetValueAsString(); + + unsigned int dProjChildCount = project->GetChildCount(); + for (unsigned int i = 0; i < dProjChildCount; i++) { + PObjectBase child = project->GetChild(i); + + // Preprocess to find arrays + ArrayItems arrays; + FindArrayObjects(child, arrays, true); + + EventVector events; + FindEventHandlers(child, events); + GenClassDeclaration(child, false, wxEmptyString, events, m_strEventHandlerPostfix, arrays); + } + + code = GetCode(project, wxT("lua_epilogue")); + if (!code.empty()) + m_source->WriteLn(code); + + return true; } -void LuaCodeGenerator::GenEvents( PObjectBase class_obj, const EventVector &events, wxString &strClassName, bool disconnect ) +void LuaCodeGenerator::GenEvents( + PObjectBase class_obj, const EventVector& events, wxString& strClassName, bool disconnect) { - if ( events.empty() ) - { - return; - } - - if( disconnect ) - { - m_source->WriteLn( wxT("-- Disconnect Events\n") ); - } - else - { - m_source->WriteLn(); - m_source->WriteLn( wxT("-- Connect Events\n") ); - } - - - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), - class_obj->GetClassName()); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT("Object name cannot be null") ); - return; - } - - /* - wxString base_class; - PProperty propSubclass = class_obj->GetProperty( wxT("subclass") ); - if ( propSubclass ) - { - wxString subclass = propSubclass->GetChildFromParent( wxT("name") ); - if ( !subclass.empty() ) - { - base_class = subclass; - } - } - - if ( base_class.empty() ) - base_class = wxT("wx.") + class_obj->GetClassName(); - - */ - wxString handlerName; - if ( events.size() > 0 ) - { - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - - handlerName = event->GetValue();// + wxT("_") + class_name; - - wxString templateName = wxString::Format( wxT("connect_%s"), event->GetName() ); - - PObjectBase obj = event->GetObject(); - if ( !GenEventEntry( obj, obj->GetObjectInfo(), templateName, handlerName, strClassName, disconnect ) ) - { - wxLogError( wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), - templateName, class_name ); - } - } - } + if (events.empty()) { + return; + } + + if (disconnect) { + m_source->WriteLn(wxT("-- Disconnect Events\n")); + } else { + m_source->WriteLn(); + m_source->WriteLn(wxT("-- Connect Events\n")); + } + + + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name cannot be null")); + return; + } + + /* + wxString base_class; + PProperty propSubclass = class_obj->GetProperty( wxT("subclass") ); + if ( propSubclass ) + { + wxString subclass = propSubclass->GetChildFromParent( wxT("name") ); + if ( !subclass.empty() ) + { + base_class = subclass; + } + } + + if ( base_class.empty() ) + base_class = wxT("wx.") + class_obj->GetClassName(); + + */ + wxString handlerName; + if (events.size() > 0) { + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + + handlerName = event->GetValue(); // + wxT("_") + class_name; + + wxString templateName = wxString::Format(wxT("connect_%s"), event->GetName()); + + PObjectBase obj = event->GetObject(); + if (!GenEventEntry(obj, obj->GetObjectInfo(), templateName, handlerName, strClassName, disconnect)) { + wxLogError( + wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), templateName, + class_name); + } + } + } } -bool LuaCodeGenerator::GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, wxString &strClassName, bool disconnect ) +bool LuaCodeGenerator::GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + wxString& strClassName, bool disconnect) { - wxString _template; - PCodeInfo code_info = obj_info->GetCodeInfo( wxT("Lua") ); - if ( code_info ) - { - _template = code_info->GetTemplate(wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); - if ( disconnect && _template.empty() ) - { - _template = code_info->GetTemplate( wxT("evt_") + templateName ); - _template.Replace( wxT("Connect"), wxT("Disconnect"), true ); - } - - if ( !_template.empty() ) - { - if( disconnect ) - { - if( m_disconnecMode == wxT("handler_name")) _template.Replace( wxT("#handler"), wxT("handler = ") + handlerName ); - else if(m_disconnecMode == wxT("source_name")) _template.Replace( wxT("#handler"), wxT("None") ); - } - else{ - _template.Replace( wxT("#handler"), handlerName ); - _template.Replace( wxT("#skip"),wxT("\n") + m_strEventHandlerPostfix ); - } - - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString code = parser.ParseTemplate(); - wxString strRootCode = parser.RootWxParentToCode(); - if(code.Find(strRootCode) != -1){ - code.Replace(strRootCode, strClassName); - } - m_source->WriteLn( code); - m_source->WriteLn(); - return true; - } - } - - for ( unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = obj_info->GetBaseClass( i, false ); - if ( GenEventEntry( obj, base_info, templateName, handlerName, strClassName, disconnect ) ) - { - return true; - } - } - - return false; + wxString _template; + PCodeInfo code_info = obj_info->GetCodeInfo(wxT("Lua")); + if (code_info) { + _template = code_info->GetTemplate( + wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); + if (disconnect && _template.empty()) { + _template = code_info->GetTemplate(wxT("evt_") + templateName); + _template.Replace(wxT("Connect"), wxT("Disconnect"), true); + } + + if (!_template.empty()) { + if (disconnect) { + if (m_disconnecMode == wxT("handler_name")) + _template.Replace(wxT("#handler"), wxT("handler = ") + handlerName); + else if (m_disconnecMode == wxT("source_name")) + _template.Replace(wxT("#handler"), wxT("None")); + } else { + _template.Replace(wxT("#handler"), handlerName); + _template.Replace(wxT("#skip"), wxT("\n") + m_strEventHandlerPostfix); + } + + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString code = parser.ParseTemplate(); + wxString strRootCode = parser.RootWxParentToCode(); + if (code.Find(strRootCode) != -1) { + code.Replace(strRootCode, strClassName); + } + m_source->WriteLn(code); + m_source->WriteLn(); + return true; + } + } + + for (unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = obj_info->GetBaseClass(i, false); + if (GenEventEntry(obj, base_info, templateName, handlerName, strClassName, disconnect)) { + return true; + } + } + + return false; } -void LuaCodeGenerator::GenVirtualEventHandlers( const EventVector& events, const wxString& eventHandlerPostfix, const wxString& strClassName ) +void LuaCodeGenerator::GenVirtualEventHandlers( + const EventVector& events, const wxString& eventHandlerPostfix, const wxString& strClassName) { - if ( events.size() > 0 ) - { - // There are problems if we create "pure" virtual handlers, because some - // events could be triggered in the constructor in which virtual methods are - // execute properly. - // So we create a default handler which will skip the event. - m_source->WriteLn( wxEmptyString ); - m_source->WriteLn( wxT("-- event handlers") ); - - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString aux = wxT("function ") + event->GetValue() + wxT("_") + strClassName + wxT("( event )"); - - if (generatedHandlers.find(aux) == generatedHandlers.end()) - { - m_source->WriteLn(aux); - m_source->Indent(); - m_source->WriteLn(wxT("\n") + eventHandlerPostfix); - m_source->Unindent(); - m_source->WriteLn(wxT("end")); - generatedHandlers.insert(aux); - } - if( i < (events.size()-1) ) m_source->WriteLn(); - } - m_source->WriteLn( wxEmptyString ); - } + if (events.size() > 0) { + // There are problems if we create "pure" virtual handlers, because some + // events could be triggered in the constructor in which virtual methods are + // execute properly. + // So we create a default handler which will skip the event. + m_source->WriteLn(wxEmptyString); + m_source->WriteLn(wxT("-- event handlers")); + + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString aux = wxT("function ") + event->GetValue() + wxT("_") + strClassName + wxT("( event )"); + + if (generatedHandlers.find(aux) == generatedHandlers.end()) { + m_source->WriteLn(aux); + m_source->Indent(); + m_source->WriteLn(wxT("\n") + eventHandlerPostfix); + m_source->Unindent(); + m_source->WriteLn(wxT("end")); + generatedHandlers.insert(aux); + } + if (i < (events.size() - 1)) + m_source->WriteLn(); + } + m_source->WriteLn(wxEmptyString); + } } -void LuaCodeGenerator::GetGenEventHandlers( PObjectBase obj ) +void LuaCodeGenerator::GetGenEventHandlers(PObjectBase obj) { - GenDefinedEventHandlers( obj->GetObjectInfo(), obj ); + GenDefinedEventHandlers(obj->GetObjectInfo(), obj); - for (unsigned int i = 0; i < obj->GetChildCount() ; i++) - { - PObjectBase child = obj->GetChild(i); - GetGenEventHandlers(child); - } + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GetGenEventHandlers(child); + } } -void LuaCodeGenerator::GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ) +void LuaCodeGenerator::GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj) { - PCodeInfo code_info = info->GetCodeInfo( wxT( "Lua" ) ); - if ( code_info ) - { - wxString _template = code_info->GetTemplate( wxT("generated_event_handlers") ); - if ( !_template.empty() ) - { - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString code = parser.ParseTemplate(); - - if ( !code.empty() ) - { - m_source->WriteLn(code); - } - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenDefinedEventHandlers( base_info, obj ); - } + PCodeInfo code_info = info->GetCodeInfo(wxT("Lua")); + if (code_info) { + wxString _template = code_info->GetTemplate(wxT("generated_event_handlers")); + if (!_template.empty()) { + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString code = parser.ParseTemplate(); + + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenDefinedEventHandlers(base_info, obj); + } } -wxString LuaCodeGenerator::GetCode(PObjectBase obj, wxString name, bool silent /*= false*/, wxString strSelf /*= wxEmptyString*/) +wxString LuaCodeGenerator::GetCode( + PObjectBase obj, wxString name, bool silent /*= false*/, wxString strSelf /*= wxEmptyString*/) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT("Lua") ); - - if (!code_info) - { - if( !silent ) - { - wxString msg( wxString::Format( wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), - name, obj->GetClassName() ) ); - wxLogError(msg); - } - return wxEmptyString; - } - - _template = code_info->GetTemplate(name); - _template.Replace(wxT("#parentname"), strSelf); - - - if (!m_strUITable.empty()) - { - _template.Replace(wxT("#utbl"), m_strUITable + wxT(".")); - } - else - { - _template.Replace(wxT("#utbl"), wxEmptyString); - } - - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString code = parser.ParseTemplate(); - - //handle unsupported classes - std::vector::iterator iter = m_strUnsupportedInstances.begin(); - for(; iter != m_strUnsupportedInstances.end(); ++iter){ - if(code.Contains(*iter)) break; - } - if(iter != m_strUnsupportedInstances.end()) - code.Prepend(wxT("--")); - - wxString strRootCode = parser.RootWxParentToCode(); - int pos = code.Find(strRootCode); - if(pos != -1){ - wxString strMid = code.Mid(pos + strRootCode.length(),3); - strMid.Trim(false); - if (strMid.GetChar(0) == ',') - { - code.Replace(strRootCode, strSelf); - } - else - { - code.Replace(strRootCode, wxEmptyString); - } - } - - return code; + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("Lua")); + + if (!code_info) { + if (!silent) { + wxString msg(wxString::Format( + wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), name, + obj->GetClassName())); + wxLogError(msg); + } + return wxEmptyString; + } + + _template = code_info->GetTemplate(name); + _template.Replace(wxT("#parentname"), strSelf); + + + if (!m_strUITable.empty()) { + _template.Replace(wxT("#utbl"), m_strUITable + wxT(".")); + } else { + _template.Replace(wxT("#utbl"), wxEmptyString); + } + + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString code = parser.ParseTemplate(); + + // handle unsupported classes + std::vector::iterator iter = m_strUnsupportedInstances.begin(); + for (; iter != m_strUnsupportedInstances.end(); ++iter) { + if (code.Contains(*iter)) + break; + } + if (iter != m_strUnsupportedInstances.end()) + code.Prepend(wxT("--")); + + wxString strRootCode = parser.RootWxParentToCode(); + int pos = code.Find(strRootCode); + if (pos != -1) { + wxString strMid = code.Mid(pos + strRootCode.length(), 3); + strMid.Trim(false); + if (strMid.GetChar(0) == ',') { + code.Replace(strRootCode, strSelf); + } else { + code.Replace(strRootCode, wxEmptyString); + } + } + + return code; } wxString LuaCodeGenerator::GetConstruction(PObjectBase obj, bool silent, wxString strSelf, ArrayItems& arrays) { - // Get the name - const auto& propName = obj->GetProperty(wxT("name")); - if (!propName) - { - // Object has no name, just get its code - return GetCode(obj, wxT("construction"), silent, strSelf); - } - - // Object has a name, check if its an array - const auto& name = propName->GetValue(); - wxString baseName; - ArrayItem unused; - if (!ParseArrayName(name, baseName, unused)) - { - // Object is not an array, just get its code - return GetCode(obj, wxT("construction"), silent, strSelf); - } - - // Object is an array, check if it needs to be declared - auto& item = arrays[baseName]; - if (item.isDeclared) - { - // Object is already declared, just get its code - return GetCode(obj, wxT("construction"), silent, strSelf); - } - - // Array needs to be declared - wxString code; - - // UI table code copied from TemplateParser - wxString strTableName; - const auto& project = AppData()->GetProjectData(); - const auto& table = project->GetProperty(wxT("ui_table")); - if (table) - { - strTableName = table->GetValueAsString(); - if (strTableName.empty()) - { - strTableName = wxT("UI"); - } - strTableName.append(wxT(".")); - } - - // Array declaration - // Base array - code.append(strTableName); - code.append(baseName); - code.append(wxT(" = {}\n")); - - // Need to fill all dimensions up to the last - if (item.maxIndex.size() > 1) - { - std::vector stackCurrent; - std::vector stackNext; - - stackCurrent.push_back(baseName); - for (size_t dimension = 0; dimension < item.maxIndex.size() - 1; ++dimension) - { - const auto size = item.maxIndex[dimension] + 1; - - stackNext.reserve(stackCurrent.size() * size); - for (const auto& array : stackCurrent) - { - for (size_t index = 0; index < size; ++index) - { - const auto targetName = wxString::Format(wxT("%s[%u]"), array, static_cast(index)); - - code.append(strTableName); - code.append(targetName); - code.append(wxT(" = {}\n")); - - stackNext.push_back(targetName); - } - } - stackCurrent.swap(stackNext); - stackNext.clear(); - } - } - - // Get the Code - code.append(GetCode(obj, wxT("construction"), silent, strSelf)); - - // Mark the array as declared - item.isDeclared = true; - - return code; + // Get the name + const auto& propName = obj->GetProperty(wxT("name")); + if (!propName) { + // Object has no name, just get its code + return GetCode(obj, wxT("construction"), silent, strSelf); + } + + // Object has a name, check if its an array + const auto& name = propName->GetValue(); + wxString baseName; + ArrayItem unused; + if (!ParseArrayName(name, baseName, unused)) { + // Object is not an array, just get its code + return GetCode(obj, wxT("construction"), silent, strSelf); + } + + // Object is an array, check if it needs to be declared + auto& item = arrays[baseName]; + if (item.isDeclared) { + // Object is already declared, just get its code + return GetCode(obj, wxT("construction"), silent, strSelf); + } + + // Array needs to be declared + wxString code; + + // UI table code copied from TemplateParser + wxString strTableName; + const auto& project = AppData()->GetProjectData(); + const auto& table = project->GetProperty(wxT("ui_table")); + if (table) { + strTableName = table->GetValueAsString(); + if (strTableName.empty()) { + strTableName = wxT("UI"); + } + strTableName.append(wxT(".")); + } + + // Array declaration + // Base array + code.append(strTableName); + code.append(baseName); + code.append(wxT(" = {}\n")); + + // Need to fill all dimensions up to the last + if (item.maxIndex.size() > 1) { + std::vector stackCurrent; + std::vector stackNext; + + stackCurrent.push_back(baseName); + for (size_t dimension = 0; dimension < item.maxIndex.size() - 1; ++dimension) { + const auto size = item.maxIndex[dimension] + 1; + + stackNext.reserve(stackCurrent.size() * size); + for (const auto& array : stackCurrent) { + for (size_t index = 0; index < size; ++index) { + const auto targetName = wxString::Format(wxT("%s[%u]"), array, static_cast(index)); + + code.append(strTableName); + code.append(targetName); + code.append(wxT(" = {}\n")); + + stackNext.push_back(targetName); + } + } + stackCurrent.swap(stackNext); + stackNext.clear(); + } + } + + // Get the Code + code.append(GetCode(obj, wxT("construction"), silent, strSelf)); + + // Mark the array as declared + item.isDeclared = true; + + return code; } -void LuaCodeGenerator::GenClassDeclaration(PObjectBase class_obj, bool /*use_enum*/, - const wxString& /*classDecoration*/, - const EventVector& events, - const wxString& /*eventHandlerPostfix*/, - ArrayItems& arrays) { - wxString strClassName = class_obj->GetClassName(); - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), - strClassName); - return; - } - - wxString strName = propName->GetValue(); - if ( strName.empty() ) - { - wxLogError( wxT("Object name can not be null") ); - return; - } - - GetGenEventHandlers( class_obj ); - GenConstructor(class_obj, events, strName, arrays); - +void LuaCodeGenerator::GenClassDeclaration( + PObjectBase class_obj, bool /*use_enum*/, const wxString& /*classDecoration*/, const EventVector& events, + const wxString& /*eventHandlerPostfix*/, ArrayItems& arrays) +{ + wxString strClassName = class_obj->GetClassName(); + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), strClassName); + return; + } + + wxString strName = propName->GetValue(); + if (strName.empty()) { + wxLogError(wxT("Object name can not be null")); + return; + } + + GetGenEventHandlers(class_obj); + GenConstructor(class_obj, events, strName, arrays); } -void LuaCodeGenerator::GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::vector< wxString >* headerIncludes ) +void LuaCodeGenerator::GenSubclassSets( + PObjectBase obj, std::set* subclasses, std::vector* headerIncludes) { - // Call GenSubclassForwardDeclarations on all children as well - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenSubclassSets( obj->GetChild( i ), subclasses, headerIncludes ); - } - - // Fill the set - PProperty subclass = obj->GetProperty( wxT("subclass") ); - if ( subclass ) - { - std::map< wxString, wxString > children; - subclass->SplitParentProperty( &children ); - - std::map< wxString, wxString >::iterator name; - name = children.find( wxT("name") ); - - if ( children.end() == name ) - { - // No name, so do nothing - return; - } - - wxString nameVal = name->second; - if ( nameVal.empty() ) - { - // No name, so do nothing - return; - } - - // Now get the header - std::map< wxString, wxString >::iterator header; - header = children.find( wxT("header") ); - - if ( children.end() == header ) - { - // No header, so do nothing - return; - } - - wxString headerVal = header->second; - if ( headerVal.empty() ) - { - // No header, so do nothing - return; - } - - // Got a header - PObjectInfo info = obj->GetObjectInfo(); - if ( !info ) - { - return; - } - - PObjectPackage pkg = info->GetPackage(); - if ( !pkg ) - { - return; - } - - wxString include = wxT("require(\"") + headerVal.Trim() + wxT("\")\n"); - std::vector< wxString >::iterator it = std::find( headerIncludes->begin(), headerIncludes->end(), include ); - if ( headerIncludes->end() == it ) - { - headerIncludes->push_back( include ); - } - } + // Call GenSubclassForwardDeclarations on all children as well + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + GenSubclassSets(obj->GetChild(i), subclasses, headerIncludes); + } + + // Fill the set + PProperty subclass = obj->GetProperty(wxT("subclass")); + if (subclass) { + std::map children; + subclass->SplitParentProperty(&children); + + std::map::iterator name; + name = children.find(wxT("name")); + + if (children.end() == name) { + // No name, so do nothing + return; + } + + wxString nameVal = name->second; + if (nameVal.empty()) { + // No name, so do nothing + return; + } + + // Now get the header + std::map::iterator header; + header = children.find(wxT("header")); + + if (children.end() == header) { + // No header, so do nothing + return; + } + + wxString headerVal = header->second; + if (headerVal.empty()) { + // No header, so do nothing + return; + } + + // Got a header + PObjectInfo info = obj->GetObjectInfo(); + if (!info) { + return; + } + + PObjectPackage pkg = info->GetPackage(); + if (!pkg) { + return; + } + + wxString include = wxT("require(\"") + headerVal.Trim() + wxT("\")\n"); + std::vector::iterator it = std::find(headerIncludes->begin(), headerIncludes->end(), include); + if (headerIncludes->end() == it) { + headerIncludes->push_back(include); + } + } } -void LuaCodeGenerator::GenIncludes( PObjectBase project, std::vector* includes, std::set< wxString >* templates ) +void LuaCodeGenerator::GenIncludes(PObjectBase project, std::vector* includes, std::set* templates) { - GenObjectIncludes( project, includes, templates ); + GenObjectIncludes(project, includes, templates); } -void LuaCodeGenerator::GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ) +void LuaCodeGenerator::GenObjectIncludes( + PObjectBase project, std::vector* includes, std::set* templates) { - // Fill the set - PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo( wxT("Lua") ); - if (code_info) - { - LuaTemplateParser parser( project, code_info->GetTemplate( wxT("include") ), m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } - - // Call GenIncludes on all children as well - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - GenObjectIncludes( project->GetChild(i), includes, templates ); - } - - // Generate includes for base classes - GenBaseIncludes( project->GetObjectInfo(), project, includes, templates ); + // Fill the set + PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo(wxT("Lua")); + if (code_info) { + LuaTemplateParser parser( + project, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } + + // Call GenIncludes on all children as well + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + GenObjectIncludes(project->GetChild(i), includes, templates); + } + + // Generate includes for base classes + GenBaseIncludes(project->GetObjectInfo(), project, includes, templates); } -void LuaCodeGenerator::GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ) +void LuaCodeGenerator::GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates) { - if ( !info ) - { - return; - } - - // Process all the base classes recursively - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenBaseIncludes( base_info, obj, includes, templates ); - } - - PCodeInfo code_info = info->GetCodeInfo( wxT("Lua") ); - if ( code_info ) - { - LuaTemplateParser parser( obj, code_info->GetTemplate( wxT("include") ), m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } + if (!info) { + return; + } + + // Process all the base classes recursively + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenBaseIncludes(base_info, obj, includes, templates); + } + + PCodeInfo code_info = info->GetCodeInfo(wxT("Lua")); + if (code_info) { + LuaTemplateParser parser( + obj, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } } -void LuaCodeGenerator::AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ) +void LuaCodeGenerator::AddUniqueIncludes(const wxString& include, std::vector* includes) { - // Split on newlines to only generate unique include lines - // This strips blank lines and trims - wxStringTokenizer tkz( include, wxT("\n"), wxTOKEN_STRTOK ); - - while ( tkz.HasMoreTokens() ) - { - wxString line = tkz.GetNextToken(); - line.Trim( false ); - line.Trim( true ); - - // If it is an include, it must be unique to be written - std::vector< wxString >::iterator it = std::find( includes->begin(), includes->end(), line ); - if ( includes->end() == it ) - { - includes->push_back( line ); - } - } + // Split on newlines to only generate unique include lines + // This strips blank lines and trims + wxStringTokenizer tkz(include, wxT("\n"), wxTOKEN_STRTOK); + + while (tkz.HasMoreTokens()) { + wxString line = tkz.GetNextToken(); + line.Trim(false); + line.Trim(true); + + // If it is an include, it must be unique to be written + std::vector::iterator it = std::find(includes->begin(), includes->end(), line); + if (includes->end() == it) { + includes->push_back(line); + } + } } -void LuaCodeGenerator::FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ) +void LuaCodeGenerator::FindDependencies(PObjectBase obj, std::set& info_set) { - unsigned int ch_count = obj->GetChildCount(); - if (ch_count > 0) - { - unsigned int i; - for (i = 0; iGetChild(i); - info_set.insert(child->GetObjectInfo()); - FindDependencies(child, info_set); - } - } + unsigned int ch_count = obj->GetChildCount(); + if (ch_count > 0) { + unsigned int i; + for (i = 0; i < ch_count; i++) { + PObjectBase child = obj->GetChild(i); + info_set.insert(child->GetObjectInfo()); + FindDependencies(child, info_set); + } + } } -void LuaCodeGenerator::GenConstructor(PObjectBase class_obj, const EventVector& events, wxString& strClassName, ArrayItems& arrays) +void LuaCodeGenerator::GenConstructor( + PObjectBase class_obj, const EventVector& events, wxString& strClassName, ArrayItems& arrays) { - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError( wxT( "Missing \"name\" property on \"%s\" class. Review your XML object description" ), - class_obj->GetClassName() ); - return; - } - - wxString strName = propName->GetValue(); - - if(m_strUITable.length() > 0) - strName = m_strUITable + wxT(".") + strName; - - m_source->WriteLn(); - m_source->WriteLn( wxT("-- create ") + strClassName ); - - m_source->WriteLn(strName + wxT(" = ") + GetCode( class_obj, wxT("cons_call") )); - - m_source->Indent(); - wxString settings = GetCode( class_obj, wxT("settings") ); - if ( !settings.IsEmpty() ) - { - m_source->WriteLn( settings ); - } - - if ( class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0 ) - { - m_source->WriteLn( wxT("function add_page(page)") ); - m_source->Indent(); - m_source->WriteLn( wxT("if ( #") + m_strUITable + wxT(".") + strClassName + wxT(".m_pages) > 0 then") ); - m_source->Indent(); - m_source->WriteLn( wxT("local previous_page = ") + m_strUITable + wxT(".") + strClassName + wxT(".m_pages[ #") + m_strUITable + wxT(".") + strClassName +wxT(".m_pages ]") ); - m_source->WriteLn( wxT("page:SetPrev(previous_page)") ); - m_source->WriteLn( wxT("previous_page:SetNext(page)") ); - m_source->Unindent(); - m_source->WriteLn( wxT("end") ); - m_source->WriteLn(wxT("table.insert( ") + m_strUITable + wxT(".") + strClassName + wxT(".m_pages, page)") ); - m_source->Unindent(); - m_source->WriteLn( wxT("end") ); - } - - for ( unsigned int i = 0; i < class_obj->GetChildCount(); i++ ) - { - GenConstruction(class_obj->GetChild(i), true , strClassName, arrays); - } - - wxString afterAddChild = GetCode( class_obj, wxT("after_addchild") ); - if ( !afterAddChild.IsEmpty() ) - { - m_source->WriteLn( afterAddChild ); - } - - GenEvents( class_obj, events, strClassName ); - - auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); - if (!afterConnectEvents.empty()) - { - m_source->WriteLn(); - m_source->WriteLn(afterConnectEvents); - } - - m_source->Unindent(); + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString strName = propName->GetValue(); + + if (m_strUITable.length() > 0) + strName = m_strUITable + wxT(".") + strName; + + m_source->WriteLn(); + m_source->WriteLn(wxT("-- create ") + strClassName); + + m_source->WriteLn(strName + wxT(" = ") + GetCode(class_obj, wxT("cons_call"))); + + m_source->Indent(); + wxString settings = GetCode(class_obj, wxT("settings")); + if (!settings.IsEmpty()) { + m_source->WriteLn(settings); + } + + if (class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0) { + m_source->WriteLn(wxT("function add_page(page)")); + m_source->Indent(); + m_source->WriteLn(wxT("if ( #") + m_strUITable + wxT(".") + strClassName + wxT(".m_pages) > 0 then")); + m_source->Indent(); + m_source->WriteLn( + wxT("local previous_page = ") + m_strUITable + wxT(".") + strClassName + wxT(".m_pages[ #") + m_strUITable + + wxT(".") + strClassName + wxT(".m_pages ]")); + m_source->WriteLn(wxT("page:SetPrev(previous_page)")); + m_source->WriteLn(wxT("previous_page:SetNext(page)")); + m_source->Unindent(); + m_source->WriteLn(wxT("end")); + m_source->WriteLn(wxT("table.insert( ") + m_strUITable + wxT(".") + strClassName + wxT(".m_pages, page)")); + m_source->Unindent(); + m_source->WriteLn(wxT("end")); + } + + for (unsigned int i = 0; i < class_obj->GetChildCount(); i++) { + GenConstruction(class_obj->GetChild(i), true, strClassName, arrays); + } + + wxString afterAddChild = GetCode(class_obj, wxT("after_addchild")); + if (!afterAddChild.IsEmpty()) { + m_source->WriteLn(afterAddChild); + } + + GenEvents(class_obj, events, strClassName); + + auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); + if (!afterConnectEvents.empty()) { + m_source->WriteLn(); + m_source->WriteLn(afterConnectEvents); + } + + m_source->Unindent(); } -void LuaCodeGenerator::GenDestructor( PObjectBase class_obj, const EventVector &events ) +void LuaCodeGenerator::GenDestructor(PObjectBase class_obj, const EventVector& events) { - m_source->WriteLn(); - // generate function definition - m_source->Indent(); - - wxString strClassName; - if ( m_disconnectEvents && !events.empty() ) - { - GenEvents( class_obj, events, strClassName, true ); - } else if (class_obj->GetPropertyAsInteger(wxT("aui_managed")) == 0) { - m_source->WriteLn(wxT("pass")); - } - - // destruct objects - GenDestruction( class_obj ); - - m_source->Unindent(); + m_source->WriteLn(); + // generate function definition + m_source->Indent(); + + wxString strClassName; + if (m_disconnectEvents && !events.empty()) { + GenEvents(class_obj, events, strClassName, true); + } else if (class_obj->GetPropertyAsInteger(wxT("aui_managed")) == 0) { + m_source->WriteLn(wxT("pass")); + } + + // destruct objects + GenDestruction(class_obj); + + m_source->Unindent(); } wxString GetParentWindow(PObjectBase obj) { - wxString strName; - PObjectBase ob = obj->GetLayout(); - if(ob) - strName = ob->GetClassName(); + wxString strName; + PObjectBase ob = obj->GetLayout(); + if (ob) + strName = ob->GetClassName(); - return strName; + return strName; } void LuaCodeGenerator::GenConstruction(PObjectBase obj, bool is_widget, wxString& strClassName, ArrayItems& arrays) { - wxString type = obj->GetObjectTypeName(); - PObjectInfo info = obj->GetObjectInfo(); - - if ( ObjectDatabase::HasCppProperties( type ) ) - { - - wxString strName; - PProperty propName = obj->GetProperty( wxT("name") ); - if(propName) - strName = propName->GetValue(); - - wxString strClass = obj->GetClassName(); - - - std::vector::iterator itr; - if(m_strUnsupportedClasses.end() != (itr = std::find(m_strUnsupportedClasses.begin(),m_strUnsupportedClasses.end(),strClass))){ - - m_source->WriteLn(wxT("--Instance ") + strName + wxT(" of Control ") + *itr + wxT(" you try to use isn't unfortunately wrapped by wxLua.")); - m_source->WriteLn(wxT("--Please try to use another control\n")); - m_strUnsupportedInstances.push_back(strName); - return; - } - - m_source->WriteLn(GetConstruction(obj, false, strClassName, arrays)); - - GenSettings( obj->GetObjectInfo(), obj, strClassName ); - - bool isWidget = !info->IsSubclassOf( wxT("sizer") ); - - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenConstruction(child, isWidget, strClassName, arrays); - - if ( type == wxT("toolbar") ) - { - GenAddToolbar(child->GetObjectInfo(), child); - } - } - - if ( !isWidget ) // sizers - { - wxString afterAddChild = GetCode( obj, wxT( "after_addchild" ) ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - - if (is_widget) - { - // the parent object is not a sizer. There is no template for - // this so we'll make it manually. - // It's not a good practice to embed templates into the source code, - // because you will need to recompile... - - wxString _template = wxT("#utbl#wxparent$name:SetSizer( #utbl$name ) #nl") - wxT("#utbl#wxparent$name:Layout()") - wxT("#ifnull #parent $size") - wxT("@{ #nl #utbl$name:Fit( #utbl#wxparent $name ) @}"); - - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString res = parser.ParseTemplate(); - res.Replace(parser.RootWxParentToCode(), wxEmptyString); - m_source->WriteLn(res); - } - } - else if ( type == wxT("splitter") ) - { - // Generating the split - switch ( obj->GetChildCount() ) - { - case 1: - { - PObjectBase sub1 = obj->GetChild(0)->GetChild(0); - wxString _template = wxT("#utbl$name:Initialize( "); - _template = _template + wxT("#utbl") + sub1->GetProperty( wxT("name") )->GetValue() + wxT(" )"); - _template.Replace(wxT("#utbl"), m_strUITable + wxT(".")); - - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - m_source->WriteLn(parser.ParseTemplate()); - break; - } - case 2: - { - PObjectBase sub1,sub2; - sub1 = obj->GetChild(0)->GetChild(0); - sub2 = obj->GetChild(1)->GetChild(0); - - wxString _template; - wxString strMode = obj->GetProperty( wxT("splitmode") )->GetValue(); - bool bSplitVertical = (strMode == wxT("wxSPLIT_VERTICAL")); - if (bSplitVertical) - { - _template = wxT("#utbl$name:SplitVertically( "); - } - else - { - _template = wxT("#utbl$name:SplitHorizontally( "); - } - - _template = _template + wxT("#utbl") + sub1->GetProperty( wxT("name") )->GetValue() + - wxT(", #utbl") + sub2->GetProperty( wxT("name") )->GetValue() + wxT(", $sashpos )"); - _template = _template + wxT("#nl #utbl$name") + wxT(":SetSplitMode(") + wxString::Format(wxT("%d"),(bSplitVertical ? 1 : 0)) + wxT(")"); - _template.Replace(wxT("#utbl"), m_strUITable + wxT(".")); - - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - m_source->WriteLn(parser.ParseTemplate()); - break; - } - default: - wxLogError( wxT("Missing subwindows for wxSplitterWindow widget.") ); - break; - } - } - else if ( type == wxT("menubar") || - type == wxT("menu") || - type == wxT("submenu") || - type == wxT("toolbar") || - type == wxT("tool") || - type == wxT("listbook") || - type == wxT("simplebook") || - type == wxT("notebook") || - type == wxT("auinotebook") || - type == wxT("treelistctrl") || - type == wxT("flatnotebook") || - type == wxT("wizard") - ) - { - wxString afterAddChild = GetCode( obj, wxT("after_addchild") ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - } - } - else if ( info->IsSubclassOf( wxT("sizeritembase") ) ) - { - - // The child must be added to the sizer having in mind the - // child object type (there are 3 different routines) - GenConstruction(obj->GetChild(0), false, strClassName, arrays); - - PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); - wxString temp_name; - if ( childInfo->IsSubclassOf( wxT("wxWindow") ) || wxT("CustomControl") == childInfo->GetClassName() ) - { - temp_name = wxT("window_add"); - } - else if ( childInfo->IsSubclassOf( wxT("sizer") ) ) - { - temp_name = wxT("sizer_add"); - } - else if ( childInfo->GetClassName() == wxT("spacer") ) - { - temp_name = wxT("spacer_add"); - } - else - { - LogDebug( wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.") ); - return; - } - - - m_source->WriteLn( GetCode( obj, temp_name ) ); - - } - else if ( type == wxT("notebookpage") || - type == wxT("flatnotebookpage") || - type == wxT("listbookpage") || - type == wxT("simplebookpage") || - type == wxT("choicebookpage") || - type == wxT("auinotebookpage") - ) - { - GenConstruction(obj->GetChild(0), false, strClassName, arrays); - m_source->WriteLn( GetCode( obj, wxT("page_add") ) ); - GenSettings( obj->GetObjectInfo(), obj, strClassName ); - } - else if ( type == wxT("treelistctrlcolumn") ) - { - m_source->WriteLn( GetCode( obj, wxT("column_add") ) ); - GenSettings( obj->GetObjectInfo(), obj, strClassName ); - } - else if ( type == wxT("tool") ) - { - // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize - // So hacky, yet so useful ... - wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize( _("bitmapsize") ); - if ( wxDefaultSize != toolbarsize ) - { - PProperty prop = obj->GetProperty( _("bitmap") ); - if ( prop ) - { - wxString oldVal = prop->GetValueAsString(); - wxString path, source; - wxSize toolsize; - TypeConv::ParseBitmapWithResource( oldVal, &path, &source, &toolsize ); - if ( _("Load From Icon Resource") == source && wxDefaultSize == toolsize ) - { - prop->SetValue( wxString::Format( wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight() ) ); - m_source->WriteLn(GetConstruction(obj, false, wxEmptyString, arrays)); - prop->SetValue( oldVal ); - return; - } - } - } - m_source->WriteLn(GetConstruction(obj, false, wxEmptyString, arrays)); - } - else - { - // Generate the children - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenConstruction(obj->GetChild( i ), false, strClassName, arrays); - } - } + wxString type = obj->GetObjectTypeName(); + PObjectInfo info = obj->GetObjectInfo(); + + if (ObjectDatabase::HasCppProperties(type)) { + + wxString strName; + PProperty propName = obj->GetProperty(wxT("name")); + if (propName) + strName = propName->GetValue(); + + wxString strClass = obj->GetClassName(); + + + std::vector::iterator itr; + if ( + m_strUnsupportedClasses.end() != + (itr = std::find(m_strUnsupportedClasses.begin(), m_strUnsupportedClasses.end(), strClass))) { + + m_source->WriteLn( + wxT("--Instance ") + strName + wxT(" of Control ") + *itr + + wxT(" you try to use isn't unfortunately wrapped by wxLua.")); + m_source->WriteLn(wxT("--Please try to use another control\n")); + m_strUnsupportedInstances.push_back(strName); + return; + } + + m_source->WriteLn(GetConstruction(obj, false, strClassName, arrays)); + + GenSettings(obj->GetObjectInfo(), obj, strClassName); + + bool isWidget = !info->IsSubclassOf(wxT("sizer")); + + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenConstruction(child, isWidget, strClassName, arrays); + + if (type == wxT("toolbar")) { + GenAddToolbar(child->GetObjectInfo(), child); + } + } + + if (!isWidget) // sizers + { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + + if (is_widget) { + // the parent object is not a sizer. There is no template for + // this so we'll make it manually. + // It's not a good practice to embed templates into the source code, + // because you will need to recompile... + + wxString _template = + wxT("#utbl#wxparent$name:SetSizer( #utbl$name ) #nl") wxT("#utbl#wxparent$name:Layout()") + wxT("#ifnull #parent $size") wxT("@{ #nl #utbl$name:Fit( #utbl#wxparent $name ) @}"); + + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString res = parser.ParseTemplate(); + res.Replace(parser.RootWxParentToCode(), wxEmptyString); + m_source->WriteLn(res); + } + } else if (type == wxT("splitter")) { + // Generating the split + switch (obj->GetChildCount()) { + case 1: { + PObjectBase sub1 = obj->GetChild(0)->GetChild(0); + wxString _template = wxT("#utbl$name:Initialize( "); + _template = _template + wxT("#utbl") + sub1->GetProperty(wxT("name"))->GetValue() + wxT(" )"); + _template.Replace(wxT("#utbl"), m_strUITable + wxT(".")); + + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + case 2: { + PObjectBase sub1, sub2; + sub1 = obj->GetChild(0)->GetChild(0); + sub2 = obj->GetChild(1)->GetChild(0); + + wxString _template; + wxString strMode = obj->GetProperty(wxT("splitmode"))->GetValue(); + bool bSplitVertical = (strMode == wxT("wxSPLIT_VERTICAL")); + if (bSplitVertical) { + _template = wxT("#utbl$name:SplitVertically( "); + } else { + _template = wxT("#utbl$name:SplitHorizontally( "); + } + + _template = _template + wxT("#utbl") + sub1->GetProperty(wxT("name"))->GetValue() + wxT(", #utbl") + + sub2->GetProperty(wxT("name"))->GetValue() + wxT(", $sashpos )"); + _template = _template + wxT("#nl #utbl$name") + wxT(":SetSplitMode(") + + wxString::Format(wxT("%d"), (bSplitVertical ? 1 : 0)) + wxT(")"); + _template.Replace(wxT("#utbl"), m_strUITable + wxT(".")); + + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + default: + wxLogError(wxT("Missing subwindows for wxSplitterWindow widget.")); + break; + } + } else if ( + type == wxT("menubar") || type == wxT("menu") || type == wxT("submenu") || type == wxT("toolbar") || + type == wxT("tool") || type == wxT("listbook") || type == wxT("simplebook") || type == wxT("notebook") || + type == wxT("auinotebook") || type == wxT("treelistctrl") || type == wxT("flatnotebook") || + type == wxT("wizard")) { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + } + } else if (info->IsSubclassOf(wxT("sizeritembase"))) { + + // The child must be added to the sizer having in mind the + // child object type (there are 3 different routines) + GenConstruction(obj->GetChild(0), false, strClassName, arrays); + + PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); + wxString temp_name; + if (childInfo->IsSubclassOf(wxT("wxWindow")) || wxT("CustomControl") == childInfo->GetClassName()) { + temp_name = wxT("window_add"); + } else if (childInfo->IsSubclassOf(wxT("sizer"))) { + temp_name = wxT("sizer_add"); + } else if (childInfo->GetClassName() == wxT("spacer")) { + temp_name = wxT("spacer_add"); + } else { + LogDebug(wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.")); + return; + } + + + m_source->WriteLn(GetCode(obj, temp_name)); + + } else if ( + type == wxT("notebookpage") || type == wxT("flatnotebookpage") || type == wxT("listbookpage") || + type == wxT("simplebookpage") || type == wxT("choicebookpage") || type == wxT("auinotebookpage")) { + GenConstruction(obj->GetChild(0), false, strClassName, arrays); + m_source->WriteLn(GetCode(obj, wxT("page_add"))); + GenSettings(obj->GetObjectInfo(), obj, strClassName); + } else if (type == wxT("treelistctrlcolumn")) { + m_source->WriteLn(GetCode(obj, wxT("column_add"))); + GenSettings(obj->GetObjectInfo(), obj, strClassName); + } else if (type == wxT("tool")) { + // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize + // So hacky, yet so useful ... + wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize(_("bitmapsize")); + if (wxDefaultSize != toolbarsize) { + PProperty prop = obj->GetProperty(_("bitmap")); + if (prop) { + wxString oldVal = prop->GetValueAsString(); + wxString path, source; + wxSize toolsize; + TypeConv::ParseBitmapWithResource(oldVal, &path, &source, &toolsize); + if (_("Load From Icon Resource") == source && wxDefaultSize == toolsize) { + prop->SetValue(wxString::Format( + wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight())); + m_source->WriteLn(GetConstruction(obj, false, wxEmptyString, arrays)); + prop->SetValue(oldVal); + return; + } + } + } + m_source->WriteLn(GetConstruction(obj, false, wxEmptyString, arrays)); + } else { + // Generate the children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + GenConstruction(obj->GetChild(i), false, strClassName, arrays); + } + } } -void LuaCodeGenerator::GenDestruction( PObjectBase obj ) +void LuaCodeGenerator::GenDestruction(PObjectBase obj) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT( "Lua" ) ); - - if ( code_info ) - { - _template = code_info->GetTemplate( wxT( "destruction" ) ); - - if ( !_template.empty() ) - { - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - } - } - } - - // Process child widgets - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenDestruction( child ); - } + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("Lua")); + + if (code_info) { + _template = code_info->GetTemplate(wxT("destruction")); + + if (!_template.empty()) { + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Process child widgets + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenDestruction(child); + } } -void LuaCodeGenerator::FindMacros( PObjectBase obj, std::vector* macros ) +void LuaCodeGenerator::FindMacros(PObjectBase obj, std::vector* macros) { - // iterate through all of the properties of all objects, add the macros - // to the vector - unsigned int i; - - for ( i = 0; i < obj->GetPropertyCount(); i++ ) - { - PProperty prop = obj->GetProperty( i ); - if ( prop->GetType() == PT_MACRO ) - { - wxString value = prop->GetValue(); - if( value.IsEmpty() ) continue; - - // Skip wx IDs - if ( ( ! value.Contains( wxT("XRCID" ) ) ) && - ( m_predMacros.end() == m_predMacros.find( value ) ) ) - { - if ( macros->end() == std::find( macros->begin(), macros->end(), value ) ) - { - macros->push_back( value ); - } - } - } - } - - for ( i = 0; i < obj->GetChildCount(); i++ ) - { - FindMacros( obj->GetChild( i ), macros ); - } + // iterate through all of the properties of all objects, add the macros + // to the vector + unsigned int i; + + for (i = 0; i < obj->GetPropertyCount(); i++) { + PProperty prop = obj->GetProperty(i); + if (prop->GetType() == PT_MACRO) { + wxString value = prop->GetValue(); + if (value.IsEmpty()) + continue; + + // Skip wx IDs + if ((!value.Contains(wxT("XRCID"))) && (m_predMacros.end() == m_predMacros.find(value))) { + if (macros->end() == std::find(macros->begin(), macros->end(), value)) { + macros->push_back(value); + } + } + } + } + + for (i = 0; i < obj->GetChildCount(); i++) { FindMacros(obj->GetChild(i), macros); } } -void LuaCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector &events) +void LuaCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector& events) { - unsigned int i; - unsigned int evt_cnt = obj->GetEventCount(); - for (i=0; i < evt_cnt; i++) - { - PEvent event = obj->GetEvent(i); - if (!event->GetValue().IsEmpty()) - events.push_back(event); - } - - for (i=0; i < obj->GetChildCount(); i++) - { - PObjectBase child = obj->GetChild(i); - FindEventHandlers(child,events); - } + unsigned int i; + unsigned int evt_cnt = obj->GetEventCount(); + for (i = 0; i < evt_cnt; i++) { + PEvent event = obj->GetEvent(i); + if (!event->GetValue().IsEmpty()) + events.push_back(event); + } + + for (i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + FindEventHandlers(child, events); + } } -void LuaCodeGenerator::GenDefines( PObjectBase project) +void LuaCodeGenerator::GenDefines(PObjectBase project) { - std::vector< wxString > macros; - FindMacros( project, ¯os ); - m_strUserIDsVec.erase(m_strUserIDsVec.begin(),m_strUserIDsVec.end()); - - // Remove the default macro from the set, for backward compatibility - std::vector< wxString >::iterator it; - it = std::find( macros.begin(), macros.end(), wxT("ID_DEFAULT") ); - if ( it != macros.end() ) - { - // The default macro is defined to wxID_ANY - m_source->WriteLn( wxT("wxID_DEFAULT = wxID_ANY -- Default") ); - macros.erase(it); - } - - unsigned int id = m_firstID; - if ( id < 1000 ) - { - wxLogWarning(wxT("First ID is Less than 1000")); - } - for (it = macros.begin() ; it != macros.end(); it++) - { - // Don't redefine wx IDs - m_source->WriteLn( wxString::Format( wxT("%s = %i"), it->c_str(), id ) ); - m_strUserIDsVec.push_back(*it); - id++; - } - if (!macros.empty()) - { - m_source->WriteLn(wxEmptyString); - } + std::vector macros; + FindMacros(project, ¯os); + m_strUserIDsVec.erase(m_strUserIDsVec.begin(), m_strUserIDsVec.end()); + + // Remove the default macro from the set, for backward compatibility + std::vector::iterator it; + it = std::find(macros.begin(), macros.end(), wxT("ID_DEFAULT")); + if (it != macros.end()) { + // The default macro is defined to wxID_ANY + m_source->WriteLn(wxT("wxID_DEFAULT = wxID_ANY -- Default")); + macros.erase(it); + } + + unsigned int id = m_firstID; + if (id < 1000) { + wxLogWarning(wxT("First ID is Less than 1000")); + } + for (it = macros.begin(); it != macros.end(); it++) { + // Don't redefine wx IDs + m_source->WriteLn(wxString::Format(wxT("%s = %i"), it->c_str(), id)); + m_strUserIDsVec.push_back(*it); + id++; + } + if (!macros.empty()) { + m_source->WriteLn(wxEmptyString); + } } -void LuaCodeGenerator::GenSettings(PObjectInfo info, PObjectBase obj, wxString &strClassName ) +void LuaCodeGenerator::GenSettings(PObjectInfo info, PObjectBase obj, wxString& strClassName) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT("Lua") ); - - if ( !code_info ) - { - return; - } - - _template = code_info->GetTemplate( wxT("settings") ); - - if ( !_template.empty() ) - { - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString code = parser.ParseTemplate(); - - wxString strRootCode = parser.RootWxParentToCode(); - if(code.Find(strRootCode) != -1){ - code.Replace(strRootCode, strClassName); - } - - if ( !code.empty() ) - { - m_source->WriteLn(code); - } - } - - // Proceeding recursively with the base classes - for (unsigned int i=0; i< info->GetBaseClassCount(false); i++) - { - PObjectInfo base_info = info->GetBaseClass(i, false); - GenSettings(base_info, obj, strClassName); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("Lua")); + + if (!code_info) { + return; + } + + _template = code_info->GetTemplate(wxT("settings")); + + if (!_template.empty()) { + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString code = parser.ParseTemplate(); + + wxString strRootCode = parser.RootWxParentToCode(); + if (code.Find(strRootCode) != -1) { + code.Replace(strRootCode, strClassName); + } + + if (!code.empty()) { + m_source->WriteLn(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenSettings(base_info, obj, strClassName); + } } -void LuaCodeGenerator::GenAddToolbar( PObjectInfo info, PObjectBase obj ) +void LuaCodeGenerator::GenAddToolbar(PObjectInfo info, PObjectBase obj) { - wxArrayString arrCode; + wxArrayString arrCode; - GetAddToolbarCode( info, obj, arrCode ); + GetAddToolbarCode(info, obj, arrCode); - for( size_t i = 0; i < arrCode.GetCount(); i++ ) m_source->WriteLn( arrCode[i] ); + for (size_t i = 0; i < arrCode.GetCount(); i++) m_source->WriteLn(arrCode[i]); } -void LuaCodeGenerator::GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ) +void LuaCodeGenerator::GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT( "Lua" ) ); - - if ( !code_info ) - return; - - _template = code_info->GetTemplate( wxT( "toolbar_add" ) ); - - if ( !_template.empty() ) - { - LuaTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - if( codelines.Index( code ) == wxNOT_FOUND ) codelines.Add( code ); - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GetAddToolbarCode( base_info, obj, codelines ); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("Lua")); + + if (!code_info) + return; + + _template = code_info->GetTemplate(wxT("toolbar_add")); + + if (!_template.empty()) { + LuaTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_strUserIDsVec); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + if (codelines.Index(code) == wxNOT_FOUND) + codelines.Add(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GetAddToolbarCode(base_info, obj, codelines); + } } /////////////////////////////////////////////////////////////////////// void LuaCodeGenerator::UseRelativePath(bool relative, wxString basePath) { - m_useRelativePath = relative; - - if (m_useRelativePath) - { - if (wxFileName::DirExists(basePath)) - { - m_basePath = basePath; - } - else - { - m_basePath = wxEmptyString; - } - } + m_useRelativePath = relative; + + if (m_useRelativePath) { + if (wxFileName::DirExists(basePath)) { + m_basePath = basePath; + } else { + m_basePath = wxEmptyString; + } + } } -#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert( wxT(#x) ) -#define ADD_PREDEFINED_PREFIX(k, v) m_predModulePrefix[ wxT(#k) ] = wxT(#v) +#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert(wxT(#x)) +#define ADD_PREDEFINED_PREFIX(k, v) m_predModulePrefix[wxT(#k)] = wxT(#v) void LuaCodeGenerator::SetupPredefinedMacros() { - /* no id matches this one when compared to it */ - ADD_PREDEFINED_MACRO(wxID_NONE); - - /* id for a separator line in the menu (invalid for normal item) */ - ADD_PREDEFINED_MACRO(wxID_SEPARATOR); - - ADD_PREDEFINED_MACRO(wxID_ANY); - - ADD_PREDEFINED_MACRO(wxID_LOWEST); - - ADD_PREDEFINED_MACRO(wxID_OPEN); - ADD_PREDEFINED_MACRO(wxID_CLOSE); - ADD_PREDEFINED_MACRO(wxID_NEW); - ADD_PREDEFINED_MACRO(wxID_SAVE); - ADD_PREDEFINED_MACRO(wxID_SAVEAS); - ADD_PREDEFINED_MACRO(wxID_REVERT); - ADD_PREDEFINED_MACRO(wxID_EXIT); - ADD_PREDEFINED_MACRO(wxID_UNDO); - ADD_PREDEFINED_MACRO(wxID_REDO); - ADD_PREDEFINED_MACRO(wxID_HELP); - ADD_PREDEFINED_MACRO(wxID_PRINT); - ADD_PREDEFINED_MACRO(wxID_PRINT_SETUP); - ADD_PREDEFINED_MACRO(wxID_PREVIEW); - ADD_PREDEFINED_MACRO(wxID_ABOUT); - ADD_PREDEFINED_MACRO(wxID_HELP_CONTENTS); - ADD_PREDEFINED_MACRO(wxID_HELP_COMMANDS); - ADD_PREDEFINED_MACRO(wxID_HELP_PROCEDURES); - ADD_PREDEFINED_MACRO(wxID_HELP_CONTEXT); - ADD_PREDEFINED_MACRO(wxID_CLOSE_ALL); - ADD_PREDEFINED_MACRO(wxID_PAGE_SETUP); - ADD_PREDEFINED_MACRO(wxID_HELP_INDEX); - ADD_PREDEFINED_MACRO(wxID_HELP_SEARCH); - ADD_PREDEFINED_MACRO(wxID_PREFERENCES); - - ADD_PREDEFINED_MACRO(wxID_EDIT); - ADD_PREDEFINED_MACRO(wxID_CUT); - ADD_PREDEFINED_MACRO(wxID_COPY); - ADD_PREDEFINED_MACRO(wxID_PASTE); - ADD_PREDEFINED_MACRO(wxID_CLEAR); - ADD_PREDEFINED_MACRO(wxID_FIND); - - ADD_PREDEFINED_MACRO(wxID_DUPLICATE); - ADD_PREDEFINED_MACRO(wxID_SELECTALL); - ADD_PREDEFINED_MACRO(wxID_DELETE); - ADD_PREDEFINED_MACRO(wxID_REPLACE); - ADD_PREDEFINED_MACRO(wxID_REPLACE_ALL); - ADD_PREDEFINED_MACRO(wxID_PROPERTIES); - - ADD_PREDEFINED_MACRO(wxID_VIEW_DETAILS); - ADD_PREDEFINED_MACRO(wxID_VIEW_LARGEICONS); - ADD_PREDEFINED_MACRO(wxID_VIEW_SMALLICONS); - ADD_PREDEFINED_MACRO(wxID_VIEW_LIST); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTDATE); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTNAME); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTSIZE); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTTYPE); - - ADD_PREDEFINED_MACRO(wxID_FILE); - ADD_PREDEFINED_MACRO(wxID_FILE1); - ADD_PREDEFINED_MACRO(wxID_FILE2); - ADD_PREDEFINED_MACRO(wxID_FILE3); - ADD_PREDEFINED_MACRO(wxID_FILE4); - ADD_PREDEFINED_MACRO(wxID_FILE5); - ADD_PREDEFINED_MACRO(wxID_FILE6); - ADD_PREDEFINED_MACRO(wxID_FILE7); - ADD_PREDEFINED_MACRO(wxID_FILE8); - ADD_PREDEFINED_MACRO(wxID_FILE9); - - /* Standard button and menu IDs */ - - ADD_PREDEFINED_MACRO(wxID_OK); - ADD_PREDEFINED_MACRO(wxID_CANCEL); - - ADD_PREDEFINED_MACRO(wxID_APPLY); - ADD_PREDEFINED_MACRO(wxID_YES); - ADD_PREDEFINED_MACRO(wxID_NO); - ADD_PREDEFINED_MACRO(wxID_STATIC); - ADD_PREDEFINED_MACRO(wxID_FORWARD); - ADD_PREDEFINED_MACRO(wxID_BACKWARD); - ADD_PREDEFINED_MACRO(wxID_DEFAULT); - ADD_PREDEFINED_MACRO(wxID_MORE); - ADD_PREDEFINED_MACRO(wxID_SETUP); - ADD_PREDEFINED_MACRO(wxID_RESET); - ADD_PREDEFINED_MACRO(wxID_CONTEXT_HELP); - ADD_PREDEFINED_MACRO(wxID_YESTOALL); - ADD_PREDEFINED_MACRO(wxID_NOTOALL); - ADD_PREDEFINED_MACRO(wxID_ABORT); - ADD_PREDEFINED_MACRO(wxID_RETRY); - ADD_PREDEFINED_MACRO(wxID_IGNORE); - ADD_PREDEFINED_MACRO(wxID_ADD); - ADD_PREDEFINED_MACRO(wxID_REMOVE); - - ADD_PREDEFINED_MACRO(wxID_UP); - ADD_PREDEFINED_MACRO(wxID_DOWN); - ADD_PREDEFINED_MACRO(wxID_HOME); - ADD_PREDEFINED_MACRO(wxID_REFRESH); - ADD_PREDEFINED_MACRO(wxID_STOP); - ADD_PREDEFINED_MACRO(wxID_INDEX); - - ADD_PREDEFINED_MACRO(wxID_BOLD); - ADD_PREDEFINED_MACRO(wxID_ITALIC); - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_CENTER); - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_FILL); - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_RIGHT); - - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_LEFT); - ADD_PREDEFINED_MACRO(wxID_UNDERLINE); - ADD_PREDEFINED_MACRO(wxID_INDENT); - ADD_PREDEFINED_MACRO(wxID_UNINDENT); - ADD_PREDEFINED_MACRO(wxID_ZOOM_100); - ADD_PREDEFINED_MACRO(wxID_ZOOM_FIT); - ADD_PREDEFINED_MACRO(wxID_ZOOM_IN); - ADD_PREDEFINED_MACRO(wxID_ZOOM_OUT); - ADD_PREDEFINED_MACRO(wxID_UNDELETE); - ADD_PREDEFINED_MACRO(wxID_REVERT_TO_SAVED); - - /* System menu IDs (used by wxUniv): */ - ADD_PREDEFINED_MACRO(wxID_SYSTEM_MENU); - ADD_PREDEFINED_MACRO(wxID_CLOSE_FRAME); - ADD_PREDEFINED_MACRO(wxID_MOVE_FRAME); - ADD_PREDEFINED_MACRO(wxID_RESIZE_FRAME); - ADD_PREDEFINED_MACRO(wxID_MAXIMIZE_FRAME); - ADD_PREDEFINED_MACRO(wxID_ICONIZE_FRAME); - ADD_PREDEFINED_MACRO(wxID_RESTORE_FRAME); - - /* IDs used by generic file dialog (13 consecutive starting from this value) */ - ADD_PREDEFINED_MACRO(wxID_FILEDLGG); - - ADD_PREDEFINED_MACRO(wxID_HIGHEST); - + /* no id matches this one when compared to it */ + ADD_PREDEFINED_MACRO(wxID_NONE); + + /* id for a separator line in the menu (invalid for normal item) */ + ADD_PREDEFINED_MACRO(wxID_SEPARATOR); + + ADD_PREDEFINED_MACRO(wxID_ANY); + + ADD_PREDEFINED_MACRO(wxID_LOWEST); + + ADD_PREDEFINED_MACRO(wxID_OPEN); + ADD_PREDEFINED_MACRO(wxID_CLOSE); + ADD_PREDEFINED_MACRO(wxID_NEW); + ADD_PREDEFINED_MACRO(wxID_SAVE); + ADD_PREDEFINED_MACRO(wxID_SAVEAS); + ADD_PREDEFINED_MACRO(wxID_REVERT); + ADD_PREDEFINED_MACRO(wxID_EXIT); + ADD_PREDEFINED_MACRO(wxID_UNDO); + ADD_PREDEFINED_MACRO(wxID_REDO); + ADD_PREDEFINED_MACRO(wxID_HELP); + ADD_PREDEFINED_MACRO(wxID_PRINT); + ADD_PREDEFINED_MACRO(wxID_PRINT_SETUP); + ADD_PREDEFINED_MACRO(wxID_PREVIEW); + ADD_PREDEFINED_MACRO(wxID_ABOUT); + ADD_PREDEFINED_MACRO(wxID_HELP_CONTENTS); + ADD_PREDEFINED_MACRO(wxID_HELP_COMMANDS); + ADD_PREDEFINED_MACRO(wxID_HELP_PROCEDURES); + ADD_PREDEFINED_MACRO(wxID_HELP_CONTEXT); + ADD_PREDEFINED_MACRO(wxID_CLOSE_ALL); + ADD_PREDEFINED_MACRO(wxID_PAGE_SETUP); + ADD_PREDEFINED_MACRO(wxID_HELP_INDEX); + ADD_PREDEFINED_MACRO(wxID_HELP_SEARCH); + ADD_PREDEFINED_MACRO(wxID_PREFERENCES); + + ADD_PREDEFINED_MACRO(wxID_EDIT); + ADD_PREDEFINED_MACRO(wxID_CUT); + ADD_PREDEFINED_MACRO(wxID_COPY); + ADD_PREDEFINED_MACRO(wxID_PASTE); + ADD_PREDEFINED_MACRO(wxID_CLEAR); + ADD_PREDEFINED_MACRO(wxID_FIND); + + ADD_PREDEFINED_MACRO(wxID_DUPLICATE); + ADD_PREDEFINED_MACRO(wxID_SELECTALL); + ADD_PREDEFINED_MACRO(wxID_DELETE); + ADD_PREDEFINED_MACRO(wxID_REPLACE); + ADD_PREDEFINED_MACRO(wxID_REPLACE_ALL); + ADD_PREDEFINED_MACRO(wxID_PROPERTIES); + + ADD_PREDEFINED_MACRO(wxID_VIEW_DETAILS); + ADD_PREDEFINED_MACRO(wxID_VIEW_LARGEICONS); + ADD_PREDEFINED_MACRO(wxID_VIEW_SMALLICONS); + ADD_PREDEFINED_MACRO(wxID_VIEW_LIST); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTDATE); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTNAME); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTSIZE); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTTYPE); + + ADD_PREDEFINED_MACRO(wxID_FILE); + ADD_PREDEFINED_MACRO(wxID_FILE1); + ADD_PREDEFINED_MACRO(wxID_FILE2); + ADD_PREDEFINED_MACRO(wxID_FILE3); + ADD_PREDEFINED_MACRO(wxID_FILE4); + ADD_PREDEFINED_MACRO(wxID_FILE5); + ADD_PREDEFINED_MACRO(wxID_FILE6); + ADD_PREDEFINED_MACRO(wxID_FILE7); + ADD_PREDEFINED_MACRO(wxID_FILE8); + ADD_PREDEFINED_MACRO(wxID_FILE9); + + /* Standard button and menu IDs */ + + ADD_PREDEFINED_MACRO(wxID_OK); + ADD_PREDEFINED_MACRO(wxID_CANCEL); + + ADD_PREDEFINED_MACRO(wxID_APPLY); + ADD_PREDEFINED_MACRO(wxID_YES); + ADD_PREDEFINED_MACRO(wxID_NO); + ADD_PREDEFINED_MACRO(wxID_STATIC); + ADD_PREDEFINED_MACRO(wxID_FORWARD); + ADD_PREDEFINED_MACRO(wxID_BACKWARD); + ADD_PREDEFINED_MACRO(wxID_DEFAULT); + ADD_PREDEFINED_MACRO(wxID_MORE); + ADD_PREDEFINED_MACRO(wxID_SETUP); + ADD_PREDEFINED_MACRO(wxID_RESET); + ADD_PREDEFINED_MACRO(wxID_CONTEXT_HELP); + ADD_PREDEFINED_MACRO(wxID_YESTOALL); + ADD_PREDEFINED_MACRO(wxID_NOTOALL); + ADD_PREDEFINED_MACRO(wxID_ABORT); + ADD_PREDEFINED_MACRO(wxID_RETRY); + ADD_PREDEFINED_MACRO(wxID_IGNORE); + ADD_PREDEFINED_MACRO(wxID_ADD); + ADD_PREDEFINED_MACRO(wxID_REMOVE); + + ADD_PREDEFINED_MACRO(wxID_UP); + ADD_PREDEFINED_MACRO(wxID_DOWN); + ADD_PREDEFINED_MACRO(wxID_HOME); + ADD_PREDEFINED_MACRO(wxID_REFRESH); + ADD_PREDEFINED_MACRO(wxID_STOP); + ADD_PREDEFINED_MACRO(wxID_INDEX); + + ADD_PREDEFINED_MACRO(wxID_BOLD); + ADD_PREDEFINED_MACRO(wxID_ITALIC); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_CENTER); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_FILL); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_RIGHT); + + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_LEFT); + ADD_PREDEFINED_MACRO(wxID_UNDERLINE); + ADD_PREDEFINED_MACRO(wxID_INDENT); + ADD_PREDEFINED_MACRO(wxID_UNINDENT); + ADD_PREDEFINED_MACRO(wxID_ZOOM_100); + ADD_PREDEFINED_MACRO(wxID_ZOOM_FIT); + ADD_PREDEFINED_MACRO(wxID_ZOOM_IN); + ADD_PREDEFINED_MACRO(wxID_ZOOM_OUT); + ADD_PREDEFINED_MACRO(wxID_UNDELETE); + ADD_PREDEFINED_MACRO(wxID_REVERT_TO_SAVED); + + /* System menu IDs (used by wxUniv): */ + ADD_PREDEFINED_MACRO(wxID_SYSTEM_MENU); + ADD_PREDEFINED_MACRO(wxID_CLOSE_FRAME); + ADD_PREDEFINED_MACRO(wxID_MOVE_FRAME); + ADD_PREDEFINED_MACRO(wxID_RESIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_MAXIMIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_ICONIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_RESTORE_FRAME); + + /* IDs used by generic file dialog (13 consecutive starting from this value) */ + ADD_PREDEFINED_MACRO(wxID_FILEDLGG); + + ADD_PREDEFINED_MACRO(wxID_HIGHEST); } void LuaTemplateParser::SetupModulePrefixes() { - // altered class names - ADD_PREDEFINED_PREFIX( wxCalendarCtrl, wx.wx ); - ADD_PREDEFINED_PREFIX( wxRichTextCtrl, wx.wx ); - ADD_PREDEFINED_PREFIX( wxHtmlWindow, wx.wx ); - ADD_PREDEFINED_PREFIX( wxAuiNotebook, wxaui.wx ); - ADD_PREDEFINED_PREFIX( wxGrid, wx.wx ); - ADD_PREDEFINED_PREFIX( wxAnimationCtrl, wx.wx ); - - // altered macros - ADD_PREDEFINED_PREFIX( wxCAL_SHOW_HOLIDAYS, wx.); - ADD_PREDEFINED_PREFIX( wxCAL_MONDAY_FIRST, wx.); - ADD_PREDEFINED_PREFIX( wxCAL_NO_MONTH_CHANGE, wx.); - ADD_PREDEFINED_PREFIX( wxCAL_NO_YEAR_CHANGE, wx.); - ADD_PREDEFINED_PREFIX( wxCAL_SEQUENTIAL_MONTH_SELECTION, wx. ); - ADD_PREDEFINED_PREFIX( wxCAL_SHOW_SURROUNDING_WEEKS, wx. ); - ADD_PREDEFINED_PREFIX( wxCAL_SUNDAY_FIRST, wx. ); - - ADD_PREDEFINED_PREFIX( wxHW_DEFAULT_STYLE, wx. ); - ADD_PREDEFINED_PREFIX( wxHW_NO_SELECTION, wx.); - ADD_PREDEFINED_PREFIX( wxHW_SCROLLBAR_AUTO, wx.); - ADD_PREDEFINED_PREFIX( wxHW_SCROLLBAR_NEVER, wx. ); - - ADD_PREDEFINED_PREFIX( wxAUI_NB_BOTTOM, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_CLOSE_BUTTON, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_CLOSE_ON_ACTIVE_TAB, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_CLOSE_ON_ALL_TABS, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_DEFAULT_STYLE, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_LEFT, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_MIDDLE_CLICK_CLOSE, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_RIGHT, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_SCROLL_BUTTONS, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_EXTERNAL_MOVE, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_FIXED_WIDTH, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_MOVE, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_SPLIT, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TOP, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_WINDOWLIST_BUTTON, wxaui. ); - - ADD_PREDEFINED_PREFIX( wxAUI_TB_TEXT, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_NO_TOOLTIPS, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_NO_AUTORESIZE, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_GRIPPER, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_OVERFLOW, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_VERTICAL, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_HORZ_LAYOUT, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_HORZ_TEXT, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_PLAIN_BACKGROUND, wxaui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_DEFAULT_STYLE, wxaui. ); - - ADD_PREDEFINED_PREFIX( wxAC_DEFAULT_STYLE, wx. ); - ADD_PREDEFINED_PREFIX( wxAC_NO_AUTORESIZE, wx. ); + // altered class names + ADD_PREDEFINED_PREFIX(wxCalendarCtrl, wx.wx); + ADD_PREDEFINED_PREFIX(wxRichTextCtrl, wx.wx); + ADD_PREDEFINED_PREFIX(wxHtmlWindow, wx.wx); + ADD_PREDEFINED_PREFIX(wxAuiNotebook, wxaui.wx); + ADD_PREDEFINED_PREFIX(wxGrid, wx.wx); + ADD_PREDEFINED_PREFIX(wxAnimationCtrl, wx.wx); + + // altered macros + ADD_PREDEFINED_PREFIX(wxCAL_SHOW_HOLIDAYS, wx.); + ADD_PREDEFINED_PREFIX(wxCAL_MONDAY_FIRST, wx.); + ADD_PREDEFINED_PREFIX(wxCAL_NO_MONTH_CHANGE, wx.); + ADD_PREDEFINED_PREFIX(wxCAL_NO_YEAR_CHANGE, wx.); + ADD_PREDEFINED_PREFIX(wxCAL_SEQUENTIAL_MONTH_SELECTION, wx.); + ADD_PREDEFINED_PREFIX(wxCAL_SHOW_SURROUNDING_WEEKS, wx.); + ADD_PREDEFINED_PREFIX(wxCAL_SUNDAY_FIRST, wx.); + + ADD_PREDEFINED_PREFIX(wxHW_DEFAULT_STYLE, wx.); + ADD_PREDEFINED_PREFIX(wxHW_NO_SELECTION, wx.); + ADD_PREDEFINED_PREFIX(wxHW_SCROLLBAR_AUTO, wx.); + ADD_PREDEFINED_PREFIX(wxHW_SCROLLBAR_NEVER, wx.); + + ADD_PREDEFINED_PREFIX(wxAUI_NB_BOTTOM, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_CLOSE_BUTTON, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_CLOSE_ON_ACTIVE_TAB, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_CLOSE_ON_ALL_TABS, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_DEFAULT_STYLE, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_LEFT, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_MIDDLE_CLICK_CLOSE, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_RIGHT, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_SCROLL_BUTTONS, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_EXTERNAL_MOVE, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_FIXED_WIDTH, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_MOVE, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_SPLIT, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TOP, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_WINDOWLIST_BUTTON, wxaui.); + + ADD_PREDEFINED_PREFIX(wxAUI_TB_TEXT, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_NO_TOOLTIPS, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_NO_AUTORESIZE, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_GRIPPER, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_OVERFLOW, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_VERTICAL, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_HORZ_LAYOUT, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_HORZ_TEXT, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_PLAIN_BACKGROUND, wxaui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_DEFAULT_STYLE, wxaui.); + + ADD_PREDEFINED_PREFIX(wxAC_DEFAULT_STYLE, wx.); + ADD_PREDEFINED_PREFIX(wxAC_NO_AUTORESIZE, wx.); } diff --git a/src/codegen/luacg.h b/src/codegen/luacg.h index f5fd5be1a..4b235ca50 100644 --- a/src/codegen/luacg.h +++ b/src/codegen/luacg.h @@ -40,218 +40,225 @@ none #define fbfSILENT true #define fbfMESSAGE false -#include "codegen/codegen.h" - #include #include #include +#include "codegen/codegen.h" + + /** -* Parse the Lua templates. -*/ + * Parse the Lua templates. + */ class LuaTemplateParser : public TemplateParser { private: - bool m_i18n; - bool m_useRelativePath; - wxString m_basePath; + bool m_i18n; + bool m_useRelativePath; + wxString m_basePath; - std::map m_predModulePrefix; - std::vector m_strUserIDsVec; + std::map m_predModulePrefix; + std::vector m_strUserIDsVec; - void SetupModulePrefixes(); + void SetupModulePrefixes(); public: - LuaTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, std::vector strUserIDsVec); - LuaTemplateParser( const LuaTemplateParser & that, wxString _template, std::vector strUserIDsVec); - - // overrides for Lua - PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; - wxString RootWxParentToCode() override; - wxString ValueToCode(PropertyType type, wxString value) override; + LuaTemplateParser( + PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, + std::vector strUserIDsVec); + LuaTemplateParser(const LuaTemplateParser& that, wxString _template, std::vector strUserIDsVec); + + // overrides for Lua + PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; + wxString RootWxParentToCode() override; + wxString ValueToCode(PropertyType type, wxString value) override; }; /** -* Generate the Lua code -*/ + * Generate the Lua code + */ class LuaCodeGenerator : public CodeGenerator { private: - PCodeWriter m_source; - - bool m_useRelativePath; - bool m_i18n; - wxString m_basePath; - unsigned int m_firstID; - bool m_disconnectEvents; - wxString m_disconnecMode; - wxString m_strEventHandlerPostfix; - wxString m_strUITable ; -private: + PCodeWriter m_source; - /** - * Predefined macros won't generate defines. - */ - std::set m_predMacros; - std::vector m_strUserIDsVec; - std::vector m_strUnsupportedClasses; - std::vector m_strUnsupportedInstances; - - void SetupPredefinedMacros(); - - /** - * Given an object and the name for a template, obtains the code. - */ - wxString GetCode(PObjectBase obj, wxString name, bool silent = false, wxString strSelf = wxEmptyString); - - /** - * Gets the construction fragment for the specified object. - * - * This method encapsulates the adjustments that need to be made for array declarations. - */ - wxString GetConstruction(PObjectBase obj, bool silent, wxString strSelf, ArrayItems& arrays); - - /** - * Stores the project's objects classes set, for generating the includes. - */ - void FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ); - - /** - * Stores all the properties for "macro" type objects, so that their - * related '#define' can be generated subsequently. - */ - void FindMacros( PObjectBase obj, std::vector< wxString >* macros ); - - /** - * Looks for "non-null" event handlers (PEvent) and collects it into a vector. - */ - void FindEventHandlers(PObjectBase obj, EventVector &events); - - /** - * Generates classes declarations inside the header file. - */ - void GenClassDeclaration(PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, const wxString& eventHandlerPostfix, ArrayItems& arrays); - - /** - * Generates the event table. - */ - void GenEvents( PObjectBase class_obj, const EventVector &events, wxString &strClassName, bool disconnect = false ); - - /** - * helper function to find the event table entry template in the class or its base classes - */ - bool GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, wxString &strClassName, bool disconnect = false ); - - /** - * helper function to find the event table entry template in the class or its base classes - */ - wxString GenEventEntryForInheritedClass( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, wxString &strClassName); - - /** - * Generates the generated_event_handlers template - */ - void GetGenEventHandlers( PObjectBase obj ); - /** - * Generates the generated_event_handlers template - */ - void GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ); - - /** - * Generates the 'import' section for files. - */ - void GenIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ); - void AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ); - - /** - * Generate a set of all subclasses to forward declare in the generated file. - */ - void GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::vector< wxString >* headerIncludes ); - - /** - * Generates the '#define' section for macros. - */ - void GenDefines( PObjectBase project); - - /** - * Generates the constructor for a class - */ - void GenConstructor(PObjectBase class_obj, const EventVector& events, wxString& strClassName, ArrayItems& arrays); - - /** - * Generates the destructor for a class - */ - void GenDestructor( PObjectBase class_obj, const EventVector &events); - - /** - * Makes the objects construction, setting up the objects' and Layout properties. - * The algorithm is similar to that used in the designer preview generation. - */ - void GenConstruction(PObjectBase obj, bool is_widget, wxString& strClassName, ArrayItems& arrays); - - /** - * Makes the objects destructions. - */ - void GenDestruction( PObjectBase obj); - - /** - * Configures the object properties, both own and inherited ones. - * Information for the class is given, because it will recursively make the - * configuration in the "super-classes". - */ - void GenSettings( PObjectInfo info, PObjectBase obj, wxString &strClassName ); - - /** - * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where - * the template is found, and the objectbase for the control. - */ - void GenAddToolbar( PObjectInfo info, PObjectBase obj ); - void GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ); - - void GenVirtualEventHandlers( const EventVector &events, const wxString& eventHandlerPostfix, const wxString& strClassName ); + bool m_useRelativePath; + bool m_i18n; + wxString m_basePath; + unsigned int m_firstID; + bool m_disconnectEvents; + wxString m_disconnecMode; + wxString m_strEventHandlerPostfix; + wxString m_strUITable; + +private: + /** + * Predefined macros won't generate defines. + */ + std::set m_predMacros; + std::vector m_strUserIDsVec; + std::vector m_strUnsupportedClasses; + std::vector m_strUnsupportedInstances; + + void SetupPredefinedMacros(); + + /** + * Given an object and the name for a template, obtains the code. + */ + wxString GetCode(PObjectBase obj, wxString name, bool silent = false, wxString strSelf = wxEmptyString); + + /** + * Gets the construction fragment for the specified object. + * + * This method encapsulates the adjustments that need to be made for array declarations. + */ + wxString GetConstruction(PObjectBase obj, bool silent, wxString strSelf, ArrayItems& arrays); + + /** + * Stores the project's objects classes set, for generating the includes. + */ + void FindDependencies(PObjectBase obj, std::set& info_set); + + /** + * Stores all the properties for "macro" type objects, so that their + * related '#define' can be generated subsequently. + */ + void FindMacros(PObjectBase obj, std::vector* macros); + + /** + * Looks for "non-null" event handlers (PEvent) and collects it into a vector. + */ + void FindEventHandlers(PObjectBase obj, EventVector& events); + + /** + * Generates classes declarations inside the header file. + */ + void GenClassDeclaration( + PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, + const wxString& eventHandlerPostfix, ArrayItems& arrays); + + /** + * Generates the event table. + */ + void GenEvents(PObjectBase class_obj, const EventVector& events, wxString& strClassName, bool disconnect = false); + + /** + * helper function to find the event table entry template in the class or its base classes + */ + bool GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + wxString& strClassName, bool disconnect = false); + + /** + * helper function to find the event table entry template in the class or its base classes + */ + wxString GenEventEntryForInheritedClass( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + wxString& strClassName); + + /** + * Generates the generated_event_handlers template + */ + void GetGenEventHandlers(PObjectBase obj); + /** + * Generates the generated_event_handlers template + */ + void GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj); + + /** + * Generates the 'import' section for files. + */ + void GenIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenObjectIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates); + void AddUniqueIncludes(const wxString& include, std::vector* includes); + + /** + * Generate a set of all subclasses to forward declare in the generated file. + */ + void GenSubclassSets(PObjectBase obj, std::set* subclasses, std::vector* headerIncludes); + + /** + * Generates the '#define' section for macros. + */ + void GenDefines(PObjectBase project); + + /** + * Generates the constructor for a class + */ + void GenConstructor(PObjectBase class_obj, const EventVector& events, wxString& strClassName, ArrayItems& arrays); + + /** + * Generates the destructor for a class + */ + void GenDestructor(PObjectBase class_obj, const EventVector& events); + + /** + * Makes the objects construction, setting up the objects' and Layout properties. + * The algorithm is similar to that used in the designer preview generation. + */ + void GenConstruction(PObjectBase obj, bool is_widget, wxString& strClassName, ArrayItems& arrays); + + /** + * Makes the objects destructions. + */ + void GenDestruction(PObjectBase obj); + + /** + * Configures the object properties, both own and inherited ones. + * Information for the class is given, because it will recursively make the + * configuration in the "super-classes". + */ + void GenSettings(PObjectInfo info, PObjectBase obj, wxString& strClassName); + + /** + * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where + * the template is found, and the objectbase for the control. + */ + void GenAddToolbar(PObjectInfo info, PObjectBase obj); + void GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines); + + void GenVirtualEventHandlers( + const EventVector& events, const wxString& eventHandlerPostfix, const wxString& strClassName); public: - /** - * Convert a wxString to the "C/C++" format. - */ - static wxString ConvertLuaString( wxString text); - - LuaCodeGenerator(); - - /** - * Set the codewriter for the source file - */ - void SetSourceWriter( PCodeWriter cw ) - { - m_source = cw; - } - - - /** - * Configures the reference path for generating relative paths to - * that passed as parameter. - * - * @note path is generated with the separators, '/', since on Windows - * the compilers interpret path correctly. - */ - void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); - - /** - * Set the First ID used during Code Generation. - */ - void SetFirstID( const unsigned int id ){ m_firstID = id; } - - /** - * Generate the project's code - */ - bool GenerateCode(PObjectBase project) override; - - /** - * Generate an inherited class - */ - void GenerateInheritedClass( PObjectBase userClasses, PObjectBase form,const wxString & genFileFullPath ); + /** + * Convert a wxString to the "C/C++" format. + */ + static wxString ConvertLuaString(wxString text); + + LuaCodeGenerator(); + + /** + * Set the codewriter for the source file + */ + void SetSourceWriter(PCodeWriter cw) { m_source = cw; } + + + /** + * Configures the reference path for generating relative paths to + * that passed as parameter. + * + * @note path is generated with the separators, '/', since on Windows + * the compilers interpret path correctly. + */ + void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); + + /** + * Set the First ID used during Code Generation. + */ + void SetFirstID(const unsigned int id) { m_firstID = id; } + + /** + * Generate the project's code + */ + bool GenerateCode(PObjectBase project) override; + + /** + * Generate an inherited class + */ + void GenerateInheritedClass(PObjectBase userClasses, PObjectBase form, const wxString& genFileFullPath); }; - -#endif // CODEGEN_LUACG_H +#endif // CODEGEN_LUACG_H diff --git a/src/codegen/phpcg.cpp b/src/codegen/phpcg.cpp index 888f7015d..19474ce9e 100644 --- a/src/codegen/phpcg.cpp +++ b/src/codegen/phpcg.cpp @@ -28,1467 +28,1256 @@ #include "phpcg.h" +#include + +#include +#include + #include "codegen/codewriter.h" -#include "utils/typeconv.h" -#include "utils/debug.h" +#include "model/objectbase.h" #include "rad/appdata.h" #include "rad/revision.h" #include "rad/version.h" -#include "model/objectbase.h" +#include "utils/debug.h" +#include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include -#include -#include - -PHPTemplateParser::PHPTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath ) -: -TemplateParser(obj,_template), -m_i18n( useI18N ), -m_useRelativePath( useRelativePath ), -m_basePath( basePath ) +PHPTemplateParser::PHPTemplateParser( + PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath) : + TemplateParser(obj, _template), m_i18n(useI18N), m_useRelativePath(useRelativePath), m_basePath(basePath) { - if ( !wxFileName::DirExists( m_basePath ) ) - { - m_basePath.clear(); - } + if (!wxFileName::DirExists(m_basePath)) { + m_basePath.clear(); + } } -PHPTemplateParser::PHPTemplateParser( const PHPTemplateParser & that, wxString _template ) -: -TemplateParser( that, _template ), -m_i18n( that.m_i18n ), -m_useRelativePath( that.m_useRelativePath ), -m_basePath( that.m_basePath ) +PHPTemplateParser::PHPTemplateParser(const PHPTemplateParser& that, wxString _template) : + TemplateParser(that, _template), + m_i18n(that.m_i18n), + m_useRelativePath(that.m_useRelativePath), + m_basePath(that.m_basePath) { } wxString PHPTemplateParser::RootWxParentToCode() { - return wxT("$this"); + return wxT("$this"); } -PTemplateParser PHPTemplateParser::CreateParser( const TemplateParser* oldparser, wxString _template ) +PTemplateParser PHPTemplateParser::CreateParser(const TemplateParser* oldparser, wxString _template) { - const PHPTemplateParser* phpOldParser = dynamic_cast< const PHPTemplateParser* >( oldparser ); - if (phpOldParser) - { - PTemplateParser newparser( new PHPTemplateParser( *phpOldParser, _template ) ); - return newparser; - } - return PTemplateParser(); + const PHPTemplateParser* phpOldParser = dynamic_cast(oldparser); + if (phpOldParser) { + PTemplateParser newparser(new PHPTemplateParser(*phpOldParser, _template)); + return newparser; + } + return PTemplateParser(); } /** -* Convert the value of the property to PHP code -*/ -wxString PHPTemplateParser::ValueToCode( PropertyType type, wxString value ) + * Convert the value of the property to PHP code + */ +wxString PHPTemplateParser::ValueToCode(PropertyType type, wxString value) { - wxString result; - - switch ( type ) - { - case PT_WXPARENT: - { - result = wxT("$this->") + value; - break; - } - case PT_WXPARENT_SB: - { - result = wxT("$") + value + wxT("->GetStaticBox()"); - break; - } - case PT_WXPARENT_CP: - { - result = wxT("$this->") + value + wxT("->GetPane()"); - break; - } - case PT_WXSTRING: - case PT_FILE: - case PT_PATH: - { - if ( value.empty() ) - { - result << wxT("wxEmptyString"); - } - else - { - result << wxT("\"") << PHPCodeGenerator::ConvertPHPString( value ) << wxT("\""); - } - break; - } - case PT_WXSTRING_I18N: - { - if ( value.empty() ) - { - result << wxT("wxEmptyString"); - } - else - { - if ( m_i18n ) - { - result << wxT("_(\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\")"); - } - else - { - result << wxT("\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\""); - } - } - break; - } - case PT_CLASS: - case PT_MACRO: - case PT_OPTION: - case PT_EDIT_OPTION: - { - result = value; - break; - } - case PT_TEXT: - case PT_FLOAT: - case PT_INT: - case PT_UINT: - { - result = value; - break; - } - case PT_BITLIST: - { - result = ( value.empty() ? wxT("0") : value ); - break; - } - case PT_WXPOINT: - { - if ( value.empty() ) - { - result = wxT("wxDefaultPosition"); - } - else - { - result << wxT("new wxPoint( ") << value << wxT(" )"); - } - break; - } - case PT_WXSIZE: - { - if ( value.empty() ) - { - result = wxT("wxDefaultSize"); - } - else - { - result << wxT("new wxSize( ") << value << wxT(" )"); - } - break; - } - case PT_BOOL: - { - result = ( value == wxT("0") ? wxT("false") : wxT("true") ); - break; - } - case PT_WXFONT: - { - if ( !value.empty() ) - { - wxFontContainer fontContainer = TypeConv::StringToFont( value ); - wxFont font = fontContainer.GetFont(); - - const int pointSize = fontContainer.GetPointSize(); - - result = wxString::Format( "new wxFont( %s, %s, %s, %s, %s, %s )", - ((pointSize <= 0) ? "wxC2D(wxNORMAL_FONT)->GetPointSize()" : (wxString() << pointSize)), - TypeConv::FontFamilyToString( fontContainer.GetFamily() ), - font.GetStyleString(), - font.GetWeightString(), - ( fontContainer.GetUnderlined() ? "true" : "false" ), - ( fontContainer.m_faceName.empty() ? "wxEmptyString" : ("\"" + fontContainer.m_faceName + "\"") ) - ); - } - else - { - result = "wxC2D(wxNORMAL_FONT)"; - } - break; - } - case PT_WXCOLOUR: - { - if ( !value.empty() ) - { - if ( value.find_first_of( wxT("wx") ) == 0 ) - { - // System Colour - result << wxT("wxSystemSettings::GetColour( ") << ValueToCode( PT_OPTION, value ) << wxT(" )"); - } - else - { - wxColour colour = TypeConv::StringToColour( value ); - result = wxString::Format( wxT("new wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue() ); - } - } - else - { - result = wxT("new wxColour()"); - } - break; - } - case PT_BITMAP: - { - wxString path; - wxString source; - wxSize icoSize; - TypeConv::ParseBitmapWithResource( value, &path, &source, &icoSize ); - - if ( path.empty() ) - { - // Empty path, generate Null Bitmap - result = wxT("wxNullBitmap"); - break; - } - - if ( path.StartsWith( wxT("file:") ) ) - { - wxLogWarning( wxT("PHP code generation does not support using URLs for bitmap properties:\n%s"), path ); - result = wxT("wxNullBitmap"); - break; - } - - if ( source == wxT("Load From File") ) - { - wxString absPath; - try - { - absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - } - catch( wxFBException& ex ) - { - wxLogError( ex.what() ); - result = wxT( "wxNullBitmap" ); - break; - } - - wxString file = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath ); - - result << wxT("new wxBitmap( \"") << PHPCodeGenerator::ConvertPHPString( file ) << wxT("\", wxBITMAP_TYPE_ANY )"); - } - else if ( source == _("Load From Embedded File") ) - { - result << wxT( "wxNullBitmap /* embedded files aren't supported */" ); - } - else if ( source == wxT("Load From Resource") ) - { - result << wxT("new wxBitmap( \"") << path << wxT("\", wxBITMAP_TYPE_RESOURCE )"); - } - else if ( source == wxT("Load From Icon Resource") ) - { - if ( wxDefaultSize == icoSize ) - { - result << wxT("new wxICON( ") << path << wxT(" )"); - } - else - { - result.Printf( wxT("new wxIcon( \"%s\", wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, icoSize.GetWidth(), icoSize.GetHeight() ); - } - } - else if (source == _("Load From XRC")) - { - // This requires that the global wxXmlResource object is set - result << wxT("wxXmlResource::Get()->LoadBitmap( \"") << path << wxT("\" )"); - } - else if ( source == _("Load From Art Provider") ) - { - wxString rid = path.BeforeFirst( wxT(':') ); - if( rid.StartsWith( wxT("gtk-") ) ) rid = wxT("wxT(\"") + rid + wxT("\")"); - - result = wxT("wxArtProvider::GetBitmap( ") + rid + wxT(", ") + path.AfterFirst( wxT(':') ) + wxT(" )"); - } - break; - - break; - } - case PT_STRINGLIST: - { - // Stringlists are generated like a sequence of wxString separated by ', '. - wxArrayString array = TypeConv::StringToArrayString( value ); - if ( array.Count() > 0 ) - { - result = ValueToCode( PT_WXSTRING_I18N, array[0] ); - } - - for ( size_t i = 1; i < array.Count(); i++ ) - { - result << wxT(", ") << ValueToCode( PT_WXSTRING_I18N, array[i] ); - } - break; - } - default: - break; - } - - return result; + wxString result; + + switch (type) { + case PT_WXPARENT: { + result = wxT("$this->") + value; + break; + } + case PT_WXPARENT_SB: { + result = wxT("$") + value + wxT("->GetStaticBox()"); + break; + } + case PT_WXPARENT_CP: { + result = wxT("$this->") + value + wxT("->GetPane()"); + break; + } + case PT_WXSTRING: + case PT_FILE: + case PT_PATH: { + if (value.empty()) { + result << wxT("wxEmptyString"); + } else { + result << wxT("\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\""); + } + break; + } + case PT_WXSTRING_I18N: { + if (value.empty()) { + result << wxT("wxEmptyString"); + } else { + if (m_i18n) { + result << wxT("_(\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\")"); + } else { + result << wxT("\"") << PHPCodeGenerator::ConvertPHPString(value) << wxT("\""); + } + } + break; + } + case PT_CLASS: + case PT_MACRO: + case PT_OPTION: + case PT_EDIT_OPTION: { + result = value; + break; + } + case PT_TEXT: + case PT_FLOAT: + case PT_INT: + case PT_UINT: { + result = value; + break; + } + case PT_BITLIST: { + result = (value.empty() ? wxT("0") : value); + break; + } + case PT_WXPOINT: { + if (value.empty()) { + result = wxT("wxDefaultPosition"); + } else { + result << wxT("new wxPoint( ") << value << wxT(" )"); + } + break; + } + case PT_WXSIZE: { + if (value.empty()) { + result = wxT("wxDefaultSize"); + } else { + result << wxT("new wxSize( ") << value << wxT(" )"); + } + break; + } + case PT_BOOL: { + result = (value == wxT("0") ? wxT("false") : wxT("true")); + break; + } + case PT_WXFONT: { + if (!value.empty()) { + wxFontContainer fontContainer = TypeConv::StringToFont(value); + wxFont font = fontContainer.GetFont(); + + const int pointSize = fontContainer.GetPointSize(); + + result = wxString::Format( + "new wxFont( %s, %s, %s, %s, %s, %s )", + ((pointSize <= 0) ? "wxC2D(wxNORMAL_FONT)->GetPointSize()" : (wxString() << pointSize)), + TypeConv::FontFamilyToString(fontContainer.GetFamily()), font.GetStyleString(), + font.GetWeightString(), (fontContainer.GetUnderlined() ? "true" : "false"), + (fontContainer.m_faceName.empty() ? "wxEmptyString" : ("\"" + fontContainer.m_faceName + "\""))); + } else { + result = "wxC2D(wxNORMAL_FONT)"; + } + break; + } + case PT_WXCOLOUR: { + if (!value.empty()) { + if (value.find_first_of(wxT("wx")) == 0) { + // System Colour + result << wxT("wxSystemSettings::GetColour( ") << ValueToCode(PT_OPTION, value) << wxT(" )"); + } else { + wxColour colour = TypeConv::StringToColour(value); + result = + wxString::Format(wxT("new wxColour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue()); + } + } else { + result = wxT("new wxColour()"); + } + break; + } + case PT_BITMAP: { + wxString path; + wxString source; + wxSize icoSize; + TypeConv::ParseBitmapWithResource(value, &path, &source, &icoSize); + + if (path.empty()) { + // Empty path, generate Null Bitmap + result = wxT("wxNullBitmap"); + break; + } + + if (path.StartsWith(wxT("file:"))) { + wxLogWarning(wxT("PHP code generation does not support using URLs for bitmap properties:\n%s"), path); + result = wxT("wxNullBitmap"); + break; + } + + if (source == wxT("Load From File")) { + wxString absPath; + try { + absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + result = wxT("wxNullBitmap"); + break; + } + + wxString file = (m_useRelativePath ? TypeConv::MakeRelativePath(absPath, m_basePath) : absPath); + + result << wxT("new wxBitmap( \"") << PHPCodeGenerator::ConvertPHPString(file) + << wxT("\", wxBITMAP_TYPE_ANY )"); + } else if (source == _("Load From Embedded File")) { + result << wxT("wxNullBitmap /* embedded files aren't supported */"); + } else if (source == wxT("Load From Resource")) { + result << wxT("new wxBitmap( \"") << path << wxT("\", wxBITMAP_TYPE_RESOURCE )"); + } else if (source == wxT("Load From Icon Resource")) { + if (wxDefaultSize == icoSize) { + result << wxT("new wxICON( ") << path << wxT(" )"); + } else { + result.Printf( + wxT("new wxIcon( \"%s\", wxBITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, icoSize.GetWidth(), + icoSize.GetHeight()); + } + } else if (source == _("Load From XRC")) { + // This requires that the global wxXmlResource object is set + result << wxT("wxXmlResource::Get()->LoadBitmap( \"") << path << wxT("\" )"); + } else if (source == _("Load From Art Provider")) { + wxString rid = path.BeforeFirst(wxT(':')); + if (rid.StartsWith(wxT("gtk-"))) + rid = wxT("wxT(\"") + rid + wxT("\")"); + + result = wxT("wxArtProvider::GetBitmap( ") + rid + wxT(", ") + path.AfterFirst(wxT(':')) + wxT(" )"); + } + break; + + break; + } + case PT_STRINGLIST: { + // Stringlists are generated like a sequence of wxString separated by ', '. + wxArrayString array = TypeConv::StringToArrayString(value); + if (array.Count() > 0) { + result = ValueToCode(PT_WXSTRING_I18N, array[0]); + } + + for (size_t i = 1; i < array.Count(); i++) { + result << wxT(", ") << ValueToCode(PT_WXSTRING_I18N, array[i]); + } + break; + } + default: + break; + } + + return result; } /////////////////////////////////////////////////////////////////////////////// PHPCodeGenerator::PHPCodeGenerator() { - SetupPredefinedMacros(); - m_useRelativePath = false; - m_i18n = false; - m_firstID = 1000; + SetupPredefinedMacros(); + m_useRelativePath = false; + m_i18n = false; + m_firstID = 1000; } -wxString PHPCodeGenerator::ConvertPHPString( wxString text ) +wxString PHPCodeGenerator::ConvertPHPString(wxString text) { - wxString result; - - for ( size_t i = 0; i < text.length(); i++ ) - { - wxChar c = text[i]; - - switch ( c ) - { - case wxT('"'): - result += wxT("\\\""); - break; - - case wxT('\\'): - result += wxT("\\\\"); - break; - - case wxT('\t'): - result += wxT("\\t"); - break; - - case wxT('\n'): - result += wxT("\\n"); - break; - - case wxT('\r'): - result += wxT("\\r"); - break; - - default: - result += c; - break; - } - } - return result; + wxString result; + + for (size_t i = 0; i < text.length(); i++) { + wxChar c = text[i]; + + switch (c) { + case wxT('"'): + result += wxT("\\\""); + break; + + case wxT('\\'): + result += wxT("\\\\"); + break; + + case wxT('\t'): + result += wxT("\\t"); + break; + + case wxT('\n'): + result += wxT("\\n"); + break; + + case wxT('\r'): + result += wxT("\\r"); + break; + + default: + result += c; + break; + } + } + return result; } -void PHPCodeGenerator::GenerateInheritedClass( PObjectBase userClasses, PObjectBase form ) +void PHPCodeGenerator::GenerateInheritedClass(PObjectBase userClasses, PObjectBase form) { - if (!userClasses) - { - wxLogError(wxT("There is no object to generate inherited class")); - return; - } - - if ( wxT("UserClasses") != userClasses->GetClassName() ) - { - wxLogError(wxT("This not a UserClasses object")); - return; - } - - wxString type = userClasses->GetPropertyAsString( wxT("type") ); - - // Start file - wxString code = GetCode( userClasses, wxT("file_comment") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, wxT("source_include") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, wxT("class_decl") ); - m_source->WriteLn( code ); - m_source->Indent(); - - code = GetCode( userClasses, type + wxT("_cons_def") ); - m_source->WriteLn( code ); - - // Do events - EventVector events; - FindEventHandlers( form, events ); - - if ( events.size() > 0 ) - { - code = GetCode( userClasses, wxT("event_handler_comment") ); - m_source->WriteLn( code ); - - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - if ( generatedHandlers.find( event->GetValue() ) == generatedHandlers.end() ) - { - m_source->WriteLn( wxString::Format( wxT("function %s( event ){"), event->GetValue() ) ); - m_source->Indent(); - m_source->WriteLn( wxString::Format( wxT("// TODO: Implement %s"), event->GetValue() ) ); - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); - m_source->WriteLn( wxEmptyString ); - generatedHandlers.insert(event->GetValue()); - } - } - m_source->WriteLn( wxEmptyString ); - } - - m_source->Unindent(); + if (!userClasses) { + wxLogError(wxT("There is no object to generate inherited class")); + return; + } + + if (wxT("UserClasses") != userClasses->GetClassName()) { + wxLogError(wxT("This not a UserClasses object")); + return; + } + + wxString type = userClasses->GetPropertyAsString(wxT("type")); + + // Start file + wxString code = GetCode(userClasses, wxT("file_comment")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + code = GetCode(userClasses, wxT("source_include")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + code = GetCode(userClasses, wxT("class_decl")); + m_source->WriteLn(code); + m_source->Indent(); + + code = GetCode(userClasses, type + wxT("_cons_def")); + m_source->WriteLn(code); + + // Do events + EventVector events; + FindEventHandlers(form, events); + + if (events.size() > 0) { + code = GetCode(userClasses, wxT("event_handler_comment")); + m_source->WriteLn(code); + + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + if (generatedHandlers.find(event->GetValue()) == generatedHandlers.end()) { + m_source->WriteLn(wxString::Format(wxT("function %s( event ){"), event->GetValue())); + m_source->Indent(); + m_source->WriteLn(wxString::Format(wxT("// TODO: Implement %s"), event->GetValue())); + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + m_source->WriteLn(wxEmptyString); + generatedHandlers.insert(event->GetValue()); + } + } + m_source->WriteLn(wxEmptyString); + } + + m_source->Unindent(); } -bool PHPCodeGenerator::GenerateCode( PObjectBase project ) +bool PHPCodeGenerator::GenerateCode(PObjectBase project) { - if (!project) - { - wxLogError(wxT("There is no project to generate code")); - return false; - } - - m_i18n = false; - PProperty i18nProperty = project->GetProperty( wxT("internationalize") ); - if (i18nProperty && i18nProperty->GetValueAsInteger()) - m_i18n = true; - - m_disconnectEvents = ( project->GetPropertyAsInteger( wxT("disconnect_php_events") ) != 0 ); - - m_source->Clear(); - - // Insert php preamble - - wxString code = GetCode( project, wxT("php_preamble") ); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - } - - code = wxString::Format( - wxT("/*\n") - wxT(" * PHP code generated with wxFormBuilder (version %s%s)\n") - wxT(" * http://www.wxformbuilder.org/\n") - wxT(" *\n") - wxT(" * PLEASE DO *NOT* EDIT THIS FILE!\n") - wxT(" */\n"), - getVersion(), getPostfixRevision(getVersion()).c_str() - ); - - m_source->WriteLn( code ); - - - PProperty propFile = project->GetProperty( wxT("file") ); - if (!propFile) - { - wxLogError( wxT("Missing \"file\" property on Project Object") ); - return false; - } - - wxString file = propFile->GetValue(); - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Generate the subclass sets - std::set< wxString > subclasses; - std::vector< wxString > headerIncludes; - - GenSubclassSets( project, &subclasses, &headerIncludes ); - - // Generating in the .h header file those include from components dependencies. - std::set< wxString > templates; - GenIncludes(project, &headerIncludes, &templates ); - - // Write the include lines - std::vector::iterator include_it; - for ( include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it ) - { - m_source->WriteLn( *include_it ); - } - if ( !headerIncludes.empty() ) - { - m_source->WriteLn(wxEmptyString); - } - - // Write internationalization support - if( m_i18n ) - { - //PHP gettext already implements this function - //m_source->WriteLn( wxT("function _(){ /*TODO: Implement this function on wxPHP*/ }") ); - //m_source->WriteLn(wxEmptyString); - } - - // Generating "defines" for macros - GenDefines( project ); - - wxString eventHandlerPostfix; - PProperty eventKindProp = project->GetProperty( wxT("skip_php_events") ); - if( eventKindProp->GetValueAsInteger() ) - { - eventHandlerPostfix = wxT("$event->Skip();"); - } - else - { - eventHandlerPostfix = wxEmptyString; - } - - PProperty disconnectMode = project->GetProperty( wxT("disconnect_mode") ); - m_disconnecMode = disconnectMode->GetValueAsString(); - - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - PObjectBase child = project->GetChild( i ); - - // Preprocess to find arrays - ArrayItems arrays; - FindArrayObjects(child, arrays, true); - - EventVector events; - FindEventHandlers( child, events ); - //GenClassDeclaration( child, useEnum, classDecoration, events, eventHandlerPrefix, eventHandlerPostfix ); - GenClassDeclaration(child, false, wxEmptyString, events, eventHandlerPostfix, arrays); - } - - code = GetCode( project, wxT("php_epilogue") ); - if( !code.empty() ) m_source->WriteLn( code ); - - return true; + if (!project) { + wxLogError(wxT("There is no project to generate code")); + return false; + } + + m_i18n = false; + PProperty i18nProperty = project->GetProperty(wxT("internationalize")); + if (i18nProperty && i18nProperty->GetValueAsInteger()) + m_i18n = true; + + m_disconnectEvents = (project->GetPropertyAsInteger(wxT("disconnect_php_events")) != 0); + + m_source->Clear(); + + // Insert php preamble + + wxString code = GetCode(project, wxT("php_preamble")); + if (!code.empty()) { + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + } + + code = wxString::Format( + wxT("/*\n") wxT(" * PHP code generated with wxFormBuilder (version %s%s)\n") + wxT(" * http://www.wxformbuilder.org/\n") wxT(" *\n") wxT(" * PLEASE DO *NOT* EDIT THIS FILE!\n") wxT(" */\n"), + getVersion(), getPostfixRevision(getVersion()).c_str()); + + m_source->WriteLn(code); + + + PProperty propFile = project->GetProperty(wxT("file")); + if (!propFile) { + wxLogError(wxT("Missing \"file\" property on Project Object")); + return false; + } + + wxString file = propFile->GetValue(); + if (file.empty()) { + file = wxT("noname"); + } + + // Generate the subclass sets + std::set subclasses; + std::vector headerIncludes; + + GenSubclassSets(project, &subclasses, &headerIncludes); + + // Generating in the .h header file those include from components dependencies. + std::set templates; + GenIncludes(project, &headerIncludes, &templates); + + // Write the include lines + std::vector::iterator include_it; + for (include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it) { + m_source->WriteLn(*include_it); + } + if (!headerIncludes.empty()) { + m_source->WriteLn(wxEmptyString); + } + + // Write internationalization support + if (m_i18n) { + // PHP gettext already implements this function + // m_source->WriteLn( wxT("function _(){ /*TODO: Implement this function on wxPHP*/ }") ); + // m_source->WriteLn(wxEmptyString); + } + + // Generating "defines" for macros + GenDefines(project); + + wxString eventHandlerPostfix; + PProperty eventKindProp = project->GetProperty(wxT("skip_php_events")); + if (eventKindProp->GetValueAsInteger()) { + eventHandlerPostfix = wxT("$event->Skip();"); + } else { + eventHandlerPostfix = wxEmptyString; + } + + PProperty disconnectMode = project->GetProperty(wxT("disconnect_mode")); + m_disconnecMode = disconnectMode->GetValueAsString(); + + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + PObjectBase child = project->GetChild(i); + + // Preprocess to find arrays + ArrayItems arrays; + FindArrayObjects(child, arrays, true); + + EventVector events; + FindEventHandlers(child, events); + // GenClassDeclaration( child, useEnum, classDecoration, events, eventHandlerPrefix, eventHandlerPostfix ); + GenClassDeclaration(child, false, wxEmptyString, events, eventHandlerPostfix, arrays); + } + + code = GetCode(project, wxT("php_epilogue")); + if (!code.empty()) + m_source->WriteLn(code); + + return true; } -void PHPCodeGenerator::GenEvents( PObjectBase class_obj, const EventVector &events, bool disconnect ) +void PHPCodeGenerator::GenEvents(PObjectBase class_obj, const EventVector& events, bool disconnect) { - if ( events.empty() ) - { - return; - } - - if( disconnect ) - { - m_source->WriteLn( wxT("// Disconnect Events") ); - } - else - { - m_source->WriteLn(); - m_source->WriteLn( wxT("// Connect Events") ); - } - - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), - class_obj->GetClassName()); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT("Object name cannot be null") ); - return; - } - - wxString base_class; - wxString handlerName; - - PProperty propSubclass = class_obj->GetProperty( wxT("subclass") ); - if ( propSubclass ) - { - wxString subclass = propSubclass->GetChildFromParent( wxT("name") ); - if ( !subclass.empty() ) - { - base_class = subclass; - } - } - - if ( base_class.empty() ) - base_class = wxT("wx") + class_obj->GetClassName(); - - if ( events.size() > 0 ) - { - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - - handlerName = event->GetValue(); - - wxString templateName = wxString::Format( wxT("connect_%s"), event->GetName() ); - - PObjectBase obj = event->GetObject(); - if ( !GenEventEntry( obj, obj->GetObjectInfo(), templateName, handlerName, disconnect ) ) - { - wxLogError( wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), - templateName, class_name ); - } - } - } + if (events.empty()) { + return; + } + + if (disconnect) { + m_source->WriteLn(wxT("// Disconnect Events")); + } else { + m_source->WriteLn(); + m_source->WriteLn(wxT("// Connect Events")); + } + + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name cannot be null")); + return; + } + + wxString base_class; + wxString handlerName; + + PProperty propSubclass = class_obj->GetProperty(wxT("subclass")); + if (propSubclass) { + wxString subclass = propSubclass->GetChildFromParent(wxT("name")); + if (!subclass.empty()) { + base_class = subclass; + } + } + + if (base_class.empty()) + base_class = wxT("wx") + class_obj->GetClassName(); + + if (events.size() > 0) { + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + + handlerName = event->GetValue(); + + wxString templateName = wxString::Format(wxT("connect_%s"), event->GetName()); + + PObjectBase obj = event->GetObject(); + if (!GenEventEntry(obj, obj->GetObjectInfo(), templateName, handlerName, disconnect)) { + wxLogError( + wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), templateName, + class_name); + } + } + } } -bool PHPCodeGenerator::GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect ) +bool PHPCodeGenerator::GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect) { - wxString _template; - PCodeInfo code_info = obj_info->GetCodeInfo( wxT("PHP") ); - if ( code_info ) - { - _template = code_info->GetTemplate(wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); - if ( disconnect && _template.empty() ) - { - _template = code_info->GetTemplate( wxT("evt_") + templateName ); - _template.Replace( wxT("Connect"), wxT("Disconnect"), true ); - } - - if ( !_template.empty() ) - { - if( disconnect ) - { - if( m_disconnecMode == wxT("handler_name")) _template.Replace( wxT("#handler"), wxT("handler = array(@$this, \"") + handlerName + wxT("\")") ); - else if(m_disconnecMode == wxT("source_name")) _template.Replace( wxT("#handler"), wxT("null") ); //wxT("$this->") + obj->GetProperty(wxT("name"))->GetValueAsString() ); - } - else - _template.Replace( wxT("#handler"), wxT("array(@$this, \"") + handlerName + wxT("\")") ); - - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn( parser.ParseTemplate() ); - return true; - } - } - - for ( unsigned int i = 0; i < obj_info->GetBaseClassCount(); i++ ) - { - PObjectInfo base_info = obj_info->GetBaseClass( i ); - if ( GenEventEntry( obj, base_info, templateName, handlerName, disconnect ) ) - { - return true; - } - } - - return false; + wxString _template; + PCodeInfo code_info = obj_info->GetCodeInfo(wxT("PHP")); + if (code_info) { + _template = code_info->GetTemplate( + wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); + if (disconnect && _template.empty()) { + _template = code_info->GetTemplate(wxT("evt_") + templateName); + _template.Replace(wxT("Connect"), wxT("Disconnect"), true); + } + + if (!_template.empty()) { + if (disconnect) { + if (m_disconnecMode == wxT("handler_name")) + _template.Replace(wxT("#handler"), wxT("handler = array(@$this, \"") + handlerName + wxT("\")")); + else if (m_disconnecMode == wxT("source_name")) + _template.Replace( + wxT("#handler"), + wxT("null")); // wxT("$this->") + obj->GetProperty(wxT("name"))->GetValueAsString() ); + } else + _template.Replace(wxT("#handler"), wxT("array(@$this, \"") + handlerName + wxT("\")")); + + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + return true; + } + } + + for (unsigned int i = 0; i < obj_info->GetBaseClassCount(); i++) { + PObjectInfo base_info = obj_info->GetBaseClass(i); + if (GenEventEntry(obj, base_info, templateName, handlerName, disconnect)) { + return true; + } + } + + return false; } -void PHPCodeGenerator::GenVirtualEventHandlers( const EventVector& events, const wxString& eventHandlerPostfix ) +void PHPCodeGenerator::GenVirtualEventHandlers(const EventVector& events, const wxString& eventHandlerPostfix) { - if ( events.size() > 0 ) - { - // There are problems if we create "pure" virtual handlers, because some - // events could be triggered in the constructor in which virtual methods are - // execute properly. - // So we create a default handler which will skip the event. - m_source->WriteLn( wxEmptyString ); - m_source->WriteLn( wxT("// Virtual event handlers, override them in your derived class") ); - - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString aux = wxT("function ") + event->GetValue() + wxT("( $event ){"); - - if (generatedHandlers.find(aux) == generatedHandlers.end()) - { - m_source->WriteLn(aux); - m_source->Indent(); - m_source->WriteLn(eventHandlerPostfix); - m_source->Unindent(); - m_source->WriteLn(wxT("}")); - - generatedHandlers.insert(aux); - } - if( i < (events.size()-1) ) m_source->WriteLn(); - } - m_source->WriteLn( wxEmptyString ); - } + if (events.size() > 0) { + // There are problems if we create "pure" virtual handlers, because some + // events could be triggered in the constructor in which virtual methods are + // execute properly. + // So we create a default handler which will skip the event. + m_source->WriteLn(wxEmptyString); + m_source->WriteLn(wxT("// Virtual event handlers, override them in your derived class")); + + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString aux = wxT("function ") + event->GetValue() + wxT("( $event ){"); + + if (generatedHandlers.find(aux) == generatedHandlers.end()) { + m_source->WriteLn(aux); + m_source->Indent(); + m_source->WriteLn(eventHandlerPostfix); + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + + generatedHandlers.insert(aux); + } + if (i < (events.size() - 1)) + m_source->WriteLn(); + } + m_source->WriteLn(wxEmptyString); + } } -void PHPCodeGenerator::GetGenEventHandlers( PObjectBase obj ) +void PHPCodeGenerator::GetGenEventHandlers(PObjectBase obj) { - GenDefinedEventHandlers( obj->GetObjectInfo(), obj ); + GenDefinedEventHandlers(obj->GetObjectInfo(), obj); - for (unsigned int i = 0; i < obj->GetChildCount() ; i++) - { - PObjectBase child = obj->GetChild(i); - GetGenEventHandlers(child); - } + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GetGenEventHandlers(child); + } } -void PHPCodeGenerator::GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ) +void PHPCodeGenerator::GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj) { - PCodeInfo code_info = info->GetCodeInfo( wxT( "PHP" ) ); - if ( code_info ) - { - wxString _template = code_info->GetTemplate( wxT("generated_event_handlers") ); - if ( !_template.empty() ) - { - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - - if ( !code.empty() ) - { - m_source->WriteLn(code); - } - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i ); - GenDefinedEventHandlers( base_info, obj ); - } + PCodeInfo code_info = info->GetCodeInfo(wxT("PHP")); + if (code_info) { + wxString _template = code_info->GetTemplate(wxT("generated_event_handlers")); + if (!_template.empty()) { + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(); i++) { + PObjectInfo base_info = info->GetBaseClass(i); + GenDefinedEventHandlers(base_info, obj); + } } wxString PHPCodeGenerator::GetCode(PObjectBase obj, wxString name, bool silent) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT("PHP") ); - - if (!code_info) - { - if( !silent ) - { - wxString msg( wxString::Format( wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), - name, obj->GetClassName() ) ); - wxLogError(msg); - } - return wxEmptyString; - } - - _template = code_info->GetTemplate(name); - - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - - return code; + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("PHP")); + + if (!code_info) { + if (!silent) { + wxString msg(wxString::Format( + wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), name, + obj->GetClassName())); + wxLogError(msg); + } + return wxEmptyString; + } + + _template = code_info->GetTemplate(name); + + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + + return code; } wxString PHPCodeGenerator::GetConstruction(PObjectBase obj, ArrayItems& arrays) { - // Get the name - const auto& propName = obj->GetProperty(wxT("name")); - if (!propName) - { - // Object has no name, just get its code - return GetCode(obj, wxT("construction")); - } - - // Object has a name, check if its an array - const auto& name = propName->GetValue(); - wxString baseName; - ArrayItem unused; - if (!ParseArrayName(name, baseName, unused)) - { - // Object is not an array, just get its code - return GetCode(obj, wxT("construction")); - } - - // Object is an array, check if it needs to be declared - auto& item = arrays[baseName]; - if (item.isDeclared) - { - // Object is already declared, just get its code - return GetCode(obj, wxT("construction")); - } - - // Array needs to be declared - wxString code; - - // Array declaration - // Base array - code.append(wxT("$this->")); - code.append(baseName); - code.append(wxT(" = array();\n")); - - // If more dimensions are present they will get created automatically - - // Get the Code - code.append(GetCode(obj, wxT("construction"))); - - // Mark the array as declared - item.isDeclared = true; - - return code; + // Get the name + const auto& propName = obj->GetProperty(wxT("name")); + if (!propName) { + // Object has no name, just get its code + return GetCode(obj, wxT("construction")); + } + + // Object has a name, check if its an array + const auto& name = propName->GetValue(); + wxString baseName; + ArrayItem unused; + if (!ParseArrayName(name, baseName, unused)) { + // Object is not an array, just get its code + return GetCode(obj, wxT("construction")); + } + + // Object is an array, check if it needs to be declared + auto& item = arrays[baseName]; + if (item.isDeclared) { + // Object is already declared, just get its code + return GetCode(obj, wxT("construction")); + } + + // Array needs to be declared + wxString code; + + // Array declaration + // Base array + code.append(wxT("$this->")); + code.append(baseName); + code.append(wxT(" = array();\n")); + + // If more dimensions are present they will get created automatically + + // Get the Code + code.append(GetCode(obj, wxT("construction"))); + + // Mark the array as declared + item.isDeclared = true; + + return code; } -void PHPCodeGenerator::GenClassDeclaration(PObjectBase class_obj, bool /*use_enum*/, - const wxString& classDecoration, - const EventVector& events, - const wxString& eventHandlerPostfix, - ArrayItems& arrays) { - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), - class_obj->GetClassName()); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT("Object name can not be null") ); - return; - } - - m_source->WriteLn( wxT("/*") ); - m_source->WriteLn( wxT(" * Class ") + class_name); - m_source->WriteLn( wxT(" */") ); - m_source->WriteLn( ); - - m_source->WriteLn( wxT("class ") + classDecoration + class_name + wxT(" extends ") + GetCode( class_obj, wxT("base") ).Trim() + wxT(" {") ); - m_source->Indent(); - - // The constructor is also included within public - GenConstructor(class_obj, events, arrays); - GenDestructor( class_obj, events ); - - m_source->WriteLn(wxEmptyString); - - // event handlers - GenVirtualEventHandlers(events, eventHandlerPostfix); - GetGenEventHandlers( class_obj ); - - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); - m_source->WriteLn(wxEmptyString); +void PHPCodeGenerator::GenClassDeclaration( + PObjectBase class_obj, bool /*use_enum*/, const wxString& classDecoration, const EventVector& events, + const wxString& eventHandlerPostfix, ArrayItems& arrays) +{ + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name can not be null")); + return; + } + + m_source->WriteLn(wxT("/*")); + m_source->WriteLn(wxT(" * Class ") + class_name); + m_source->WriteLn(wxT(" */")); + m_source->WriteLn(); + + m_source->WriteLn( + wxT("class ") + classDecoration + class_name + wxT(" extends ") + GetCode(class_obj, wxT("base")).Trim() + + wxT(" {")); + m_source->Indent(); + + // The constructor is also included within public + GenConstructor(class_obj, events, arrays); + GenDestructor(class_obj, events); + + m_source->WriteLn(wxEmptyString); + + // event handlers + GenVirtualEventHandlers(events, eventHandlerPostfix); + GetGenEventHandlers(class_obj); + + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + m_source->WriteLn(wxEmptyString); } -void PHPCodeGenerator::GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::vector< wxString >* headerIncludes ) +void PHPCodeGenerator::GenSubclassSets( + PObjectBase obj, std::set* subclasses, std::vector* headerIncludes) { - // Call GenSubclassForwardDeclarations on all children as well - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenSubclassSets( obj->GetChild( i ), subclasses, headerIncludes ); - } - - // Fill the set - PProperty subclass = obj->GetProperty( wxT("subclass") ); - if ( subclass ) - { - std::map< wxString, wxString > children; - subclass->SplitParentProperty( &children ); - - std::map< wxString, wxString >::iterator name; - name = children.find( wxT("name") ); - - if ( children.end() == name ) - { - // No name, so do nothing - return; - } - - wxString nameVal = name->second; - if ( nameVal.empty() ) - { - // No name, so do nothing - return; - } - - // Now get the header - std::map< wxString, wxString >::iterator header; - header = children.find( wxT("header") ); - - if ( children.end() == header ) - { - // No header, so do nothing - return; - } - - wxString headerVal = header->second; - if ( headerVal.empty() ) - { - // No header, so do nothing - return; - } - - // Got a header - PObjectInfo info = obj->GetObjectInfo(); - if ( !info ) - { - return; - } - - PObjectPackage pkg = info->GetPackage(); - if ( !pkg ) - { - return; - } - - wxString include = wxT("include_once ") + headerVal + wxT(";"); - std::vector< wxString >::iterator it = std::find( headerIncludes->begin(), headerIncludes->end(), include ); - if ( headerIncludes->end() == it ) - { - headerIncludes->push_back( include ); - } - } + // Call GenSubclassForwardDeclarations on all children as well + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + GenSubclassSets(obj->GetChild(i), subclasses, headerIncludes); + } + + // Fill the set + PProperty subclass = obj->GetProperty(wxT("subclass")); + if (subclass) { + std::map children; + subclass->SplitParentProperty(&children); + + std::map::iterator name; + name = children.find(wxT("name")); + + if (children.end() == name) { + // No name, so do nothing + return; + } + + wxString nameVal = name->second; + if (nameVal.empty()) { + // No name, so do nothing + return; + } + + // Now get the header + std::map::iterator header; + header = children.find(wxT("header")); + + if (children.end() == header) { + // No header, so do nothing + return; + } + + wxString headerVal = header->second; + if (headerVal.empty()) { + // No header, so do nothing + return; + } + + // Got a header + PObjectInfo info = obj->GetObjectInfo(); + if (!info) { + return; + } + + PObjectPackage pkg = info->GetPackage(); + if (!pkg) { + return; + } + + wxString include = wxT("include_once ") + headerVal + wxT(";"); + std::vector::iterator it = std::find(headerIncludes->begin(), headerIncludes->end(), include); + if (headerIncludes->end() == it) { + headerIncludes->push_back(include); + } + } } -void PHPCodeGenerator::GenIncludes( PObjectBase project, std::vector* includes, std::set< wxString >* templates ) +void PHPCodeGenerator::GenIncludes(PObjectBase project, std::vector* includes, std::set* templates) { - GenObjectIncludes( project, includes, templates ); + GenObjectIncludes(project, includes, templates); } -void PHPCodeGenerator::GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ) +void PHPCodeGenerator::GenObjectIncludes( + PObjectBase project, std::vector* includes, std::set* templates) { - // Fill the set - PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo( wxT("PHP") ); - if (code_info) - { - PHPTemplateParser parser( project, code_info->GetTemplate( wxT("include") ), m_i18n, m_useRelativePath, m_basePath ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } - - // Call GenIncludes on all children as well - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - GenObjectIncludes( project->GetChild(i), includes, templates ); - } - - // Generate includes for base classes - GenBaseIncludes( project->GetObjectInfo(), project, includes, templates ); + // Fill the set + PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo(wxT("PHP")); + if (code_info) { + PHPTemplateParser parser( + project, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } + + // Call GenIncludes on all children as well + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + GenObjectIncludes(project->GetChild(i), includes, templates); + } + + // Generate includes for base classes + GenBaseIncludes(project->GetObjectInfo(), project, includes, templates); } -void PHPCodeGenerator::GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ) +void PHPCodeGenerator::GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates) { - if ( !info ) - { - return; - } - - // Process all the base classes recursively - for ( unsigned int i = 0; i < info->GetBaseClassCount(); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i ); - GenBaseIncludes( base_info, obj, includes, templates ); - } - - PCodeInfo code_info = info->GetCodeInfo( wxT("PHP") ); - if ( code_info ) - { - PHPTemplateParser parser( obj, code_info->GetTemplate( wxT("include") ), m_i18n, m_useRelativePath, m_basePath ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } + if (!info) { + return; + } + + // Process all the base classes recursively + for (unsigned int i = 0; i < info->GetBaseClassCount(); i++) { + PObjectInfo base_info = info->GetBaseClass(i); + GenBaseIncludes(base_info, obj, includes, templates); + } + + PCodeInfo code_info = info->GetCodeInfo(wxT("PHP")); + if (code_info) { + PHPTemplateParser parser(obj, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } } -void PHPCodeGenerator::AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ) +void PHPCodeGenerator::AddUniqueIncludes(const wxString& include, std::vector* includes) { - // Split on newlines to only generate unique include lines - // This strips blank lines and trims - wxStringTokenizer tkz( include, wxT("\n"), wxTOKEN_STRTOK ); - - while ( tkz.HasMoreTokens() ) - { - wxString line = tkz.GetNextToken(); - line.Trim( false ); - line.Trim( true ); - - // If it is not an include line, it will be written - if ( !line.StartsWith( wxT("import") ) ) - { - includes->push_back( line ); - continue; - } - - // If it is an include, it must be unique to be written - std::vector< wxString >::iterator it = std::find( includes->begin(), includes->end(), line ); - if ( includes->end() == it ) - { - includes->push_back( line ); - } - } + // Split on newlines to only generate unique include lines + // This strips blank lines and trims + wxStringTokenizer tkz(include, wxT("\n"), wxTOKEN_STRTOK); + + while (tkz.HasMoreTokens()) { + wxString line = tkz.GetNextToken(); + line.Trim(false); + line.Trim(true); + + // If it is not an include line, it will be written + if (!line.StartsWith(wxT("import"))) { + includes->push_back(line); + continue; + } + + // If it is an include, it must be unique to be written + std::vector::iterator it = std::find(includes->begin(), includes->end(), line); + if (includes->end() == it) { + includes->push_back(line); + } + } } -void PHPCodeGenerator::FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ) +void PHPCodeGenerator::FindDependencies(PObjectBase obj, std::set& info_set) { - unsigned int ch_count = obj->GetChildCount(); - if (ch_count > 0) - { - unsigned int i; - for (i = 0; iGetChild(i); - info_set.insert(child->GetObjectInfo()); - FindDependencies(child, info_set); - } - } + unsigned int ch_count = obj->GetChildCount(); + if (ch_count > 0) { + unsigned int i; + for (i = 0; i < ch_count; i++) { + PObjectBase child = obj->GetChild(i); + info_set.insert(child->GetObjectInfo()); + FindDependencies(child, info_set); + } + } } void PHPCodeGenerator::GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays) { - m_source->WriteLn(); - // generate function definition - m_source->WriteLn( GetCode( class_obj, wxT("cons_def") ) ); - m_source->Indent(); - - m_source->WriteLn( GetCode( class_obj, wxT("cons_call") ) ); - m_source->WriteLn(); - - wxString settings = GetCode( class_obj, wxT("settings") ); - if ( !settings.IsEmpty() ) - { - m_source->WriteLn( settings ); - } - - for ( unsigned int i = 0; i < class_obj->GetChildCount(); i++ ) - { - GenConstruction(class_obj->GetChild( i ), true, arrays); - } - - wxString afterAddChild = GetCode( class_obj, wxT("after_addchild") ); - if ( !afterAddChild.IsEmpty() ) - { - m_source->WriteLn( afterAddChild ); - } - - GenEvents( class_obj, events ); - - auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); - if (!afterConnectEvents.empty()) - { - m_source->WriteLn(); - m_source->WriteLn(afterConnectEvents); - } - - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); - m_source->WriteLn(wxEmptyString); - - if ( class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0 ) - { - m_source->WriteLn( wxT("function AddPage($page){") ); - m_source->Indent(); - m_source->WriteLn( wxT("if(count($this->m_pages) > 0){") ); - m_source->Indent(); - m_source->WriteLn( wxT("$previous_page = $this->m_pages[count($this->m_pages)-1];") ); - m_source->WriteLn( wxT("$page->SetPrev($previous_page);") ); - m_source->WriteLn( wxT("$previous_page->SetNext($page);") ); - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); - m_source->WriteLn( wxT("$this->m_pages[] = $page;") ); - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); - } + m_source->WriteLn(); + // generate function definition + m_source->WriteLn(GetCode(class_obj, wxT("cons_def"))); + m_source->Indent(); + + m_source->WriteLn(GetCode(class_obj, wxT("cons_call"))); + m_source->WriteLn(); + + wxString settings = GetCode(class_obj, wxT("settings")); + if (!settings.IsEmpty()) { + m_source->WriteLn(settings); + } + + for (unsigned int i = 0; i < class_obj->GetChildCount(); i++) { + GenConstruction(class_obj->GetChild(i), true, arrays); + } + + wxString afterAddChild = GetCode(class_obj, wxT("after_addchild")); + if (!afterAddChild.IsEmpty()) { + m_source->WriteLn(afterAddChild); + } + + GenEvents(class_obj, events); + + auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); + if (!afterConnectEvents.empty()) { + m_source->WriteLn(); + m_source->WriteLn(afterConnectEvents); + } + + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + m_source->WriteLn(wxEmptyString); + + if (class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0) { + m_source->WriteLn(wxT("function AddPage($page){")); + m_source->Indent(); + m_source->WriteLn(wxT("if(count($this->m_pages) > 0){")); + m_source->Indent(); + m_source->WriteLn(wxT("$previous_page = $this->m_pages[count($this->m_pages)-1];")); + m_source->WriteLn(wxT("$page->SetPrev($previous_page);")); + m_source->WriteLn(wxT("$previous_page->SetNext($page);")); + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + m_source->WriteLn(wxT("$this->m_pages[] = $page;")); + m_source->Unindent(); + m_source->WriteLn(wxT("}")); + } } -void PHPCodeGenerator::GenDestructor( PObjectBase class_obj, const EventVector &events ) +void PHPCodeGenerator::GenDestructor(PObjectBase class_obj, const EventVector& events) { - m_source->WriteLn(); - // generate function definition - m_source->WriteLn( wxT("function __destruct( ){") ); - m_source->Indent(); + m_source->WriteLn(); + // generate function definition + m_source->WriteLn(wxT("function __destruct( ){")); + m_source->Indent(); - if ( m_disconnectEvents && !events.empty() ) - { - GenEvents( class_obj, events, true ); - } + if (m_disconnectEvents && !events.empty()) { + GenEvents(class_obj, events, true); + } - // destruct objects - GenDestruction( class_obj ); + // destruct objects + GenDestruction(class_obj); - m_source->Unindent(); - m_source->WriteLn( wxT("}") ); + m_source->Unindent(); + m_source->WriteLn(wxT("}")); } void PHPCodeGenerator::GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays) { - wxString type = obj->GetObjectTypeName(); - PObjectInfo info = obj->GetObjectInfo(); - - if ( ObjectDatabase::HasCppProperties( type ) ) - { - m_source->WriteLn(GetConstruction(obj, arrays)); - - GenSettings( obj->GetObjectInfo(), obj ); - - bool isWidget = !info->IsSubclassOf( wxT("sizer") ); - - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenConstruction(child, isWidget, arrays); - - if ( type == wxT("toolbar") ) - { - GenAddToolbar(child->GetObjectInfo(), child); - } - } - - if ( !isWidget ) // sizers - { - wxString afterAddChild = GetCode( obj, wxT( "after_addchild" ) ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - - if (is_widget) - { - // the parent object is not a sizer. There is no template for - // this so we'll make it manually. - // It's not a good practice to embed templates into the source code, - // because you will need to recompile... - - wxString _template = wxT("#wxparent $name->SetSizer( @$$name ); #nl") - wxT("#wxparent $name->Layout();") - wxT("#ifnull #parent $size") - wxT("@{ #nl @$$name->Fit( #wxparent $name ); @}"); - - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn(parser.ParseTemplate()); - } - } - else if ( type == wxT("splitter") ) - { - // Generating the split - switch ( obj->GetChildCount() ) - { - case 1: - { - PObjectBase sub1 = obj->GetChild(0)->GetChild(0); - wxString _template = wxT("@$this->$name->Initialize( "); - _template = _template + wxT("@$this->") + sub1->GetProperty( wxT("name") )->GetValue() + wxT(" );"); - - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn(parser.ParseTemplate()); - break; - } - case 2: - { - PObjectBase sub1,sub2; - sub1 = obj->GetChild(0)->GetChild(0); - sub2 = obj->GetChild(1)->GetChild(0); - - wxString _template; - if ( obj->GetProperty( wxT("splitmode") )->GetValue() == wxT("wxSPLIT_VERTICAL") ) - { - _template = wxT("@$this->$name->SplitVertically( "); - } - else - { - _template = wxT("@$this->$name->SplitHorizontally( "); - } - - _template = _template + wxT("@$this->") + sub1->GetProperty( wxT("name") )->GetValue() + - wxT(", @$this->") + sub2->GetProperty( wxT("name") )->GetValue() + wxT(", $sashpos );"); - - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - m_source->WriteLn(parser.ParseTemplate()); - break; - } - default: - wxLogError( wxT("Missing subwindows for wxSplitterWindow widget.") ); - break; - } - } - else if ( - type == wxT("menubar") || - type == wxT("menu") || - type == wxT("submenu") || - type == wxT("toolbar") || - type == wxT("ribbonbar") || - type == wxT("listbook") || - type == wxT("simplebook") || - type == wxT("notebook") || - type == wxT("auinotebook") || - type == wxT("treelistctrl") || - type == wxT("flatnotebook") || - type == wxT("wizard") - ) - { - wxString afterAddChild = GetCode( obj, wxT("after_addchild") ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - } - } - else if ( info->IsSubclassOf( wxT("sizeritembase") ) ) - { - // The child must be added to the sizer having in mind the - // child object type (there are 3 different routines) - GenConstruction(obj->GetChild(0), false, arrays); - - PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); - wxString temp_name; - if ( childInfo->IsSubclassOf( wxT("wxWindow") ) || wxT("CustomControl") == childInfo->GetClassName() ) - { - temp_name = wxT("window_add"); - } - else if ( childInfo->IsSubclassOf( wxT("sizer") ) ) - { - temp_name = wxT("sizer_add"); - } - else if ( childInfo->GetClassName() == wxT("spacer") ) - { - temp_name = wxT("spacer_add"); - } - else - { - LogDebug( wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.") ); - return; - } - - m_source->WriteLn( GetCode( obj, temp_name ) ); - } - else if ( type == wxT("notebookpage") || - type == wxT("flatnotebookpage") || - type == wxT("listbookpage") || - type == wxT("simplebookpage") || - type == wxT("choicebookpage") || - type == wxT("auinotebookpage") - ) - { - GenConstruction(obj->GetChild(0), false, arrays); - m_source->WriteLn( GetCode( obj, wxT("page_add") ) ); - GenSettings( obj->GetObjectInfo(), obj ); - } - else if ( type == wxT("treelistctrlcolumn") ) - { - m_source->WriteLn( GetCode( obj, wxT("column_add") ) ); - GenSettings( obj->GetObjectInfo(), obj ); - } - else if ( type == wxT("tool") ) - { - // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize - // So hacky, yet so useful ... - wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize( _("bitmapsize") ); - if ( wxDefaultSize != toolbarsize ) - { - PProperty prop = obj->GetProperty( _("bitmap") ); - if ( prop ) - { - wxString oldVal = prop->GetValueAsString(); - wxString path, source; - wxSize toolsize; - TypeConv::ParseBitmapWithResource( oldVal, &path, &source, &toolsize ); - if ( wxT("Load From Icon Resource") == source && wxDefaultSize == toolsize ) - { - prop->SetValue( wxString::Format( wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight() ) ); - m_source->WriteLn(GetConstruction(obj, arrays)); - prop->SetValue( oldVal ); - return; - } - } - } - m_source->WriteLn(GetConstruction(obj, arrays)); - } - else - { - // Generate the children - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenConstruction(obj->GetChild(i), false, arrays); - } - } + wxString type = obj->GetObjectTypeName(); + PObjectInfo info = obj->GetObjectInfo(); + + if (ObjectDatabase::HasCppProperties(type)) { + m_source->WriteLn(GetConstruction(obj, arrays)); + + GenSettings(obj->GetObjectInfo(), obj); + + bool isWidget = !info->IsSubclassOf(wxT("sizer")); + + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenConstruction(child, isWidget, arrays); + + if (type == wxT("toolbar")) { + GenAddToolbar(child->GetObjectInfo(), child); + } + } + + if (!isWidget) // sizers + { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + + if (is_widget) { + // the parent object is not a sizer. There is no template for + // this so we'll make it manually. + // It's not a good practice to embed templates into the source code, + // because you will need to recompile... + + wxString _template = wxT("#wxparent $name->SetSizer( @$$name ); #nl") wxT("#wxparent $name->Layout();") + wxT("#ifnull #parent $size") wxT("@{ #nl @$$name->Fit( #wxparent $name ); @}"); + + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + } + } else if (type == wxT("splitter")) { + // Generating the split + switch (obj->GetChildCount()) { + case 1: { + PObjectBase sub1 = obj->GetChild(0)->GetChild(0); + wxString _template = wxT("@$this->$name->Initialize( "); + _template = _template + wxT("@$this->") + sub1->GetProperty(wxT("name"))->GetValue() + wxT(" );"); + + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + case 2: { + PObjectBase sub1, sub2; + sub1 = obj->GetChild(0)->GetChild(0); + sub2 = obj->GetChild(1)->GetChild(0); + + wxString _template; + if (obj->GetProperty(wxT("splitmode"))->GetValue() == wxT("wxSPLIT_VERTICAL")) { + _template = wxT("@$this->$name->SplitVertically( "); + } else { + _template = wxT("@$this->$name->SplitHorizontally( "); + } + + _template = _template + wxT("@$this->") + sub1->GetProperty(wxT("name"))->GetValue() + + wxT(", @$this->") + sub2->GetProperty(wxT("name"))->GetValue() + wxT(", $sashpos );"); + + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + default: + wxLogError(wxT("Missing subwindows for wxSplitterWindow widget.")); + break; + } + } else if ( + type == wxT("menubar") || type == wxT("menu") || type == wxT("submenu") || type == wxT("toolbar") || + type == wxT("ribbonbar") || type == wxT("listbook") || type == wxT("simplebook") || type == wxT("notebook") || + type == wxT("auinotebook") || type == wxT("treelistctrl") || type == wxT("flatnotebook") || + type == wxT("wizard")) { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + } + } else if (info->IsSubclassOf(wxT("sizeritembase"))) { + // The child must be added to the sizer having in mind the + // child object type (there are 3 different routines) + GenConstruction(obj->GetChild(0), false, arrays); + + PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); + wxString temp_name; + if (childInfo->IsSubclassOf(wxT("wxWindow")) || wxT("CustomControl") == childInfo->GetClassName()) { + temp_name = wxT("window_add"); + } else if (childInfo->IsSubclassOf(wxT("sizer"))) { + temp_name = wxT("sizer_add"); + } else if (childInfo->GetClassName() == wxT("spacer")) { + temp_name = wxT("spacer_add"); + } else { + LogDebug(wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.")); + return; + } + + m_source->WriteLn(GetCode(obj, temp_name)); + } else if ( + type == wxT("notebookpage") || type == wxT("flatnotebookpage") || type == wxT("listbookpage") || + type == wxT("simplebookpage") || type == wxT("choicebookpage") || type == wxT("auinotebookpage")) { + GenConstruction(obj->GetChild(0), false, arrays); + m_source->WriteLn(GetCode(obj, wxT("page_add"))); + GenSettings(obj->GetObjectInfo(), obj); + } else if (type == wxT("treelistctrlcolumn")) { + m_source->WriteLn(GetCode(obj, wxT("column_add"))); + GenSettings(obj->GetObjectInfo(), obj); + } else if (type == wxT("tool")) { + // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize + // So hacky, yet so useful ... + wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize(_("bitmapsize")); + if (wxDefaultSize != toolbarsize) { + PProperty prop = obj->GetProperty(_("bitmap")); + if (prop) { + wxString oldVal = prop->GetValueAsString(); + wxString path, source; + wxSize toolsize; + TypeConv::ParseBitmapWithResource(oldVal, &path, &source, &toolsize); + if (wxT("Load From Icon Resource") == source && wxDefaultSize == toolsize) { + prop->SetValue(wxString::Format( + wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight())); + m_source->WriteLn(GetConstruction(obj, arrays)); + prop->SetValue(oldVal); + return; + } + } + } + m_source->WriteLn(GetConstruction(obj, arrays)); + } else { + // Generate the children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { GenConstruction(obj->GetChild(i), false, arrays); } + } } -void PHPCodeGenerator::GenDestruction( PObjectBase obj ) +void PHPCodeGenerator::GenDestruction(PObjectBase obj) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT( "PHP" ) ); - - if ( code_info ) - { - _template = code_info->GetTemplate( wxT( "destruction" ) ); - - if ( !_template.empty() ) - { - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - } - } - } - - // Process child widgets - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenDestruction( child ); - } + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("PHP")); + + if (code_info) { + _template = code_info->GetTemplate(wxT("destruction")); + + if (!_template.empty()) { + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Process child widgets + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenDestruction(child); + } } -void PHPCodeGenerator::FindMacros( PObjectBase obj, std::vector* macros ) +void PHPCodeGenerator::FindMacros(PObjectBase obj, std::vector* macros) { - // iterate through all of the properties of all objects, add the macros - // to the vector - unsigned int i; - - for ( i = 0; i < obj->GetPropertyCount(); i++ ) - { - PProperty prop = obj->GetProperty( i ); - if ( prop->GetType() == PT_MACRO ) - { - wxString value = prop->GetValue(); - if( value.IsEmpty() ) continue; - - // Skip wx IDs - if ( ( ! value.Contains( wxT("XRCID" ) ) ) && - ( m_predMacros.end() == m_predMacros.find( value ) ) ) - { - if ( macros->end() == std::find( macros->begin(), macros->end(), value ) ) - { - macros->push_back( value ); - } - } - } - } - - for ( i = 0; i < obj->GetChildCount(); i++ ) - { - FindMacros( obj->GetChild( i ), macros ); - } + // iterate through all of the properties of all objects, add the macros + // to the vector + unsigned int i; + + for (i = 0; i < obj->GetPropertyCount(); i++) { + PProperty prop = obj->GetProperty(i); + if (prop->GetType() == PT_MACRO) { + wxString value = prop->GetValue(); + if (value.IsEmpty()) + continue; + + // Skip wx IDs + if ((!value.Contains(wxT("XRCID"))) && (m_predMacros.end() == m_predMacros.find(value))) { + if (macros->end() == std::find(macros->begin(), macros->end(), value)) { + macros->push_back(value); + } + } + } + } + + for (i = 0; i < obj->GetChildCount(); i++) { FindMacros(obj->GetChild(i), macros); } } -void PHPCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector &events) +void PHPCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector& events) { - unsigned int i; - for (i=0; i < obj->GetEventCount(); i++) - { - PEvent event = obj->GetEvent(i); - if (!event->GetValue().IsEmpty()) - events.push_back(event); - } - - for (i=0; i < obj->GetChildCount(); i++) - { - PObjectBase child = obj->GetChild(i); - FindEventHandlers(child,events); - } + unsigned int i; + for (i = 0; i < obj->GetEventCount(); i++) { + PEvent event = obj->GetEvent(i); + if (!event->GetValue().IsEmpty()) + events.push_back(event); + } + + for (i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + FindEventHandlers(child, events); + } } -void PHPCodeGenerator::GenDefines( PObjectBase project) +void PHPCodeGenerator::GenDefines(PObjectBase project) { - std::vector< wxString > macros; - FindMacros( project, ¯os ); - - // Remove the default macro from the set, for backward compatibility - std::vector< wxString >::iterator it; - it = std::find( macros.begin(), macros.end(), wxT("ID_DEFAULT") ); - if ( it != macros.end() ) - { - // The default macro is defined to wxID_ANY - m_source->WriteLn( wxT("const ID_DEFAULT = wxID_ANY; // Default") ); - macros.erase(it); - } - - unsigned int id = m_firstID; - if ( id < 1000 ) - { - wxLogWarning(wxT("First ID is Less than 1000")); - } - for (it = macros.begin() ; it != macros.end(); it++) - { - // Don't redefine wx IDs - m_source->WriteLn( wxString::Format( wxT("const %s = %i;"), it->c_str(), id ) ); - id++; - } - if (!macros.empty()) - { - m_source->WriteLn(wxEmptyString); - } + std::vector macros; + FindMacros(project, ¯os); + + // Remove the default macro from the set, for backward compatibility + std::vector::iterator it; + it = std::find(macros.begin(), macros.end(), wxT("ID_DEFAULT")); + if (it != macros.end()) { + // The default macro is defined to wxID_ANY + m_source->WriteLn(wxT("const ID_DEFAULT = wxID_ANY; // Default")); + macros.erase(it); + } + + unsigned int id = m_firstID; + if (id < 1000) { + wxLogWarning(wxT("First ID is Less than 1000")); + } + for (it = macros.begin(); it != macros.end(); it++) { + // Don't redefine wx IDs + m_source->WriteLn(wxString::Format(wxT("const %s = %i;"), it->c_str(), id)); + id++; + } + if (!macros.empty()) { + m_source->WriteLn(wxEmptyString); + } } void PHPCodeGenerator::GenSettings(PObjectInfo info, PObjectBase obj) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT("PHP") ); - - if ( !code_info ) - { - return; - } - - _template = code_info->GetTemplate( wxT("settings") ); - - if ( !_template.empty() ) - { - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn(code); - } - } - - // Proceeding recursively with the base classes - for (unsigned int i=0; i< info->GetBaseClassCount(); i++) - { - PObjectInfo base_info = info->GetBaseClass(i); - GenSettings(base_info,obj); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("PHP")); + + if (!code_info) { + return; + } + + _template = code_info->GetTemplate(wxT("settings")); + + if (!_template.empty()) { + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(); i++) { + PObjectInfo base_info = info->GetBaseClass(i); + GenSettings(base_info, obj); + } } -void PHPCodeGenerator::GenAddToolbar( PObjectInfo info, PObjectBase obj ) +void PHPCodeGenerator::GenAddToolbar(PObjectInfo info, PObjectBase obj) { - wxArrayString arrCode; + wxArrayString arrCode; - GetAddToolbarCode( info, obj, arrCode ); + GetAddToolbarCode(info, obj, arrCode); - for( size_t i = 0; i < arrCode.GetCount(); i++ ) m_source->WriteLn( arrCode[i] ); + for (size_t i = 0; i < arrCode.GetCount(); i++) m_source->WriteLn(arrCode[i]); } -void PHPCodeGenerator::GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ) +void PHPCodeGenerator::GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT( "PHP" ) ); - - if ( !code_info ) - return; - - _template = code_info->GetTemplate( wxT( "toolbar_add" ) ); - - if ( !_template.empty() ) - { - PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - if( codelines.Index( code ) == wxNOT_FOUND ) codelines.Add( code ); - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i ); - GetAddToolbarCode( base_info, obj, codelines ); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("PHP")); + + if (!code_info) + return; + + _template = code_info->GetTemplate(wxT("toolbar_add")); + + if (!_template.empty()) { + PHPTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + if (codelines.Index(code) == wxNOT_FOUND) + codelines.Add(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(); i++) { + PObjectInfo base_info = info->GetBaseClass(i); + GetAddToolbarCode(base_info, obj, codelines); + } } /////////////////////////////////////////////////////////////////////// void PHPCodeGenerator::UseRelativePath(bool relative, wxString basePath) { - m_useRelativePath = relative; - - if (m_useRelativePath) - { - if (wxFileName::DirExists(basePath)) - { - m_basePath = basePath; - } - else - { - m_basePath = wxEmptyString; - } - } + m_useRelativePath = relative; + + if (m_useRelativePath) { + if (wxFileName::DirExists(basePath)) { + m_basePath = basePath; + } else { + m_basePath = wxEmptyString; + } + } } /* wxString CppCodeGenerator::ConvertToRelativePath(wxString path, wxString basePath) @@ -1503,139 +1292,138 @@ auxPath = _STDSTR(filename.GetFullPath()); return auxPath; }*/ -#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert( wxT(#x) ) -#define ADD_PREDEFINED_PREFIX(k, v) m_predModulePrefix[ wxT(#k) ] = wxT(#v) +#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert(wxT(#x)) +#define ADD_PREDEFINED_PREFIX(k, v) m_predModulePrefix[wxT(#k)] = wxT(#v) void PHPCodeGenerator::SetupPredefinedMacros() { - /* no id matches this one when compared to it */ - ADD_PREDEFINED_MACRO(wxID_NONE); - - /* id for a separator line in the menu (invalid for normal item) */ - ADD_PREDEFINED_MACRO(wxID_SEPARATOR); - - ADD_PREDEFINED_MACRO(wxID_ANY); - - ADD_PREDEFINED_MACRO(wxID_LOWEST); - - ADD_PREDEFINED_MACRO(wxID_OPEN); - ADD_PREDEFINED_MACRO(wxID_CLOSE); - ADD_PREDEFINED_MACRO(wxID_NEW); - ADD_PREDEFINED_MACRO(wxID_SAVE); - ADD_PREDEFINED_MACRO(wxID_SAVEAS); - ADD_PREDEFINED_MACRO(wxID_REVERT); - ADD_PREDEFINED_MACRO(wxID_EXIT); - ADD_PREDEFINED_MACRO(wxID_UNDO); - ADD_PREDEFINED_MACRO(wxID_REDO); - ADD_PREDEFINED_MACRO(wxID_HELP); - ADD_PREDEFINED_MACRO(wxID_PRINT); - ADD_PREDEFINED_MACRO(wxID_PRINT_SETUP); - ADD_PREDEFINED_MACRO(wxID_PREVIEW); - ADD_PREDEFINED_MACRO(wxID_ABOUT); - ADD_PREDEFINED_MACRO(wxID_HELP_CONTENTS); - ADD_PREDEFINED_MACRO(wxID_HELP_COMMANDS); - ADD_PREDEFINED_MACRO(wxID_HELP_PROCEDURES); - ADD_PREDEFINED_MACRO(wxID_HELP_CONTEXT); - ADD_PREDEFINED_MACRO(wxID_CLOSE_ALL); - ADD_PREDEFINED_MACRO(wxID_PAGE_SETUP); - ADD_PREDEFINED_MACRO(wxID_HELP_INDEX); - ADD_PREDEFINED_MACRO(wxID_HELP_SEARCH); - ADD_PREDEFINED_MACRO(wxID_PREFERENCES); - - ADD_PREDEFINED_MACRO(wxID_EDIT); - ADD_PREDEFINED_MACRO(wxID_CUT); - ADD_PREDEFINED_MACRO(wxID_COPY); - ADD_PREDEFINED_MACRO(wxID_PASTE); - ADD_PREDEFINED_MACRO(wxID_CLEAR); - ADD_PREDEFINED_MACRO(wxID_FIND); - - ADD_PREDEFINED_MACRO(wxID_DUPLICATE); - ADD_PREDEFINED_MACRO(wxID_SELECTALL); - ADD_PREDEFINED_MACRO(wxID_DELETE); - ADD_PREDEFINED_MACRO(wxID_REPLACE); - ADD_PREDEFINED_MACRO(wxID_REPLACE_ALL); - ADD_PREDEFINED_MACRO(wxID_PROPERTIES); - - ADD_PREDEFINED_MACRO(wxID_VIEW_DETAILS); - ADD_PREDEFINED_MACRO(wxID_VIEW_LARGEICONS); - ADD_PREDEFINED_MACRO(wxID_VIEW_SMALLICONS); - ADD_PREDEFINED_MACRO(wxID_VIEW_LIST); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTDATE); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTNAME); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTSIZE); - ADD_PREDEFINED_MACRO(wxID_VIEW_SORTTYPE); - - ADD_PREDEFINED_MACRO(wxID_FILE); - ADD_PREDEFINED_MACRO(wxID_FILE1); - ADD_PREDEFINED_MACRO(wxID_FILE2); - ADD_PREDEFINED_MACRO(wxID_FILE3); - ADD_PREDEFINED_MACRO(wxID_FILE4); - ADD_PREDEFINED_MACRO(wxID_FILE5); - ADD_PREDEFINED_MACRO(wxID_FILE6); - ADD_PREDEFINED_MACRO(wxID_FILE7); - ADD_PREDEFINED_MACRO(wxID_FILE8); - ADD_PREDEFINED_MACRO(wxID_FILE9); - - /* Standard button and menu IDs */ - - ADD_PREDEFINED_MACRO(wxID_OK); - ADD_PREDEFINED_MACRO(wxID_CANCEL); - - ADD_PREDEFINED_MACRO(wxID_APPLY); - ADD_PREDEFINED_MACRO(wxID_YES); - ADD_PREDEFINED_MACRO(wxID_NO); - ADD_PREDEFINED_MACRO(wxID_STATIC); - ADD_PREDEFINED_MACRO(wxID_FORWARD); - ADD_PREDEFINED_MACRO(wxID_BACKWARD); - ADD_PREDEFINED_MACRO(wxID_DEFAULT); - ADD_PREDEFINED_MACRO(wxID_MORE); - ADD_PREDEFINED_MACRO(wxID_SETUP); - ADD_PREDEFINED_MACRO(wxID_RESET); - ADD_PREDEFINED_MACRO(wxID_CONTEXT_HELP); - ADD_PREDEFINED_MACRO(wxID_YESTOALL); - ADD_PREDEFINED_MACRO(wxID_NOTOALL); - ADD_PREDEFINED_MACRO(wxID_ABORT); - ADD_PREDEFINED_MACRO(wxID_RETRY); - ADD_PREDEFINED_MACRO(wxID_IGNORE); - ADD_PREDEFINED_MACRO(wxID_ADD); - ADD_PREDEFINED_MACRO(wxID_REMOVE); - - ADD_PREDEFINED_MACRO(wxID_UP); - ADD_PREDEFINED_MACRO(wxID_DOWN); - ADD_PREDEFINED_MACRO(wxID_HOME); - ADD_PREDEFINED_MACRO(wxID_REFRESH); - ADD_PREDEFINED_MACRO(wxID_STOP); - ADD_PREDEFINED_MACRO(wxID_INDEX); - - ADD_PREDEFINED_MACRO(wxID_BOLD); - ADD_PREDEFINED_MACRO(wxID_ITALIC); - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_CENTER); - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_FILL); - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_RIGHT); - - ADD_PREDEFINED_MACRO(wxID_JUSTIFY_LEFT); - ADD_PREDEFINED_MACRO(wxID_UNDERLINE); - ADD_PREDEFINED_MACRO(wxID_INDENT); - ADD_PREDEFINED_MACRO(wxID_UNINDENT); - ADD_PREDEFINED_MACRO(wxID_ZOOM_100); - ADD_PREDEFINED_MACRO(wxID_ZOOM_FIT); - ADD_PREDEFINED_MACRO(wxID_ZOOM_IN); - ADD_PREDEFINED_MACRO(wxID_ZOOM_OUT); - ADD_PREDEFINED_MACRO(wxID_UNDELETE); - ADD_PREDEFINED_MACRO(wxID_REVERT_TO_SAVED); - - /* System menu IDs (used by wxUniv): */ - ADD_PREDEFINED_MACRO(wxID_SYSTEM_MENU); - ADD_PREDEFINED_MACRO(wxID_CLOSE_FRAME); - ADD_PREDEFINED_MACRO(wxID_MOVE_FRAME); - ADD_PREDEFINED_MACRO(wxID_RESIZE_FRAME); - ADD_PREDEFINED_MACRO(wxID_MAXIMIZE_FRAME); - ADD_PREDEFINED_MACRO(wxID_ICONIZE_FRAME); - ADD_PREDEFINED_MACRO(wxID_RESTORE_FRAME); - - /* IDs used by generic file dialog (13 consecutive starting from this value) */ - ADD_PREDEFINED_MACRO(wxID_FILEDLGG); - - ADD_PREDEFINED_MACRO(wxID_HIGHEST); - + /* no id matches this one when compared to it */ + ADD_PREDEFINED_MACRO(wxID_NONE); + + /* id for a separator line in the menu (invalid for normal item) */ + ADD_PREDEFINED_MACRO(wxID_SEPARATOR); + + ADD_PREDEFINED_MACRO(wxID_ANY); + + ADD_PREDEFINED_MACRO(wxID_LOWEST); + + ADD_PREDEFINED_MACRO(wxID_OPEN); + ADD_PREDEFINED_MACRO(wxID_CLOSE); + ADD_PREDEFINED_MACRO(wxID_NEW); + ADD_PREDEFINED_MACRO(wxID_SAVE); + ADD_PREDEFINED_MACRO(wxID_SAVEAS); + ADD_PREDEFINED_MACRO(wxID_REVERT); + ADD_PREDEFINED_MACRO(wxID_EXIT); + ADD_PREDEFINED_MACRO(wxID_UNDO); + ADD_PREDEFINED_MACRO(wxID_REDO); + ADD_PREDEFINED_MACRO(wxID_HELP); + ADD_PREDEFINED_MACRO(wxID_PRINT); + ADD_PREDEFINED_MACRO(wxID_PRINT_SETUP); + ADD_PREDEFINED_MACRO(wxID_PREVIEW); + ADD_PREDEFINED_MACRO(wxID_ABOUT); + ADD_PREDEFINED_MACRO(wxID_HELP_CONTENTS); + ADD_PREDEFINED_MACRO(wxID_HELP_COMMANDS); + ADD_PREDEFINED_MACRO(wxID_HELP_PROCEDURES); + ADD_PREDEFINED_MACRO(wxID_HELP_CONTEXT); + ADD_PREDEFINED_MACRO(wxID_CLOSE_ALL); + ADD_PREDEFINED_MACRO(wxID_PAGE_SETUP); + ADD_PREDEFINED_MACRO(wxID_HELP_INDEX); + ADD_PREDEFINED_MACRO(wxID_HELP_SEARCH); + ADD_PREDEFINED_MACRO(wxID_PREFERENCES); + + ADD_PREDEFINED_MACRO(wxID_EDIT); + ADD_PREDEFINED_MACRO(wxID_CUT); + ADD_PREDEFINED_MACRO(wxID_COPY); + ADD_PREDEFINED_MACRO(wxID_PASTE); + ADD_PREDEFINED_MACRO(wxID_CLEAR); + ADD_PREDEFINED_MACRO(wxID_FIND); + + ADD_PREDEFINED_MACRO(wxID_DUPLICATE); + ADD_PREDEFINED_MACRO(wxID_SELECTALL); + ADD_PREDEFINED_MACRO(wxID_DELETE); + ADD_PREDEFINED_MACRO(wxID_REPLACE); + ADD_PREDEFINED_MACRO(wxID_REPLACE_ALL); + ADD_PREDEFINED_MACRO(wxID_PROPERTIES); + + ADD_PREDEFINED_MACRO(wxID_VIEW_DETAILS); + ADD_PREDEFINED_MACRO(wxID_VIEW_LARGEICONS); + ADD_PREDEFINED_MACRO(wxID_VIEW_SMALLICONS); + ADD_PREDEFINED_MACRO(wxID_VIEW_LIST); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTDATE); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTNAME); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTSIZE); + ADD_PREDEFINED_MACRO(wxID_VIEW_SORTTYPE); + + ADD_PREDEFINED_MACRO(wxID_FILE); + ADD_PREDEFINED_MACRO(wxID_FILE1); + ADD_PREDEFINED_MACRO(wxID_FILE2); + ADD_PREDEFINED_MACRO(wxID_FILE3); + ADD_PREDEFINED_MACRO(wxID_FILE4); + ADD_PREDEFINED_MACRO(wxID_FILE5); + ADD_PREDEFINED_MACRO(wxID_FILE6); + ADD_PREDEFINED_MACRO(wxID_FILE7); + ADD_PREDEFINED_MACRO(wxID_FILE8); + ADD_PREDEFINED_MACRO(wxID_FILE9); + + /* Standard button and menu IDs */ + + ADD_PREDEFINED_MACRO(wxID_OK); + ADD_PREDEFINED_MACRO(wxID_CANCEL); + + ADD_PREDEFINED_MACRO(wxID_APPLY); + ADD_PREDEFINED_MACRO(wxID_YES); + ADD_PREDEFINED_MACRO(wxID_NO); + ADD_PREDEFINED_MACRO(wxID_STATIC); + ADD_PREDEFINED_MACRO(wxID_FORWARD); + ADD_PREDEFINED_MACRO(wxID_BACKWARD); + ADD_PREDEFINED_MACRO(wxID_DEFAULT); + ADD_PREDEFINED_MACRO(wxID_MORE); + ADD_PREDEFINED_MACRO(wxID_SETUP); + ADD_PREDEFINED_MACRO(wxID_RESET); + ADD_PREDEFINED_MACRO(wxID_CONTEXT_HELP); + ADD_PREDEFINED_MACRO(wxID_YESTOALL); + ADD_PREDEFINED_MACRO(wxID_NOTOALL); + ADD_PREDEFINED_MACRO(wxID_ABORT); + ADD_PREDEFINED_MACRO(wxID_RETRY); + ADD_PREDEFINED_MACRO(wxID_IGNORE); + ADD_PREDEFINED_MACRO(wxID_ADD); + ADD_PREDEFINED_MACRO(wxID_REMOVE); + + ADD_PREDEFINED_MACRO(wxID_UP); + ADD_PREDEFINED_MACRO(wxID_DOWN); + ADD_PREDEFINED_MACRO(wxID_HOME); + ADD_PREDEFINED_MACRO(wxID_REFRESH); + ADD_PREDEFINED_MACRO(wxID_STOP); + ADD_PREDEFINED_MACRO(wxID_INDEX); + + ADD_PREDEFINED_MACRO(wxID_BOLD); + ADD_PREDEFINED_MACRO(wxID_ITALIC); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_CENTER); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_FILL); + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_RIGHT); + + ADD_PREDEFINED_MACRO(wxID_JUSTIFY_LEFT); + ADD_PREDEFINED_MACRO(wxID_UNDERLINE); + ADD_PREDEFINED_MACRO(wxID_INDENT); + ADD_PREDEFINED_MACRO(wxID_UNINDENT); + ADD_PREDEFINED_MACRO(wxID_ZOOM_100); + ADD_PREDEFINED_MACRO(wxID_ZOOM_FIT); + ADD_PREDEFINED_MACRO(wxID_ZOOM_IN); + ADD_PREDEFINED_MACRO(wxID_ZOOM_OUT); + ADD_PREDEFINED_MACRO(wxID_UNDELETE); + ADD_PREDEFINED_MACRO(wxID_REVERT_TO_SAVED); + + /* System menu IDs (used by wxUniv): */ + ADD_PREDEFINED_MACRO(wxID_SYSTEM_MENU); + ADD_PREDEFINED_MACRO(wxID_CLOSE_FRAME); + ADD_PREDEFINED_MACRO(wxID_MOVE_FRAME); + ADD_PREDEFINED_MACRO(wxID_RESIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_MAXIMIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_ICONIZE_FRAME); + ADD_PREDEFINED_MACRO(wxID_RESTORE_FRAME); + + /* IDs used by generic file dialog (13 consecutive starting from this value) */ + ADD_PREDEFINED_MACRO(wxID_FILEDLGG); + + ADD_PREDEFINED_MACRO(wxID_HIGHEST); } diff --git a/src/codegen/phpcg.h b/src/codegen/phpcg.h index c15bf569f..833c6e9d9 100644 --- a/src/codegen/phpcg.h +++ b/src/codegen/phpcg.h @@ -31,7 +31,8 @@ @author Michal Bližňák - michal.bliznak@gmail.com @note The implementation of the generation of relative paths is a little hacky, and not a solution. -The value of all properties that are file or a directory paths must be absolute, otherwise the code generation will not work. +The value of all properties that are file or a directory paths must be absolute, otherwise the code generation will not +work. */ #ifndef CODEGEN_PHPCG_H @@ -41,201 +42,203 @@ The value of all properties that are file or a directory paths must be absolute, #define fbfSILENT true #define fbfMESSAGE false -#include "codegen/codegen.h" - #include #include +#include "codegen/codegen.h" + + /** -* Parse the PHP templates. -*/ + * Parse the PHP templates. + */ class PHPTemplateParser : public TemplateParser { private: - bool m_i18n; - bool m_useRelativePath; - wxString m_basePath; + bool m_i18n; + bool m_useRelativePath; + wxString m_basePath; public: - PHPTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath ); - PHPTemplateParser( const PHPTemplateParser & that, wxString _template ); + PHPTemplateParser(PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath); + PHPTemplateParser(const PHPTemplateParser& that, wxString _template); - // overrides for PHP - PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; - wxString RootWxParentToCode() override; - wxString ValueToCode(PropertyType type, wxString value) override; + // overrides for PHP + PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; + wxString RootWxParentToCode() override; + wxString ValueToCode(PropertyType type, wxString value) override; }; /** -* Generate the PHP code -*/ + * Generate the PHP code + */ class PHPCodeGenerator : public CodeGenerator { private: - PCodeWriter m_source; - - bool m_useRelativePath; - bool m_i18n; - wxString m_basePath; - unsigned int m_firstID; - bool m_disconnectEvents; - wxString m_disconnecMode; - - /** - * Predefined macros won't generate defines. - */ - std::set m_predMacros; - - void SetupPredefinedMacros(); - - /** - * Given an object and the name for a template, obtains the code. - */ - wxString GetCode( PObjectBase obj, wxString name, bool silent = false); - - /** - * Gets the construction fragment for the specified object. - * - * This method encapsulates the adjustments that need to be made for array declarations. - */ - wxString GetConstruction(PObjectBase obj, ArrayItems& arrays); - - /** - * Stores the project's objects classes set, for generating the includes. - */ - void FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ); - - /** - * Stores all the properties for "macro" type objects, so that their - * related '#define' can be generated subsequently. - */ - void FindMacros( PObjectBase obj, std::vector< wxString >* macros ); - - /** - * Looks for "non-null" event handlers (PEvent) and collects it into a vector. - */ - void FindEventHandlers(PObjectBase obj, EventVector &events); - - /** - * Generates classes declarations inside the header file. - */ - void GenClassDeclaration(PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, const wxString& eventHandlerPostfix, ArrayItems& arrays); - - /** - * Generates the event table. - */ - void GenEvents( PObjectBase class_obj, const EventVector &events, bool disconnect = false ); - - /** - * helper function to find the event table entry template in the class or its base classes - */ - bool GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect = false ); - - /** - * Generates the generated_event_handlers template - */ - void GetGenEventHandlers( PObjectBase obj ); - /** - * Generates the generated_event_handlers template - */ - void GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ); - - /** - * Generates the 'import' section for files. - */ - void GenIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ); - void AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ); - - /** - * Generate a set of all subclasses to forward declare in the generated file. - */ - void GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::vector< wxString >* headerIncludes ); - - /** - * Generates the '#define' section for macros. - */ - void GenDefines( PObjectBase project); - - /** - * Generates the constructor for a class - */ - void GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays); - - /** - * Generates the destructor for a class - */ - void GenDestructor( PObjectBase class_obj, const EventVector &events ); - - /** - * Makes the objects construction, setting up the objects' and Layout properties. - * The algorithm is similar to that used in the designer preview generation. - */ - void GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays); - - /** - * Makes the objects destructions. - */ - void GenDestruction( PObjectBase obj); - - /** - * Configures the object properties, both own and inherited ones. - * Information for the class is given, because it will recursively make the - * configuration in the "super-classes". - */ - void GenSettings( PObjectInfo info, PObjectBase obj); - - /** - * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where - * the template is found, and the objectbase for the control. - */ - void GenAddToolbar( PObjectInfo info, PObjectBase obj ); - void GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ); - - void GenVirtualEventHandlers( const EventVector &events, const wxString& eventHandlerPostfix ); + PCodeWriter m_source; + + bool m_useRelativePath; + bool m_i18n; + wxString m_basePath; + unsigned int m_firstID; + bool m_disconnectEvents; + wxString m_disconnecMode; + + /** + * Predefined macros won't generate defines. + */ + std::set m_predMacros; + + void SetupPredefinedMacros(); + + /** + * Given an object and the name for a template, obtains the code. + */ + wxString GetCode(PObjectBase obj, wxString name, bool silent = false); + + /** + * Gets the construction fragment for the specified object. + * + * This method encapsulates the adjustments that need to be made for array declarations. + */ + wxString GetConstruction(PObjectBase obj, ArrayItems& arrays); + + /** + * Stores the project's objects classes set, for generating the includes. + */ + void FindDependencies(PObjectBase obj, std::set& info_set); + + /** + * Stores all the properties for "macro" type objects, so that their + * related '#define' can be generated subsequently. + */ + void FindMacros(PObjectBase obj, std::vector* macros); + + /** + * Looks for "non-null" event handlers (PEvent) and collects it into a vector. + */ + void FindEventHandlers(PObjectBase obj, EventVector& events); + + /** + * Generates classes declarations inside the header file. + */ + void GenClassDeclaration( + PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, + const wxString& eventHandlerPostfix, ArrayItems& arrays); + + /** + * Generates the event table. + */ + void GenEvents(PObjectBase class_obj, const EventVector& events, bool disconnect = false); + + /** + * helper function to find the event table entry template in the class or its base classes + */ + bool GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + bool disconnect = false); + + /** + * Generates the generated_event_handlers template + */ + void GetGenEventHandlers(PObjectBase obj); + /** + * Generates the generated_event_handlers template + */ + void GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj); + + /** + * Generates the 'import' section for files. + */ + void GenIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenObjectIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates); + void AddUniqueIncludes(const wxString& include, std::vector* includes); + + /** + * Generate a set of all subclasses to forward declare in the generated file. + */ + void GenSubclassSets(PObjectBase obj, std::set* subclasses, std::vector* headerIncludes); + + /** + * Generates the '#define' section for macros. + */ + void GenDefines(PObjectBase project); + + /** + * Generates the constructor for a class + */ + void GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays); + + /** + * Generates the destructor for a class + */ + void GenDestructor(PObjectBase class_obj, const EventVector& events); + + /** + * Makes the objects construction, setting up the objects' and Layout properties. + * The algorithm is similar to that used in the designer preview generation. + */ + void GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays); + + /** + * Makes the objects destructions. + */ + void GenDestruction(PObjectBase obj); + + /** + * Configures the object properties, both own and inherited ones. + * Information for the class is given, because it will recursively make the + * configuration in the "super-classes". + */ + void GenSettings(PObjectInfo info, PObjectBase obj); + + /** + * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where + * the template is found, and the objectbase for the control. + */ + void GenAddToolbar(PObjectInfo info, PObjectBase obj); + void GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines); + + void GenVirtualEventHandlers(const EventVector& events, const wxString& eventHandlerPostfix); public: - /** - * Convert a wxString to the "C/C++" format. - */ - static wxString ConvertPHPString( wxString text); - - PHPCodeGenerator(); - - /** - * Set the codewriter for the source file - */ - void SetSourceWriter( PCodeWriter cw ) - { - m_source = cw; - } - - - /** - * Configures the reference path for generating relative paths to - * that passed as parameter. - * - * @note path is generated with the separators, '/', since on Windows - * the compilers interpret path correctly. - */ - void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); - - /** - * Set the First ID used during Code Generation. - */ - void SetFirstID( const unsigned int id ){ m_firstID = id; } - - /** - * Generate the project's code - */ - bool GenerateCode(PObjectBase project) override; - - /** - * Generate an inherited class - */ - void GenerateInheritedClass( PObjectBase userClasses, PObjectBase form ); + /** + * Convert a wxString to the "C/C++" format. + */ + static wxString ConvertPHPString(wxString text); + + PHPCodeGenerator(); + + /** + * Set the codewriter for the source file + */ + void SetSourceWriter(PCodeWriter cw) { m_source = cw; } + + + /** + * Configures the reference path for generating relative paths to + * that passed as parameter. + * + * @note path is generated with the separators, '/', since on Windows + * the compilers interpret path correctly. + */ + void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); + + /** + * Set the First ID used during Code Generation. + */ + void SetFirstID(const unsigned int id) { m_firstID = id; } + + /** + * Generate the project's code + */ + bool GenerateCode(PObjectBase project) override; + + /** + * Generate an inherited class + */ + void GenerateInheritedClass(PObjectBase userClasses, PObjectBase form); }; - -#endif // CODEGEN_PHPCG_H +#endif // CODEGEN_PHPCG_H diff --git a/src/codegen/pythoncg.cpp b/src/codegen/pythoncg.cpp index 065d6294b..1b35c1765 100644 --- a/src/codegen/pythoncg.cpp +++ b/src/codegen/pythoncg.cpp @@ -28,6 +28,12 @@ #include "pythoncg.h" +#include + +#include +#include + +#include "codegen/codewriter.h" #include "model/objectbase.h" #include "rad/appdata.h" #include "rad/revision.h" @@ -35,1547 +41,1341 @@ #include "utils/debug.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "codegen/codewriter.h" -#include - -#include -#include -PythonTemplateParser::PythonTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, wxString imagePathWrapperFunctionName ) -: -TemplateParser(obj,_template), -m_i18n( useI18N ), -m_useRelativePath( useRelativePath ), -m_basePath( basePath ), -m_imagePathWrapperFunctionName ( imagePathWrapperFunctionName ) +PythonTemplateParser::PythonTemplateParser( + PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, + wxString imagePathWrapperFunctionName) : + TemplateParser(obj, _template), + m_i18n(useI18N), + m_useRelativePath(useRelativePath), + m_basePath(basePath), + m_imagePathWrapperFunctionName(imagePathWrapperFunctionName) { - if ( !wxFileName::DirExists( m_basePath ) ) - { - m_basePath.clear(); - } + if (!wxFileName::DirExists(m_basePath)) { + m_basePath.clear(); + } - SetupModulePrefixes(); + SetupModulePrefixes(); } -PythonTemplateParser::PythonTemplateParser( const PythonTemplateParser & that, wxString _template ) -: -TemplateParser( that, _template ), -m_i18n( that.m_i18n ), -m_useRelativePath( that.m_useRelativePath ), -m_basePath( that.m_basePath ), -m_imagePathWrapperFunctionName( that.m_imagePathWrapperFunctionName ) +PythonTemplateParser::PythonTemplateParser(const PythonTemplateParser& that, wxString _template) : + TemplateParser(that, _template), + m_i18n(that.m_i18n), + m_useRelativePath(that.m_useRelativePath), + m_basePath(that.m_basePath), + m_imagePathWrapperFunctionName(that.m_imagePathWrapperFunctionName) { - SetupModulePrefixes(); + SetupModulePrefixes(); } wxString PythonTemplateParser::RootWxParentToCode() { - return wxT("self"); + return wxT("self"); } -PTemplateParser PythonTemplateParser::CreateParser( const TemplateParser* oldparser, wxString _template ) +PTemplateParser PythonTemplateParser::CreateParser(const TemplateParser* oldparser, wxString _template) { - const PythonTemplateParser* pythonOldParser = dynamic_cast< const PythonTemplateParser* >( oldparser ); - if (pythonOldParser) - { - PTemplateParser newparser( new PythonTemplateParser( *pythonOldParser, _template ) ); - return newparser; - } - return PTemplateParser(); + const PythonTemplateParser* pythonOldParser = dynamic_cast(oldparser); + if (pythonOldParser) { + PTemplateParser newparser(new PythonTemplateParser(*pythonOldParser, _template)); + return newparser; + } + return PTemplateParser(); } /** -* Convert the value of the property to Python code -*/ -wxString PythonTemplateParser::ValueToCode( PropertyType type, wxString value ) + * Convert the value of the property to Python code + */ +wxString PythonTemplateParser::ValueToCode(PropertyType type, wxString value) { - wxString result; - - switch ( type ) - { - case PT_WXPARENT: - { - result = wxT("self.") + value; - break; - } - case PT_WXPARENT_SB: - { - result = value + wxT(".GetStaticBox()"); - break; - } - case PT_WXPARENT_CP: - { - result = wxT("self.") + value + wxT(".GetPane()"); - break; - } - case PT_WXSTRING: - case PT_FILE: - case PT_PATH: - { - if ( value.empty() ) - { - result << wxT("wx.EmptyString"); - } - else - { - result << wxT("u\"") << PythonCodeGenerator::ConvertPythonString( value ) << wxT("\""); - } - break; - } - case PT_WXSTRING_I18N: - { - if ( value.empty() ) - { - result << wxT("wx.EmptyString"); - } - else - { - if ( m_i18n ) - { - result << wxT("_(u\"") << PythonCodeGenerator::ConvertPythonString(value) << wxT("\")"); - } - else - { - result << wxT("u\"") << PythonCodeGenerator::ConvertPythonString(value) << wxT("\""); - } - } - break; - } - case PT_CLASS: - case PT_MACRO: - case PT_OPTION: - case PT_EDIT_OPTION: - { - result = value; - wxString pred = m_predModulePrefix[value]; - - if( !pred.empty() ) result.Replace( wxT("wx"), pred ); - else - { - if( result.StartsWith( wxT("XRCID") ) ) - result.Prepend( wxT("wx.xrc.") ); - else - result.Replace( wxT("wx"), wxT("wx.") ); - } - - break; - } - case PT_TEXT: - case PT_FLOAT: - case PT_INT: - case PT_UINT: - { - result = value; - break; - } - case PT_BITLIST: - { - result = ( value.empty() ? wxT("0") : value ); - - wxString pred, bit; - wxStringTokenizer bits( result, wxT("|"), wxTOKEN_STRTOK ); - - while( bits.HasMoreTokens() ) - { - bit = bits.GetNextToken(); - pred = m_predModulePrefix[bit]; - - if( bit.Contains( wxT("wx") ) ) - { - if( !pred.empty() ) result.Replace( bit, pred + bit.AfterFirst('x') ); - else - result.Replace( bit, wxT("wx.") + bit.AfterFirst('x') ); - } - } - break; - } - case PT_WXPOINT: - { - if ( value.empty() ) - { - result = wxT("wx.DefaultPosition"); - } - else - { - result << wxT("wx.Point( ") << value << wxT(" )"); - } - break; - } - case PT_WXSIZE: - { - if ( value.empty() ) - { - result = wxT("wx.DefaultSize"); - } - else - { - result << wxT("wx.Size( ") << value << wxT(" )"); - } - break; - } - case PT_BOOL: - { - result = ( value == wxT("0") ? wxT("False") : wxT("True") ); - break; - } - case PT_WXFONT: - { - if ( !value.empty() ) - { - wxFontContainer fontContainer = TypeConv::StringToFont( value ); - wxFont font = fontContainer.GetFont(); - - const int pointSize = fontContainer.GetPointSize(); - - result = wxString::Format( "wx.Font( %s, %s, %s, %s, %s, %s )", - ((pointSize <= 0) ? "wx.NORMAL_FONT.GetPointSize()" : (wxString() << pointSize)), - TypeConv::FontFamilyToString( fontContainer.GetFamily() ).replace( 0, 2, "wx." ), - font.GetStyleString().replace( 0, 2, "wx." ), - font.GetWeightString().replace( 0, 2, "wx." ), - ( fontContainer.GetUnderlined() ? "True" : "False" ), - ( fontContainer.m_faceName.empty() ? "wx.EmptyString" : ("\"" + fontContainer.m_faceName + "\"") ) - ); - } - else - { - result = wxT("wx.NORMAL_FONT"); - } - break; - } - case PT_WXCOLOUR: - { - if ( !value.empty() ) - { - if ( value.find_first_of( wxT("wx") ) == 0 ) - { - // System Colour - result << wxT("wx.SystemSettings.GetColour( ") << ValueToCode( PT_OPTION, value ) << wxT(" )"); - } - else - { - wxColour colour = TypeConv::StringToColour( value ); - result = wxString::Format( wxT("wx.Colour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue() ); - } - } - else - { - result = wxT("wx.Colour()"); - } - break; - } - case PT_BITMAP: - { - wxString path; - wxString source; - wxSize icoSize; - TypeConv::ParseBitmapWithResource( value, &path, &source, &icoSize ); - - if ( path.empty() ) - { - // Empty path, generate Null Bitmap - result = wxT("wx.NullBitmap"); - break; - } - - if ( path.StartsWith( wxT("file:") ) ) - { - wxLogWarning( wxT("Python code generation does not support using URLs for bitmap properties:\n%s"), path ); - result = wxT("wx.NullBitmap"); - break; - } - - if ( source == _("Load From File") || source == _("Load From Embedded File")) - { - wxString absPath; - try - { - absPath = TypeConv::MakeAbsolutePath( path, AppData()->GetProjectPath() ); - } - catch( wxFBException& ex ) - { - wxLogError( ex.what() ); - result = wxT( "wx.NullBitmap" ); - break; - } - - wxString file = ( m_useRelativePath ? TypeConv::MakeRelativePath( absPath, m_basePath ) : absPath ); - - result << wxT("wx.Bitmap( "); - if ( !m_imagePathWrapperFunctionName.empty() ) - { - result << wxT( "self." ) << m_imagePathWrapperFunctionName << wxT( "( "); - } - result << wxT( "u\"") << PythonCodeGenerator::ConvertPythonString( file ) << wxT( "\"" ); - if ( !m_imagePathWrapperFunctionName.empty() ) - { - result << wxT( " )"); - } - result << wxT( ", wx.BITMAP_TYPE_ANY )"); - - } - else if ( source == _("Load From Resource") ) - { - result << wxT("wx.Bitmap( u\"") << path << wxT("\", wx.BITMAP_TYPE_RESOURCE )"); - } - else if ( source == _("Load From Icon Resource") ) - { - if ( wxDefaultSize == icoSize ) - { - result << wxT("wx.ICON( ") << path << wxT(" )"); - } - else - { - result.Printf( wxT("wx.Icon( u\"%s\", wx.BITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, icoSize.GetWidth(), icoSize.GetHeight() ); - } - } - else if (source == _("Load From XRC")) - { - // NOTE: The module wx.xrc is part of the default code template - result << wxT("wx.xrc.XmlResource.Get().LoadBitmap( u\"") << path << wxT("\" )"); - } - else if ( source == _("Load From Art Provider") ) - { - wxString rid = path.BeforeFirst( wxT(':') ); - - if( rid.StartsWith( wxT("gtk-") ) ) - { - rid = wxT("u\"") + rid + wxT("\""); - } - else - rid.Replace( wxT("wx"), wxT("wx.") ); - - wxString cid = path.AfterFirst( wxT(':') ); - cid.Replace( wxT("wx"), wxT("wx.") ); - - result = wxT("wx.ArtProvider.GetBitmap( ") + rid + wxT(", ") + cid + wxT(" )"); - } - break; - } - case PT_STRINGLIST: - { - // Stringlists are generated like a sequence of wxString separated by ', '. - wxArrayString array = TypeConv::StringToArrayString( value ); - if ( array.Count() > 0 ) - { - result = ValueToCode( PT_WXSTRING_I18N, array[0] ); - } - - for ( size_t i = 1; i < array.Count(); i++ ) - { - result << wxT(", ") << ValueToCode( PT_WXSTRING_I18N, array[i] ); - } - break; - } - default: - break; - } - - return result; + wxString result; + + switch (type) { + case PT_WXPARENT: { + result = wxT("self.") + value; + break; + } + case PT_WXPARENT_SB: { + result = value + wxT(".GetStaticBox()"); + break; + } + case PT_WXPARENT_CP: { + result = wxT("self.") + value + wxT(".GetPane()"); + break; + } + case PT_WXSTRING: + case PT_FILE: + case PT_PATH: { + if (value.empty()) { + result << wxT("wx.EmptyString"); + } else { + result << wxT("u\"") << PythonCodeGenerator::ConvertPythonString(value) << wxT("\""); + } + break; + } + case PT_WXSTRING_I18N: { + if (value.empty()) { + result << wxT("wx.EmptyString"); + } else { + if (m_i18n) { + result << wxT("_(u\"") << PythonCodeGenerator::ConvertPythonString(value) << wxT("\")"); + } else { + result << wxT("u\"") << PythonCodeGenerator::ConvertPythonString(value) << wxT("\""); + } + } + break; + } + case PT_CLASS: + case PT_MACRO: + case PT_OPTION: + case PT_EDIT_OPTION: { + result = value; + wxString pred = m_predModulePrefix[value]; + + if (!pred.empty()) + result.Replace(wxT("wx"), pred); + else { + if (result.StartsWith(wxT("XRCID"))) + result.Prepend(wxT("wx.xrc.")); + else + result.Replace(wxT("wx"), wxT("wx.")); + } + + break; + } + case PT_TEXT: + case PT_FLOAT: + case PT_INT: + case PT_UINT: { + result = value; + break; + } + case PT_BITLIST: { + result = (value.empty() ? wxT("0") : value); + + wxString pred, bit; + wxStringTokenizer bits(result, wxT("|"), wxTOKEN_STRTOK); + + while (bits.HasMoreTokens()) { + bit = bits.GetNextToken(); + pred = m_predModulePrefix[bit]; + + if (bit.Contains(wxT("wx"))) { + if (!pred.empty()) + result.Replace(bit, pred + bit.AfterFirst('x')); + else + result.Replace(bit, wxT("wx.") + bit.AfterFirst('x')); + } + } + break; + } + case PT_WXPOINT: { + if (value.empty()) { + result = wxT("wx.DefaultPosition"); + } else { + result << wxT("wx.Point( ") << value << wxT(" )"); + } + break; + } + case PT_WXSIZE: { + if (value.empty()) { + result = wxT("wx.DefaultSize"); + } else { + result << wxT("wx.Size( ") << value << wxT(" )"); + } + break; + } + case PT_BOOL: { + result = (value == wxT("0") ? wxT("False") : wxT("True")); + break; + } + case PT_WXFONT: { + if (!value.empty()) { + wxFontContainer fontContainer = TypeConv::StringToFont(value); + wxFont font = fontContainer.GetFont(); + + const int pointSize = fontContainer.GetPointSize(); + + result = wxString::Format( + "wx.Font( %s, %s, %s, %s, %s, %s )", + ((pointSize <= 0) ? "wx.NORMAL_FONT.GetPointSize()" : (wxString() << pointSize)), + TypeConv::FontFamilyToString(fontContainer.GetFamily()).replace(0, 2, "wx."), + font.GetStyleString().replace(0, 2, "wx."), font.GetWeightString().replace(0, 2, "wx."), + (fontContainer.GetUnderlined() ? "True" : "False"), + (fontContainer.m_faceName.empty() ? "wx.EmptyString" : ("\"" + fontContainer.m_faceName + "\""))); + } else { + result = wxT("wx.NORMAL_FONT"); + } + break; + } + case PT_WXCOLOUR: { + if (!value.empty()) { + if (value.find_first_of(wxT("wx")) == 0) { + // System Colour + result << wxT("wx.SystemSettings.GetColour( ") << ValueToCode(PT_OPTION, value) << wxT(" )"); + } else { + wxColour colour = TypeConv::StringToColour(value); + result = + wxString::Format(wxT("wx.Colour( %i, %i, %i )"), colour.Red(), colour.Green(), colour.Blue()); + } + } else { + result = wxT("wx.Colour()"); + } + break; + } + case PT_BITMAP: { + wxString path; + wxString source; + wxSize icoSize; + TypeConv::ParseBitmapWithResource(value, &path, &source, &icoSize); + + if (path.empty()) { + // Empty path, generate Null Bitmap + result = wxT("wx.NullBitmap"); + break; + } + + if (path.StartsWith(wxT("file:"))) { + wxLogWarning( + wxT("Python code generation does not support using URLs for bitmap properties:\n%s"), path); + result = wxT("wx.NullBitmap"); + break; + } + + if (source == _("Load From File") || source == _("Load From Embedded File")) { + wxString absPath; + try { + absPath = TypeConv::MakeAbsolutePath(path, AppData()->GetProjectPath()); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + result = wxT("wx.NullBitmap"); + break; + } + + wxString file = (m_useRelativePath ? TypeConv::MakeRelativePath(absPath, m_basePath) : absPath); + + result << wxT("wx.Bitmap( "); + if (!m_imagePathWrapperFunctionName.empty()) { + result << wxT("self.") << m_imagePathWrapperFunctionName << wxT("( "); + } + result << wxT("u\"") << PythonCodeGenerator::ConvertPythonString(file) << wxT("\""); + if (!m_imagePathWrapperFunctionName.empty()) { + result << wxT(" )"); + } + result << wxT(", wx.BITMAP_TYPE_ANY )"); + + } else if (source == _("Load From Resource")) { + result << wxT("wx.Bitmap( u\"") << path << wxT("\", wx.BITMAP_TYPE_RESOURCE )"); + } else if (source == _("Load From Icon Resource")) { + if (wxDefaultSize == icoSize) { + result << wxT("wx.ICON( ") << path << wxT(" )"); + } else { + result.Printf( + wxT("wx.Icon( u\"%s\", wx.BITMAP_TYPE_ICO_RESOURCE, %i, %i )"), path, icoSize.GetWidth(), + icoSize.GetHeight()); + } + } else if (source == _("Load From XRC")) { + // NOTE: The module wx.xrc is part of the default code template + result << wxT("wx.xrc.XmlResource.Get().LoadBitmap( u\"") << path << wxT("\" )"); + } else if (source == _("Load From Art Provider")) { + wxString rid = path.BeforeFirst(wxT(':')); + + if (rid.StartsWith(wxT("gtk-"))) { + rid = wxT("u\"") + rid + wxT("\""); + } else + rid.Replace(wxT("wx"), wxT("wx.")); + + wxString cid = path.AfterFirst(wxT(':')); + cid.Replace(wxT("wx"), wxT("wx.")); + + result = wxT("wx.ArtProvider.GetBitmap( ") + rid + wxT(", ") + cid + wxT(" )"); + } + break; + } + case PT_STRINGLIST: { + // Stringlists are generated like a sequence of wxString separated by ', '. + wxArrayString array = TypeConv::StringToArrayString(value); + if (array.Count() > 0) { + result = ValueToCode(PT_WXSTRING_I18N, array[0]); + } + + for (size_t i = 1; i < array.Count(); i++) { + result << wxT(", ") << ValueToCode(PT_WXSTRING_I18N, array[i]); + } + break; + } + default: + break; + } + + return result; } /////////////////////////////////////////////////////////////////////////////// PythonCodeGenerator::PythonCodeGenerator() { - SetupPredefinedMacros(); - m_useRelativePath = false; - m_i18n = false; - m_firstID = 1000; + SetupPredefinedMacros(); + m_useRelativePath = false; + m_i18n = false; + m_firstID = 1000; } -wxString PythonCodeGenerator::ConvertPythonString( wxString text ) +wxString PythonCodeGenerator::ConvertPythonString(wxString text) { - wxString result; - - for ( size_t i = 0; i < text.length(); i++ ) - { - wxChar c = text[i]; - - switch ( c ) - { - case wxT('"'): - result += wxT("\\\""); - break; - - case wxT('\\'): - result += wxT("\\\\"); - break; - - case wxT('\t'): - result += wxT("\\t"); - break; - - case wxT('\n'): - result += wxT("\\n"); - break; - - case wxT('\r'): - result += wxT("\\r"); - break; - - default: - result += c; - break; - } - } - return result; + wxString result; + + for (size_t i = 0; i < text.length(); i++) { + wxChar c = text[i]; + + switch (c) { + case wxT('"'): + result += wxT("\\\""); + break; + + case wxT('\\'): + result += wxT("\\\\"); + break; + + case wxT('\t'): + result += wxT("\\t"); + break; + + case wxT('\n'): + result += wxT("\\n"); + break; + + case wxT('\r'): + result += wxT("\\r"); + break; + + default: + result += c; + break; + } + } + return result; } -void PythonCodeGenerator::GenerateInheritedClass( PObjectBase userClasses, PObjectBase form ) +void PythonCodeGenerator::GenerateInheritedClass(PObjectBase userClasses, PObjectBase form) { - if (!userClasses) - { - wxLogError(wxT("There is no object to generate inherited class")); - return; - } - - if ( wxT("UserClasses") != userClasses->GetClassName() ) - { - wxLogError(wxT("This not a UserClasses object")); - return; - } - - wxString type = userClasses->GetPropertyAsString( wxT("type") ); - - // Start file - wxString code = GetCode( userClasses, wxT("file_comment") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, wxT("source_include") ); - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - - code = GetCode( userClasses, wxT("class_decl") ); - m_source->WriteLn( code ); - m_source->Indent(); - - code = GetCode( userClasses, type + wxT("_cons_def") ); - m_source->WriteLn( code ); - - // Do events - EventVector events; - FindEventHandlers( form, events ); - - if ( events.size() > 0 ) - { - code = GetCode( userClasses, wxT("event_handler_comment") ); - m_source->WriteLn( code ); - - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - if ( generatedHandlers.find( event->GetValue() ) == generatedHandlers.end() ) - { - m_source->WriteLn( wxString::Format( wxT("def %s( self, event ):"), event->GetValue() ) ); - m_source->Indent(); - m_source->WriteLn( wxString::Format( wxT("# TODO: Implement %s"), event->GetValue() ) ); - m_source->WriteLn( wxT("pass") ); - m_source->Unindent(); - m_source->WriteLn( wxEmptyString ); - generatedHandlers.insert(event->GetValue()); - } - } - m_source->WriteLn( wxEmptyString ); - } - - m_source->Unindent(); + if (!userClasses) { + wxLogError(wxT("There is no object to generate inherited class")); + return; + } + + if (wxT("UserClasses") != userClasses->GetClassName()) { + wxLogError(wxT("This not a UserClasses object")); + return; + } + + wxString type = userClasses->GetPropertyAsString(wxT("type")); + + // Start file + wxString code = GetCode(userClasses, wxT("file_comment")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + code = GetCode(userClasses, wxT("source_include")); + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + + code = GetCode(userClasses, wxT("class_decl")); + m_source->WriteLn(code); + m_source->Indent(); + + code = GetCode(userClasses, type + wxT("_cons_def")); + m_source->WriteLn(code); + + // Do events + EventVector events; + FindEventHandlers(form, events); + + if (events.size() > 0) { + code = GetCode(userClasses, wxT("event_handler_comment")); + m_source->WriteLn(code); + + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + if (generatedHandlers.find(event->GetValue()) == generatedHandlers.end()) { + m_source->WriteLn(wxString::Format(wxT("def %s( self, event ):"), event->GetValue())); + m_source->Indent(); + m_source->WriteLn(wxString::Format(wxT("# TODO: Implement %s"), event->GetValue())); + m_source->WriteLn(wxT("pass")); + m_source->Unindent(); + m_source->WriteLn(wxEmptyString); + generatedHandlers.insert(event->GetValue()); + } + } + m_source->WriteLn(wxEmptyString); + } + + m_source->Unindent(); } -bool PythonCodeGenerator::GenerateCode( PObjectBase project ) +bool PythonCodeGenerator::GenerateCode(PObjectBase project) { - if (!project) - { - wxLogError(wxT("There is no project to generate code")); - return false; - } - - m_i18n = false; - PProperty i18nProperty = project->GetProperty( wxT("internationalize") ); - if (i18nProperty && i18nProperty->GetValueAsInteger()) - m_i18n = true; - - m_disconnectEvents = ( project->GetPropertyAsInteger( wxT("disconnect_python_events") ) != 0 ); - - m_source->Clear(); - - // Insert python preamble - - wxString code = GetCode( project, wxT("python_preamble") ); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - m_source->WriteLn( wxEmptyString ); - } - - code = wxString::Format( - wxT("###########################################################################\n") - wxT("## Python code generated with wxFormBuilder (version %s%s)\n") - wxT("## http://www.wxformbuilder.org/\n") - wxT("##\n") - wxT("## PLEASE DO *NOT* EDIT THIS FILE!\n") - wxT("###########################################################################\n"), - getVersion(), getPostfixRevision(getVersion()).c_str() - ); - - m_source->WriteLn( code ); - - - PProperty propFile = project->GetProperty( wxT("file") ); - if (!propFile) - { - wxLogError( wxT("Missing \"file\" property on Project Object") ); - return false; - } - - wxString file = propFile->GetValue(); - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Generate the subclass sets - std::set< wxString > subclasses; - std::vector< wxString > headerIncludes; - - GenSubclassSets( project, &subclasses, &headerIncludes ); - - // Generating in the .h header file those include from components dependencies. - std::set< wxString > templates; - GenIncludes(project, &headerIncludes, &templates ); - - // Write the include lines - std::vector::iterator include_it; - for ( include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it ) - { - m_source->WriteLn( *include_it ); - } - if ( !headerIncludes.empty() ) - { - m_source->WriteLn(wxEmptyString); - } - - // Write internationalization support - if( m_i18n ) - { - m_source->WriteLn( wxT("import gettext") ); - m_source->WriteLn( wxT("_ = gettext.gettext") ); - m_source->WriteLn(wxEmptyString); - } - - // Generating "defines" for macros - GenDefines( project ); - - wxString eventHandlerPostfix; - PProperty eventKindProp = project->GetProperty( wxT("skip_python_events") ); - if( eventKindProp->GetValueAsInteger() ) - { - eventHandlerPostfix = wxT("event.Skip()"); - } - else - eventHandlerPostfix = wxT("pass"); - - PProperty disconnectMode = project->GetProperty( wxT("disconnect_mode") ); - m_disconnecMode = disconnectMode->GetValueAsString(); - - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - PObjectBase child = project->GetChild( i ); - - // Preprocess to find arrays - ArrayItems arrays; - FindArrayObjects(child, arrays, true); - - EventVector events; - FindEventHandlers( child, events ); - //GenClassDeclaration( child, useEnum, classDecoration, events, eventHandlerPrefix, eventHandlerPostfix ); - GenClassDeclaration(child, false, wxEmptyString, events, eventHandlerPostfix, arrays); - } - - code = GetCode( project, wxT("python_epilogue") ); - if( !code.empty() ) m_source->WriteLn( code ); - - return true; + if (!project) { + wxLogError(wxT("There is no project to generate code")); + return false; + } + + m_i18n = false; + PProperty i18nProperty = project->GetProperty(wxT("internationalize")); + if (i18nProperty && i18nProperty->GetValueAsInteger()) + m_i18n = true; + + m_disconnectEvents = (project->GetPropertyAsInteger(wxT("disconnect_python_events")) != 0); + + m_source->Clear(); + + // Insert python preamble + + wxString code = GetCode(project, wxT("python_preamble")); + if (!code.empty()) { + m_source->WriteLn(code); + m_source->WriteLn(wxEmptyString); + } + + code = wxString::Format( + wxT("###########################################################################\n") + wxT("## Python code generated with wxFormBuilder (version %s%s)\n") wxT("## http://www.wxformbuilder.org/\n") + wxT("##\n") wxT("## PLEASE DO *NOT* EDIT THIS FILE!\n") + wxT("###########################################################################\n"), + getVersion(), getPostfixRevision(getVersion()).c_str()); + + m_source->WriteLn(code); + + + PProperty propFile = project->GetProperty(wxT("file")); + if (!propFile) { + wxLogError(wxT("Missing \"file\" property on Project Object")); + return false; + } + + wxString file = propFile->GetValue(); + if (file.empty()) { + file = wxT("noname"); + } + + // Generate the subclass sets + std::set subclasses; + std::vector headerIncludes; + + GenSubclassSets(project, &subclasses, &headerIncludes); + + // Generating in the .h header file those include from components dependencies. + std::set templates; + GenIncludes(project, &headerIncludes, &templates); + + // Write the include lines + std::vector::iterator include_it; + for (include_it = headerIncludes.begin(); include_it != headerIncludes.end(); ++include_it) { + m_source->WriteLn(*include_it); + } + if (!headerIncludes.empty()) { + m_source->WriteLn(wxEmptyString); + } + + // Write internationalization support + if (m_i18n) { + m_source->WriteLn(wxT("import gettext")); + m_source->WriteLn(wxT("_ = gettext.gettext")); + m_source->WriteLn(wxEmptyString); + } + + // Generating "defines" for macros + GenDefines(project); + + wxString eventHandlerPostfix; + PProperty eventKindProp = project->GetProperty(wxT("skip_python_events")); + if (eventKindProp->GetValueAsInteger()) { + eventHandlerPostfix = wxT("event.Skip()"); + } else + eventHandlerPostfix = wxT("pass"); + + PProperty disconnectMode = project->GetProperty(wxT("disconnect_mode")); + m_disconnecMode = disconnectMode->GetValueAsString(); + + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + PObjectBase child = project->GetChild(i); + + // Preprocess to find arrays + ArrayItems arrays; + FindArrayObjects(child, arrays, true); + + EventVector events; + FindEventHandlers(child, events); + // GenClassDeclaration( child, useEnum, classDecoration, events, eventHandlerPrefix, eventHandlerPostfix ); + GenClassDeclaration(child, false, wxEmptyString, events, eventHandlerPostfix, arrays); + } + + code = GetCode(project, wxT("python_epilogue")); + if (!code.empty()) + m_source->WriteLn(code); + + return true; } -void PythonCodeGenerator::GenEvents( PObjectBase class_obj, const EventVector &events, bool disconnect ) +void PythonCodeGenerator::GenEvents(PObjectBase class_obj, const EventVector& events, bool disconnect) { - if ( events.empty() ) - { - return; - } - - if( disconnect ) - { - m_source->WriteLn( wxT("# Disconnect Events") ); - } - else - { - m_source->WriteLn(); - m_source->WriteLn( wxT("# Connect Events") ); - } - - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), - class_obj->GetClassName()); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT("Object name cannot be null") ); - return; - } - - wxString base_class; - wxString handlerName; - - PProperty propSubclass = class_obj->GetProperty( wxT("subclass") ); - if ( propSubclass ) - { - wxString subclass = propSubclass->GetChildFromParent( wxT("name") ); - if ( !subclass.empty() ) - { - base_class = subclass; - } - } - - if ( base_class.empty() ) - base_class = wxT("wx.") + class_obj->GetClassName(); - - if ( events.size() > 0 ) - { - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - - handlerName = event->GetValue(); - - wxString templateName = wxString::Format( wxT("connect_%s"), event->GetName() ); - - PObjectBase obj = event->GetObject(); - if ( !GenEventEntry( obj, obj->GetObjectInfo(), templateName, handlerName, disconnect ) ) - { - wxLogError( wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), - templateName, class_name ); - } - } - } + if (events.empty()) { + return; + } + + if (disconnect) { + m_source->WriteLn(wxT("# Disconnect Events")); + } else { + m_source->WriteLn(); + m_source->WriteLn(wxT("# Connect Events")); + } + + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name cannot be null")); + return; + } + + wxString base_class; + wxString handlerName; + + PProperty propSubclass = class_obj->GetProperty(wxT("subclass")); + if (propSubclass) { + wxString subclass = propSubclass->GetChildFromParent(wxT("name")); + if (!subclass.empty()) { + base_class = subclass; + } + } + + if (base_class.empty()) + base_class = wxT("wx.") + class_obj->GetClassName(); + + if (events.size() > 0) { + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + + handlerName = event->GetValue(); + + wxString templateName = wxString::Format(wxT("connect_%s"), event->GetName()); + + PObjectBase obj = event->GetObject(); + if (!GenEventEntry(obj, obj->GetObjectInfo(), templateName, handlerName, disconnect)) { + wxLogError( + wxT("Missing \"evt_%s\" template for \"%s\" class. Review your XML object description"), templateName, + class_name); + } + } + } } -bool PythonCodeGenerator::GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect ) +bool PythonCodeGenerator::GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect) { - wxString _template; - PCodeInfo code_info = obj_info->GetCodeInfo( wxT("Python") ); - if ( code_info ) - { - _template = code_info->GetTemplate(wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); - if ( disconnect && _template.empty() ) - { - _template = code_info->GetTemplate( wxT("evt_") + templateName ); - _template.Replace( wxT("Bind"), wxT("Unbind"), true ); - } - - if ( !_template.empty() ) - { - if( disconnect ) - { - if( m_disconnecMode == wxT("handler_name")) _template.Replace( wxT("#handler"), wxT("handler = self.") + handlerName ); - else if(m_disconnecMode == wxT("source_name")) _template.Replace( wxT("#handler"), wxT("None") ); //wxT("self.") + obj->GetProperty(wxT("name"))->GetValueAsString() ); - } - else - _template.Replace( wxT("#handler"), wxT("self.") + handlerName ); - - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - m_source->WriteLn( parser.ParseTemplate() ); - return true; - } - } - - for ( unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = obj_info->GetBaseClass( i, false ); - if ( GenEventEntry( obj, base_info, templateName, handlerName, disconnect ) ) - { - return true; - } - } - - return false; + wxString _template; + PCodeInfo code_info = obj_info->GetCodeInfo(wxT("Python")); + if (code_info) { + _template = code_info->GetTemplate( + wxString::Format(wxT("evt_%s%s"), disconnect ? wxT("dis") : wxEmptyString, templateName)); + if (disconnect && _template.empty()) { + _template = code_info->GetTemplate(wxT("evt_") + templateName); + _template.Replace(wxT("Bind"), wxT("Unbind"), true); + } + + if (!_template.empty()) { + if (disconnect) { + if (m_disconnecMode == wxT("handler_name")) + _template.Replace(wxT("#handler"), wxT("handler = self.") + handlerName); + else if (m_disconnecMode == wxT("source_name")) + _template.Replace( + wxT("#handler"), + wxT("None")); // wxT("self.") + obj->GetProperty(wxT("name"))->GetValueAsString() ); + } else + _template.Replace(wxT("#handler"), wxT("self.") + handlerName); + + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + m_source->WriteLn(parser.ParseTemplate()); + return true; + } + } + + for (unsigned int i = 0; i < obj_info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = obj_info->GetBaseClass(i, false); + if (GenEventEntry(obj, base_info, templateName, handlerName, disconnect)) { + return true; + } + } + + return false; } -void PythonCodeGenerator::GenVirtualEventHandlers( const EventVector& events, const wxString& eventHandlerPostfix ) +void PythonCodeGenerator::GenVirtualEventHandlers(const EventVector& events, const wxString& eventHandlerPostfix) { - if ( events.size() > 0 ) - { - // There are problems if we create "pure" virtual handlers, because some - // events could be triggered in the constructor in which virtual methods are - // execute properly. - // So we create a default handler which will skip the event. - m_source->WriteLn( wxEmptyString ); - m_source->WriteLn( wxT("# Virtual event handlers, override them in your derived class") ); - - std::set generatedHandlers; - for ( size_t i = 0; i < events.size(); i++ ) - { - PEvent event = events[i]; - wxString aux = wxT("def ") + event->GetValue() + wxT("( self, event ):"); - - if (generatedHandlers.find(aux) == generatedHandlers.end()) - { - m_source->WriteLn(aux); - m_source->Indent(); - m_source->WriteLn(eventHandlerPostfix); - m_source->Unindent(); - - generatedHandlers.insert(aux); - } - if( i < (events.size()-1) ) m_source->WriteLn(); - } - m_source->WriteLn( wxEmptyString ); - } + if (events.size() > 0) { + // There are problems if we create "pure" virtual handlers, because some + // events could be triggered in the constructor in which virtual methods are + // execute properly. + // So we create a default handler which will skip the event. + m_source->WriteLn(wxEmptyString); + m_source->WriteLn(wxT("# Virtual event handlers, override them in your derived class")); + + std::set generatedHandlers; + for (size_t i = 0; i < events.size(); i++) { + PEvent event = events[i]; + wxString aux = wxT("def ") + event->GetValue() + wxT("( self, event ):"); + + if (generatedHandlers.find(aux) == generatedHandlers.end()) { + m_source->WriteLn(aux); + m_source->Indent(); + m_source->WriteLn(eventHandlerPostfix); + m_source->Unindent(); + + generatedHandlers.insert(aux); + } + if (i < (events.size() - 1)) + m_source->WriteLn(); + } + m_source->WriteLn(wxEmptyString); + } } -void PythonCodeGenerator::GetGenEventHandlers( PObjectBase obj ) +void PythonCodeGenerator::GetGenEventHandlers(PObjectBase obj) { - GenDefinedEventHandlers( obj->GetObjectInfo(), obj ); + GenDefinedEventHandlers(obj->GetObjectInfo(), obj); - for (unsigned int i = 0; i < obj->GetChildCount() ; i++) - { - PObjectBase child = obj->GetChild(i); - GetGenEventHandlers(child); - } + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GetGenEventHandlers(child); + } } -void PythonCodeGenerator::GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ) +void PythonCodeGenerator::GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj) { - PCodeInfo code_info = info->GetCodeInfo( wxT( "Python" ) ); - if ( code_info ) - { - wxString _template = code_info->GetTemplate( wxT("generated_event_handlers") ); - if ( !_template.empty() ) - { - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString code = parser.ParseTemplate(); - - if ( !code.empty() ) - { - m_source->WriteLn(code); - } - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenDefinedEventHandlers( base_info, obj ); - } + PCodeInfo code_info = info->GetCodeInfo(wxT("Python")); + if (code_info) { + wxString _template = code_info->GetTemplate(wxT("generated_event_handlers")); + if (!_template.empty()) { + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + wxString code = parser.ParseTemplate(); + + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenDefinedEventHandlers(base_info, obj); + } } void PythonCodeGenerator::GenImagePathWrapperFunction() { - if ( !m_imagePathWrapperFunctionName.empty() ) - { - m_source->WriteLn( wxT( "# Virtual image path resolution method. Override this in your derived class." ) ); - wxString decl = wxT( "def " ) + m_imagePathWrapperFunctionName + wxT("( self, bitmap_path ):"); - m_source->WriteLn( decl ); - m_source->Indent(); - m_source->WriteLn( wxT("return bitmap_path") ); - m_source->WriteLn( wxT("") ); - m_source->Unindent(); - } + if (!m_imagePathWrapperFunctionName.empty()) { + m_source->WriteLn(wxT("# Virtual image path resolution method. Override this in your derived class.")); + wxString decl = wxT("def ") + m_imagePathWrapperFunctionName + wxT("( self, bitmap_path ):"); + m_source->WriteLn(decl); + m_source->Indent(); + m_source->WriteLn(wxT("return bitmap_path")); + m_source->WriteLn(wxT("")); + m_source->Unindent(); + } } wxString PythonCodeGenerator::GetCode(PObjectBase obj, wxString name, bool silent) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT("Python") ); - - if (!code_info) - { - if( !silent ) - { - wxString msg( wxString::Format( wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), - name, obj->GetClassName() ) ); - wxLogError(msg); - } - return wxEmptyString; - } - - _template = code_info->GetTemplate(name); - - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString code = parser.ParseTemplate(); - - return code; + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("Python")); + + if (!code_info) { + if (!silent) { + wxString msg(wxString::Format( + wxT("Missing \"%s\" template for \"%s\" class. Review your XML object description"), name, + obj->GetClassName())); + wxLogError(msg); + } + return wxEmptyString; + } + + _template = code_info->GetTemplate(name); + + PythonTemplateParser parser(obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + wxString code = parser.ParseTemplate(); + + return code; } wxString PythonCodeGenerator::GetConstruction(PObjectBase obj, bool silent, ArrayItems& arrays) { - // Get the name - const auto& propName = obj->GetProperty(wxT("name")); - if (!propName) - { - // Object has no name, just get its code - return GetCode(obj, wxT("construction"), silent); - } - - // Object has a name, check if its an array - const auto& name = propName->GetValue(); - wxString baseName; - ArrayItem unused; - if (!ParseArrayName(name, baseName, unused)) - { - // Object is not an array, just get its code - return GetCode(obj, wxT("construction"), silent); - } - - // Object is an array, check if it needs to be declared - auto& item = arrays[baseName]; - if (item.isDeclared) - { - // Object is already declared, just get its code - return GetCode(obj, wxT("construction"), silent); - } - - // Array needs to be declared - wxString code; - - // Array declaration - // Base array - code.append(wxT("self.")); - code.append(baseName); - code.append(wxT(" = {}\n")); - - // Need to fill all dimensions up to the last - if (item.maxIndex.size() > 1) - { - std::vector stackCurrent; - std::vector stackNext; - - stackCurrent.push_back(baseName); - for (size_t dimension = 0; dimension < item.maxIndex.size() - 1; ++dimension) - { - const auto size = item.maxIndex[dimension] + 1; - - stackNext.reserve(stackCurrent.size() * size); - for (const auto& array : stackCurrent) - { - for (size_t index = 0; index < size; ++index) - { - const auto targetName = wxString::Format(wxT("%s[%u]"), array, static_cast(index)); - - code.append(wxT("self.")); - code.append(targetName); - code.append(wxT(" = {}\n")); - - stackNext.push_back(targetName); - } - } - stackCurrent.swap(stackNext); - stackNext.clear(); - } - } - - // Get the Code - code.append(GetCode(obj, wxT("construction"), silent)); - - // Mark the array as declared - item.isDeclared = true; - - return code; + // Get the name + const auto& propName = obj->GetProperty(wxT("name")); + if (!propName) { + // Object has no name, just get its code + return GetCode(obj, wxT("construction"), silent); + } + + // Object has a name, check if its an array + const auto& name = propName->GetValue(); + wxString baseName; + ArrayItem unused; + if (!ParseArrayName(name, baseName, unused)) { + // Object is not an array, just get its code + return GetCode(obj, wxT("construction"), silent); + } + + // Object is an array, check if it needs to be declared + auto& item = arrays[baseName]; + if (item.isDeclared) { + // Object is already declared, just get its code + return GetCode(obj, wxT("construction"), silent); + } + + // Array needs to be declared + wxString code; + + // Array declaration + // Base array + code.append(wxT("self.")); + code.append(baseName); + code.append(wxT(" = {}\n")); + + // Need to fill all dimensions up to the last + if (item.maxIndex.size() > 1) { + std::vector stackCurrent; + std::vector stackNext; + + stackCurrent.push_back(baseName); + for (size_t dimension = 0; dimension < item.maxIndex.size() - 1; ++dimension) { + const auto size = item.maxIndex[dimension] + 1; + + stackNext.reserve(stackCurrent.size() * size); + for (const auto& array : stackCurrent) { + for (size_t index = 0; index < size; ++index) { + const auto targetName = wxString::Format(wxT("%s[%u]"), array, static_cast(index)); + + code.append(wxT("self.")); + code.append(targetName); + code.append(wxT(" = {}\n")); + + stackNext.push_back(targetName); + } + } + stackCurrent.swap(stackNext); + stackNext.clear(); + } + } + + // Get the Code + code.append(GetCode(obj, wxT("construction"), silent)); + + // Mark the array as declared + item.isDeclared = true; + + return code; } -void PythonCodeGenerator::GenClassDeclaration(PObjectBase class_obj, bool /*use_enum*/, - const wxString& classDecoration, - const EventVector& events, - const wxString& eventHandlerPostfix, - ArrayItems& arrays) { - PProperty propName = class_obj->GetProperty( wxT("name") ); - if ( !propName ) - { - wxLogError(wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), - class_obj->GetClassName()); - return; - } - - wxString class_name = propName->GetValue(); - if ( class_name.empty() ) - { - wxLogError( wxT("Object name can not be null") ); - return; - } - - m_source->WriteLn( wxT("###########################################################################") ); - m_source->WriteLn( wxT("## Class ") + class_name); - m_source->WriteLn( wxT("###########################################################################") ); - m_source->WriteLn( ); - - m_source->WriteLn( wxT("class ") + classDecoration + class_name + wxT(" ( ") + GetCode( class_obj, wxT("base") ).Trim() + wxT(" ):") ); - m_source->Indent(); - - // The constructor is also included within public - GenConstructor(class_obj, events, arrays); - GenDestructor( class_obj, events ); - - m_source->WriteLn(wxEmptyString); - - // event handlers - GenVirtualEventHandlers(events, eventHandlerPostfix); - GetGenEventHandlers( class_obj ); - - // Bitmap wrapper code - GenImagePathWrapperFunction(); - - m_source->Unindent(); - m_source->WriteLn(wxEmptyString); +void PythonCodeGenerator::GenClassDeclaration( + PObjectBase class_obj, bool /*use_enum*/, const wxString& classDecoration, const EventVector& events, + const wxString& eventHandlerPostfix, ArrayItems& arrays) +{ + PProperty propName = class_obj->GetProperty(wxT("name")); + if (!propName) { + wxLogError( + wxT("Missing \"name\" property on \"%s\" class. Review your XML object description"), + class_obj->GetClassName()); + return; + } + + wxString class_name = propName->GetValue(); + if (class_name.empty()) { + wxLogError(wxT("Object name can not be null")); + return; + } + + m_source->WriteLn(wxT("###########################################################################")); + m_source->WriteLn(wxT("## Class ") + class_name); + m_source->WriteLn(wxT("###########################################################################")); + m_source->WriteLn(); + + m_source->WriteLn( + wxT("class ") + classDecoration + class_name + wxT(" ( ") + GetCode(class_obj, wxT("base")).Trim() + wxT(" ):")); + m_source->Indent(); + + // The constructor is also included within public + GenConstructor(class_obj, events, arrays); + GenDestructor(class_obj, events); + + m_source->WriteLn(wxEmptyString); + + // event handlers + GenVirtualEventHandlers(events, eventHandlerPostfix); + GetGenEventHandlers(class_obj); + + // Bitmap wrapper code + GenImagePathWrapperFunction(); + + m_source->Unindent(); + m_source->WriteLn(wxEmptyString); } -void PythonCodeGenerator::GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::vector< wxString >* headerIncludes ) +void PythonCodeGenerator::GenSubclassSets( + PObjectBase obj, std::set* subclasses, std::vector* headerIncludes) { - // Call GenSubclassForwardDeclarations on all children as well - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenSubclassSets( obj->GetChild( i ), subclasses, headerIncludes ); - } - - // Fill the set - PProperty subclass = obj->GetProperty( wxT("subclass") ); - if ( subclass ) - { - std::map< wxString, wxString > children; - subclass->SplitParentProperty( &children ); - - std::map< wxString, wxString >::iterator name; - name = children.find( wxT("name") ); - - if ( children.end() == name ) - { - // No name, so do nothing - return; - } - - wxString nameVal = name->second; - if ( nameVal.empty() ) - { - // No name, so do nothing - return; - } - - // Now get the header - std::map< wxString, wxString >::iterator header; - header = children.find( wxT("header") ); - - if ( children.end() == header ) - { - // No header, so do nothing - return; - } - - wxString headerVal = header->second; - if ( headerVal.empty() ) - { - // No header, so do nothing - return; - } - - // Got a header - PObjectInfo info = obj->GetObjectInfo(); - if ( !info ) - { - return; - } - - PObjectPackage pkg = info->GetPackage(); - if ( !pkg ) - { - return; - } - - wxString include = wxT("from ") + headerVal + wxT(" import ") + nameVal; - std::vector< wxString >::iterator it = std::find( headerIncludes->begin(), headerIncludes->end(), include ); - if ( headerIncludes->end() == it ) - { - headerIncludes->push_back( include ); - } - } + // Call GenSubclassForwardDeclarations on all children as well + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + GenSubclassSets(obj->GetChild(i), subclasses, headerIncludes); + } + + // Fill the set + PProperty subclass = obj->GetProperty(wxT("subclass")); + if (subclass) { + std::map children; + subclass->SplitParentProperty(&children); + + std::map::iterator name; + name = children.find(wxT("name")); + + if (children.end() == name) { + // No name, so do nothing + return; + } + + wxString nameVal = name->second; + if (nameVal.empty()) { + // No name, so do nothing + return; + } + + // Now get the header + std::map::iterator header; + header = children.find(wxT("header")); + + if (children.end() == header) { + // No header, so do nothing + return; + } + + wxString headerVal = header->second; + if (headerVal.empty()) { + // No header, so do nothing + return; + } + + // Got a header + PObjectInfo info = obj->GetObjectInfo(); + if (!info) { + return; + } + + PObjectPackage pkg = info->GetPackage(); + if (!pkg) { + return; + } + + wxString include = wxT("from ") + headerVal + wxT(" import ") + nameVal; + std::vector::iterator it = std::find(headerIncludes->begin(), headerIncludes->end(), include); + if (headerIncludes->end() == it) { + headerIncludes->push_back(include); + } + } } -void PythonCodeGenerator::GenIncludes( PObjectBase project, std::vector* includes, std::set< wxString >* templates ) +void PythonCodeGenerator::GenIncludes( + PObjectBase project, std::vector* includes, std::set* templates) { - GenObjectIncludes( project, includes, templates ); + GenObjectIncludes(project, includes, templates); } -void PythonCodeGenerator::GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ) +void PythonCodeGenerator::GenObjectIncludes( + PObjectBase project, std::vector* includes, std::set* templates) { - // Fill the set - PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo( wxT("Python") ); - if (code_info) - { - PythonTemplateParser parser( project, code_info->GetTemplate( wxT("include") ), m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } - - // Call GenIncludes on all children as well - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - GenObjectIncludes( project->GetChild(i), includes, templates ); - } - - // Generate includes for base classes - GenBaseIncludes( project->GetObjectInfo(), project, includes, templates ); + // Fill the set + PCodeInfo code_info = project->GetObjectInfo()->GetCodeInfo(wxT("Python")); + if (code_info) { + PythonTemplateParser parser( + project, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath, + m_imagePathWrapperFunctionName); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } + + // Call GenIncludes on all children as well + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + GenObjectIncludes(project->GetChild(i), includes, templates); + } + + // Generate includes for base classes + GenBaseIncludes(project->GetObjectInfo(), project, includes, templates); } -void PythonCodeGenerator::GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ) +void PythonCodeGenerator::GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates) { - if ( !info ) - { - return; - } - - // Process all the base classes recursively - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GenBaseIncludes( base_info, obj, includes, templates ); - } - - PCodeInfo code_info = info->GetCodeInfo( wxT("Python") ); - if ( code_info ) - { - PythonTemplateParser parser( obj, code_info->GetTemplate( wxT("include") ), m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString include = parser.ParseTemplate(); - if ( !include.empty() ) - { - if ( templates->insert( include ).second ) - { - AddUniqueIncludes( include, includes ); - } - } - } + if (!info) { + return; + } + + // Process all the base classes recursively + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenBaseIncludes(base_info, obj, includes, templates); + } + + PCodeInfo code_info = info->GetCodeInfo(wxT("Python")); + if (code_info) { + PythonTemplateParser parser( + obj, code_info->GetTemplate(wxT("include")), m_i18n, m_useRelativePath, m_basePath, + m_imagePathWrapperFunctionName); + wxString include = parser.ParseTemplate(); + if (!include.empty()) { + if (templates->insert(include).second) { + AddUniqueIncludes(include, includes); + } + } + } } -void PythonCodeGenerator::AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ) +void PythonCodeGenerator::AddUniqueIncludes(const wxString& include, std::vector* includes) { - // Split on newlines to only generate unique include lines - // This strips blank lines and trims - wxStringTokenizer tkz( include, wxT("\n"), wxTOKEN_STRTOK ); - - while ( tkz.HasMoreTokens() ) - { - wxString line = tkz.GetNextToken(); - line.Trim( false ); - line.Trim( true ); - - // If it is not an include line, it will be written - if ( !line.StartsWith( wxT("import") ) ) - { - includes->push_back( line ); - continue; - } - - // If it is an include, it must be unique to be written - std::vector< wxString >::iterator it = std::find( includes->begin(), includes->end(), line ); - if ( includes->end() == it ) - { - includes->push_back( line ); - } - } + // Split on newlines to only generate unique include lines + // This strips blank lines and trims + wxStringTokenizer tkz(include, wxT("\n"), wxTOKEN_STRTOK); + + while (tkz.HasMoreTokens()) { + wxString line = tkz.GetNextToken(); + line.Trim(false); + line.Trim(true); + + // If it is not an include line, it will be written + if (!line.StartsWith(wxT("import"))) { + includes->push_back(line); + continue; + } + + // If it is an include, it must be unique to be written + std::vector::iterator it = std::find(includes->begin(), includes->end(), line); + if (includes->end() == it) { + includes->push_back(line); + } + } } -void PythonCodeGenerator::FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ) +void PythonCodeGenerator::FindDependencies(PObjectBase obj, std::set& info_set) { - unsigned int ch_count = obj->GetChildCount(); - if (ch_count > 0) - { - unsigned int i; - for (i = 0; iGetChild(i); - info_set.insert(child->GetObjectInfo()); - FindDependencies(child, info_set); - } - } + unsigned int ch_count = obj->GetChildCount(); + if (ch_count > 0) { + unsigned int i; + for (i = 0; i < ch_count; i++) { + PObjectBase child = obj->GetChild(i); + info_set.insert(child->GetObjectInfo()); + FindDependencies(child, info_set); + } + } } void PythonCodeGenerator::GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays) { - m_source->WriteLn(); - // generate function definition - m_source->WriteLn( GetCode( class_obj, wxT("cons_def") ) ); - m_source->Indent(); - - m_source->WriteLn( GetCode( class_obj, wxT("cons_call") ) ); - m_source->WriteLn(); - - wxString settings = GetCode( class_obj, wxT("settings") ); - if ( !settings.IsEmpty() ) - { - m_source->WriteLn( settings ); - } - - for ( unsigned int i = 0; i < class_obj->GetChildCount(); i++ ) - { - GenConstruction(class_obj->GetChild(i), true, arrays); - } - - wxString afterAddChild = GetCode( class_obj, wxT("after_addchild") ); - if ( !afterAddChild.IsEmpty() ) - { - m_source->WriteLn( afterAddChild ); - } - - GenEvents( class_obj, events ); - - auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); - if (!afterConnectEvents.empty()) - { - m_source->WriteLn(); - m_source->WriteLn(afterConnectEvents); - } - - m_source->Unindent(); - - if ( class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0 ) - { - m_source->WriteLn( wxT("def add_page(self, page):") ); - m_source->Indent(); - m_source->WriteLn( wxT("if self.m_pages:") ); - m_source->Indent(); - m_source->WriteLn( wxT("previous_page = self.m_pages[-1]") ); - m_source->WriteLn( wxT("page.SetPrev(previous_page)") ); - m_source->WriteLn( wxT("previous_page.SetNext(page)") ); - m_source->Unindent(); - m_source->WriteLn( wxT("self.m_pages.append(page)") ); - m_source->Unindent(); - } + m_source->WriteLn(); + // generate function definition + m_source->WriteLn(GetCode(class_obj, wxT("cons_def"))); + m_source->Indent(); + + m_source->WriteLn(GetCode(class_obj, wxT("cons_call"))); + m_source->WriteLn(); + + wxString settings = GetCode(class_obj, wxT("settings")); + if (!settings.IsEmpty()) { + m_source->WriteLn(settings); + } + + for (unsigned int i = 0; i < class_obj->GetChildCount(); i++) { + GenConstruction(class_obj->GetChild(i), true, arrays); + } + + wxString afterAddChild = GetCode(class_obj, wxT("after_addchild")); + if (!afterAddChild.IsEmpty()) { + m_source->WriteLn(afterAddChild); + } + + GenEvents(class_obj, events); + + auto afterConnectEvents = GetCode(class_obj, wxT("after_connectevents")); + if (!afterConnectEvents.empty()) { + m_source->WriteLn(); + m_source->WriteLn(afterConnectEvents); + } + + m_source->Unindent(); + + if (class_obj->GetObjectTypeName() == wxT("wizard") && class_obj->GetChildCount() > 0) { + m_source->WriteLn(wxT("def add_page(self, page):")); + m_source->Indent(); + m_source->WriteLn(wxT("if self.m_pages:")); + m_source->Indent(); + m_source->WriteLn(wxT("previous_page = self.m_pages[-1]")); + m_source->WriteLn(wxT("page.SetPrev(previous_page)")); + m_source->WriteLn(wxT("previous_page.SetNext(page)")); + m_source->Unindent(); + m_source->WriteLn(wxT("self.m_pages.append(page)")); + m_source->Unindent(); + } } -void PythonCodeGenerator::GenDestructor( PObjectBase class_obj, const EventVector &events ) +void PythonCodeGenerator::GenDestructor(PObjectBase class_obj, const EventVector& events) { - m_source->WriteLn(); - // generate function definition - m_source->WriteLn( wxT("def __del__( self ):") ); - m_source->Indent(); - - if ( m_disconnectEvents && !events.empty() ) - { - GenEvents( class_obj, events, true ); - } else if (class_obj->GetPropertyAsInteger(wxT("aui_managed")) == 0) { - m_source->WriteLn(wxT("pass")); - } - - // destruct objects - GenDestruction( class_obj ); - - m_source->Unindent(); + m_source->WriteLn(); + // generate function definition + m_source->WriteLn(wxT("def __del__( self ):")); + m_source->Indent(); + + if (m_disconnectEvents && !events.empty()) { + GenEvents(class_obj, events, true); + } else if (class_obj->GetPropertyAsInteger(wxT("aui_managed")) == 0) { + m_source->WriteLn(wxT("pass")); + } + + // destruct objects + GenDestruction(class_obj); + + m_source->Unindent(); } void PythonCodeGenerator::GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays) { - wxString type = obj->GetObjectTypeName(); - PObjectInfo info = obj->GetObjectInfo(); - - if ( ObjectDatabase::HasCppProperties( type ) ) - { - m_source->WriteLn(GetConstruction(obj, false, arrays)); - - GenSettings( obj->GetObjectInfo(), obj ); - - bool isWidget = !info->IsSubclassOf( wxT("sizer") ); - - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenConstruction(child, isWidget, arrays); - - if ( type == wxT("toolbar") ) - { - GenAddToolbar(child->GetObjectInfo(), child); - } - } - - if ( !isWidget ) // sizers - { - wxString afterAddChild = GetCode( obj, wxT( "after_addchild" ) ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - - if (is_widget) - { - // the parent object is not a sizer. There is no template for - // this so we'll make it manually. - // It's not a good practice to embed templates into the source code, - // because you will need to recompile... - - wxString _template = wxT("#wxparent $name.SetSizer( $name ) #nl") - wxT("#wxparent $name.Layout()") - wxT("#ifnull #parent $size") - wxT("@{ #nl $name.Fit( #wxparent $name ) @}"); - - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - m_source->WriteLn(parser.ParseTemplate()); - } - } - else if ( type == wxT("splitter") ) - { - // Generating the split - switch ( obj->GetChildCount() ) - { - case 1: - { - PObjectBase sub1 = obj->GetChild(0)->GetChild(0); - wxString _template = wxT("self.$name.Initialize( "); - _template = _template + wxT("self.") + sub1->GetProperty( wxT("name") )->GetValue() + wxT(" )"); - - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - m_source->WriteLn(parser.ParseTemplate()); - break; - } - case 2: - { - PObjectBase sub1,sub2; - sub1 = obj->GetChild(0)->GetChild(0); - sub2 = obj->GetChild(1)->GetChild(0); - - wxString _template; - if ( obj->GetProperty( wxT("splitmode") )->GetValue() == wxT("wxSPLIT_VERTICAL") ) - { - _template = wxT("self.$name.SplitVertically( "); - } - else - { - _template = wxT("self.$name.SplitHorizontally( "); - } - - _template = _template + wxT("self.") + sub1->GetProperty( wxT("name") )->GetValue() + - wxT(", self.") + sub2->GetProperty( wxT("name") )->GetValue() + wxT(", $sashpos )"); - - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - m_source->WriteLn(parser.ParseTemplate()); - break; - } - default: - wxLogError( wxT("Missing subwindows for wxSplitterWindow widget.") ); - break; - } - } - else if ( type == wxT("menubar") || - type == wxT("menu") || - type == wxT("submenu") || - type == wxT( "ribbonbar" ) || - type == wxT("toolbar") || - type == wxT("tool") || - type == wxT("listbook") || - type == wxT("simplebook" ) || - type == wxT("notebook") || - type == wxT("auinotebook") || - type == wxT("treelistctrl") || - type == wxT("flatnotebook") || - type == wxT("wizard") - ) - { - wxString afterAddChild = GetCode( obj, wxT("after_addchild") ); - if ( !afterAddChild.empty() ) - { - m_source->WriteLn( afterAddChild ); - } - m_source->WriteLn(); - } - } - else if ( info->IsSubclassOf( wxT("sizeritembase") ) ) - { - // The child must be added to the sizer having in mind the - // child object type (there are 3 different routines) - GenConstruction(obj->GetChild(0), false, arrays); - - PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); - wxString temp_name; - if ( childInfo->IsSubclassOf( wxT("wxWindow") ) || wxT("CustomControl") == childInfo->GetClassName() ) - { - temp_name = wxT("window_add"); - } - else if ( childInfo->IsSubclassOf( wxT("sizer") ) ) - { - temp_name = wxT("sizer_add"); - } - else if ( childInfo->GetClassName() == wxT("spacer") ) - { - temp_name = wxT("spacer_add"); - } - else - { - LogDebug( wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.") ); - return; - } - - m_source->WriteLn( GetCode( obj, temp_name ) ); - } - else if ( type == wxT("notebookpage") || - type == wxT("flatnotebookpage") || - type == wxT("listbookpage") || - type == wxT("simplebookpage") || - type == wxT("choicebookpage") || - type == wxT("auinotebookpage") - ) - { - GenConstruction(obj->GetChild(0), false, arrays); - m_source->WriteLn( GetCode( obj, wxT("page_add") ) ); - GenSettings( obj->GetObjectInfo(), obj ); - } - else if ( type == wxT("treelistctrlcolumn") ) - { - m_source->WriteLn( GetCode( obj, wxT("column_add") ) ); - GenSettings( obj->GetObjectInfo(), obj ); - } - else if ( type == wxT("tool") ) - { - // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize - // So hacky, yet so useful ... - wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize( _("bitmapsize") ); - if ( wxDefaultSize != toolbarsize ) - { - PProperty prop = obj->GetProperty( _("bitmap") ); - if ( prop ) - { - wxString oldVal = prop->GetValueAsString(); - wxString path, source; - wxSize toolsize; - TypeConv::ParseBitmapWithResource( oldVal, &path, &source, &toolsize ); - if ( _("Load From Icon Resource") == source && wxDefaultSize == toolsize ) - { - prop->SetValue( wxString::Format( wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight() ) ); - m_source->WriteLn(GetConstruction(obj, false, arrays)); - prop->SetValue( oldVal ); - return; - } - } - } - m_source->WriteLn(GetConstruction(obj, false, arrays)); - } - else - { - // Generate the children - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - GenConstruction(obj->GetChild(i), false, arrays); - } - } + wxString type = obj->GetObjectTypeName(); + PObjectInfo info = obj->GetObjectInfo(); + + if (ObjectDatabase::HasCppProperties(type)) { + m_source->WriteLn(GetConstruction(obj, false, arrays)); + + GenSettings(obj->GetObjectInfo(), obj); + + bool isWidget = !info->IsSubclassOf(wxT("sizer")); + + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenConstruction(child, isWidget, arrays); + + if (type == wxT("toolbar")) { + GenAddToolbar(child->GetObjectInfo(), child); + } + } + + if (!isWidget) // sizers + { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + + if (is_widget) { + // the parent object is not a sizer. There is no template for + // this so we'll make it manually. + // It's not a good practice to embed templates into the source code, + // because you will need to recompile... + + wxString _template = wxT("#wxparent $name.SetSizer( $name ) #nl") wxT("#wxparent $name.Layout()") + wxT("#ifnull #parent $size") wxT("@{ #nl $name.Fit( #wxparent $name ) @}"); + + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + m_source->WriteLn(parser.ParseTemplate()); + } + } else if (type == wxT("splitter")) { + // Generating the split + switch (obj->GetChildCount()) { + case 1: { + PObjectBase sub1 = obj->GetChild(0)->GetChild(0); + wxString _template = wxT("self.$name.Initialize( "); + _template = _template + wxT("self.") + sub1->GetProperty(wxT("name"))->GetValue() + wxT(" )"); + + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + case 2: { + PObjectBase sub1, sub2; + sub1 = obj->GetChild(0)->GetChild(0); + sub2 = obj->GetChild(1)->GetChild(0); + + wxString _template; + if (obj->GetProperty(wxT("splitmode"))->GetValue() == wxT("wxSPLIT_VERTICAL")) { + _template = wxT("self.$name.SplitVertically( "); + } else { + _template = wxT("self.$name.SplitHorizontally( "); + } + + _template = _template + wxT("self.") + sub1->GetProperty(wxT("name"))->GetValue() + wxT(", self.") + + sub2->GetProperty(wxT("name"))->GetValue() + wxT(", $sashpos )"); + + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + m_source->WriteLn(parser.ParseTemplate()); + break; + } + default: + wxLogError(wxT("Missing subwindows for wxSplitterWindow widget.")); + break; + } + } else if ( + type == wxT("menubar") || type == wxT("menu") || type == wxT("submenu") || type == wxT("ribbonbar") || + type == wxT("toolbar") || type == wxT("tool") || type == wxT("listbook") || type == wxT("simplebook") || + type == wxT("notebook") || type == wxT("auinotebook") || type == wxT("treelistctrl") || + type == wxT("flatnotebook") || type == wxT("wizard")) { + wxString afterAddChild = GetCode(obj, wxT("after_addchild")); + if (!afterAddChild.empty()) { + m_source->WriteLn(afterAddChild); + } + m_source->WriteLn(); + } + } else if (info->IsSubclassOf(wxT("sizeritembase"))) { + // The child must be added to the sizer having in mind the + // child object type (there are 3 different routines) + GenConstruction(obj->GetChild(0), false, arrays); + + PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo(); + wxString temp_name; + if (childInfo->IsSubclassOf(wxT("wxWindow")) || wxT("CustomControl") == childInfo->GetClassName()) { + temp_name = wxT("window_add"); + } else if (childInfo->IsSubclassOf(wxT("sizer"))) { + temp_name = wxT("sizer_add"); + } else if (childInfo->GetClassName() == wxT("spacer")) { + temp_name = wxT("spacer_add"); + } else { + LogDebug(wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.")); + return; + } + + m_source->WriteLn(GetCode(obj, temp_name)); + } else if ( + type == wxT("notebookpage") || type == wxT("flatnotebookpage") || type == wxT("listbookpage") || + type == wxT("simplebookpage") || type == wxT("choicebookpage") || type == wxT("auinotebookpage")) { + GenConstruction(obj->GetChild(0), false, arrays); + m_source->WriteLn(GetCode(obj, wxT("page_add"))); + GenSettings(obj->GetObjectInfo(), obj); + } else if (type == wxT("treelistctrlcolumn")) { + m_source->WriteLn(GetCode(obj, wxT("column_add"))); + GenSettings(obj->GetObjectInfo(), obj); + } else if (type == wxT("tool")) { + // If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize + // So hacky, yet so useful ... + wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize(_("bitmapsize")); + if (wxDefaultSize != toolbarsize) { + PProperty prop = obj->GetProperty(_("bitmap")); + if (prop) { + wxString oldVal = prop->GetValueAsString(); + wxString path, source; + wxSize toolsize; + TypeConv::ParseBitmapWithResource(oldVal, &path, &source, &toolsize); + if (_("Load From Icon Resource") == source && wxDefaultSize == toolsize) { + prop->SetValue(wxString::Format( + wxT("%s; %s [%i; %i]"), path, source, toolbarsize.GetWidth(), toolbarsize.GetHeight())); + m_source->WriteLn(GetConstruction(obj, false, arrays)); + prop->SetValue(oldVal); + return; + } + } + } + m_source->WriteLn(GetConstruction(obj, false, arrays)); + } else { + // Generate the children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { GenConstruction(obj->GetChild(i), false, arrays); } + } } -void PythonCodeGenerator::GenDestruction( PObjectBase obj ) +void PythonCodeGenerator::GenDestruction(PObjectBase obj) { - wxString _template; - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT( "Python" ) ); - - if ( code_info ) - { - _template = code_info->GetTemplate( wxT( "destruction" ) ); - - if ( !_template.empty() ) - { - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn( code ); - } - } - } - - // Process child widgets - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - { - PObjectBase child = obj->GetChild( i ); - GenDestruction( child ); - } + wxString _template; + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("Python")); + + if (code_info) { + _template = code_info->GetTemplate(wxT("destruction")); + + if (!_template.empty()) { + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + } + + // Process child widgets + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + GenDestruction(child); + } } -void PythonCodeGenerator::FindMacros( PObjectBase obj, std::vector* macros ) +void PythonCodeGenerator::FindMacros(PObjectBase obj, std::vector* macros) { - // iterate through all of the properties of all objects, add the macros - // to the vector - unsigned int i; - - for ( i = 0; i < obj->GetPropertyCount(); i++ ) - { - PProperty prop = obj->GetProperty( i ); - if ( prop->GetType() == PT_MACRO ) - { - wxString value = prop->GetValue(); - if( value.IsEmpty() ) continue; - - //if( value.Contains( wxT("wx") ) && !value.Contains( wxT("wx.") ) ) value.Replace( wxT("wx"), wxT("wx.") ); - value.Replace( wxT("wx"), wxT("wx.") ); - - // Skip wx IDs - if ( ( ! value.Contains( wxT("XRCID" ) ) ) && - ( m_predMacros.end() == m_predMacros.find( value ) ) ) - { - if ( macros->end() == std::find( macros->begin(), macros->end(), value ) ) - { - macros->push_back( value ); - } - } - } - } - - for ( i = 0; i < obj->GetChildCount(); i++ ) - { - FindMacros( obj->GetChild( i ), macros ); - } + // iterate through all of the properties of all objects, add the macros + // to the vector + unsigned int i; + + for (i = 0; i < obj->GetPropertyCount(); i++) { + PProperty prop = obj->GetProperty(i); + if (prop->GetType() == PT_MACRO) { + wxString value = prop->GetValue(); + if (value.IsEmpty()) + continue; + + // if( value.Contains( wxT("wx") ) && !value.Contains( wxT("wx.") ) ) value.Replace( wxT("wx"), wxT("wx.") + // ); + value.Replace(wxT("wx"), wxT("wx.")); + + // Skip wx IDs + if ((!value.Contains(wxT("XRCID"))) && (m_predMacros.end() == m_predMacros.find(value))) { + if (macros->end() == std::find(macros->begin(), macros->end(), value)) { + macros->push_back(value); + } + } + } + } + + for (i = 0; i < obj->GetChildCount(); i++) { FindMacros(obj->GetChild(i), macros); } } -void PythonCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector &events) +void PythonCodeGenerator::FindEventHandlers(PObjectBase obj, EventVector& events) { - unsigned int i; - for (i=0; i < obj->GetEventCount(); i++) - { - PEvent event = obj->GetEvent(i); - if (!event->GetValue().IsEmpty()) - events.push_back(event); - } - - for (i=0; i < obj->GetChildCount(); i++) - { - PObjectBase child = obj->GetChild(i); - FindEventHandlers(child,events); - } + unsigned int i; + for (i = 0; i < obj->GetEventCount(); i++) { + PEvent event = obj->GetEvent(i); + if (!event->GetValue().IsEmpty()) + events.push_back(event); + } + + for (i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); + FindEventHandlers(child, events); + } } -void PythonCodeGenerator::GenDefines( PObjectBase project) +void PythonCodeGenerator::GenDefines(PObjectBase project) { - std::vector< wxString > macros; - FindMacros( project, ¯os ); - - // Remove the default macro from the set, for backward compatibility - std::vector< wxString >::iterator it; - it = std::find( macros.begin(), macros.end(), wxT("ID_DEFAULT") ); - if ( it != macros.end() ) - { - // The default macro is defined to wxID_ANY - m_source->WriteLn( wxT("ID_DEFAULT = wx.ID_ANY # Default") ); - macros.erase(it); - } - - unsigned int id = m_firstID; - if ( id < 1000 ) - { - wxLogWarning(wxT("First ID is Less than 1000")); - } - for (it = macros.begin() ; it != macros.end(); it++) - { - // Don't redefine wx IDs - m_source->WriteLn( wxString::Format( wxT("%s = %i"), it->c_str(), id ) ); - id++; - } - if (!macros.empty()) - { - m_source->WriteLn(wxEmptyString); - } + std::vector macros; + FindMacros(project, ¯os); + + // Remove the default macro from the set, for backward compatibility + std::vector::iterator it; + it = std::find(macros.begin(), macros.end(), wxT("ID_DEFAULT")); + if (it != macros.end()) { + // The default macro is defined to wxID_ANY + m_source->WriteLn(wxT("ID_DEFAULT = wx.ID_ANY # Default")); + macros.erase(it); + } + + unsigned int id = m_firstID; + if (id < 1000) { + wxLogWarning(wxT("First ID is Less than 1000")); + } + for (it = macros.begin(); it != macros.end(); it++) { + // Don't redefine wx IDs + m_source->WriteLn(wxString::Format(wxT("%s = %i"), it->c_str(), id)); + id++; + } + if (!macros.empty()) { + m_source->WriteLn(wxEmptyString); + } } void PythonCodeGenerator::GenSettings(PObjectInfo info, PObjectBase obj) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT("Python") ); - - if ( !code_info ) - { - return; - } - - _template = code_info->GetTemplate( wxT("settings") ); - - if ( !_template.empty() ) - { - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - m_source->WriteLn(code); - } - } - - // Proceeding recursively with the base classes - for (unsigned int i=0; i< info->GetBaseClassCount(false); i++) - { - PObjectInfo base_info = info->GetBaseClass(i, false); - GenSettings(base_info,obj); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("Python")); + + if (!code_info) { + return; + } + + _template = code_info->GetTemplate(wxT("settings")); + + if (!_template.empty()) { + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + m_source->WriteLn(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GenSettings(base_info, obj); + } } -void PythonCodeGenerator::GenAddToolbar( PObjectInfo info, PObjectBase obj ) +void PythonCodeGenerator::GenAddToolbar(PObjectInfo info, PObjectBase obj) { - wxArrayString arrCode; + wxArrayString arrCode; - GetAddToolbarCode( info, obj, arrCode ); + GetAddToolbarCode(info, obj, arrCode); - for( size_t i = 0; i < arrCode.GetCount(); i++ ) m_source->WriteLn( arrCode[i] ); + for (size_t i = 0; i < arrCode.GetCount(); i++) m_source->WriteLn(arrCode[i]); } -void PythonCodeGenerator::GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ) +void PythonCodeGenerator::GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines) { - wxString _template; - PCodeInfo code_info = info->GetCodeInfo( wxT( "Python" ) ); - - if ( !code_info ) - return; - - _template = code_info->GetTemplate( wxT( "toolbar_add" ) ); - - if ( !_template.empty() ) - { - PythonTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName ); - wxString code = parser.ParseTemplate(); - if ( !code.empty() ) - { - if( codelines.Index( code ) == wxNOT_FOUND ) codelines.Add( code ); - } - } - - // Proceeding recursively with the base classes - for ( unsigned int i = 0; i < info->GetBaseClassCount(false); i++ ) - { - PObjectInfo base_info = info->GetBaseClass( i, false ); - GetAddToolbarCode( base_info, obj, codelines ); - } + wxString _template; + PCodeInfo code_info = info->GetCodeInfo(wxT("Python")); + + if (!code_info) + return; + + _template = code_info->GetTemplate(wxT("toolbar_add")); + + if (!_template.empty()) { + PythonTemplateParser parser( + obj, _template, m_i18n, m_useRelativePath, m_basePath, m_imagePathWrapperFunctionName); + wxString code = parser.ParseTemplate(); + if (!code.empty()) { + if (codelines.Index(code) == wxNOT_FOUND) + codelines.Add(code); + } + } + + // Proceeding recursively with the base classes + for (unsigned int i = 0; i < info->GetBaseClassCount(false); i++) { + PObjectInfo base_info = info->GetBaseClass(i, false); + GetAddToolbarCode(base_info, obj, codelines); + } } /////////////////////////////////////////////////////////////////////// void PythonCodeGenerator::UseRelativePath(bool relative, wxString basePath) { - m_useRelativePath = relative; - - if (m_useRelativePath) - { - if (wxFileName::DirExists(basePath)) - { - m_basePath = basePath; - } - else - { - m_basePath = wxEmptyString; - } - } + m_useRelativePath = relative; + + if (m_useRelativePath) { + if (wxFileName::DirExists(basePath)) { + m_basePath = basePath; + } else { + m_basePath = wxEmptyString; + } + } } /* @@ -1591,300 +1391,299 @@ auxPath = _STDSTR(filename.GetFullPath()); return auxPath; }*/ -void PythonCodeGenerator::SetImagePathWrapperFunctionName( wxString imagePathWrapperFunctionName ) +void PythonCodeGenerator::SetImagePathWrapperFunctionName(wxString imagePathWrapperFunctionName) { - m_imagePathWrapperFunctionName = imagePathWrapperFunctionName; + m_imagePathWrapperFunctionName = imagePathWrapperFunctionName; } -#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert( wxT(#x) ) -#define ADD_PREDEFINED_PREFIX(k, v) m_predModulePrefix[ wxT(#k) ] = wxT(#v) +#define ADD_PREDEFINED_MACRO(x) m_predMacros.insert(wxT(#x)) +#define ADD_PREDEFINED_PREFIX(k, v) m_predModulePrefix[wxT(#k)] = wxT(#v) void PythonCodeGenerator::SetupPredefinedMacros() { - /* no id matches this one when compared to it */ - ADD_PREDEFINED_MACRO(wx.ID_NONE); - - /* id for a separator line in the menu (invalid for normal item) */ - ADD_PREDEFINED_MACRO(wx.ID_SEPARATOR); - - ADD_PREDEFINED_MACRO(wx.ID_ANY); - - ADD_PREDEFINED_MACRO(wx.ID_LOWEST); - - ADD_PREDEFINED_MACRO(wx.ID_OPEN); - ADD_PREDEFINED_MACRO(wx.ID_CLOSE); - ADD_PREDEFINED_MACRO(wx.ID_NEW); - ADD_PREDEFINED_MACRO(wx.ID_SAVE); - ADD_PREDEFINED_MACRO(wx.ID_SAVEAS); - ADD_PREDEFINED_MACRO(wx.ID_REVERT); - ADD_PREDEFINED_MACRO(wx.ID_EXIT); - ADD_PREDEFINED_MACRO(wx.ID_UNDO); - ADD_PREDEFINED_MACRO(wx.ID_REDO); - ADD_PREDEFINED_MACRO(wx.ID_HELP); - ADD_PREDEFINED_MACRO(wx.ID_PRINT); - ADD_PREDEFINED_MACRO(wx.ID_PRINT_SETUP); - ADD_PREDEFINED_MACRO(wx.ID_PREVIEW); - ADD_PREDEFINED_MACRO(wx.ID_ABOUT); - ADD_PREDEFINED_MACRO(wx.ID_HELP_CONTENTS); - ADD_PREDEFINED_MACRO(wx.ID_HELP_COMMANDS); - ADD_PREDEFINED_MACRO(wx.ID_HELP_PROCEDURES); - ADD_PREDEFINED_MACRO(wx.ID_HELP_CONTEXT); - ADD_PREDEFINED_MACRO(wx.ID_CLOSE_ALL); - ADD_PREDEFINED_MACRO(wx.ID_PAGE_SETUP); - ADD_PREDEFINED_MACRO(wx.ID_HELP_INDEX); - ADD_PREDEFINED_MACRO(wx.ID_HELP_SEARCH); - ADD_PREDEFINED_MACRO(wx.ID_PREFERENCES); - - ADD_PREDEFINED_MACRO(wx.ID_EDIT); - ADD_PREDEFINED_MACRO(wx.ID_CUT); - ADD_PREDEFINED_MACRO(wx.ID_COPY); - ADD_PREDEFINED_MACRO(wx.ID_PASTE); - ADD_PREDEFINED_MACRO(wx.ID_CLEAR); - ADD_PREDEFINED_MACRO(wx.ID_FIND); - - ADD_PREDEFINED_MACRO(wx.ID_DUPLICATE); - ADD_PREDEFINED_MACRO(wx.ID_SELECTALL); - ADD_PREDEFINED_MACRO(wx.ID_DELETE); - ADD_PREDEFINED_MACRO(wx.ID_REPLACE); - ADD_PREDEFINED_MACRO(wx.ID_REPLACE_ALL); - ADD_PREDEFINED_MACRO(wx.ID_PROPERTIES); - - ADD_PREDEFINED_MACRO(wx.ID_VIEW_DETAILS); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_LARGEICONS); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_SMALLICONS); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_LIST); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTDATE); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTNAME); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTSIZE); - ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTTYPE); - - ADD_PREDEFINED_MACRO(wx.ID_FILE); - ADD_PREDEFINED_MACRO(wx.ID_FILE1); - ADD_PREDEFINED_MACRO(wx.ID_FILE2); - ADD_PREDEFINED_MACRO(wx.ID_FILE3); - ADD_PREDEFINED_MACRO(wx.ID_FILE4); - ADD_PREDEFINED_MACRO(wx.ID_FILE5); - ADD_PREDEFINED_MACRO(wx.ID_FILE6); - ADD_PREDEFINED_MACRO(wx.ID_FILE7); - ADD_PREDEFINED_MACRO(wx.ID_FILE8); - ADD_PREDEFINED_MACRO(wx.ID_FILE9); - - /* Standard button and menu IDs */ - - ADD_PREDEFINED_MACRO(wx.ID_OK); - ADD_PREDEFINED_MACRO(wx.ID_CANCEL); - - ADD_PREDEFINED_MACRO(wx.ID_APPLY); - ADD_PREDEFINED_MACRO(wx.ID_YES); - ADD_PREDEFINED_MACRO(wx.ID_NO); - ADD_PREDEFINED_MACRO(wx.ID_STATIC); - ADD_PREDEFINED_MACRO(wx.ID_FORWARD); - ADD_PREDEFINED_MACRO(wx.ID_BACKWARD); - ADD_PREDEFINED_MACRO(wx.ID_DEFAULT); - ADD_PREDEFINED_MACRO(wx.ID_MORE); - ADD_PREDEFINED_MACRO(wx.ID_SETUP); - ADD_PREDEFINED_MACRO(wx.ID_RESET); - ADD_PREDEFINED_MACRO(wx.ID_CONTEXT_HELP); - ADD_PREDEFINED_MACRO(wx.ID_YESTOALL); - ADD_PREDEFINED_MACRO(wx.ID_NOTOALL); - ADD_PREDEFINED_MACRO(wx.ID_ABORT); - ADD_PREDEFINED_MACRO(wx.ID_RETRY); - ADD_PREDEFINED_MACRO(wx.ID_IGNORE); - ADD_PREDEFINED_MACRO(wx.ID_ADD); - ADD_PREDEFINED_MACRO(wx.ID_REMOVE); - - ADD_PREDEFINED_MACRO(wx.ID_UP); - ADD_PREDEFINED_MACRO(wx.ID_DOWN); - ADD_PREDEFINED_MACRO(wx.ID_HOME); - ADD_PREDEFINED_MACRO(wx.ID_REFRESH); - ADD_PREDEFINED_MACRO(wx.ID_STOP); - ADD_PREDEFINED_MACRO(wx.ID_INDEX); - - ADD_PREDEFINED_MACRO(wx.ID_BOLD); - ADD_PREDEFINED_MACRO(wx.ID_ITALIC); - ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_CENTER); - ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_FILL); - ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_RIGHT); - - ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_LEFT); - ADD_PREDEFINED_MACRO(wx.ID_UNDERLINE); - ADD_PREDEFINED_MACRO(wx.ID_INDENT); - ADD_PREDEFINED_MACRO(wx.ID_UNINDENT); - ADD_PREDEFINED_MACRO(wx.ID_ZOOM_100); - ADD_PREDEFINED_MACRO(wx.ID_ZOOM_FIT); - ADD_PREDEFINED_MACRO(wx.ID_ZOOM_IN); - ADD_PREDEFINED_MACRO(wx.ID_ZOOM_OUT); - ADD_PREDEFINED_MACRO(wx.ID_UNDELETE); - ADD_PREDEFINED_MACRO(wx.ID_REVERT_TO_SAVED); - - /* System menu IDs (used by wxUniv): */ - ADD_PREDEFINED_MACRO(wx.ID_SYSTEM_MENU); - ADD_PREDEFINED_MACRO(wx.ID_CLOSE_FRAME); - ADD_PREDEFINED_MACRO(wx.ID_MOVE_FRAME); - ADD_PREDEFINED_MACRO(wx.ID_RESIZE_FRAME); - ADD_PREDEFINED_MACRO(wx.ID_MAXIMIZE_FRAME); - ADD_PREDEFINED_MACRO(wx.ID_ICONIZE_FRAME); - ADD_PREDEFINED_MACRO(wx.ID_RESTORE_FRAME); - - /* IDs used by generic file dialog (13 consecutive starting from this value) */ - ADD_PREDEFINED_MACRO(wx.ID_FILEDLGG); - - ADD_PREDEFINED_MACRO(wx.ID_HIGHEST); - + /* no id matches this one when compared to it */ + ADD_PREDEFINED_MACRO(wx.ID_NONE); + + /* id for a separator line in the menu (invalid for normal item) */ + ADD_PREDEFINED_MACRO(wx.ID_SEPARATOR); + + ADD_PREDEFINED_MACRO(wx.ID_ANY); + + ADD_PREDEFINED_MACRO(wx.ID_LOWEST); + + ADD_PREDEFINED_MACRO(wx.ID_OPEN); + ADD_PREDEFINED_MACRO(wx.ID_CLOSE); + ADD_PREDEFINED_MACRO(wx.ID_NEW); + ADD_PREDEFINED_MACRO(wx.ID_SAVE); + ADD_PREDEFINED_MACRO(wx.ID_SAVEAS); + ADD_PREDEFINED_MACRO(wx.ID_REVERT); + ADD_PREDEFINED_MACRO(wx.ID_EXIT); + ADD_PREDEFINED_MACRO(wx.ID_UNDO); + ADD_PREDEFINED_MACRO(wx.ID_REDO); + ADD_PREDEFINED_MACRO(wx.ID_HELP); + ADD_PREDEFINED_MACRO(wx.ID_PRINT); + ADD_PREDEFINED_MACRO(wx.ID_PRINT_SETUP); + ADD_PREDEFINED_MACRO(wx.ID_PREVIEW); + ADD_PREDEFINED_MACRO(wx.ID_ABOUT); + ADD_PREDEFINED_MACRO(wx.ID_HELP_CONTENTS); + ADD_PREDEFINED_MACRO(wx.ID_HELP_COMMANDS); + ADD_PREDEFINED_MACRO(wx.ID_HELP_PROCEDURES); + ADD_PREDEFINED_MACRO(wx.ID_HELP_CONTEXT); + ADD_PREDEFINED_MACRO(wx.ID_CLOSE_ALL); + ADD_PREDEFINED_MACRO(wx.ID_PAGE_SETUP); + ADD_PREDEFINED_MACRO(wx.ID_HELP_INDEX); + ADD_PREDEFINED_MACRO(wx.ID_HELP_SEARCH); + ADD_PREDEFINED_MACRO(wx.ID_PREFERENCES); + + ADD_PREDEFINED_MACRO(wx.ID_EDIT); + ADD_PREDEFINED_MACRO(wx.ID_CUT); + ADD_PREDEFINED_MACRO(wx.ID_COPY); + ADD_PREDEFINED_MACRO(wx.ID_PASTE); + ADD_PREDEFINED_MACRO(wx.ID_CLEAR); + ADD_PREDEFINED_MACRO(wx.ID_FIND); + + ADD_PREDEFINED_MACRO(wx.ID_DUPLICATE); + ADD_PREDEFINED_MACRO(wx.ID_SELECTALL); + ADD_PREDEFINED_MACRO(wx.ID_DELETE); + ADD_PREDEFINED_MACRO(wx.ID_REPLACE); + ADD_PREDEFINED_MACRO(wx.ID_REPLACE_ALL); + ADD_PREDEFINED_MACRO(wx.ID_PROPERTIES); + + ADD_PREDEFINED_MACRO(wx.ID_VIEW_DETAILS); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_LARGEICONS); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_SMALLICONS); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_LIST); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTDATE); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTNAME); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTSIZE); + ADD_PREDEFINED_MACRO(wx.ID_VIEW_SORTTYPE); + + ADD_PREDEFINED_MACRO(wx.ID_FILE); + ADD_PREDEFINED_MACRO(wx.ID_FILE1); + ADD_PREDEFINED_MACRO(wx.ID_FILE2); + ADD_PREDEFINED_MACRO(wx.ID_FILE3); + ADD_PREDEFINED_MACRO(wx.ID_FILE4); + ADD_PREDEFINED_MACRO(wx.ID_FILE5); + ADD_PREDEFINED_MACRO(wx.ID_FILE6); + ADD_PREDEFINED_MACRO(wx.ID_FILE7); + ADD_PREDEFINED_MACRO(wx.ID_FILE8); + ADD_PREDEFINED_MACRO(wx.ID_FILE9); + + /* Standard button and menu IDs */ + + ADD_PREDEFINED_MACRO(wx.ID_OK); + ADD_PREDEFINED_MACRO(wx.ID_CANCEL); + + ADD_PREDEFINED_MACRO(wx.ID_APPLY); + ADD_PREDEFINED_MACRO(wx.ID_YES); + ADD_PREDEFINED_MACRO(wx.ID_NO); + ADD_PREDEFINED_MACRO(wx.ID_STATIC); + ADD_PREDEFINED_MACRO(wx.ID_FORWARD); + ADD_PREDEFINED_MACRO(wx.ID_BACKWARD); + ADD_PREDEFINED_MACRO(wx.ID_DEFAULT); + ADD_PREDEFINED_MACRO(wx.ID_MORE); + ADD_PREDEFINED_MACRO(wx.ID_SETUP); + ADD_PREDEFINED_MACRO(wx.ID_RESET); + ADD_PREDEFINED_MACRO(wx.ID_CONTEXT_HELP); + ADD_PREDEFINED_MACRO(wx.ID_YESTOALL); + ADD_PREDEFINED_MACRO(wx.ID_NOTOALL); + ADD_PREDEFINED_MACRO(wx.ID_ABORT); + ADD_PREDEFINED_MACRO(wx.ID_RETRY); + ADD_PREDEFINED_MACRO(wx.ID_IGNORE); + ADD_PREDEFINED_MACRO(wx.ID_ADD); + ADD_PREDEFINED_MACRO(wx.ID_REMOVE); + + ADD_PREDEFINED_MACRO(wx.ID_UP); + ADD_PREDEFINED_MACRO(wx.ID_DOWN); + ADD_PREDEFINED_MACRO(wx.ID_HOME); + ADD_PREDEFINED_MACRO(wx.ID_REFRESH); + ADD_PREDEFINED_MACRO(wx.ID_STOP); + ADD_PREDEFINED_MACRO(wx.ID_INDEX); + + ADD_PREDEFINED_MACRO(wx.ID_BOLD); + ADD_PREDEFINED_MACRO(wx.ID_ITALIC); + ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_CENTER); + ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_FILL); + ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_RIGHT); + + ADD_PREDEFINED_MACRO(wx.ID_JUSTIFY_LEFT); + ADD_PREDEFINED_MACRO(wx.ID_UNDERLINE); + ADD_PREDEFINED_MACRO(wx.ID_INDENT); + ADD_PREDEFINED_MACRO(wx.ID_UNINDENT); + ADD_PREDEFINED_MACRO(wx.ID_ZOOM_100); + ADD_PREDEFINED_MACRO(wx.ID_ZOOM_FIT); + ADD_PREDEFINED_MACRO(wx.ID_ZOOM_IN); + ADD_PREDEFINED_MACRO(wx.ID_ZOOM_OUT); + ADD_PREDEFINED_MACRO(wx.ID_UNDELETE); + ADD_PREDEFINED_MACRO(wx.ID_REVERT_TO_SAVED); + + /* System menu IDs (used by wxUniv): */ + ADD_PREDEFINED_MACRO(wx.ID_SYSTEM_MENU); + ADD_PREDEFINED_MACRO(wx.ID_CLOSE_FRAME); + ADD_PREDEFINED_MACRO(wx.ID_MOVE_FRAME); + ADD_PREDEFINED_MACRO(wx.ID_RESIZE_FRAME); + ADD_PREDEFINED_MACRO(wx.ID_MAXIMIZE_FRAME); + ADD_PREDEFINED_MACRO(wx.ID_ICONIZE_FRAME); + ADD_PREDEFINED_MACRO(wx.ID_RESTORE_FRAME); + + /* IDs used by generic file dialog (13 consecutive starting from this value) */ + ADD_PREDEFINED_MACRO(wx.ID_FILEDLGG); + + ADD_PREDEFINED_MACRO(wx.ID_HIGHEST); } void PythonTemplateParser::SetupModulePrefixes() { - // altered class names - ADD_PREDEFINED_PREFIX( wxCalendarCtrl, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxRichTextCtrl, wx.richtext. ); - ADD_PREDEFINED_PREFIX( wxStyledTextCtrl, wx.stc. ); - ADD_PREDEFINED_PREFIX( wxHtmlWindow, wx.html. ); - ADD_PREDEFINED_PREFIX( wxAuiNotebook, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxGrid, wx.grid. ); - ADD_PREDEFINED_PREFIX( wxAnimationCtrl, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxDatePickerCtrl, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxTimePickerCtrl, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxHyperlinkCtrl, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxMediaCtrl, wx.media. ); - - // altered macros - ADD_PREDEFINED_PREFIX( wxCAL_SHOW_HOLIDAYS, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_MONDAY_FIRST, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_NO_MONTH_CHANGE, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_NO_YEAR_CHANGE, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_SEQUENTIAL_MONTH_SELECTION, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_SHOW_SURROUNDING_WEEKS, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_SHOW_WEEK_NUMBERS, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxCAL_SUNDAY_FIRST, wx.adv. ); - - ADD_PREDEFINED_PREFIX( wxHL_ALIGN_CENTRE, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxHL_ALIGN_LEFT, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxHL_ALIGN_RIGHT, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxHL_CONTEXTMENU, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxHL_DEFAULT_STYLE, wx.adv. ); - - ADD_PREDEFINED_PREFIX( wxHW_DEFAULT_STYLE, wx.html. ); - ADD_PREDEFINED_PREFIX( wxHW_NO_SELECTION, wx.html. ); - ADD_PREDEFINED_PREFIX( wxHW_SCROLLBAR_AUTO, wx.html. ); - ADD_PREDEFINED_PREFIX( wxHW_SCROLLBAR_NEVER, wx.html. ); - - ADD_PREDEFINED_PREFIX( wxAUI_NB_BOTTOM, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_CLOSE_BUTTON, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_CLOSE_ON_ACTIVE_TAB, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_CLOSE_ON_ALL_TABS, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_DEFAULT_STYLE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_LEFT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_MIDDLE_CLICK_CLOSE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_RIGHT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_SCROLL_BUTTONS, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_EXTERNAL_MOVE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_FIXED_WIDTH, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_MOVE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TAB_SPLIT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_TOP, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_NB_WINDOWLIST_BUTTON, wx.aui. ); - - ADD_PREDEFINED_PREFIX( wxAUI_TB_TEXT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_NO_TOOLTIPS, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_NO_AUTORESIZE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_GRIPPER, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_OVERFLOW, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_VERTICAL, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_HORZ_LAYOUT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_HORZ_TEXT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_PLAIN_BACKGROUND, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_TB_DEFAULT_STYLE, wx.aui. ); - - ADD_PREDEFINED_PREFIX( wxAUI_MGR_ALLOW_FLOATING, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_ALLOW_ACTIVE_PANE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_TRANSPARENT_DRAG, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_TRANSPARENT_HINT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_VENETIAN_BLINDS_HINT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_RECTANGLE_HINT, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_HINT_FADE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_NO_VENETIAN_BLINDS_FADE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_LIVE_RESIZE, wx.aui. ); - ADD_PREDEFINED_PREFIX( wxAUI_MGR_DEFAULT, wx.aui. ); - - ADD_PREDEFINED_PREFIX( wxGRID_AUTOSIZE, wx.grid. ); - - ADD_PREDEFINED_PREFIX( wxAC_DEFAULT_STYLE, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxAC_NO_AUTORESIZE, wx.adv. ); - - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_DEFAULT_STYLE, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_FOLDBAR_STYLE, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_SHOW_PAGE_LABELS, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_SHOW_PAGE_ICONS, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_FLOW_HORIZONTAL, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_FLOW_VERTICAL, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_SHOW_PANEL_EXT_BUTTONS, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_SHOW_TOGGLE_BUTTON, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_BAR_SHOW_HELP_BUTTON, wx.lib.agw.ribbon. ); - - ADD_PREDEFINED_PREFIX( wxRIBBON_PANEL_DEFAULT_STYLE, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_PANEL_NO_AUTO_MINIMISE, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_PANEL_EXT_BUTTON, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_PANEL_MINIMISE_BUTTON, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_PANEL_STRETCH, wx.lib.agw.ribbon. ); - ADD_PREDEFINED_PREFIX( wxRIBBON_PANEL_FLEXIBLE, wx.lib.agw.ribbon. ); - - ADD_PREDEFINED_PREFIX( wxPG_AUTO_SORT, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_HIDE_CATEGORIES, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_ALPHABETIC_MODE, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_BOLD_MODIFIED, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_SPLITTER_AUTO_CENTER, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_TOOLTIPS, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_HIDE_MARGIN, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_STATIC_SPLITTER, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_STATIC_LAYOUT, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_LIMITED_EDITING, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_DEFAULT_STYLE, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_INIT_NOCAT, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_NO_FLAT_TOOLBAR, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_MODE_BUTTONS, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_HELP_AS_TOOLTIPS, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_NATIVE_DOUBLE_BUFFERING, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_AUTO_UNSPECIFIED_VALUES, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_WRITEONLY_BUILTIN_ATTRIBUTES, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_HIDE_PAGE_BUTTONS, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_MULTIPLE_SELECTION, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_ENABLE_TLP_TRACKING, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_NO_TOOLBAR_DIVIDER, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_EX_TOOLBAR_SEPARATOR, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_DESCRIPTION, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_TOOLBAR, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPGMAN_DEFAULT_STYLE, wx.propgrid. ); - ADD_PREDEFINED_PREFIX( wxPG_NO_INTERNAL_BORDER, wx.propgrid. ); - - ADD_PREDEFINED_PREFIX( wxDATAVIEW_CELL_ACTIVATABLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDATAVIEW_CELL_INERT, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDATAVIEW_COL_HIDDEN, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDATAVIEW_COL_REORDERABLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDATAVIEW_COL_RESIZABLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDATAVIEW_COL_SORTABLE, wx.dataview. ); - - ADD_PREDEFINED_PREFIX( wxDV_SINGLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDV_MULTIPLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDV_ROW_LINES, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDV_HORIZ_RULES, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDV_VERT_RULES, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDV_VARIABLE_LINE_HEIGHT, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxDV_NO_HEADER, wx.dataview. ); - - ADD_PREDEFINED_PREFIX( wxTL_SINGLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxTL_MULTIPLE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxTL_CHECKBOX, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxTL_3STATE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxTL_USER_3STATE, wx.dataview. ); - ADD_PREDEFINED_PREFIX( wxTL_DEFAULT_STYLE, wx.dataview. ); - - ADD_PREDEFINED_PREFIX( wxDP_SPIN, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxDP_DROPDOWN, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxDP_SHOWCENTURY, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxDP_ALLOWNONE, wx.adv. ); - ADD_PREDEFINED_PREFIX( wxDP_DEFAULT, wx.adv. ); - - ADD_PREDEFINED_PREFIX( wxTP_DEFAULT, wx.adv. ); + // altered class names + ADD_PREDEFINED_PREFIX(wxCalendarCtrl, wx.adv.); + ADD_PREDEFINED_PREFIX(wxRichTextCtrl, wx.richtext.); + ADD_PREDEFINED_PREFIX(wxStyledTextCtrl, wx.stc.); + ADD_PREDEFINED_PREFIX(wxHtmlWindow, wx.html.); + ADD_PREDEFINED_PREFIX(wxAuiNotebook, wx.aui.); + ADD_PREDEFINED_PREFIX(wxGrid, wx.grid.); + ADD_PREDEFINED_PREFIX(wxAnimationCtrl, wx.adv.); + ADD_PREDEFINED_PREFIX(wxDatePickerCtrl, wx.adv.); + ADD_PREDEFINED_PREFIX(wxTimePickerCtrl, wx.adv.); + ADD_PREDEFINED_PREFIX(wxHyperlinkCtrl, wx.adv.); + ADD_PREDEFINED_PREFIX(wxMediaCtrl, wx.media.); + + // altered macros + ADD_PREDEFINED_PREFIX(wxCAL_SHOW_HOLIDAYS, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_MONDAY_FIRST, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_NO_MONTH_CHANGE, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_NO_YEAR_CHANGE, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_SEQUENTIAL_MONTH_SELECTION, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_SHOW_SURROUNDING_WEEKS, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_SHOW_WEEK_NUMBERS, wx.adv.); + ADD_PREDEFINED_PREFIX(wxCAL_SUNDAY_FIRST, wx.adv.); + + ADD_PREDEFINED_PREFIX(wxHL_ALIGN_CENTRE, wx.adv.); + ADD_PREDEFINED_PREFIX(wxHL_ALIGN_LEFT, wx.adv.); + ADD_PREDEFINED_PREFIX(wxHL_ALIGN_RIGHT, wx.adv.); + ADD_PREDEFINED_PREFIX(wxHL_CONTEXTMENU, wx.adv.); + ADD_PREDEFINED_PREFIX(wxHL_DEFAULT_STYLE, wx.adv.); + + ADD_PREDEFINED_PREFIX(wxHW_DEFAULT_STYLE, wx.html.); + ADD_PREDEFINED_PREFIX(wxHW_NO_SELECTION, wx.html.); + ADD_PREDEFINED_PREFIX(wxHW_SCROLLBAR_AUTO, wx.html.); + ADD_PREDEFINED_PREFIX(wxHW_SCROLLBAR_NEVER, wx.html.); + + ADD_PREDEFINED_PREFIX(wxAUI_NB_BOTTOM, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_CLOSE_BUTTON, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_CLOSE_ON_ACTIVE_TAB, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_CLOSE_ON_ALL_TABS, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_DEFAULT_STYLE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_LEFT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_MIDDLE_CLICK_CLOSE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_RIGHT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_SCROLL_BUTTONS, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_EXTERNAL_MOVE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_FIXED_WIDTH, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_MOVE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TAB_SPLIT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_TOP, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_NB_WINDOWLIST_BUTTON, wx.aui.); + + ADD_PREDEFINED_PREFIX(wxAUI_TB_TEXT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_NO_TOOLTIPS, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_NO_AUTORESIZE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_GRIPPER, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_OVERFLOW, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_VERTICAL, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_HORZ_LAYOUT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_HORZ_TEXT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_PLAIN_BACKGROUND, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_TB_DEFAULT_STYLE, wx.aui.); + + ADD_PREDEFINED_PREFIX(wxAUI_MGR_ALLOW_FLOATING, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_ALLOW_ACTIVE_PANE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_TRANSPARENT_DRAG, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_TRANSPARENT_HINT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_VENETIAN_BLINDS_HINT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_RECTANGLE_HINT, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_HINT_FADE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_NO_VENETIAN_BLINDS_FADE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_LIVE_RESIZE, wx.aui.); + ADD_PREDEFINED_PREFIX(wxAUI_MGR_DEFAULT, wx.aui.); + + ADD_PREDEFINED_PREFIX(wxGRID_AUTOSIZE, wx.grid.); + + ADD_PREDEFINED_PREFIX(wxAC_DEFAULT_STYLE, wx.adv.); + ADD_PREDEFINED_PREFIX(wxAC_NO_AUTORESIZE, wx.adv.); + + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_DEFAULT_STYLE, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_FOLDBAR_STYLE, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_SHOW_PAGE_LABELS, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_SHOW_PAGE_ICONS, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_FLOW_HORIZONTAL, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_FLOW_VERTICAL, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_SHOW_PANEL_EXT_BUTTONS, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_SHOW_TOGGLE_BUTTON, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_BAR_SHOW_HELP_BUTTON, wx.lib.agw.ribbon.); + + ADD_PREDEFINED_PREFIX(wxRIBBON_PANEL_DEFAULT_STYLE, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_PANEL_NO_AUTO_MINIMISE, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_PANEL_EXT_BUTTON, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_PANEL_MINIMISE_BUTTON, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_PANEL_STRETCH, wx.lib.agw.ribbon.); + ADD_PREDEFINED_PREFIX(wxRIBBON_PANEL_FLEXIBLE, wx.lib.agw.ribbon.); + + ADD_PREDEFINED_PREFIX(wxPG_AUTO_SORT, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_HIDE_CATEGORIES, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_ALPHABETIC_MODE, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_BOLD_MODIFIED, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_SPLITTER_AUTO_CENTER, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_TOOLTIPS, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_HIDE_MARGIN, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_STATIC_SPLITTER, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_STATIC_LAYOUT, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_LIMITED_EDITING, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_DEFAULT_STYLE, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_INIT_NOCAT, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_NO_FLAT_TOOLBAR, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_MODE_BUTTONS, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_HELP_AS_TOOLTIPS, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_NATIVE_DOUBLE_BUFFERING, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_AUTO_UNSPECIFIED_VALUES, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_WRITEONLY_BUILTIN_ATTRIBUTES, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_HIDE_PAGE_BUTTONS, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_MULTIPLE_SELECTION, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_ENABLE_TLP_TRACKING, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_NO_TOOLBAR_DIVIDER, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_EX_TOOLBAR_SEPARATOR, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_DESCRIPTION, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_TOOLBAR, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPGMAN_DEFAULT_STYLE, wx.propgrid.); + ADD_PREDEFINED_PREFIX(wxPG_NO_INTERNAL_BORDER, wx.propgrid.); + + ADD_PREDEFINED_PREFIX(wxDATAVIEW_CELL_ACTIVATABLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDATAVIEW_CELL_INERT, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDATAVIEW_COL_HIDDEN, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDATAVIEW_COL_REORDERABLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDATAVIEW_COL_RESIZABLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDATAVIEW_COL_SORTABLE, wx.dataview.); + + ADD_PREDEFINED_PREFIX(wxDV_SINGLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDV_MULTIPLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDV_ROW_LINES, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDV_HORIZ_RULES, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDV_VERT_RULES, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDV_VARIABLE_LINE_HEIGHT, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxDV_NO_HEADER, wx.dataview.); + + ADD_PREDEFINED_PREFIX(wxTL_SINGLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxTL_MULTIPLE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxTL_CHECKBOX, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxTL_3STATE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxTL_USER_3STATE, wx.dataview.); + ADD_PREDEFINED_PREFIX(wxTL_DEFAULT_STYLE, wx.dataview.); + + ADD_PREDEFINED_PREFIX(wxDP_SPIN, wx.adv.); + ADD_PREDEFINED_PREFIX(wxDP_DROPDOWN, wx.adv.); + ADD_PREDEFINED_PREFIX(wxDP_SHOWCENTURY, wx.adv.); + ADD_PREDEFINED_PREFIX(wxDP_ALLOWNONE, wx.adv.); + ADD_PREDEFINED_PREFIX(wxDP_DEFAULT, wx.adv.); + + ADD_PREDEFINED_PREFIX(wxTP_DEFAULT, wx.adv.); } diff --git a/src/codegen/pythoncg.h b/src/codegen/pythoncg.h index fa23c3cfb..34dfe993c 100644 --- a/src/codegen/pythoncg.h +++ b/src/codegen/pythoncg.h @@ -31,7 +31,8 @@ @author Michal Bližňák - michal.bliznak@gmail.com @note The implementation of the generation of relative paths is a little hacky, and not a solution. -The value of all properties that are file or a directory paths must be absolute, otherwise the code generation will not work. +The value of all properties that are file or a directory paths must be absolute, otherwise the code generation will not +work. */ #ifndef CODEGEN_PYTHONCG_H @@ -41,219 +42,223 @@ The value of all properties that are file or a directory paths must be absolute, #define fbfSILENT true #define fbfMESSAGE false -#include "codegen/codegen.h" - #include #include #include +#include "codegen/codegen.h" + + /** -* Parse the Python templates. -*/ + * Parse the Python templates. + */ class PythonTemplateParser : public TemplateParser { private: - bool m_i18n; - bool m_useRelativePath; - wxString m_basePath; - wxString m_imagePathWrapperFunctionName; + bool m_i18n; + bool m_useRelativePath; + wxString m_basePath; + wxString m_imagePathWrapperFunctionName; - std::map m_predModulePrefix; + std::map m_predModulePrefix; - void SetupModulePrefixes(); + void SetupModulePrefixes(); public: - PythonTemplateParser( PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, wxString imagePathWrapperFunctionName ); - PythonTemplateParser( const PythonTemplateParser & that, wxString _template ); - - // overrides for Python - PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; - wxString RootWxParentToCode() override; - wxString ValueToCode(PropertyType type, wxString value) override; + PythonTemplateParser( + PObjectBase obj, wxString _template, bool useI18N, bool useRelativePath, wxString basePath, + wxString imagePathWrapperFunctionName); + PythonTemplateParser(const PythonTemplateParser& that, wxString _template); + + // overrides for Python + PTemplateParser CreateParser(const TemplateParser* oldparser, wxString _template) override; + wxString RootWxParentToCode() override; + wxString ValueToCode(PropertyType type, wxString value) override; }; /** -* Generate the Python code -*/ + * Generate the Python code + */ class PythonCodeGenerator : public CodeGenerator { private: - PCodeWriter m_source; - - bool m_useRelativePath; - bool m_i18n; - wxString m_basePath; - wxString m_imagePathWrapperFunctionName; - unsigned int m_firstID; - bool m_disconnectEvents; - wxString m_disconnecMode; - - /** - * Predefined macros won't generate defines. - */ - std::set m_predMacros; - - void SetupPredefinedMacros(); - - /** - * Given an object and the name for a template, obtains the code. - */ - wxString GetCode( PObjectBase obj, wxString name, bool silent = false); - - /** - * Gets the construction fragment for the specified object. - * - * This method encapsulates the adjustments that need to be made for array declarations. - */ - wxString GetConstruction(PObjectBase obj, bool silent, ArrayItems& arrays); - - /** - * Stores the project's objects classes set, for generating the includes. - */ - void FindDependencies( PObjectBase obj, std::set< PObjectInfo >& info_set ); - - /** - * Stores all the properties for "macro" type objects, so that their - * related '#define' can be generated subsequently. - */ - void FindMacros( PObjectBase obj, std::vector< wxString >* macros ); - - /** - * Looks for "non-null" event handlers (PEvent) and collects it into a vector. - */ - void FindEventHandlers(PObjectBase obj, EventVector &events); - - /** - * Generates classes declarations inside the header file. - */ - void GenClassDeclaration(PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, const wxString& eventHandlerPostfix, ArrayItems& arrays); - - /** - * Generates the event table. - */ - void GenEvents( PObjectBase class_obj, const EventVector &events, bool disconnect = false ); - - /** - * helper function to find the event table entry template in the class or its base classes - */ - bool GenEventEntry( PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, bool disconnect = false ); - - /** - * Generates the generated_event_handlers template - */ - void GetGenEventHandlers( PObjectBase obj ); - /** - * Generates the generated_event_handlers template - */ - void GenDefinedEventHandlers( PObjectInfo info, PObjectBase obj ); - - /** - * Generates the 'import' section for files. - */ - void GenIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenObjectIncludes( PObjectBase project, std::vector< wxString >* includes, std::set< wxString >* templates ); - void GenBaseIncludes( PObjectInfo info, PObjectBase obj, std::vector< wxString >* includes, std::set< wxString >* templates ); - void AddUniqueIncludes( const wxString& include, std::vector< wxString >* includes ); - - /** - * Generate a set of all subclasses to forward declare in the generated file. - */ - void GenSubclassSets( PObjectBase obj, std::set< wxString >* subclasses, std::vector< wxString >* headerIncludes ); - - /** - * Generates the '#define' section for macros. - */ - void GenDefines( PObjectBase project); - - /** - * Generates the constructor for a class - */ - void GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays); - - /** - * Generates the destructor for a class - */ - void GenDestructor( PObjectBase class_obj, const EventVector &events ); - - /** - * Makes the objects construction, setting up the objects' and Layout properties. - * The algorithm is similar to that used in the designer preview generation. - */ - void GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays); - - /** - * Makes the objects destructions. - */ - void GenDestruction( PObjectBase obj); - - /** - * Configures the object properties, both own and inherited ones. - * Information for the class is given, because it will recursively make the - * configuration in the "super-classes". - */ - void GenSettings( PObjectInfo info, PObjectBase obj); - - /** - * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where - * the template is found, and the objectbase for the control. - */ - void GenAddToolbar( PObjectInfo info, PObjectBase obj ); - void GetAddToolbarCode( PObjectInfo info, PObjectBase obj, wxArrayString& codelines ); - - void GenVirtualEventHandlers( const EventVector &events, const wxString& eventHandlerPostfix ); - void GenImagePathWrapperFunction(); + PCodeWriter m_source; + + bool m_useRelativePath; + bool m_i18n; + wxString m_basePath; + wxString m_imagePathWrapperFunctionName; + unsigned int m_firstID; + bool m_disconnectEvents; + wxString m_disconnecMode; + + /** + * Predefined macros won't generate defines. + */ + std::set m_predMacros; + + void SetupPredefinedMacros(); + + /** + * Given an object and the name for a template, obtains the code. + */ + wxString GetCode(PObjectBase obj, wxString name, bool silent = false); + + /** + * Gets the construction fragment for the specified object. + * + * This method encapsulates the adjustments that need to be made for array declarations. + */ + wxString GetConstruction(PObjectBase obj, bool silent, ArrayItems& arrays); + + /** + * Stores the project's objects classes set, for generating the includes. + */ + void FindDependencies(PObjectBase obj, std::set& info_set); + + /** + * Stores all the properties for "macro" type objects, so that their + * related '#define' can be generated subsequently. + */ + void FindMacros(PObjectBase obj, std::vector* macros); + + /** + * Looks for "non-null" event handlers (PEvent) and collects it into a vector. + */ + void FindEventHandlers(PObjectBase obj, EventVector& events); + + /** + * Generates classes declarations inside the header file. + */ + void GenClassDeclaration( + PObjectBase class_obj, bool use_enum, const wxString& classDecoration, const EventVector& events, + const wxString& eventHandlerPostfix, ArrayItems& arrays); + + /** + * Generates the event table. + */ + void GenEvents(PObjectBase class_obj, const EventVector& events, bool disconnect = false); + + /** + * helper function to find the event table entry template in the class or its base classes + */ + bool GenEventEntry( + PObjectBase obj, PObjectInfo obj_info, const wxString& templateName, const wxString& handlerName, + bool disconnect = false); + + /** + * Generates the generated_event_handlers template + */ + void GetGenEventHandlers(PObjectBase obj); + /** + * Generates the generated_event_handlers template + */ + void GenDefinedEventHandlers(PObjectInfo info, PObjectBase obj); + + /** + * Generates the 'import' section for files. + */ + void GenIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenObjectIncludes(PObjectBase project, std::vector* includes, std::set* templates); + void GenBaseIncludes( + PObjectInfo info, PObjectBase obj, std::vector* includes, std::set* templates); + void AddUniqueIncludes(const wxString& include, std::vector* includes); + + /** + * Generate a set of all subclasses to forward declare in the generated file. + */ + void GenSubclassSets(PObjectBase obj, std::set* subclasses, std::vector* headerIncludes); + + /** + * Generates the '#define' section for macros. + */ + void GenDefines(PObjectBase project); + + /** + * Generates the constructor for a class + */ + void GenConstructor(PObjectBase class_obj, const EventVector& events, ArrayItems& arrays); + + /** + * Generates the destructor for a class + */ + void GenDestructor(PObjectBase class_obj, const EventVector& events); + + /** + * Makes the objects construction, setting up the objects' and Layout properties. + * The algorithm is similar to that used in the designer preview generation. + */ + void GenConstruction(PObjectBase obj, bool is_widget, ArrayItems& arrays); + + /** + * Makes the objects destructions. + */ + void GenDestruction(PObjectBase obj); + + /** + * Configures the object properties, both own and inherited ones. + * Information for the class is given, because it will recursively make the + * configuration in the "super-classes". + */ + void GenSettings(PObjectInfo info, PObjectBase obj); + + /** + * Adds a control for a toolbar. Needs the objectinfo (wxWindow type) where + * the template is found, and the objectbase for the control. + */ + void GenAddToolbar(PObjectInfo info, PObjectBase obj); + void GetAddToolbarCode(PObjectInfo info, PObjectBase obj, wxArrayString& codelines); + + void GenVirtualEventHandlers(const EventVector& events, const wxString& eventHandlerPostfix); + void GenImagePathWrapperFunction(); public: - /** - * Convert a wxString to the "C/C++" format. - */ - static wxString ConvertPythonString( wxString text); - - PythonCodeGenerator(); - - /** - * Set the codewriter for the source file - */ - void SetSourceWriter( PCodeWriter cw ) - { - m_source = cw; - } - - - /** - * Configures the reference path for generating relative paths to - * that passed as parameter. - * - * @note path is generated with the separators, '/', since on Windows - * the compilers interpret path correctly. - */ - void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); - - /** - * Set the First ID used during Code Generation. - */ - void SetFirstID( const unsigned int id ){ m_firstID = id; } - - /** - * Configures the function name, image paths should be wrapped - * into when generating python code. - * - * When set to a non-empty string, this will generate a default - * implementation of the method in each class, that just returns - * the unmodified path string. - */ - void SetImagePathWrapperFunctionName( wxString imagePathWrapperFunctionName ); - - /** - * Generate the project's code - */ - bool GenerateCode(PObjectBase project) override; - - /** - * Generate an inherited class - */ - void GenerateInheritedClass( PObjectBase userClasses, PObjectBase form ); + /** + * Convert a wxString to the "C/C++" format. + */ + static wxString ConvertPythonString(wxString text); + + PythonCodeGenerator(); + + /** + * Set the codewriter for the source file + */ + void SetSourceWriter(PCodeWriter cw) { m_source = cw; } + + + /** + * Configures the reference path for generating relative paths to + * that passed as parameter. + * + * @note path is generated with the separators, '/', since on Windows + * the compilers interpret path correctly. + */ + void UseRelativePath(bool relative = false, wxString basePath = wxEmptyString); + + /** + * Set the First ID used during Code Generation. + */ + void SetFirstID(const unsigned int id) { m_firstID = id; } + + /** + * Configures the function name, image paths should be wrapped + * into when generating python code. + * + * When set to a non-empty string, this will generate a default + * implementation of the method in each class, that just returns + * the unmodified path string. + */ + void SetImagePathWrapperFunctionName(wxString imagePathWrapperFunctionName); + + /** + * Generate the project's code + */ + bool GenerateCode(PObjectBase project) override; + + /** + * Generate an inherited class + */ + void GenerateInheritedClass(PObjectBase userClasses, PObjectBase form); }; - -#endif // CODEGEN_PYTHONCG_H +#endif // CODEGEN_PYTHONCG_H diff --git a/src/codegen/xrccg.cpp b/src/codegen/xrccg.cpp index ba6341a71..361395871 100644 --- a/src/codegen/xrccg.cpp +++ b/src/codegen/xrccg.cpp @@ -25,210 +25,180 @@ #include "xrccg.h" +#include + +#include "codegen/codewriter.h" #include "model/objectbase.h" #include "utils/typeconv.h" -#include "codegen/codewriter.h" -#include -void XrcCodeGenerator::SetWriter( PCodeWriter cw ) +void XrcCodeGenerator::SetWriter(PCodeWriter cw) { - m_cw = cw; + m_cw = cw; } -bool XrcCodeGenerator::GenerateCode( PObjectBase project ) +bool XrcCodeGenerator::GenerateCode(PObjectBase project) { - m_cw->Clear(); - m_contextMenus.clear(); - - ticpp::Document doc; - ticpp::Declaration decl( "1.0", "UTF-8", "yes" ); - doc.LinkEndChild( &decl ); - - ticpp::Element element( "resource" ); - element.SetAttribute("xmlns", "http://www.wxwidgets.org/wxxrc"); - element.SetAttribute("version", "2.5.3.0"); - - // If project is not actually a "Project", generate it - if ( project->GetClassName() == wxT("Project") ) - { - for( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - ticpp::Element* child = GetElement( project->GetChild( i ) ); - if ( child ) - { - element.LinkEndChild( child ); - delete child; - } - } - } - else - { - ticpp::Element* child = GetElement( project ); - if ( child ) - { - element.LinkEndChild( child ); - delete child; - } - } - - // generate context menus as top-level menus - for( std::vector::iterator it = m_contextMenus.begin(); it != m_contextMenus.end(); ++it ) - { - element.LinkEndChild( *it ); - delete *it; - } - - doc.LinkEndChild( &element ); - - TiXmlPrinter printer; - printer.SetIndent( "\t" ); - - printer.SetLineBreak("\n"); - - doc.Accept( &printer ); - const std::string& xrcFile = printer.Str(); - - m_cw->Write( _WXSTR( xrcFile ) ); - - return true; - + m_cw->Clear(); + m_contextMenus.clear(); + + ticpp::Document doc; + ticpp::Declaration decl("1.0", "UTF-8", "yes"); + doc.LinkEndChild(&decl); + + ticpp::Element element("resource"); + element.SetAttribute("xmlns", "http://www.wxwidgets.org/wxxrc"); + element.SetAttribute("version", "2.5.3.0"); + + // If project is not actually a "Project", generate it + if (project->GetClassName() == wxT("Project")) { + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + ticpp::Element* child = GetElement(project->GetChild(i)); + if (child) { + element.LinkEndChild(child); + delete child; + } + } + } else { + ticpp::Element* child = GetElement(project); + if (child) { + element.LinkEndChild(child); + delete child; + } + } + + // generate context menus as top-level menus + for (std::vector::iterator it = m_contextMenus.begin(); it != m_contextMenus.end(); ++it) { + element.LinkEndChild(*it); + delete *it; + } + + doc.LinkEndChild(&element); + + TiXmlPrinter printer; + printer.SetIndent("\t"); + + printer.SetLineBreak("\n"); + + doc.Accept(&printer); + const std::string& xrcFile = printer.Str(); + + m_cw->Write(_WXSTR(xrcFile)); + + return true; } -ticpp::Element* XrcCodeGenerator::GetElement( PObjectBase obj, ticpp::Element* parent ) +ticpp::Element* XrcCodeGenerator::GetElement(PObjectBase obj, ticpp::Element* parent) { - ticpp::Element *element = NULL; - - IComponent *comp = obj->GetObjectInfo()->GetComponent(); - - if ( comp ) - element = comp->ExportToXrc( obj.get() ); - - if ( element ) - { - std::string class_name = element->GetAttribute( "class" ); - if ( class_name == "__dummyitem__" ) - { - delete element; - element = NULL; - - if ( obj->GetChildCount() > 0 ) - element = GetElement( obj->GetChild( 0 ) ); - - return element; - } - else if ( class_name == "spacer" ) - { - // Dirty hack to replace the containing sizeritem with the spacer - if ( parent ) - { - parent->SetAttribute( "class", "spacer" ); - for ( ticpp::Node* child = element->FirstChild( false ); child; child = child->NextSibling( false ) ) - { - parent->LinkEndChild( child->Clone().release() ); - } - delete element; - return NULL; - } - - } - else if ( class_name == "wxFrame" ) - { - // Dirty hack to prevent sizer generation directly under a wxFrame - // If there is a sizer, the size property of the wxFrame is ignored - // when loading the xrc file at runtime - if (obj->GetPropertyAsInteger(_("xrc_skip_sizer")) != 0) { - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - ticpp::Element* aux = NULL; - - PObjectBase child = obj->GetChild( i ); - if ( child->GetObjectInfo()->IsSubclassOf( wxT("sizer") ) ) - { - if ( child->GetChildCount() == 1 ) - { - PObjectBase sizeritem = child->GetChild( 0 ); - if ( sizeritem ) - { - aux = GetElement( sizeritem->GetChild( 0 ), element ); - } - } - } - - if ( !aux ) - { - aux = GetElement( child, element ); - } - - if ( aux ) - { - element->LinkEndChild( aux ); - delete aux; - } - } - return element; - } - } - else if( class_name == "wxMenu" ) - { - if (parent) { - // Do not generate context menus assigned to forms or widgets - std::string parent_name = parent->GetAttribute("class"); - if ((parent_name != "wxMenuBar") && (parent_name != "wxMenu")) { - // insert context menu into vector for delayed processing (context menus will be - // generated as top-level menus) - for (unsigned int i = 0; i < obj->GetChildCount(); i++) { - ticpp::Element* aux = GetElement(obj->GetChild(i), element); - if (aux) { - element->LinkEndChild(aux); - delete aux; - } - } - - m_contextMenus.push_back(element); - return nullptr; - } - } - } - else if ( class_name == "wxCollapsiblePane" ) - { - if (obj->GetChildCount() > 0) { - ticpp::Element *aux = new ticpp::Element( "object" ); - aux->SetAttribute( "class", "panewindow" ); - - ticpp::Element *child = GetElement( obj->GetChild( 0 ), aux ); - - aux->LinkEndChild( child ); - element->LinkEndChild( aux ); - - delete aux; - delete child; - } - - return element; - } - - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - ticpp::Element *aux = GetElement( obj->GetChild( i ), element ); - if ( aux ) - { - element->LinkEndChild( aux ); - delete aux; - } - } - } - else - { - if( obj->GetObjectTypeName() != wxT("nonvisual") ) - { - // The componenet does not XRC - element = new ticpp::Element( "object" ); - element->SetAttribute( "class", "unknown" ); - element->SetAttribute( "name", _STDSTR( obj->GetPropertyAsString( _( "name" ) ) ) ); - } - } - - return element; + ticpp::Element* element = NULL; + + IComponent* comp = obj->GetObjectInfo()->GetComponent(); + + if (comp) + element = comp->ExportToXrc(obj.get()); + + if (element) { + std::string class_name = element->GetAttribute("class"); + if (class_name == "__dummyitem__") { + delete element; + element = NULL; + + if (obj->GetChildCount() > 0) + element = GetElement(obj->GetChild(0)); + + return element; + } else if (class_name == "spacer") { + // Dirty hack to replace the containing sizeritem with the spacer + if (parent) { + parent->SetAttribute("class", "spacer"); + for (ticpp::Node* child = element->FirstChild(false); child; child = child->NextSibling(false)) { + parent->LinkEndChild(child->Clone().release()); + } + delete element; + return NULL; + } + + } else if (class_name == "wxFrame") { + // Dirty hack to prevent sizer generation directly under a wxFrame + // If there is a sizer, the size property of the wxFrame is ignored + // when loading the xrc file at runtime + if (obj->GetPropertyAsInteger(_("xrc_skip_sizer")) != 0) { + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + ticpp::Element* aux = NULL; + + PObjectBase child = obj->GetChild(i); + if (child->GetObjectInfo()->IsSubclassOf(wxT("sizer"))) { + if (child->GetChildCount() == 1) { + PObjectBase sizeritem = child->GetChild(0); + if (sizeritem) { + aux = GetElement(sizeritem->GetChild(0), element); + } + } + } + + if (!aux) { + aux = GetElement(child, element); + } + + if (aux) { + element->LinkEndChild(aux); + delete aux; + } + } + return element; + } + } else if (class_name == "wxMenu") { + if (parent) { + // Do not generate context menus assigned to forms or widgets + std::string parent_name = parent->GetAttribute("class"); + if ((parent_name != "wxMenuBar") && (parent_name != "wxMenu")) { + // insert context menu into vector for delayed processing (context menus will be + // generated as top-level menus) + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + ticpp::Element* aux = GetElement(obj->GetChild(i), element); + if (aux) { + element->LinkEndChild(aux); + delete aux; + } + } + + m_contextMenus.push_back(element); + return nullptr; + } + } + } else if (class_name == "wxCollapsiblePane") { + if (obj->GetChildCount() > 0) { + ticpp::Element* aux = new ticpp::Element("object"); + aux->SetAttribute("class", "panewindow"); + + ticpp::Element* child = GetElement(obj->GetChild(0), aux); + + aux->LinkEndChild(child); + element->LinkEndChild(aux); + + delete aux; + delete child; + } + + return element; + } + + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + ticpp::Element* aux = GetElement(obj->GetChild(i), element); + if (aux) { + element->LinkEndChild(aux); + delete aux; + } + } + } else { + if (obj->GetObjectTypeName() != wxT("nonvisual")) { + // The componenet does not XRC + element = new ticpp::Element("object"); + element->SetAttribute("class", "unknown"); + element->SetAttribute("name", _STDSTR(obj->GetPropertyAsString(_("name")))); + } + } + + return element; } diff --git a/src/codegen/xrccg.h b/src/codegen/xrccg.h index 3288cd067..52cb49547 100644 --- a/src/codegen/xrccg.h +++ b/src/codegen/xrccg.h @@ -28,9 +28,10 @@ #include "codegen/codegen.h" + namespace ticpp { - class Element; +class Element; } /// XRC code generator. @@ -38,18 +39,17 @@ namespace ticpp class XrcCodeGenerator : public CodeGenerator { private: - PCodeWriter m_cw; - std::vector m_contextMenus; + PCodeWriter m_cw; + std::vector m_contextMenus; - ticpp::Element* GetElement( PObjectBase obj, ticpp::Element* parent = NULL ); + ticpp::Element* GetElement(PObjectBase obj, ticpp::Element* parent = NULL); public: - /// Configures the code writer for the XML file. - void SetWriter( PCodeWriter cw ); + /// Configures the code writer for the XML file. + void SetWriter(PCodeWriter cw); - /// Generates the XRC code for the project. - bool GenerateCode(PObjectBase project) override; + /// Generates the XRC code for the project. + bool GenerateCode(PObjectBase project) override; }; - -#endif // CODEGEN_XRCCG_H +#endif // CODEGEN_XRCCG_H diff --git a/src/maingui.cpp b/src/maingui.cpp index ee481e6d2..39334a6ee 100644 --- a/src/maingui.cpp +++ b/src/maingui.cpp @@ -22,457 +22,404 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "maingui.h" +#include +#include +#include +#include +#include + #include "model/objectbase.h" #include "rad/appdata.h" +#include "rad/mainframe.h" #include "rad/revision.h" #include "rad/version.h" -#include "rad/mainframe.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include -#include -#include -#include -#include - #if wxVERSION_NUMBER >= 2905 && wxVERSION_NUMBER <= 3100 -#include + #include #elif wxVERSION_NUMBER > 3100 -#include + #include #endif // Abnormal Termination Handling #if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER - #include + #include #elif defined(_WIN32) && defined(__MINGW32__) - #include - #include - #include - - #if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR /* MinGW-w64 required */ - __stdcall EXCEPTION_DISPOSITION StructuredExceptionHandler( struct _EXCEPTION_RECORD *ExceptionRecord, /* breaks build with MinGW 32 */ - void * EstablisherFrame, - struct _CONTEXT *ContextRecord, - void * DispatcherContext ); - #else - EXCEPTION_DISPOSITION StructuredExceptionHandler( struct _EXCEPTION_RECORD *ExceptionRecord, - void * EstablisherFrame, - struct _CONTEXT *ContextRecord, - void * DispatcherContext ); - #endif + #include + #include + #include + + #if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR /* MinGW-w64 required */ +__stdcall EXCEPTION_DISPOSITION StructuredExceptionHandler( + struct _EXCEPTION_RECORD* ExceptionRecord, /* breaks build with MinGW 32 */ + void* EstablisherFrame, struct _CONTEXT* ContextRecord, void* DispatcherContext); + #else +EXCEPTION_DISPOSITION StructuredExceptionHandler( + struct _EXCEPTION_RECORD* ExceptionRecord, void* EstablisherFrame, struct _CONTEXT* ContextRecord, + void* DispatcherContext); + #endif #endif void LogStack(); static const wxCmdLineEntryDesc s_cmdLineDesc[] = { - { wxCMD_LINE_SWITCH, "g", "generate", "Generate code from passed file.", wxCMD_LINE_VAL_STRING, - 0 }, - { wxCMD_LINE_OPTION, "l", "language", - "Override the code_generation property from the passed file and generate the passed " - "languages. Separate multiple languages with commas.", - wxCMD_LINE_VAL_STRING, 0 }, - { wxCMD_LINE_SWITCH, "h", "help", "Show this help message.", wxCMD_LINE_VAL_STRING, - wxCMD_LINE_OPTION_HELP }, - { wxCMD_LINE_SWITCH, "v", "version", "Print version information.", wxCMD_LINE_VAL_STRING, 0 }, - { wxCMD_LINE_PARAM, nullptr, nullptr, "File to open.", wxCMD_LINE_VAL_STRING, - wxCMD_LINE_PARAM_OPTIONAL }, - { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 } -}; + {wxCMD_LINE_SWITCH, "g", "generate", "Generate code from passed file.", wxCMD_LINE_VAL_STRING, 0}, + {wxCMD_LINE_OPTION, "l", "language", + "Override the code_generation property from the passed file and generate the passed " + "languages. Separate multiple languages with commas.", + wxCMD_LINE_VAL_STRING, 0}, + {wxCMD_LINE_SWITCH, "h", "help", "Show this help message.", wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_HELP}, + {wxCMD_LINE_SWITCH, "v", "version", "Print version information.", wxCMD_LINE_VAL_STRING, 0}, + {wxCMD_LINE_PARAM, nullptr, nullptr, "File to open.", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL}, + {wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0}}; + +IMPLEMENT_APP(MyApp) -IMPLEMENT_APP( MyApp ) int MyApp::OnRun() { - // Abnormal Termination Handling - #if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER - ::wxHandleFatalExceptions( true ); - #elif defined(_WIN32) && defined(__MINGW32__) - // Structured Exception handlers are stored in a linked list at FS:[0] for 32-bit and GS:[0] for 64-bit - // https://github.com/wine-mirror/wine/blob/1aff1e6a370ee8c0213a0fd4b220d121da8527aa/include/winternl.h#L347 - // THIS MUST BE A LOCAL VARIABLE - windows won't use an object outside of the thread's stack frame - EXCEPTION_REGISTRATION ex; - ex.handler = StructuredExceptionHandler; - - #if defined(__amd64__) || defined(__x86_64__) // 64-bit - asm volatile ("movq %%gs:0, %0" : "=r" (ex.prev)); - asm volatile ("movq %0, %%gs:0" : : "r" (&ex)); - #elif defined(__i386__) || defined(_X86_) // 32-bit - asm volatile ("movl %%fs:0, %0" : "=r" (ex.prev)); - asm volatile ("movl %0, %%fs:0" : : "r" (&ex)); - #endif - #endif - - // Using a space so the initial 'w' will not be capitalized in wxLogGUI dialogs - wxApp::SetAppName( wxT( " wxFormBuilder" ) ); - - // Creating the wxConfig manually so there will be no space - // The old config (if any) is returned, delete it - delete wxConfigBase::Set( new wxConfig( wxT("wxFormBuilder") ) ); - - // Get the data directory - auto& stdPaths = wxStandardPaths::Get(); - #if defined(__WINDOWS__) - // The CMake stage build roots the whole directory structure at the build directory - // so don't ignore that one - stdPaths.DontIgnoreAppSubDir(); - #endif - wxString dataDir = stdPaths.GetDataDir(); - dataDir.Replace( GetAppName(), wxT("wxformbuilder") ); - - // Log to stderr while working on the command line - delete wxLog::SetActiveTarget( new wxLogStderr ); - - // Message output to the same as the log target - delete wxMessageOutput::Set( new wxMessageOutputLog ); - - // Parse command line - wxCmdLineParser parser( s_cmdLineDesc, argc, argv ); - if ( 0 != parser.Parse() ) - { - return 1; - } - - if (parser.Found("v")) { - std::cout << "wxFormBuilder " << getVersion() << getPostfixRevision(getVersion()) << std::endl; - return EXIT_SUCCESS; - } - - // Get project to load - wxString projectToLoad = wxEmptyString; - if ( parser.GetParamCount() > 0 ) - { - projectToLoad = parser.GetParam(); - } - - bool justGenerate = false; - wxString language; - bool hasLanguage = parser.Found( wxT("l"), &language ); - if ( parser.Found( wxT("g") ) ) - { - if ( projectToLoad.empty() ) - { - wxLogError( _("You must pass a path to a project file. Nothing to generate.") ); - return 2; - } - - if ( hasLanguage ) - { - if ( language.empty() ) - { - wxLogError( _("Empty language option. Nothing generated.") ); - return 3; - } - language.Replace( wxT(","), wxT("|"), true ); - } - - // generate code - justGenerate = true; - } - else - { - delete wxLog::SetActiveTarget( new wxLogGui ); - } - - // Create singleton AppData - wait to initialize until sure that this is not the second - // instance of a project file. - AppDataCreate( dataDir ); - - // Make passed project name absolute - try - { - if ( !projectToLoad.empty() ) - { - wxFileName projectPath( projectToLoad ); - if ( !projectPath.IsOk() ) - { - THROW_WXFBEX( wxT("This path is invalid: ") << projectToLoad ); - } - - if ( !projectPath.IsAbsolute() ) - { - if ( !projectPath.MakeAbsolute() ) - { - THROW_WXFBEX( wxT("Could not make path absolute: ") << projectToLoad ); - } - } - projectToLoad = projectPath.GetFullPath(); - } - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - - // If the project is already loaded in another instance, switch to that instance and quit - if ( !projectToLoad.empty() && !justGenerate ) - { - if ( ::wxFileExists( projectToLoad ) ) - { - if ( !AppData()->VerifySingleInstance( projectToLoad ) ) - { - return 4; - } - } - } - - // Init handlers - wxInitAllImageHandlers(); - wxXmlResource::Get()->InitAllHandlers(); - #if wxVERSION_NUMBER >= 2905 && wxVERSION_NUMBER <= 3100 - wxXmlResource::Get()->AddHandler(new wxAuiNotebookXmlHandler); - #elif wxVERSION_NUMBER > 3100 - wxXmlResource::Get()->AddHandler(new wxAuiXmlHandler); - #endif - - // Init AppData - try - { - AppDataInit(); - } - catch( wxFBException& ex ) - { - wxLogError( _("Error loading application: %s\nwxFormBuilder cannot continue."), ex.what() ); - wxLog::FlushActive(); - return 5; - } - - wxSystemOptions::SetOption( wxT( "msw.remap" ), 0 ); - wxSystemOptions::SetOption( wxT( "msw.staticbox.optimized-paint" ), 0 ); - - m_frame = NULL; - - wxYield(); - - // Read size and position from config file - wxConfigBase *config = wxConfigBase::Get(); - config->SetPath( wxT("/mainframe") ); - int x, y, w, h; - x = y = w = h = -1; - config->Read( wxT( "PosX" ), &x ); - config->Read( wxT( "PosY" ), &y ); - config->Read( wxT( "SizeW" ), &w ); - config->Read( wxT( "SizeH" ), &h ); - - long style = config->Read( wxT("style"), wxFB_WIDE_GUI ); - if ( style != wxFB_CLASSIC_GUI ) - { - style = wxFB_WIDE_GUI; - } - - config->SetPath( wxT("/") ); - - m_frame = new MainFrame( NULL ,wxID_ANY, (int)style, wxPoint( x, y ), wxSize( w, h ) ); - if ( !justGenerate ) - { - m_frame->Show( TRUE ); - SetTopWindow( m_frame ); - - #ifdef __WXFB_DEBUG__ - wxLogWindow* log = dynamic_cast< wxLogWindow* >( AppData()->GetDebugLogTarget() ); - if ( log ) - { - m_frame->AddChild( log->GetFrame() ); - } - #endif //__WXFB_DEBUG__ - } - - // This is not necessary for wxFB to work. However, Windows sets the Current Working Directory - // to the directory from which a .fbp file was opened, if opened from Windows Explorer. - // This puts an unnecessary lock on the directory. - // This changes the CWD to the already locked app directory as a workaround - #ifdef __WXMSW__ - ::wxSetWorkingDirectory( dataDir ); - #endif - - if ( !projectToLoad.empty() ) - { - if ( AppData()->LoadProject( projectToLoad, justGenerate ) ) - { - if ( justGenerate ) - { - if ( hasLanguage ) - { - PObjectBase project = AppData()->GetProjectData(); - PProperty codeGen = project->GetProperty( _("code_generation") ); - if ( codeGen ) - { - codeGen->SetValue( language ); - } - } - AppData()->GenerateCode( false, true ); - return 0; - } - else - { - m_frame->InsertRecentProject( projectToLoad ); - return wxApp::OnRun(); - } - } - else - { - wxLogError( wxT("Unable to load project: %s"), projectToLoad ); - } - } - - if ( justGenerate ) - { - return 6; - } - - AppData()->NewProject(); +// Abnormal Termination Handling +#if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER + ::wxHandleFatalExceptions(true); +#elif defined(_WIN32) && defined(__MINGW32__) + // Structured Exception handlers are stored in a linked list at FS:[0] for 32-bit and GS:[0] for 64-bit + // https://github.com/wine-mirror/wine/blob/1aff1e6a370ee8c0213a0fd4b220d121da8527aa/include/winternl.h#L347 + // THIS MUST BE A LOCAL VARIABLE - windows won't use an object outside of the thread's stack frame + EXCEPTION_REGISTRATION ex; + ex.handler = StructuredExceptionHandler; + + #if defined(__amd64__) || defined(__x86_64__) // 64-bit + asm volatile("movq %%gs:0, %0" : "=r"(ex.prev)); + asm volatile("movq %0, %%gs:0" : : "r"(&ex)); + #elif defined(__i386__) || defined(_X86_) // 32-bit + asm volatile("movl %%fs:0, %0" : "=r"(ex.prev)); + asm volatile("movl %0, %%fs:0" : : "r"(&ex)); + #endif +#endif + + // Using a space so the initial 'w' will not be capitalized in wxLogGUI dialogs + wxApp::SetAppName(wxT(" wxFormBuilder")); + + // Creating the wxConfig manually so there will be no space + // The old config (if any) is returned, delete it + delete wxConfigBase::Set(new wxConfig(wxT("wxFormBuilder"))); + + // Get the data directory + auto& stdPaths = wxStandardPaths::Get(); +#if defined(__WINDOWS__) + // The CMake stage build roots the whole directory structure at the build directory + // so don't ignore that one + stdPaths.DontIgnoreAppSubDir(); +#endif + wxString dataDir = stdPaths.GetDataDir(); + dataDir.Replace(GetAppName(), wxT("wxformbuilder")); + + // Log to stderr while working on the command line + delete wxLog::SetActiveTarget(new wxLogStderr); + + // Message output to the same as the log target + delete wxMessageOutput::Set(new wxMessageOutputLog); + + // Parse command line + wxCmdLineParser parser(s_cmdLineDesc, argc, argv); + if (0 != parser.Parse()) { + return 1; + } + + if (parser.Found("v")) { + std::cout << "wxFormBuilder " << getVersion() << getPostfixRevision(getVersion()) << std::endl; + return EXIT_SUCCESS; + } + + // Get project to load + wxString projectToLoad = wxEmptyString; + if (parser.GetParamCount() > 0) { + projectToLoad = parser.GetParam(); + } + + bool justGenerate = false; + wxString language; + bool hasLanguage = parser.Found(wxT("l"), &language); + if (parser.Found(wxT("g"))) { + if (projectToLoad.empty()) { + wxLogError(_("You must pass a path to a project file. Nothing to generate.")); + return 2; + } + + if (hasLanguage) { + if (language.empty()) { + wxLogError(_("Empty language option. Nothing generated.")); + return 3; + } + language.Replace(wxT(","), wxT("|"), true); + } + + // generate code + justGenerate = true; + } else { + delete wxLog::SetActiveTarget(new wxLogGui); + } + + // Create singleton AppData - wait to initialize until sure that this is not the second + // instance of a project file. + AppDataCreate(dataDir); + + // Make passed project name absolute + try { + if (!projectToLoad.empty()) { + wxFileName projectPath(projectToLoad); + if (!projectPath.IsOk()) { + THROW_WXFBEX(wxT("This path is invalid: ") << projectToLoad); + } + + if (!projectPath.IsAbsolute()) { + if (!projectPath.MakeAbsolute()) { + THROW_WXFBEX(wxT("Could not make path absolute: ") << projectToLoad); + } + } + projectToLoad = projectPath.GetFullPath(); + } + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + + // If the project is already loaded in another instance, switch to that instance and quit + if (!projectToLoad.empty() && !justGenerate) { + if (::wxFileExists(projectToLoad)) { + if (!AppData()->VerifySingleInstance(projectToLoad)) { + return 4; + } + } + } + + // Init handlers + wxInitAllImageHandlers(); + wxXmlResource::Get()->InitAllHandlers(); +#if wxVERSION_NUMBER >= 2905 && wxVERSION_NUMBER <= 3100 + wxXmlResource::Get()->AddHandler(new wxAuiNotebookXmlHandler); +#elif wxVERSION_NUMBER > 3100 + wxXmlResource::Get()->AddHandler(new wxAuiXmlHandler); +#endif + + // Init AppData + try { + AppDataInit(); + } catch (wxFBException& ex) { + wxLogError(_("Error loading application: %s\nwxFormBuilder cannot continue."), ex.what()); + wxLog::FlushActive(); + return 5; + } + + wxSystemOptions::SetOption(wxT("msw.remap"), 0); + wxSystemOptions::SetOption(wxT("msw.staticbox.optimized-paint"), 0); + + m_frame = NULL; + + wxYield(); + + // Read size and position from config file + wxConfigBase* config = wxConfigBase::Get(); + config->SetPath(wxT("/mainframe")); + int x, y, w, h; + x = y = w = h = -1; + config->Read(wxT("PosX"), &x); + config->Read(wxT("PosY"), &y); + config->Read(wxT("SizeW"), &w); + config->Read(wxT("SizeH"), &h); + + long style = config->Read(wxT("style"), wxFB_WIDE_GUI); + if (style != wxFB_CLASSIC_GUI) { + style = wxFB_WIDE_GUI; + } + + config->SetPath(wxT("/")); + + m_frame = new MainFrame(NULL, wxID_ANY, (int)style, wxPoint(x, y), wxSize(w, h)); + if (!justGenerate) { + m_frame->Show(TRUE); + SetTopWindow(m_frame); + +#ifdef __WXFB_DEBUG__ + wxLogWindow* log = dynamic_cast(AppData()->GetDebugLogTarget()); + if (log) { + m_frame->AddChild(log->GetFrame()); + } +#endif //__WXFB_DEBUG__ + } + +// This is not necessary for wxFB to work. However, Windows sets the Current Working Directory +// to the directory from which a .fbp file was opened, if opened from Windows Explorer. +// This puts an unnecessary lock on the directory. +// This changes the CWD to the already locked app directory as a workaround +#ifdef __WXMSW__ + ::wxSetWorkingDirectory(dataDir); +#endif + + if (!projectToLoad.empty()) { + if (AppData()->LoadProject(projectToLoad, justGenerate)) { + if (justGenerate) { + if (hasLanguage) { + PObjectBase project = AppData()->GetProjectData(); + PProperty codeGen = project->GetProperty(_("code_generation")); + if (codeGen) { + codeGen->SetValue(language); + } + } + AppData()->GenerateCode(false, true); + return 0; + } else { + m_frame->InsertRecentProject(projectToLoad); + return wxApp::OnRun(); + } + } else { + wxLogError(wxT("Unable to load project: %s"), projectToLoad); + } + } + + if (justGenerate) { + return 6; + } + + AppData()->NewProject(); #ifdef __WXMAC__ // document to open on startup - if(!m_mac_file_name.IsEmpty()) - { - if ( AppData()->LoadProject( m_mac_file_name ) ) - m_frame->InsertRecentProject( m_mac_file_name ); + if (!m_mac_file_name.IsEmpty()) { + if (AppData()->LoadProject(m_mac_file_name)) + m_frame->InsertRecentProject(m_mac_file_name); } #endif - return wxApp::OnRun(); + return wxApp::OnRun(); } bool MyApp::OnInit() { - // Initialization is done in OnRun, so MinGW SEH works for all code (it needs a local variable, OnInit is called before OnRun) - return true; + // Initialization is done in OnRun, so MinGW SEH works for all code (it needs a local variable, OnInit is called + // before OnRun) + return true; } int MyApp::OnExit() { - MacroDictionary::Destroy(); - AppDataDestroy(); + MacroDictionary::Destroy(); + AppDataDestroy(); - if( !wxTheClipboard->IsOpened() ) - { - if ( !wxTheClipboard->Open() ) - { + if (!wxTheClipboard->IsOpened()) { + if (!wxTheClipboard->Open()) { return wxApp::OnExit(); } - } + } // Allow clipboard data to persist after close wxTheClipboard->Flush(); wxTheClipboard->Close(); - return wxApp::OnExit(); + return wxApp::OnExit(); } #ifdef __WXMAC__ -void MyApp::MacOpenFile(const wxString &fileName) +void MyApp::MacOpenFile(const wxString& fileName) { - if(m_frame == NULL) m_mac_file_name = fileName; - else - { - if(!m_frame->SaveWarning()) return; - - if ( AppData()->LoadProject( fileName ) ) - m_frame->InsertRecentProject( fileName ); + if (m_frame == NULL) + m_mac_file_name = fileName; + else { + if (!m_frame->SaveWarning()) + return; + + if (AppData()->LoadProject(fileName)) + m_frame->InsertRecentProject(fileName); } } #endif #if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER - class StackLogger : public wxStackWalker - { - protected: - void OnStackFrame(const wxStackFrame& frame) override { - // Build param string - wxString params; - size_t paramCount = frame.GetParamCount(); - if ( paramCount > 0 ) - { - params << wxT("( "); - - for ( size_t i = 0; i < paramCount; ++i ) - { - wxString type, name, value; - if ( frame.GetParam( i, &type, &name, &value) ) - { - params << type << wxT(" ") << name << wxT(" = ") << value << wxT(", "); - } - } - - params << wxT(")"); - } - - wxString source; - if ( frame.HasSourceLocation() ) - { - source.Printf( wxT("%s@%i"), frame.GetFileName(), frame.GetLine() ); - } - - wxLogError( wxT("%03i %i %s %s %s %s"), - frame.GetLevel(), - frame.GetAddress(), - frame.GetModule(), - frame.GetName(), - params, - source ); - } - }; - - void MyApp::OnFatalException() - { - LogStack(); - } +class StackLogger : public wxStackWalker +{ +protected: + void OnStackFrame(const wxStackFrame& frame) override + { + // Build param string + wxString params; + size_t paramCount = frame.GetParamCount(); + if (paramCount > 0) { + params << wxT("( "); + + for (size_t i = 0; i < paramCount; ++i) { + wxString type, name, value; + if (frame.GetParam(i, &type, &name, &value)) { + params << type << wxT(" ") << name << wxT(" = ") << value << wxT(", "); + } + } + + params << wxT(")"); + } + + wxString source; + if (frame.HasSourceLocation()) { + source.Printf(wxT("%s@%i"), frame.GetFileName(), frame.GetLine()); + } + + wxLogError( + wxT("%03i %i %s %s %s %s"), frame.GetLevel(), frame.GetAddress(), frame.GetModule(), frame.GetName(), params, + source); + } +}; + +void MyApp::OnFatalException() +{ + LogStack(); +} #elif defined(_WIN32) && defined(__MINGW32__) - static _CONTEXT* context = 0; - EXCEPTION_DISPOSITION StructuredExceptionHandler( struct _EXCEPTION_RECORD *ExceptionRecord, - void * EstablisherFrame, - struct _CONTEXT *ContextRecord, - void * DispatcherContext ) - { - context = ContextRecord; - LogStack(); - return ExceptionContinueSearch; - } - - class StackLogger - { - public: - virtual ~StackLogger() = default; - - void WalkFromException() - { - try - { - std::stringstream output; - dbg::stack s( 0, context ); - dbg::stack::const_iterator frame; - for ( frame = s.begin(); frame != s.end(); ++frame ) - { - output << *frame; - wxLogError( wxString( output.str().c_str(), *wxConvCurrent ) ); - output.str( "" ); - } - } - catch ( std::exception& ex ) - { - wxLogError( wxString( ex.what(), *wxConvCurrent ) ); - } - } - }; +static _CONTEXT* context = 0; +EXCEPTION_DISPOSITION StructuredExceptionHandler( + struct _EXCEPTION_RECORD* ExceptionRecord, void* EstablisherFrame, struct _CONTEXT* ContextRecord, + void* DispatcherContext) +{ + context = ContextRecord; + LogStack(); + return ExceptionContinueSearch; +} + +class StackLogger +{ +public: + virtual ~StackLogger() = default; + + void WalkFromException() + { + try { + std::stringstream output; + dbg::stack s(0, context); + dbg::stack::const_iterator frame; + for (frame = s.begin(); frame != s.end(); ++frame) { + output << *frame; + wxLogError(wxString(output.str().c_str(), *wxConvCurrent)); + output.str(""); + } + } catch (std::exception& ex) { + wxLogError(wxString(ex.what(), *wxConvCurrent)); + } + } +}; #endif #if (wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER) || (defined(_WIN32) && defined(__MINGW32__)) class LoggingStackWalker : public StackLogger { public: - LoggingStackWalker() { - wxLog::Suspend(); - } + LoggingStackWalker() { wxLog::Suspend(); } - ~LoggingStackWalker() override { - wxLogError( wxT("A Fatal Error Occurred. Click Details for a backtrace.") ); + ~LoggingStackWalker() override + { + wxLogError(wxT("A Fatal Error Occurred. Click Details for a backtrace.")); wxLog::Resume(); wxLog* logger = wxLog::GetActiveTarget(); - if ( 0 != logger ) - { + if (0 != logger) { logger->Flush(); } exit(1); diff --git a/src/maingui.h b/src/maingui.h index 69b2c6530..f990177c1 100644 --- a/src/maingui.h +++ b/src/maingui.h @@ -22,32 +22,35 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef MAINGUI_H #define MAINGUI_H #include + class MainFrame; + class MyApp : public wxApp { private: - MainFrame *m_frame; + MainFrame* m_frame; public: - bool OnInit() override; - #if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER - void OnFatalException() override; - #endif - int OnRun() override; - int OnExit() override; - - #ifdef __WXMAC__ - wxString m_mac_file_name; - void MacOpenFile(const wxString &fileName) override; - #endif + bool OnInit() override; +#if wxUSE_ON_FATAL_EXCEPTION && wxUSE_STACKWALKER + void OnFatalException() override; +#endif + int OnRun() override; + int OnExit() override; + +#ifdef __WXMAC__ + wxString m_mac_file_name; + void MacOpenFile(const wxString& fileName) override; +#endif }; DECLARE_APP(MyApp) -#endif // MAINGUI_H +#endif // MAINGUI_H diff --git a/src/model/database.cpp b/src/model/database.cpp index 22f3d1b5c..8e4af8014 100644 --- a/src/model/database.cpp +++ b/src/model/database.cpp @@ -25,18 +25,18 @@ #include "database.h" +#include +#include +#include +#include + +#include "model/objectbase.h" #include "rad/bitmaps.h" #include "rad/wxfbmanager.h" #include "utils/debug.h" #include "utils/stringutils.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "model/objectbase.h" - -#include -#include -#include -#include //#define DEBUG_PRINT(x) cout << x @@ -64,163 +64,154 @@ ObjectPackage::ObjectPackage(wxString name, wxString desc, wxBitmap icon) { - m_name = name; - m_desc = desc; - m_icon = icon; + m_name = name; + m_desc = desc; + m_icon = icon; } PObjectInfo ObjectPackage::GetObjectInfo(unsigned int idx) { - assert (idx < m_objs.size()); - return m_objs[idx]; + assert(idx < m_objs.size()); + return m_objs[idx]; } -void ObjectPackage::AppendPackage( PObjectPackage package ) +void ObjectPackage::AppendPackage(PObjectPackage package) { - m_objs.insert( m_objs.end(), package->m_objs.begin(), package->m_objs.end() ); + m_objs.insert(m_objs.end(), package->m_objs.begin(), package->m_objs.end()); } /////////////////////////////////////////////////////////////////////////////// ObjectDatabase::ObjectDatabase() { - //InitObjectTypes(); - // InitWidgetTypes(); - InitPropertyTypes(); + // InitObjectTypes(); + // InitWidgetTypes(); + InitPropertyTypes(); } ObjectDatabase::~ObjectDatabase() { - for (const auto& plugin : m_pluginLibraries) { - if (plugin.second.freeComponentLibrary && plugin.second.componentLibrary) { - plugin.second.freeComponentLibrary(plugin.second.componentLibrary); - } - } + for (const auto& plugin : m_pluginLibraries) { + if (plugin.second.freeComponentLibrary && plugin.second.componentLibrary) { + plugin.second.freeComponentLibrary(plugin.second.componentLibrary); + } + } } PObjectInfo ObjectDatabase::GetObjectInfo(wxString class_name) { - PObjectInfo info; - ObjectInfoMap::iterator it = m_objs.find( class_name ); + PObjectInfo info; + ObjectInfoMap::iterator it = m_objs.find(class_name); - if ( it != m_objs.end() ) - { - info = it->second; - } + if (it != m_objs.end()) { + info = it->second; + } - return info; + return info; } PObjectPackage ObjectDatabase::GetPackage(unsigned int idx) { - assert (idx < m_pkgs.size()); + assert(idx < m_pkgs.size()); - return m_pkgs[idx]; + return m_pkgs[idx]; } /** -* @todo La herencia de propiedades ha de ser de forma recursiva. -*/ + * @todo La herencia de propiedades ha de ser de forma recursiva. + */ PObjectBase ObjectDatabase::NewObject(PObjectInfo obj_info) { - PObjectBase object; - - // Llagados aquí el objeto se crea seguro... - object = PObjectBase(new ObjectBase(obj_info->GetClassName())); - object->SetObjectTypeName(obj_info->GetObjectTypeName()); // *FIXME* - - object->SetObjectInfo(obj_info); - - PPropertyInfo prop_info; - PEventInfo event_info; - PObjectInfo class_info = obj_info; - - unsigned int base = 0; - - while (class_info) - { - unsigned int i; - for (i = 0; i < class_info->GetPropertyCount(); i++) - { - prop_info = class_info->GetPropertyInfo(i); - - PProperty property(new Property(prop_info, object)); - - // Set the default value, either from the property info, or an override from this class - wxString defaultValue = prop_info->GetDefaultValue(); - if ( base > 0 ) - { - wxString defaultValueTemp = obj_info->GetBaseClassDefaultPropertyValue( base - 1, prop_info->GetName() ); - if ( !defaultValueTemp.empty() ) - { - defaultValue = defaultValueTemp; - } - } - property->SetValue( defaultValue ); - - // Las propiedades están implementadas con una estructura "map", - // ello implica que no habrá propiedades duplicadas. - // En otro caso habrá que asegurarse de que dicha propiedad - // no existe. - // Otra cosa importante, es que el orden en que se insertan - // las propiedades, de abajo-arriba, esto permite que se pueda redefir - // alguna propiedad. - object->AddProperty (property); - } - - for (i=0; i < class_info->GetEventCount(); i++) - { - event_info = class_info->GetEventInfo(i); - PEvent event(new Event(event_info,object)); - // notice that for event there isn't a default value on its creation - // because there is not handler at the moment - object->AddEvent(event); - } - - class_info = ( base < obj_info->GetBaseClassCount() ? - obj_info->GetBaseClass(base++) : PObjectInfo()); - } - - // si el objeto tiene la propiedad name (reservada para el nombre del - // objeto) le añadimos el contador para no repetir nombres. - - obj_info->IncrementInstanceCount(); - - unsigned int ins = obj_info->GetInstanceCount(); - PProperty pname = object->GetProperty( wxT(NAME_TAG) ); - if (pname) - pname->SetValue(pname->GetValue() + StringUtils::IntToStr(ins)); - - return object; + PObjectBase object; + + // Llagados aquí el objeto se crea seguro... + object = PObjectBase(new ObjectBase(obj_info->GetClassName())); + object->SetObjectTypeName(obj_info->GetObjectTypeName()); // *FIXME* + + object->SetObjectInfo(obj_info); + + PPropertyInfo prop_info; + PEventInfo event_info; + PObjectInfo class_info = obj_info; + + unsigned int base = 0; + + while (class_info) { + unsigned int i; + for (i = 0; i < class_info->GetPropertyCount(); i++) { + prop_info = class_info->GetPropertyInfo(i); + + PProperty property(new Property(prop_info, object)); + + // Set the default value, either from the property info, or an override from this class + wxString defaultValue = prop_info->GetDefaultValue(); + if (base > 0) { + wxString defaultValueTemp = obj_info->GetBaseClassDefaultPropertyValue(base - 1, prop_info->GetName()); + if (!defaultValueTemp.empty()) { + defaultValue = defaultValueTemp; + } + } + property->SetValue(defaultValue); + + // Las propiedades están implementadas con una estructura "map", + // ello implica que no habrá propiedades duplicadas. + // En otro caso habrá que asegurarse de que dicha propiedad + // no existe. + // Otra cosa importante, es que el orden en que se insertan + // las propiedades, de abajo-arriba, esto permite que se pueda redefir + // alguna propiedad. + object->AddProperty(property); + } + + for (i = 0; i < class_info->GetEventCount(); i++) { + event_info = class_info->GetEventInfo(i); + PEvent event(new Event(event_info, object)); + // notice that for event there isn't a default value on its creation + // because there is not handler at the moment + object->AddEvent(event); + } + + class_info = (base < obj_info->GetBaseClassCount() ? obj_info->GetBaseClass(base++) : PObjectInfo()); + } + + // si el objeto tiene la propiedad name (reservada para el nombre del + // objeto) le añadimos el contador para no repetir nombres. + + obj_info->IncrementInstanceCount(); + + unsigned int ins = obj_info->GetInstanceCount(); + PProperty pname = object->GetProperty(wxT(NAME_TAG)); + if (pname) + pname->SetValue(pname->GetValue() + StringUtils::IntToStr(ins)); + + return object; } -int ObjectDatabase::CountChildrenWithSameType(PObjectBase parent,PObjectType type) +int ObjectDatabase::CountChildrenWithSameType(PObjectBase parent, PObjectType type) { - unsigned int count = 0; - unsigned int numChildren = parent->GetChildCount(); - for (unsigned int i=0; i < numChildren ; i++) - { - if (type == parent->GetChild(i)->GetObjectInfo()->GetObjectType()) - count++; - } - - return count; + unsigned int count = 0; + unsigned int numChildren = parent->GetChildCount(); + for (unsigned int i = 0; i < numChildren; i++) { + if (type == parent->GetChild(i)->GetObjectInfo()->GetObjectType()) + count++; + } + + return count; } int ObjectDatabase::CountChildrenWithSameType(PObjectBase parent, const std::set& types) { - unsigned int count = 0; - unsigned int numChildren = parent->GetChildCount(); - for (unsigned int i = 0; i < numChildren; ++i) - { - if (types.find(parent->GetChild(i)->GetObjectInfo()->GetObjectType()) != types.end()) - ++count; - } - - return count; + unsigned int count = 0; + unsigned int numChildren = parent->GetChildCount(); + for (unsigned int i = 0; i < numChildren; ++i) { + if (types.find(parent->GetChild(i)->GetObjectInfo()->GetObjectType()) != types.end()) + ++count; + } + + return count; } /** @@ -239,1311 +230,1105 @@ el máximo definido. El objeto no se crea si supera el máximo permitido. * Nota: quizá sea conveniente que el método cree el objeto sin enlazarlo * en el árbol, para facilitar el undo-redo. */ -PObjectBase ObjectDatabase::CreateObject( std::string classname, PObjectBase parent) +PObjectBase ObjectDatabase::CreateObject(std::string classname, PObjectBase parent) { - PObjectBase object; - PObjectInfo objInfo = GetObjectInfo( _WXSTR(classname) ); - - if (!objInfo) - { - THROW_WXFBEX( wxT("Unknown Object Type: ") << _WXSTR(classname) << wxT("\n") - wxT("The most likely causes are that this copy of wxFormBuilder is out of date, or that there is a plugin missing.\n") - wxT("Please check at http://www.wxFormBuilder.org") << wxT("\n") ) - } - - PObjectType objType = objInfo->GetObjectType(); - - if (parent) - { - // Comprobamos si el tipo es válido - PObjectType parentType = parent->GetObjectInfo()->GetObjectType(); - - //AUI - bool aui = false; - if( parentType->GetName() == wxT("form") ) - { - aui = parent->GetPropertyAsInteger(wxT("aui_managed")) != 0; - } - - int max = parentType->FindChildType(objType, aui); - - // FIXME! Esto es un parche para evitar crear los tipos menubar,statusbar y - // toolbar en un form que no sea wxFrame. - // Hay que modificar el conjunto de tipos para permitir tener varios tipos - // de forms (como childType de project), pero hay mucho código no válido - // para forms que no sean de tipo "form". Dicho de otra manera, hay - // código que dependen del nombre del tipo, cosa que hay que evitar. - if (parentType->GetName() == wxT("form") && parent->GetClassName() != wxT("Frame") && - (objType->GetName() == wxT("statusbar") || - objType->GetName() == wxT("menubar") || - objType->GetName() == wxT("ribbonbar") || - objType->GetName() == wxT("toolbar") )) - return PObjectBase(); // tipo no válido - - // No menu dropdown for wxToolBar until wx 2.9 :( - if ( parentType->GetName() == wxT("tool") ) - { - PObjectBase gParent = parent->GetParent(); - if ( - ( gParent->GetClassName() == wxT("wxToolBar") ) && - ( objType->GetName() == wxT("menu") ) - ) - return PObjectBase(); // not a valid type - } - - if (max != 0) // tipo válido - { - bool create = true; - - // we check the number of instances - int count; - if (objType == GetObjectType(wxT("sizer")) || objType == GetObjectType(wxT("gbsizer"))) - { - count = CountChildrenWithSameType(parent, { GetObjectType(wxT("sizer")), GetObjectType(wxT("gbsizer")) }); - } - else - { - count = CountChildrenWithSameType(parent, objType); - } - - if (max > 0 && count >= max) - create = false; - - if (create) - object = NewObject(objInfo); - } - else // max == 0 - { - // el tipo no es válido, vamos a comprobar si podemos insertarlo - // como hijo de un "item" - bool created = false; - for (unsigned int i=0; !created && i < parentType->GetChildTypeCount(); i++) - { - PObjectType childType = parentType->GetChildType(i); - int childMax = childType->FindChildType(objType, aui); - - if (childType->IsItem() && childMax != 0) - { - childMax = parentType->FindChildType(childType, aui); - - // si el tipo es un item y además el tipo del objeto a crear - // puede ser hijo del tipo del item vamos a intentar crear la - // instancia del item para crear el objeto como hijo de este - if (childMax < 0 || CountChildrenWithSameType(parent, childType) < childMax) - { - // No hay problemas para crear el item debajo de parent - PObjectBase item = NewObject(GetObjectInfo(childType->GetName())); - - //PObjectBase obj = CreateObject(classname,item); - PObjectBase obj = NewObject(objInfo); - - // la siguiente condición debe cumplirse siempre - // ya que un item debe siempre contener a otro objeto - if (obj) - { - // enlazamos item y obj - item->AddChild(obj); - obj->SetParent(item); - - // sizeritem es un tipo de objeto reservado, para que el uso sea - // más práctico se asignan unos valores por defecto en función - // del tipo de objeto creado - if ( item->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - SetDefaultLayoutProperties(item); - - object = item; - created = true; - } - else - wxLogError(wxT("Review your definitions file (objtypes.xml)")); - } - } - } - } - /////////////////////////////////////////////////////////////////////// - // Nota: provisionalmente vamos a enlazar el objeto al padre pero - // esto debería hacerse fuera para poder implementar el Undo-Redo - /////////////////////////////////////////////////////////////////////// - //if (object) - //{ - // parent->AddChild(object); - // object->SetParent(parent); - //} - } - else // parent == NULL; - { - object = NewObject(objInfo); - } - - return object; + PObjectBase object; + PObjectInfo objInfo = GetObjectInfo(_WXSTR(classname)); + + if (!objInfo) { + THROW_WXFBEX( + wxT("Unknown Object Type: ") << _WXSTR(classname) + << wxT("\n") wxT("The most likely causes are that this copy of wxFormBuilder is " + "out of date, or that there is a plugin missing.\n") + wxT("Please check at http://www.wxFormBuilder.org") + << wxT("\n")) + } + + PObjectType objType = objInfo->GetObjectType(); + + if (parent) { + // Comprobamos si el tipo es válido + PObjectType parentType = parent->GetObjectInfo()->GetObjectType(); + + // AUI + bool aui = false; + if (parentType->GetName() == wxT("form")) { + aui = parent->GetPropertyAsInteger(wxT("aui_managed")) != 0; + } + + int max = parentType->FindChildType(objType, aui); + + // FIXME! Esto es un parche para evitar crear los tipos menubar,statusbar y + // toolbar en un form que no sea wxFrame. + // Hay que modificar el conjunto de tipos para permitir tener varios tipos + // de forms (como childType de project), pero hay mucho código no válido + // para forms que no sean de tipo "form". Dicho de otra manera, hay + // código que dependen del nombre del tipo, cosa que hay que evitar. + if ( + parentType->GetName() == wxT("form") && parent->GetClassName() != wxT("Frame") && + (objType->GetName() == wxT("statusbar") || objType->GetName() == wxT("menubar") || + objType->GetName() == wxT("ribbonbar") || objType->GetName() == wxT("toolbar"))) + return PObjectBase(); // tipo no válido + + // No menu dropdown for wxToolBar until wx 2.9 :( + if (parentType->GetName() == wxT("tool")) { + PObjectBase gParent = parent->GetParent(); + if ((gParent->GetClassName() == wxT("wxToolBar")) && (objType->GetName() == wxT("menu"))) + return PObjectBase(); // not a valid type + } + + if (max != 0) // tipo válido + { + bool create = true; + + // we check the number of instances + int count; + if (objType == GetObjectType(wxT("sizer")) || objType == GetObjectType(wxT("gbsizer"))) { + count = CountChildrenWithSameType(parent, {GetObjectType(wxT("sizer")), GetObjectType(wxT("gbsizer"))}); + } else { + count = CountChildrenWithSameType(parent, objType); + } + + if (max > 0 && count >= max) + create = false; + + if (create) + object = NewObject(objInfo); + } else // max == 0 + { + // el tipo no es válido, vamos a comprobar si podemos insertarlo + // como hijo de un "item" + bool created = false; + for (unsigned int i = 0; !created && i < parentType->GetChildTypeCount(); i++) { + PObjectType childType = parentType->GetChildType(i); + int childMax = childType->FindChildType(objType, aui); + + if (childType->IsItem() && childMax != 0) { + childMax = parentType->FindChildType(childType, aui); + + // si el tipo es un item y además el tipo del objeto a crear + // puede ser hijo del tipo del item vamos a intentar crear la + // instancia del item para crear el objeto como hijo de este + if (childMax < 0 || CountChildrenWithSameType(parent, childType) < childMax) { + // No hay problemas para crear el item debajo de parent + PObjectBase item = NewObject(GetObjectInfo(childType->GetName())); + + // PObjectBase obj = CreateObject(classname,item); + PObjectBase obj = NewObject(objInfo); + + // la siguiente condición debe cumplirse siempre + // ya que un item debe siempre contener a otro objeto + if (obj) { + // enlazamos item y obj + item->AddChild(obj); + obj->SetParent(item); + + // sizeritem es un tipo de objeto reservado, para que el uso sea + // más práctico se asignan unos valores por defecto en función + // del tipo de objeto creado + if (item->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) + SetDefaultLayoutProperties(item); + + object = item; + created = true; + } else + wxLogError(wxT("Review your definitions file (objtypes.xml)")); + } + } + } + } + /////////////////////////////////////////////////////////////////////// + // Nota: provisionalmente vamos a enlazar el objeto al padre pero + // esto debería hacerse fuera para poder implementar el Undo-Redo + /////////////////////////////////////////////////////////////////////// + // if (object) + //{ + // parent->AddChild(object); + // object->SetParent(parent); + // } + } else // parent == NULL; + { + object = NewObject(objInfo); + } + + return object; } PObjectBase ObjectDatabase::CopyObject(PObjectBase obj) { - assert(obj); - - PObjectInfo objInfo = obj->GetObjectInfo(); - - PObjectBase copyObj = NewObject(objInfo); // creamos la copia - assert(copyObj); - - // copiamos las propiedades - unsigned int i; - unsigned int count = obj->GetPropertyCount(); - for (i = 0; i < count; i++) - { - PProperty objProp = obj->GetProperty(i); - assert(objProp); - - PProperty copyProp = copyObj->GetProperty(objProp->GetName()); - assert(copyProp); - - wxString propValue = objProp->GetValue(); - copyProp->SetValue(propValue); - } - - // ...and the event handlers - count = obj->GetEventCount(); - for (i = 0; i < count; i++) - { - PEvent event = obj->GetEvent(i); - PEvent copyEvent = copyObj->GetEvent(event->GetName()); - copyEvent->SetValue(event->GetValue()); - } - - // creamos recursivamente los hijos - count = obj->GetChildCount(); - for (i = 0; iGetChild(i)); - copyObj->AddChild(childCopy); - childCopy->SetParent(copyObj); - } - - return copyObj; + assert(obj); + + PObjectInfo objInfo = obj->GetObjectInfo(); + + PObjectBase copyObj = NewObject(objInfo); // creamos la copia + assert(copyObj); + + // copiamos las propiedades + unsigned int i; + unsigned int count = obj->GetPropertyCount(); + for (i = 0; i < count; i++) { + PProperty objProp = obj->GetProperty(i); + assert(objProp); + + PProperty copyProp = copyObj->GetProperty(objProp->GetName()); + assert(copyProp); + + wxString propValue = objProp->GetValue(); + copyProp->SetValue(propValue); + } + + // ...and the event handlers + count = obj->GetEventCount(); + for (i = 0; i < count; i++) { + PEvent event = obj->GetEvent(i); + PEvent copyEvent = copyObj->GetEvent(event->GetName()); + copyEvent->SetValue(event->GetValue()); + } + + // creamos recursivamente los hijos + count = obj->GetChildCount(); + for (i = 0; i < count; i++) { + PObjectBase childCopy = CopyObject(obj->GetChild(i)); + copyObj->AddChild(childCopy); + childCopy->SetParent(copyObj); + } + + return copyObj; } void ObjectDatabase::SetDefaultLayoutProperties(PObjectBase sizeritem) { - if ( !sizeritem->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - { - LogDebug( wxT("SetDefaultLayoutProperties expects a subclass of sizeritembase") ); - return; - } - - PObjectBase child = sizeritem->GetChild(0); - PObjectInfo childInfo = child->GetObjectInfo(); - wxString obj_type = child->GetObjectTypeName(); - - PProperty proportion = sizeritem->GetProperty( wxT("proportion") ); - - if ( childInfo->IsSubclassOf( wxT("sizer") ) || childInfo->IsSubclassOf( wxT("gbsizer") ) || obj_type == wxT("splitter") || childInfo->GetClassName() == wxT("spacer") ) - { - if ( proportion ) - { - proportion->SetValue( wxT("1") ); - } - sizeritem->GetProperty( wxT("flag") )->SetValue( wxT("wxEXPAND") ); - } - else if ( childInfo->GetClassName() == wxT("wxStaticLine") ) - { - sizeritem->GetProperty( wxT("flag") )->SetValue( wxT("wxEXPAND | wxALL") ); - } - else if ( childInfo->GetClassName() == wxT("wxToolBar") ) - { - sizeritem->GetProperty( wxT("flag") )->SetValue( wxT("wxEXPAND") ); - } - else if ( obj_type == wxT("widget") || obj_type == wxT("statusbar") ) - { - if ( proportion ) - { - proportion->SetValue( wxT("0") ); - } - sizeritem->GetProperty( wxT("flag") )->SetValue( wxT("wxALL") ); - } - else if ( obj_type == wxT("notebook") || - obj_type == wxT("flatnotebook") || - obj_type == wxT("listbook") || - obj_type == wxT("simplebook") || - obj_type == wxT("choicebook") || - obj_type == wxT("auinotebook") || - obj_type == wxT("treelistctrl") || - obj_type == wxT("expanded_widget") || - obj_type == wxT("container") - ) - { - if ( proportion ) - { - proportion->SetValue( wxT("1") ); - } - sizeritem->GetProperty( wxT("flag") )->SetValue( wxT("wxEXPAND | wxALL") ); - } + if (!sizeritem->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) { + LogDebug(wxT("SetDefaultLayoutProperties expects a subclass of sizeritembase")); + return; + } + + PObjectBase child = sizeritem->GetChild(0); + PObjectInfo childInfo = child->GetObjectInfo(); + wxString obj_type = child->GetObjectTypeName(); + + PProperty proportion = sizeritem->GetProperty(wxT("proportion")); + + if ( + childInfo->IsSubclassOf(wxT("sizer")) || childInfo->IsSubclassOf(wxT("gbsizer")) || obj_type == wxT("splitter") || + childInfo->GetClassName() == wxT("spacer")) { + if (proportion) { + proportion->SetValue(wxT("1")); + } + sizeritem->GetProperty(wxT("flag"))->SetValue(wxT("wxEXPAND")); + } else if (childInfo->GetClassName() == wxT("wxStaticLine")) { + sizeritem->GetProperty(wxT("flag"))->SetValue(wxT("wxEXPAND | wxALL")); + } else if (childInfo->GetClassName() == wxT("wxToolBar")) { + sizeritem->GetProperty(wxT("flag"))->SetValue(wxT("wxEXPAND")); + } else if (obj_type == wxT("widget") || obj_type == wxT("statusbar")) { + if (proportion) { + proportion->SetValue(wxT("0")); + } + sizeritem->GetProperty(wxT("flag"))->SetValue(wxT("wxALL")); + } else if ( + obj_type == wxT("notebook") || obj_type == wxT("flatnotebook") || obj_type == wxT("listbook") || + obj_type == wxT("simplebook") || obj_type == wxT("choicebook") || obj_type == wxT("auinotebook") || + obj_type == wxT("treelistctrl") || obj_type == wxT("expanded_widget") || obj_type == wxT("container")) { + if (proportion) { + proportion->SetValue(wxT("1")); + } + sizeritem->GetProperty(wxT("flag"))->SetValue(wxT("wxEXPAND | wxALL")); + } } void ObjectDatabase::ResetObjectCounters() { - ObjectInfoMap::iterator it; - for (it = m_objs.begin() ; it != m_objs.end() ; it++) - { - it->second->ResetInstanceCount(); - } + ObjectInfoMap::iterator it; + for (it = m_objs.begin(); it != m_objs.end(); it++) { it->second->ResetInstanceCount(); } } /////////////////////////////////////////////////////////////////////// -PObjectBase ObjectDatabase::CreateObject( ticpp::Element* xml_obj, PObjectBase parent ) +PObjectBase ObjectDatabase::CreateObject(ticpp::Element* xml_obj, PObjectBase parent) { - try - { - std::string class_name; - xml_obj->GetAttribute( CLASS_TAG, &class_name, false ); - - PObjectBase newobject = CreateObject( class_name, parent ); - - // It is possible the CreateObject returns an "item" containing the object, e.g. SizerItem or SplitterItem - // If that is the case, reassign "object" to the actual object - PObjectBase object = newobject; - if ( object && object->GetChildCount() > 0 ) - { - object = object->GetChild( 0 ); - } - - if ( object ) - { - // Get the state of expansion in the object tree - bool expanded; - xml_obj->GetAttributeOrDefault( EXPANDED_TAG, &expanded, true ); - object->SetExpanded( expanded ); - - // Load the properties - ticpp::Element* xml_prop = xml_obj->FirstChildElement( PROPERTY_TAG, false ); - while ( xml_prop ) - { - std::string prop_name; - xml_prop->GetAttribute( NAME_TAG, &prop_name, false ); - PProperty prop = object->GetProperty( _WXSTR(prop_name) ); - - if ( prop ) // does the property exist - { - // load the value - prop->SetValue( _WXSTR( xml_prop->GetText( false ) ) ); - } - else - { - std::string value = xml_prop->GetText( false ); - if ( !value.empty() ) - { - wxLogError( wxT("The property named \"%s\" of class \"%s\" is not supported by this version of wxFormBuilder.\n") - wxT("If your project file was just converted from an older version, then the conversion was not complete.\n") - wxT("Otherwise, this project is from a newer version of wxFormBuilder.\n\n") - wxT("The property's value is: %s\n") - wxT("If you save this project, YOU WILL LOSE DATA"), _WXSTR(prop_name), _WXSTR(class_name), _WXSTR(value) ); - } - } - - xml_prop = xml_prop->NextSiblingElement( PROPERTY_TAG, false ); - } - - // load the event handlers - ticpp::Element* xml_event = xml_obj->FirstChildElement( EVENT_TAG, false ); - while ( xml_event ) - { - std::string event_name; - xml_event->GetAttribute( NAME_TAG, &event_name, false ); - PEvent event = object->GetEvent( _WXSTR(event_name) ); - if ( event ) - { - event->SetValue( _WXSTR( xml_event->GetText( false ) ) ); - } - - xml_event = xml_event->NextSiblingElement( EVENT_TAG, false ); - } - - - if ( parent ) - { - // set up parent/child relationship - parent->AddChild( newobject ); - newobject->SetParent( parent ); - } - - // create the children - ticpp::Element* child = xml_obj->FirstChildElement( OBJECT_TAG, false ); - while ( child ) - { - CreateObject( child, object ); - child = child->NextSiblingElement( OBJECT_TAG, false ); - } - } - - return newobject; - } - catch( ticpp::Exception& ) - { - return PObjectBase(); - } + try { + std::string class_name; + xml_obj->GetAttribute(CLASS_TAG, &class_name, false); + + PObjectBase newobject = CreateObject(class_name, parent); + + // It is possible the CreateObject returns an "item" containing the object, e.g. SizerItem or SplitterItem + // If that is the case, reassign "object" to the actual object + PObjectBase object = newobject; + if (object && object->GetChildCount() > 0) { + object = object->GetChild(0); + } + + if (object) { + // Get the state of expansion in the object tree + bool expanded; + xml_obj->GetAttributeOrDefault(EXPANDED_TAG, &expanded, true); + object->SetExpanded(expanded); + + // Load the properties + ticpp::Element* xml_prop = xml_obj->FirstChildElement(PROPERTY_TAG, false); + while (xml_prop) { + std::string prop_name; + xml_prop->GetAttribute(NAME_TAG, &prop_name, false); + PProperty prop = object->GetProperty(_WXSTR(prop_name)); + + if (prop) // does the property exist + { + // load the value + prop->SetValue(_WXSTR(xml_prop->GetText(false))); + } else { + std::string value = xml_prop->GetText(false); + if (!value.empty()) { + wxLogError( + wxT("The property named \"%s\" of class \"%s\" is not supported by this version of " + "wxFormBuilder.\n") wxT("If your project file was just converted from an older version, " + "then the conversion was not complete.\n") + wxT("Otherwise, this project is from a newer version of wxFormBuilder.\n\n") + wxT("The property's value is: %s\n") wxT("If you save this project, YOU WILL LOSE DATA"), + _WXSTR(prop_name), _WXSTR(class_name), _WXSTR(value)); + } + } + + xml_prop = xml_prop->NextSiblingElement(PROPERTY_TAG, false); + } + + // load the event handlers + ticpp::Element* xml_event = xml_obj->FirstChildElement(EVENT_TAG, false); + while (xml_event) { + std::string event_name; + xml_event->GetAttribute(NAME_TAG, &event_name, false); + PEvent event = object->GetEvent(_WXSTR(event_name)); + if (event) { + event->SetValue(_WXSTR(xml_event->GetText(false))); + } + + xml_event = xml_event->NextSiblingElement(EVENT_TAG, false); + } + + + if (parent) { + // set up parent/child relationship + parent->AddChild(newobject); + newobject->SetParent(parent); + } + + // create the children + ticpp::Element* child = xml_obj->FirstChildElement(OBJECT_TAG, false); + while (child) { + CreateObject(child, object); + child = child->NextSiblingElement(OBJECT_TAG, false); + } + } + + return newobject; + } catch (ticpp::Exception&) { + return PObjectBase(); + } } ////////////////////////////// -bool IncludeInPalette(wxString /*type*/) { - return true; +bool IncludeInPalette(wxString /*type*/) +{ + return true; } -void ObjectDatabase::LoadPlugins( PwxFBManager manager ) +void ObjectDatabase::LoadPlugins(PwxFBManager manager) { - // Load some default templates - LoadCodeGen( m_xmlPath + wxT("properties.cppcode") ); - LoadCodeGen( m_xmlPath + wxT("properties.pythoncode") ); - LoadCodeGen( m_xmlPath + wxT("properties.luacode") ); - LoadCodeGen( m_xmlPath + wxT("properties.phpcode") ); - LoadPackage( m_xmlPath + wxT("default.xml"), m_iconPath ); - LoadCodeGen( m_xmlPath + wxT("default.cppcode") ); - LoadCodeGen( m_xmlPath + wxT("default.pythoncode") ); - LoadCodeGen( m_xmlPath + wxT("default.luacode") ); - LoadCodeGen( m_xmlPath + wxT("default.phpcode") ); - - // Map to temporarily hold plugins. - // Used to both set page order and to prevent two plugins with the same name. - typedef std::map< wxString, PObjectPackage > PackageMap; - PackageMap packages; - - // Open plugins directory for iteration - if ( !wxDir::Exists( m_pluginPath ) ) - { - return; - } - - wxDir pluginsDir( m_pluginPath ); - if ( !pluginsDir.IsOpened() ) - { - return; - } - - // Iterate through plugin directories and load the package from the xml subdirectory - wxString pluginDirName; - bool moreDirectories = pluginsDir.GetFirst( &pluginDirName, wxEmptyString, wxDIR_DIRS | wxDIR_HIDDEN ); - while ( moreDirectories ) - { - // Iterate through .xml files in the xml directory - wxString nextPluginPath = m_pluginPath + pluginDirName; - wxString nextPluginXmlPath = nextPluginPath + wxFILE_SEP_PATH + wxT("xml"); - wxString nextPluginIconPath = nextPluginPath + wxFILE_SEP_PATH + wxT("icons"); - if ( wxDir::Exists( nextPluginPath ) ) - { - if ( wxDir::Exists( nextPluginXmlPath ) ) - { - wxDir pluginXmlDir( nextPluginXmlPath ); - if ( pluginXmlDir.IsOpened() ) - { - std::map< wxString, PObjectPackage > packagesToSetup; - wxString packageXmlFile; - bool moreXmlFiles = pluginXmlDir.GetFirst( &packageXmlFile, wxT("*.xml"), wxDIR_FILES | wxDIR_HIDDEN ); - while ( moreXmlFiles ) - { - try - { - wxFileName nextXmlFile( nextPluginXmlPath + wxFILE_SEP_PATH + packageXmlFile ); - if ( !nextXmlFile.IsAbsolute() ) - { - nextXmlFile.MakeAbsolute(); - } - - PObjectPackage package = LoadPackage( nextXmlFile.GetFullPath(), nextPluginIconPath ); - if ( package ) - { - // Load all packages, then setup all packages - // this allows multiple packages sharing one library - packagesToSetup[ nextXmlFile.GetFullPath() ] = package; - } - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - moreXmlFiles = pluginXmlDir.GetNext( &packageXmlFile ); - } - - std::map< wxString, PObjectPackage >::iterator packageIt; - for ( packageIt = packagesToSetup.begin(); packageIt != packagesToSetup.end(); ++packageIt ) - { - // Setup the inheritance for base classes - wxFileName fullNextPluginPath( nextPluginPath ); - if ( !fullNextPluginPath.IsAbsolute() ) - { - fullNextPluginPath.MakeAbsolute(); - } - wxFileName xmlFileName( packageIt->first ); - try - { - SetupPackage( xmlFileName.GetFullPath(), fullNextPluginPath.GetFullPath(), manager ); - - // Load the C++ code templates - xmlFileName.SetExt( wxT("cppcode") ); - LoadCodeGen( xmlFileName.GetFullPath() ); - - // Load the Python code templates - xmlFileName.SetExt( wxT("pythoncode") ); - LoadCodeGen( xmlFileName.GetFullPath() ); - - // Load the PHP code templates - xmlFileName.SetExt( wxT("phpcode") ); - LoadCodeGen( xmlFileName.GetFullPath() ); - - // Load the Lua code templates - xmlFileName.SetExt( wxT("luacode") ); - LoadCodeGen( xmlFileName.GetFullPath() ); - - std::pair< PackageMap::iterator, bool > addedPackage = packages.insert( PackageMap::value_type( packageIt->second->GetPackageName(), packageIt->second ) ); - if ( !addedPackage.second ) - { - addedPackage.first->second->AppendPackage( packageIt->second ); - LogDebug( "Merged plugins named \"" + packageIt->second->GetPackageName() + "\"" ); - } - - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } - } - } - } - - moreDirectories = pluginsDir.GetNext( &pluginDirName ); + // Load some default templates + LoadCodeGen(m_xmlPath + wxT("properties.cppcode")); + LoadCodeGen(m_xmlPath + wxT("properties.pythoncode")); + LoadCodeGen(m_xmlPath + wxT("properties.luacode")); + LoadCodeGen(m_xmlPath + wxT("properties.phpcode")); + LoadPackage(m_xmlPath + wxT("default.xml"), m_iconPath); + LoadCodeGen(m_xmlPath + wxT("default.cppcode")); + LoadCodeGen(m_xmlPath + wxT("default.pythoncode")); + LoadCodeGen(m_xmlPath + wxT("default.luacode")); + LoadCodeGen(m_xmlPath + wxT("default.phpcode")); + + // Map to temporarily hold plugins. + // Used to both set page order and to prevent two plugins with the same name. + typedef std::map PackageMap; + PackageMap packages; + + // Open plugins directory for iteration + if (!wxDir::Exists(m_pluginPath)) { + return; + } + + wxDir pluginsDir(m_pluginPath); + if (!pluginsDir.IsOpened()) { + return; + } + + // Iterate through plugin directories and load the package from the xml subdirectory + wxString pluginDirName; + bool moreDirectories = pluginsDir.GetFirst(&pluginDirName, wxEmptyString, wxDIR_DIRS | wxDIR_HIDDEN); + while (moreDirectories) { + // Iterate through .xml files in the xml directory + wxString nextPluginPath = m_pluginPath + pluginDirName; + wxString nextPluginXmlPath = nextPluginPath + wxFILE_SEP_PATH + wxT("xml"); + wxString nextPluginIconPath = nextPluginPath + wxFILE_SEP_PATH + wxT("icons"); + if (wxDir::Exists(nextPluginPath)) { + if (wxDir::Exists(nextPluginXmlPath)) { + wxDir pluginXmlDir(nextPluginXmlPath); + if (pluginXmlDir.IsOpened()) { + std::map packagesToSetup; + wxString packageXmlFile; + bool moreXmlFiles = + pluginXmlDir.GetFirst(&packageXmlFile, wxT("*.xml"), wxDIR_FILES | wxDIR_HIDDEN); + while (moreXmlFiles) { + try { + wxFileName nextXmlFile(nextPluginXmlPath + wxFILE_SEP_PATH + packageXmlFile); + if (!nextXmlFile.IsAbsolute()) { + nextXmlFile.MakeAbsolute(); + } + + PObjectPackage package = LoadPackage(nextXmlFile.GetFullPath(), nextPluginIconPath); + if (package) { + // Load all packages, then setup all packages + // this allows multiple packages sharing one library + packagesToSetup[nextXmlFile.GetFullPath()] = package; + } + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + moreXmlFiles = pluginXmlDir.GetNext(&packageXmlFile); + } + + std::map::iterator packageIt; + for (packageIt = packagesToSetup.begin(); packageIt != packagesToSetup.end(); ++packageIt) { + // Setup the inheritance for base classes + wxFileName fullNextPluginPath(nextPluginPath); + if (!fullNextPluginPath.IsAbsolute()) { + fullNextPluginPath.MakeAbsolute(); + } + wxFileName xmlFileName(packageIt->first); + try { + SetupPackage(xmlFileName.GetFullPath(), fullNextPluginPath.GetFullPath(), manager); + + // Load the C++ code templates + xmlFileName.SetExt(wxT("cppcode")); + LoadCodeGen(xmlFileName.GetFullPath()); + + // Load the Python code templates + xmlFileName.SetExt(wxT("pythoncode")); + LoadCodeGen(xmlFileName.GetFullPath()); + + // Load the PHP code templates + xmlFileName.SetExt(wxT("phpcode")); + LoadCodeGen(xmlFileName.GetFullPath()); + + // Load the Lua code templates + xmlFileName.SetExt(wxT("luacode")); + LoadCodeGen(xmlFileName.GetFullPath()); + + std::pair addedPackage = packages.insert( + PackageMap::value_type(packageIt->second->GetPackageName(), packageIt->second)); + if (!addedPackage.second) { + addedPackage.first->second->AppendPackage(packageIt->second); + LogDebug("Merged plugins named \"" + packageIt->second->GetPackageName() + "\""); + } + + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } + } + } + } + + moreDirectories = pluginsDir.GetNext(&pluginDirName); } - // Add packages to final data structure - m_pkgs.reserve(packages.size()); - for (auto& package : packages) - { - m_pkgs.push_back(package.second); - } + // Add packages to final data structure + m_pkgs.reserve(packages.size()); + for (auto& package : packages) { m_pkgs.push_back(package.second); } } -void ObjectDatabase::SetupPackage(const wxString& file, [[maybe_unused]] const wxString& path, PwxFBManager manager) { - #ifdef __WXMSW__ - wxString libPath = path; - #else - wxStandardPathsBase& stdpaths = wxStandardPaths::Get(); - wxString libPath = stdpaths.GetPluginsDir(); - libPath.Replace( wxTheApp->GetAppName(), wxT("wxformbuilder") ); - #endif +void ObjectDatabase::SetupPackage(const wxString& file, [[maybe_unused]] const wxString& path, PwxFBManager manager) +{ +#ifdef __WXMSW__ + wxString libPath = path; +#else + wxStandardPathsBase& stdpaths = wxStandardPaths::Get(); + wxString libPath = stdpaths.GetPluginsDir(); + libPath.Replace(wxTheApp->GetAppName(), wxT("wxformbuilder")); +#endif // Renamed libraries for convenience in debug using a "-xx" wx version as suffix. // This will also prevent loading debug libraries in release and vice versa, // that used to cause crashes when trying to debug. wxString wxver = wxT(""); - #ifdef DEBUG - #ifdef APPEND_WXVERSION - wxver = wxver + wxString::Format( wxT("-%i%i"), wxMAJOR_VERSION, wxMINOR_VERSION ); - #endif - #endif - - try - { - ticpp::Document doc; - XMLUtils::LoadXMLFile( doc, true, file ); - - ticpp::Element* root = doc.FirstChildElement( PACKAGE_TAG ); - - // get the library to import - std::string lib; - root->GetAttributeOrDefault( "lib", &lib, "" ); - if ( !lib.empty() ) - { - #ifdef __WINDOWS__ - // On Windows the plugin libraries reside in the directory of the plugin resources, - // construct a relative path to that location to be able to find them with the default - // search algorithm - lib = "plugins/" + lib + "/" + lib; - #endif - auto pluginLibrary = m_pluginLibraries.find(lib); - if (pluginLibrary == m_pluginLibraries.end()) { - ImportComponentLibrary(lib, manager); - } - } - - ticpp::Element* elem_obj = root->FirstChildElement( OBJINFO_TAG, false ); - while ( elem_obj ) - { - std::string wxver_obj; - elem_obj->GetAttributeOrDefault(WXVERSION_TAG, &wxver_obj, ""); - if (!wxver_obj.empty()) - { - long wxversion = 0; - // skip widgets supported by higher wxWidgets version than used for the build - if((!_WXSTR(wxver_obj).ToLong(&wxversion)) || (wxversion > wxVERSION_NUMBER)) - { - elem_obj = elem_obj->NextSiblingElement( OBJINFO_TAG, false ); - continue; - } - } - - std::string class_name; - elem_obj->GetAttribute( CLASS_TAG, &class_name ); - - PObjectInfo class_info = GetObjectInfo( _WXSTR(class_name) ); - - ticpp::Element* elem_base = elem_obj->FirstChildElement( "inherits", false ); - while ( elem_base ) - { - std::string base_name; - elem_base->GetAttribute( CLASS_TAG, &base_name ); - - // Add a reference to its base class - PObjectInfo base_info = GetObjectInfo( _WXSTR(base_name) ); - if ( class_info && base_info ) - { - size_t baseIndex = class_info->AddBaseClass( base_info ); - - std::string prop_name, value; - ticpp::Element* inheritedProperty = elem_base->FirstChildElement( "property", false ); - while( inheritedProperty ) - { - inheritedProperty->GetAttribute( NAME_TAG, &prop_name ); - value = inheritedProperty->GetText(); - class_info->AddBaseClassDefaultPropertyValue( baseIndex, _WXSTR(prop_name), _WXSTR(value) ); - inheritedProperty = inheritedProperty->NextSiblingElement( "property", false ); - } - } - elem_base = elem_base->NextSiblingElement( "inherits", false ); - } - - // Add the "C++" base class, predefined for the components and widgets - wxString typeName = class_info->GetObjectTypeName(); - if ( HasCppProperties( typeName ) ) - { - PObjectInfo cpp_interface = GetObjectInfo( wxT("C++") ); - if ( cpp_interface ) - { - size_t baseIndex = class_info->AddBaseClass( cpp_interface ); - if ( typeName == wxT("sizer") || - typeName == wxT("gbsizer") || - typeName == wxT("menuitem") ) - { - class_info->AddBaseClassDefaultPropertyValue( baseIndex, _("permission"), _("none") ); - } - } - } - - elem_obj = elem_obj->NextSiblingElement( OBJINFO_TAG, false ); - } - } - catch ( ticpp::Exception& ex ) - { - THROW_WXFBEX( _WXSTR(ex.m_details) ); - } +#ifdef DEBUG + #ifdef APPEND_WXVERSION + wxver = wxver + wxString::Format(wxT("-%i%i"), wxMAJOR_VERSION, wxMINOR_VERSION); + #endif +#endif + + try { + ticpp::Document doc; + XMLUtils::LoadXMLFile(doc, true, file); + + ticpp::Element* root = doc.FirstChildElement(PACKAGE_TAG); + + // get the library to import + std::string lib; + root->GetAttributeOrDefault("lib", &lib, ""); + if (!lib.empty()) { +#ifdef __WINDOWS__ + // On Windows the plugin libraries reside in the directory of the plugin resources, + // construct a relative path to that location to be able to find them with the default + // search algorithm + lib = "plugins/" + lib + "/" + lib; +#endif + auto pluginLibrary = m_pluginLibraries.find(lib); + if (pluginLibrary == m_pluginLibraries.end()) { + ImportComponentLibrary(lib, manager); + } + } + + ticpp::Element* elem_obj = root->FirstChildElement(OBJINFO_TAG, false); + while (elem_obj) { + std::string wxver_obj; + elem_obj->GetAttributeOrDefault(WXVERSION_TAG, &wxver_obj, ""); + if (!wxver_obj.empty()) { + long wxversion = 0; + // skip widgets supported by higher wxWidgets version than used for the build + if ((!_WXSTR(wxver_obj).ToLong(&wxversion)) || (wxversion > wxVERSION_NUMBER)) { + elem_obj = elem_obj->NextSiblingElement(OBJINFO_TAG, false); + continue; + } + } + + std::string class_name; + elem_obj->GetAttribute(CLASS_TAG, &class_name); + + PObjectInfo class_info = GetObjectInfo(_WXSTR(class_name)); + + ticpp::Element* elem_base = elem_obj->FirstChildElement("inherits", false); + while (elem_base) { + std::string base_name; + elem_base->GetAttribute(CLASS_TAG, &base_name); + + // Add a reference to its base class + PObjectInfo base_info = GetObjectInfo(_WXSTR(base_name)); + if (class_info && base_info) { + size_t baseIndex = class_info->AddBaseClass(base_info); + + std::string prop_name, value; + ticpp::Element* inheritedProperty = elem_base->FirstChildElement("property", false); + while (inheritedProperty) { + inheritedProperty->GetAttribute(NAME_TAG, &prop_name); + value = inheritedProperty->GetText(); + class_info->AddBaseClassDefaultPropertyValue(baseIndex, _WXSTR(prop_name), _WXSTR(value)); + inheritedProperty = inheritedProperty->NextSiblingElement("property", false); + } + } + elem_base = elem_base->NextSiblingElement("inherits", false); + } + + // Add the "C++" base class, predefined for the components and widgets + wxString typeName = class_info->GetObjectTypeName(); + if (HasCppProperties(typeName)) { + PObjectInfo cpp_interface = GetObjectInfo(wxT("C++")); + if (cpp_interface) { + size_t baseIndex = class_info->AddBaseClass(cpp_interface); + if (typeName == wxT("sizer") || typeName == wxT("gbsizer") || typeName == wxT("menuitem")) { + class_info->AddBaseClassDefaultPropertyValue(baseIndex, _("permission"), _("none")); + } + } + } + + elem_obj = elem_obj->NextSiblingElement(OBJINFO_TAG, false); + } + } catch (ticpp::Exception& ex) { + THROW_WXFBEX(_WXSTR(ex.m_details)); + } } bool ObjectDatabase::HasCppProperties(wxString type) { - return (type == wxT("notebook") || - type == wxT("flatnotebook") || - type == wxT("listbook") || - type == wxT("simplebook") || - type == wxT("choicebook") || - type == wxT("auinotebook") || - type == wxT("widget") || - type == wxT("expanded_widget") || - type == wxT("propgrid") || - type == wxT("propgridman") || - type == wxT("statusbar") || - type == wxT("component") || - type == wxT("container") || - type == wxT("menubar") || - type == wxT("menu") || - type == wxT("menuitem") || - type == wxT("submenu") || - type == wxT("toolbar") || - type == wxT("ribbonbar") || - type == wxT("ribbonpage") || - type == wxT("ribbonpanel") || - type == wxT("ribbonbuttonbar") || - type == wxT("ribbonbutton") || - type == wxT("ribbondropdownbutton" ) || - type == wxT("ribbonhybridbutton" ) || - type == wxT("ribbontogglebutton" ) || - type == wxT("ribbontoolbar") || - type == wxT("ribbontool") || - type == wxT("ribbondropdowntool" ) || - type == wxT("ribbonhybridtool" ) || - type == wxT("ribbontoggletool" ) || - type == wxT("ribbongallery") || - type == wxT("ribbongalleryitem") || - type == wxT("dataviewctrl") || - type == wxT("dataviewtreectrl") || - type == wxT("dataviewlistctrl") || - type == wxT("dataviewlistcolumn") || - type == wxT("dataviewcolumn") || - type == wxT("tool") || - type == wxT("splitter") || - type == wxT("treelistctrl") || - type == wxT("sizer") || - type == wxT("nonvisual") || - type == wxT("gbsizer") || - type == wxT("propgriditem") || - type == wxT("propgridpage") || - type == wxT("gbsizer") || - type == wxT("wizardpagesimple") - ); + return ( + type == wxT("notebook") || type == wxT("flatnotebook") || type == wxT("listbook") || type == wxT("simplebook") || + type == wxT("choicebook") || type == wxT("auinotebook") || type == wxT("widget") || + type == wxT("expanded_widget") || type == wxT("propgrid") || type == wxT("propgridman") || + type == wxT("statusbar") || type == wxT("component") || type == wxT("container") || type == wxT("menubar") || + type == wxT("menu") || type == wxT("menuitem") || type == wxT("submenu") || type == wxT("toolbar") || + type == wxT("ribbonbar") || type == wxT("ribbonpage") || type == wxT("ribbonpanel") || + type == wxT("ribbonbuttonbar") || type == wxT("ribbonbutton") || type == wxT("ribbondropdownbutton") || + type == wxT("ribbonhybridbutton") || type == wxT("ribbontogglebutton") || type == wxT("ribbontoolbar") || + type == wxT("ribbontool") || type == wxT("ribbondropdowntool") || type == wxT("ribbonhybridtool") || + type == wxT("ribbontoggletool") || type == wxT("ribbongallery") || type == wxT("ribbongalleryitem") || + type == wxT("dataviewctrl") || type == wxT("dataviewtreectrl") || type == wxT("dataviewlistctrl") || + type == wxT("dataviewlistcolumn") || type == wxT("dataviewcolumn") || type == wxT("tool") || + type == wxT("splitter") || type == wxT("treelistctrl") || type == wxT("sizer") || type == wxT("nonvisual") || + type == wxT("gbsizer") || type == wxT("propgriditem") || type == wxT("propgridpage") || type == wxT("gbsizer") || + type == wxT("wizardpagesimple")); } -void ObjectDatabase::LoadCodeGen( const wxString& file ) +void ObjectDatabase::LoadCodeGen(const wxString& file) { - try - { - ticpp::Document doc; - XMLUtils::LoadXMLFile( doc, true, file ); - - // read the codegen element - ticpp::Element* elem_codegen = doc.FirstChildElement("codegen"); - std::string language; - elem_codegen->GetAttribute( "language", &language ); - wxString lang = _WXSTR(language); - - // read the templates - ticpp::Element* elem_templates = elem_codegen->FirstChildElement( "templates", false ); - while ( elem_templates ) - { - - std::string prop_name; - elem_templates->GetAttribute( "property", &prop_name, false ); - bool hasProp = !prop_name.empty(); - - std::string class_name; - elem_templates->GetAttribute( "class", &class_name, !hasProp ); - - PCodeInfo code_info( new CodeInfo() ); - - ticpp::Element* elem_template = elem_templates->FirstChildElement( "template", false ); - while ( elem_template ) - { - std::string template_name; - elem_template->GetAttribute( "name", &template_name ); - - std::string template_code = elem_template->GetText( false ); - - code_info->AddTemplate( _WXSTR(template_name), _WXSTR(template_code) ); - - elem_template = elem_template->NextSiblingElement( "template", false ); - } - - if ( hasProp ) - { - // store code info for properties - if ( !m_propertyTypeTemplates[ ParsePropertyType( _WXSTR(prop_name) ) ].insert( LangTemplateMap::value_type( lang, code_info ) ).second ) - { - wxLogError( _("Found second template definition for property \"%s\" for language \"%s\""), _WXSTR(prop_name), lang ); - } - } - else - { - // store code info for objects - PObjectInfo obj_info = GetObjectInfo( _WXSTR(class_name) ); - if ( obj_info ) - { - obj_info->AddCodeInfo( lang, code_info ); - } - } - - elem_templates = elem_templates->NextSiblingElement( "templates", false ); - } - } - catch( ticpp::Exception& ex ) - { - wxLogError( _WXSTR(ex.m_details) ); - } - catch( wxFBException& ex ) - { - wxLogError( ex.what() ); - } + try { + ticpp::Document doc; + XMLUtils::LoadXMLFile(doc, true, file); + + // read the codegen element + ticpp::Element* elem_codegen = doc.FirstChildElement("codegen"); + std::string language; + elem_codegen->GetAttribute("language", &language); + wxString lang = _WXSTR(language); + + // read the templates + ticpp::Element* elem_templates = elem_codegen->FirstChildElement("templates", false); + while (elem_templates) { + + std::string prop_name; + elem_templates->GetAttribute("property", &prop_name, false); + bool hasProp = !prop_name.empty(); + + std::string class_name; + elem_templates->GetAttribute("class", &class_name, !hasProp); + + PCodeInfo code_info(new CodeInfo()); + + ticpp::Element* elem_template = elem_templates->FirstChildElement("template", false); + while (elem_template) { + std::string template_name; + elem_template->GetAttribute("name", &template_name); + + std::string template_code = elem_template->GetText(false); + + code_info->AddTemplate(_WXSTR(template_name), _WXSTR(template_code)); + + elem_template = elem_template->NextSiblingElement("template", false); + } + + if (hasProp) { + // store code info for properties + if (!m_propertyTypeTemplates[ParsePropertyType(_WXSTR(prop_name))] + .insert(LangTemplateMap::value_type(lang, code_info)) + .second) { + wxLogError( + _("Found second template definition for property \"%s\" for language \"%s\""), _WXSTR(prop_name), + lang); + } + } else { + // store code info for objects + PObjectInfo obj_info = GetObjectInfo(_WXSTR(class_name)); + if (obj_info) { + obj_info->AddCodeInfo(lang, code_info); + } + } + + elem_templates = elem_templates->NextSiblingElement("templates", false); + } + } catch (ticpp::Exception& ex) { + wxLogError(_WXSTR(ex.m_details)); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } } -PObjectPackage ObjectDatabase::LoadPackage( const wxString& file, const wxString& iconPath ) +PObjectPackage ObjectDatabase::LoadPackage(const wxString& file, const wxString& iconPath) { - PObjectPackage package; - - try - { - ticpp::Document doc; - XMLUtils::LoadXMLFile( doc, true, file ); - - ticpp::Element* root = doc.FirstChildElement( PACKAGE_TAG ); - - // Name Attribute - std::string pkg_name; - root->GetAttribute( NAME_TAG, &pkg_name ); - - // Description Attribute - std::string pkg_desc; - root->GetAttributeOrDefault( PKGDESC_TAG, &pkg_desc, "" ); - - // Icon Path Attribute - std::string pkgIconName; - root->GetAttributeOrDefault( ICON_TAG, &pkgIconName, "" ); - wxString pkgIconPath = iconPath + wxFILE_SEP_PATH + _WXSTR(pkgIconName); - - wxBitmap pkg_icon; - if ( !pkgIconName.empty() && wxFileName::FileExists( pkgIconPath ) ) - { - wxImage image( pkgIconPath, wxBITMAP_TYPE_ANY ); - pkg_icon = wxBitmap( image.Scale( 16, 16 ) ); - } - else - { - pkg_icon = AppBitmaps::GetBitmap( wxT("unknown"), 16 ); - } - - package = PObjectPackage ( new ObjectPackage( _WXSTR(pkg_name), _WXSTR(pkg_desc), pkg_icon ) ); - - - ticpp::Element* elem_obj = root->FirstChildElement( OBJINFO_TAG, false ); - - while (elem_obj) - { - std::string class_name; - elem_obj->GetAttribute( CLASS_TAG, &class_name ); - - std::string type; - elem_obj->GetAttribute( "type", &type ); - - std::string icon; - elem_obj->GetAttributeOrDefault( "icon", &icon, "" ); - wxString iconFullPath = iconPath + wxFILE_SEP_PATH + _WXSTR(icon); - - std::string smallIcon; - elem_obj->GetAttributeOrDefault( "smallIcon", &smallIcon, "" ); - wxString smallIconFullPath = iconPath + wxFILE_SEP_PATH + _WXSTR(smallIcon); - - std::string wxver; - elem_obj->GetAttributeOrDefault( WXVERSION_TAG, &wxver, "" ); - if( wxver != "" ) - { - long wxversion = 0; - // skip widgets supported by higher wxWidgets version than used for the build - if( (! _WXSTR(wxver).ToLong( &wxversion ) ) || (wxversion > wxVERSION_NUMBER) ) - { - elem_obj = elem_obj->NextSiblingElement( OBJINFO_TAG, false ); - continue; - } - } - - bool startGroup; - elem_obj->GetAttributeOrDefault( "startgroup", &startGroup, false ); - - PObjectInfo obj_info( new ObjectInfo( _WXSTR(class_name), GetObjectType( _WXSTR(type) ), package, startGroup ) ); - - if ( !icon.empty() && wxFileName::FileExists( iconFullPath ) ) - { - wxImage img( iconFullPath, wxBITMAP_TYPE_ANY ); - obj_info->SetIconFile( wxBitmap( img.Scale( ICON_SIZE, ICON_SIZE ) ) ); - } - else - { - obj_info->SetIconFile( AppBitmaps::GetBitmap( wxT("unknown"), ICON_SIZE ) ); - } - - if ( !smallIcon.empty() && wxFileName::FileExists( smallIconFullPath ) ) - { - wxImage img( smallIconFullPath, wxBITMAP_TYPE_ANY ); - obj_info->SetSmallIconFile( wxBitmap( img.Scale( SMALL_ICON_SIZE, SMALL_ICON_SIZE ) ) ); - } - else - { - wxImage img = obj_info->GetIconFile().ConvertToImage(); - obj_info->SetSmallIconFile( wxBitmap( img.Scale( SMALL_ICON_SIZE, SMALL_ICON_SIZE ) ) ); - } - - // Parse the Properties - std::set< PropertyType > types; - ParseProperties( elem_obj, obj_info, obj_info->GetCategory(), &types ); - ParseEvents ( elem_obj, obj_info, obj_info->GetCategory() ); - - // Add the ObjectInfo to the map - m_objs.insert(ObjectInfoMap::value_type( _WXSTR(class_name), obj_info ) ); - - // Add the object to the palette - if ( ShowInPalette( obj_info->GetObjectTypeName() ) ) - { - package->Add( obj_info ); - } - - elem_obj = elem_obj->NextSiblingElement( OBJINFO_TAG, false ); - } - } - catch ( ticpp::Exception& ex ) - { - THROW_WXFBEX( _WXSTR(ex.m_details) ); - } - - return package; + PObjectPackage package; + + try { + ticpp::Document doc; + XMLUtils::LoadXMLFile(doc, true, file); + + ticpp::Element* root = doc.FirstChildElement(PACKAGE_TAG); + + // Name Attribute + std::string pkg_name; + root->GetAttribute(NAME_TAG, &pkg_name); + + // Description Attribute + std::string pkg_desc; + root->GetAttributeOrDefault(PKGDESC_TAG, &pkg_desc, ""); + + // Icon Path Attribute + std::string pkgIconName; + root->GetAttributeOrDefault(ICON_TAG, &pkgIconName, ""); + wxString pkgIconPath = iconPath + wxFILE_SEP_PATH + _WXSTR(pkgIconName); + + wxBitmap pkg_icon; + if (!pkgIconName.empty() && wxFileName::FileExists(pkgIconPath)) { + wxImage image(pkgIconPath, wxBITMAP_TYPE_ANY); + pkg_icon = wxBitmap(image.Scale(16, 16)); + } else { + pkg_icon = AppBitmaps::GetBitmap(wxT("unknown"), 16); + } + + package = PObjectPackage(new ObjectPackage(_WXSTR(pkg_name), _WXSTR(pkg_desc), pkg_icon)); + + + ticpp::Element* elem_obj = root->FirstChildElement(OBJINFO_TAG, false); + + while (elem_obj) { + std::string class_name; + elem_obj->GetAttribute(CLASS_TAG, &class_name); + + std::string type; + elem_obj->GetAttribute("type", &type); + + std::string icon; + elem_obj->GetAttributeOrDefault("icon", &icon, ""); + wxString iconFullPath = iconPath + wxFILE_SEP_PATH + _WXSTR(icon); + + std::string smallIcon; + elem_obj->GetAttributeOrDefault("smallIcon", &smallIcon, ""); + wxString smallIconFullPath = iconPath + wxFILE_SEP_PATH + _WXSTR(smallIcon); + + std::string wxver; + elem_obj->GetAttributeOrDefault(WXVERSION_TAG, &wxver, ""); + if (wxver != "") { + long wxversion = 0; + // skip widgets supported by higher wxWidgets version than used for the build + if ((!_WXSTR(wxver).ToLong(&wxversion)) || (wxversion > wxVERSION_NUMBER)) { + elem_obj = elem_obj->NextSiblingElement(OBJINFO_TAG, false); + continue; + } + } + + bool startGroup; + elem_obj->GetAttributeOrDefault("startgroup", &startGroup, false); + + PObjectInfo obj_info(new ObjectInfo(_WXSTR(class_name), GetObjectType(_WXSTR(type)), package, startGroup)); + + if (!icon.empty() && wxFileName::FileExists(iconFullPath)) { + wxImage img(iconFullPath, wxBITMAP_TYPE_ANY); + obj_info->SetIconFile(wxBitmap(img.Scale(ICON_SIZE, ICON_SIZE))); + } else { + obj_info->SetIconFile(AppBitmaps::GetBitmap(wxT("unknown"), ICON_SIZE)); + } + + if (!smallIcon.empty() && wxFileName::FileExists(smallIconFullPath)) { + wxImage img(smallIconFullPath, wxBITMAP_TYPE_ANY); + obj_info->SetSmallIconFile(wxBitmap(img.Scale(SMALL_ICON_SIZE, SMALL_ICON_SIZE))); + } else { + wxImage img = obj_info->GetIconFile().ConvertToImage(); + obj_info->SetSmallIconFile(wxBitmap(img.Scale(SMALL_ICON_SIZE, SMALL_ICON_SIZE))); + } + + // Parse the Properties + std::set types; + ParseProperties(elem_obj, obj_info, obj_info->GetCategory(), &types); + ParseEvents(elem_obj, obj_info, obj_info->GetCategory()); + + // Add the ObjectInfo to the map + m_objs.insert(ObjectInfoMap::value_type(_WXSTR(class_name), obj_info)); + + // Add the object to the palette + if (ShowInPalette(obj_info->GetObjectTypeName())) { + package->Add(obj_info); + } + + elem_obj = elem_obj->NextSiblingElement(OBJINFO_TAG, false); + } + } catch (ticpp::Exception& ex) { + THROW_WXFBEX(_WXSTR(ex.m_details)); + } + + return package; } -void ObjectDatabase::ParseProperties( ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category, std::set< PropertyType >* types ) +void ObjectDatabase::ParseProperties( + ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category, std::set* types) { - ticpp::Element* elem_category = elem_obj->FirstChildElement( CATEGORY_TAG, false ); - while ( elem_category ) - { - // Category name attribute - std::string cname; - elem_category->GetAttribute( NAME_TAG, &cname ); - PPropertyCategory new_cat( new PropertyCategory( _WXSTR( cname ) ) ); - - // Add category - category->AddCategory( new_cat ); - - // Recurse - ParseProperties( elem_category, obj_info, new_cat, types ); - - elem_category = elem_category->NextSiblingElement( CATEGORY_TAG, false ); - } - - ticpp::Element* elem_prop = elem_obj->FirstChildElement( PROPERTY_TAG, false ); - while ( elem_prop ) - { - // Property Name Attribute - std::string pname; - elem_prop->GetAttribute( NAME_TAG, &pname ); - category->AddProperty( _WXSTR(pname) ); - - std::string description; - elem_prop->GetAttributeOrDefault( DESCRIPTION_TAG, &description, "" ); - - std::string customEditor; - elem_prop->GetAttributeOrDefault( CUSTOM_EDITOR_TAG, &customEditor, "" ); - - std::string prop_type; - elem_prop->GetAttribute( "type", &prop_type ); - PropertyType ptype; - try - { - ptype = ParsePropertyType( _WXSTR( prop_type ) ); - } - catch( wxFBException& ex ) - { - wxLogError( wxT("Error: %s\nWhile parsing property \"%s\" of class \"%s\""), ex.what(), _WXSTR(pname), obj_info->GetClassName() ); - elem_prop = elem_prop->NextSiblingElement( PROPERTY_TAG, false ); - continue; - } - - // Get default value - std::string def_value; - try - { - ticpp::Node* lastChild = elem_prop->LastChild(false); - if (lastChild && lastChild->Type() == TiXmlNode::TEXT) - { - ticpp::Text* text = lastChild->ToText(); - wxASSERT(text); - def_value = text->Value(); - } - } - catch (ticpp::Exception& ex) - { - wxLogDebug(ex.what()); - } - - // if the property is a "bitlist" then parse all of the options - POptionList opt_list; - std::list< PropertyChild > children; - if ( ptype == PT_BITLIST || ptype == PT_OPTION || ptype == PT_EDIT_OPTION ) - { - opt_list = POptionList( new OptionList() ); - ticpp::Element* elem_opt = elem_prop->FirstChildElement( "option", false ); - while( elem_opt ) - { - std::string macro_name; - elem_opt->GetAttribute( NAME_TAG, ¯o_name ); - - std::string macro_description; - elem_opt->GetAttributeOrDefault( DESCRIPTION_TAG, ¯o_description, "" ); - - opt_list->AddOption( _WXSTR(macro_name), _WXSTR(macro_description) ); - - m_macroSet.insert( _WXSTR(macro_name) ); - - elem_opt = elem_opt->NextSiblingElement( "option", false ); - } - } - else if ( ptype == PT_PARENT ) - { - // If the property is a parent, then get the children - def_value.clear(); - ticpp::Element* elem_child = elem_prop->FirstChildElement( "child", false ); - while ( elem_child ) - { - PropertyChild child; - - std::string child_name; - elem_child->GetAttribute( NAME_TAG, &child_name ); - child.m_name = _WXSTR( child_name ); - - std::string child_description; - elem_child->GetAttributeOrDefault( DESCRIPTION_TAG, &child_description, "" ); - child.m_description = _WXSTR( child_description ); - - std::string child_type; - elem_child->GetAttributeOrDefault( "type", &child_type, "wxString" ); - child.m_type = ParsePropertyType( _WXSTR( child_type ) ); - - // Get default value - // Empty tags don't contain any child so this will throw in that case - std::string child_value; - try - { - ticpp::Node* lastChild = elem_child->LastChild(false); - if (lastChild && lastChild->Type() == TiXmlNode::TEXT) - { - ticpp::Text* text = lastChild->ToText(); - wxASSERT(text); - child_value = text->Value(); - } - } - catch (ticpp::Exception& ex) - { - wxLogDebug(ex.what()); - } - child.m_defaultValue = _WXSTR(child_value); - - // build parent default value - if (children.size() > 0) - { - def_value += "; "; - } - def_value += child_value; - - children.push_back(child); - - elem_child = elem_child->NextSiblingElement( "child", false ); - } - } - - // create an instance of PropertyInfo - PPropertyInfo prop_info( new PropertyInfo( _WXSTR(pname), ptype, _WXSTR(def_value), _WXSTR(description), _WXSTR(customEditor), opt_list, children ) ); - - // add the PropertyInfo to the property - obj_info->AddPropertyInfo( prop_info ); - - // merge property code templates, once per property type - if ( types->insert( ptype ).second ) - { - LangTemplateMap& propLangTemplates = m_propertyTypeTemplates[ ptype ]; - LangTemplateMap::iterator lang; - for ( lang = propLangTemplates.begin(); lang != propLangTemplates.end(); ++lang ) - { - if ( lang->second ) - { - obj_info->AddCodeInfo( lang->first, lang->second ); - } - } - } - - elem_prop = elem_prop->NextSiblingElement( PROPERTY_TAG, false ); - } + ticpp::Element* elem_category = elem_obj->FirstChildElement(CATEGORY_TAG, false); + while (elem_category) { + // Category name attribute + std::string cname; + elem_category->GetAttribute(NAME_TAG, &cname); + PPropertyCategory new_cat(new PropertyCategory(_WXSTR(cname))); + + // Add category + category->AddCategory(new_cat); + + // Recurse + ParseProperties(elem_category, obj_info, new_cat, types); + + elem_category = elem_category->NextSiblingElement(CATEGORY_TAG, false); + } + + ticpp::Element* elem_prop = elem_obj->FirstChildElement(PROPERTY_TAG, false); + while (elem_prop) { + // Property Name Attribute + std::string pname; + elem_prop->GetAttribute(NAME_TAG, &pname); + category->AddProperty(_WXSTR(pname)); + + std::string description; + elem_prop->GetAttributeOrDefault(DESCRIPTION_TAG, &description, ""); + + std::string customEditor; + elem_prop->GetAttributeOrDefault(CUSTOM_EDITOR_TAG, &customEditor, ""); + + std::string prop_type; + elem_prop->GetAttribute("type", &prop_type); + PropertyType ptype; + try { + ptype = ParsePropertyType(_WXSTR(prop_type)); + } catch (wxFBException& ex) { + wxLogError( + wxT("Error: %s\nWhile parsing property \"%s\" of class \"%s\""), ex.what(), _WXSTR(pname), + obj_info->GetClassName()); + elem_prop = elem_prop->NextSiblingElement(PROPERTY_TAG, false); + continue; + } + + // Get default value + std::string def_value; + try { + ticpp::Node* lastChild = elem_prop->LastChild(false); + if (lastChild && lastChild->Type() == TiXmlNode::TEXT) { + ticpp::Text* text = lastChild->ToText(); + wxASSERT(text); + def_value = text->Value(); + } + } catch (ticpp::Exception& ex) { + wxLogDebug(ex.what()); + } + + // if the property is a "bitlist" then parse all of the options + POptionList opt_list; + std::list children; + if (ptype == PT_BITLIST || ptype == PT_OPTION || ptype == PT_EDIT_OPTION) { + opt_list = POptionList(new OptionList()); + ticpp::Element* elem_opt = elem_prop->FirstChildElement("option", false); + while (elem_opt) { + std::string macro_name; + elem_opt->GetAttribute(NAME_TAG, ¯o_name); + + std::string macro_description; + elem_opt->GetAttributeOrDefault(DESCRIPTION_TAG, ¯o_description, ""); + + opt_list->AddOption(_WXSTR(macro_name), _WXSTR(macro_description)); + + m_macroSet.insert(_WXSTR(macro_name)); + + elem_opt = elem_opt->NextSiblingElement("option", false); + } + } else if (ptype == PT_PARENT) { + // If the property is a parent, then get the children + def_value.clear(); + ticpp::Element* elem_child = elem_prop->FirstChildElement("child", false); + while (elem_child) { + PropertyChild child; + + std::string child_name; + elem_child->GetAttribute(NAME_TAG, &child_name); + child.m_name = _WXSTR(child_name); + + std::string child_description; + elem_child->GetAttributeOrDefault(DESCRIPTION_TAG, &child_description, ""); + child.m_description = _WXSTR(child_description); + + std::string child_type; + elem_child->GetAttributeOrDefault("type", &child_type, "wxString"); + child.m_type = ParsePropertyType(_WXSTR(child_type)); + + // Get default value + // Empty tags don't contain any child so this will throw in that case + std::string child_value; + try { + ticpp::Node* lastChild = elem_child->LastChild(false); + if (lastChild && lastChild->Type() == TiXmlNode::TEXT) { + ticpp::Text* text = lastChild->ToText(); + wxASSERT(text); + child_value = text->Value(); + } + } catch (ticpp::Exception& ex) { + wxLogDebug(ex.what()); + } + child.m_defaultValue = _WXSTR(child_value); + + // build parent default value + if (children.size() > 0) { + def_value += "; "; + } + def_value += child_value; + + children.push_back(child); + + elem_child = elem_child->NextSiblingElement("child", false); + } + } + + // create an instance of PropertyInfo + PPropertyInfo prop_info(new PropertyInfo( + _WXSTR(pname), ptype, _WXSTR(def_value), _WXSTR(description), _WXSTR(customEditor), opt_list, children)); + + // add the PropertyInfo to the property + obj_info->AddPropertyInfo(prop_info); + + // merge property code templates, once per property type + if (types->insert(ptype).second) { + LangTemplateMap& propLangTemplates = m_propertyTypeTemplates[ptype]; + LangTemplateMap::iterator lang; + for (lang = propLangTemplates.begin(); lang != propLangTemplates.end(); ++lang) { + if (lang->second) { + obj_info->AddCodeInfo(lang->first, lang->second); + } + } + } + + elem_prop = elem_prop->NextSiblingElement(PROPERTY_TAG, false); + } } -void ObjectDatabase::ParseEvents( ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category ) +void ObjectDatabase::ParseEvents(ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category) { - ticpp::Element* elem_category = elem_obj->FirstChildElement( CATEGORY_TAG, false ); - while ( elem_category ) - { - // Category name attribute - std::string cname; - elem_category->GetAttribute( NAME_TAG, &cname ); - PPropertyCategory new_cat( new PropertyCategory( _WXSTR( cname ) ) ); - - // Add category - category->AddCategory( new_cat ); - - // Recurse - ParseEvents( elem_category, obj_info, new_cat ); - - elem_category = elem_category->NextSiblingElement( CATEGORY_TAG, false ); - } - - ticpp::Element* elem_evt = elem_obj->FirstChildElement( EVENT_TAG, false ); - while ( elem_evt ) - { - // Event Name Attribute - std::string evt_name; - elem_evt->GetAttribute( NAME_TAG, &evt_name ); - category->AddEvent( _WXSTR(evt_name) ); - - // Event class - std::string evt_class; - elem_evt->GetAttributeOrDefault( EVENT_CLASS_TAG, &evt_class, "wxEvent" ); - - - // Help string - std::string description; - elem_evt->GetAttributeOrDefault( DESCRIPTION_TAG, &description, "" ); - - // Get default value - std::string def_value; - try - { - ticpp::Node* lastChild = elem_evt->LastChild(false); - if (lastChild && lastChild->Type() == TiXmlNode::TEXT) - { - ticpp::Text* text = lastChild->ToText(); - wxASSERT(text); - def_value = text->Value(); - } - } - catch (ticpp::Exception& ex) - { - wxLogDebug(ex.what()); - } - - // create an instance of EventInfo - PEventInfo evt_info( - new EventInfo( _WXSTR(evt_name), _WXSTR(evt_class), _WXSTR(def_value), _WXSTR(description))); - - // add the EventInfo to the event - obj_info->AddEventInfo(evt_info); - - elem_evt = elem_evt->NextSiblingElement( EVENT_TAG, false ); - } + ticpp::Element* elem_category = elem_obj->FirstChildElement(CATEGORY_TAG, false); + while (elem_category) { + // Category name attribute + std::string cname; + elem_category->GetAttribute(NAME_TAG, &cname); + PPropertyCategory new_cat(new PropertyCategory(_WXSTR(cname))); + + // Add category + category->AddCategory(new_cat); + + // Recurse + ParseEvents(elem_category, obj_info, new_cat); + + elem_category = elem_category->NextSiblingElement(CATEGORY_TAG, false); + } + + ticpp::Element* elem_evt = elem_obj->FirstChildElement(EVENT_TAG, false); + while (elem_evt) { + // Event Name Attribute + std::string evt_name; + elem_evt->GetAttribute(NAME_TAG, &evt_name); + category->AddEvent(_WXSTR(evt_name)); + + // Event class + std::string evt_class; + elem_evt->GetAttributeOrDefault(EVENT_CLASS_TAG, &evt_class, "wxEvent"); + + + // Help string + std::string description; + elem_evt->GetAttributeOrDefault(DESCRIPTION_TAG, &description, ""); + + // Get default value + std::string def_value; + try { + ticpp::Node* lastChild = elem_evt->LastChild(false); + if (lastChild && lastChild->Type() == TiXmlNode::TEXT) { + ticpp::Text* text = lastChild->ToText(); + wxASSERT(text); + def_value = text->Value(); + } + } catch (ticpp::Exception& ex) { + wxLogDebug(ex.what()); + } + + // create an instance of EventInfo + PEventInfo evt_info(new EventInfo(_WXSTR(evt_name), _WXSTR(evt_class), _WXSTR(def_value), _WXSTR(description))); + + // add the EventInfo to the event + obj_info->AddEventInfo(evt_info); + + elem_evt = elem_evt->NextSiblingElement(EVENT_TAG, false); + } } bool ObjectDatabase::ShowInPalette(wxString type) { - return (type == wxT("form") || - type == wxT("wizard") || - type == wxT("wizardpagesimple") || - type == wxT("menubar_form") || - type == wxT("toolbar_form") || - type == wxT("sizer") || - type == wxT("gbsizer") || - type == wxT("menu") || - type == wxT("menuitem") || - type == wxT("submenu") || - type == wxT("tool") || - type == wxT("ribbonbar") || - type == wxT("ribbonpage") || - type == wxT("ribbonpanel") || - type == wxT("ribbonbuttonbar") || - type == wxT("ribbonbutton") || - type == wxT("ribbondropdownbutton" ) || - type == wxT("ribbonhybridbutton" ) || - type == wxT("ribbontogglebutton" ) || - type == wxT("ribbontoolbar") || - type == wxT("ribbontool") || - type == wxT("ribbondropdowntool" ) || - type == wxT("ribbonhybridtool" ) || - type == wxT("ribbontoggletool" ) || - type == wxT("ribbongallery") || - type == wxT("ribbongalleryitem") || - type == wxT("dataviewctrl") || - type == wxT("dataviewtreectrl") || - type == wxT("dataviewlistctrl") || - type == wxT("dataviewlistcolumn") || - type == wxT("dataviewcolumn") || - type == wxT("notebook") || - type == wxT("flatnotebook") || - type == wxT("listbook") || - type == wxT("simplebook") || - type == wxT("choicebook") || - type == wxT("auinotebook") || - type == wxT("widget") || - type == wxT("expanded_widget") || - type == wxT("propgrid") || - type == wxT("propgridman") || - type == wxT("propgridpage") || - type == wxT("propgriditem") || - type == wxT("statusbar") || - type == wxT("component") || - type == wxT("container") || - type == wxT("menubar") || - type == wxT("treelistctrl") || - type == wxT("treelistctrlcolumn") || - type == wxT("toolbar") || - type == wxT("nonvisual") || - type == wxT("splitter") - ); + return ( + type == wxT("form") || type == wxT("wizard") || type == wxT("wizardpagesimple") || type == wxT("menubar_form") || + type == wxT("toolbar_form") || type == wxT("sizer") || type == wxT("gbsizer") || type == wxT("menu") || + type == wxT("menuitem") || type == wxT("submenu") || type == wxT("tool") || type == wxT("ribbonbar") || + type == wxT("ribbonpage") || type == wxT("ribbonpanel") || type == wxT("ribbonbuttonbar") || + type == wxT("ribbonbutton") || type == wxT("ribbondropdownbutton") || type == wxT("ribbonhybridbutton") || + type == wxT("ribbontogglebutton") || type == wxT("ribbontoolbar") || type == wxT("ribbontool") || + type == wxT("ribbondropdowntool") || type == wxT("ribbonhybridtool") || type == wxT("ribbontoggletool") || + type == wxT("ribbongallery") || type == wxT("ribbongalleryitem") || type == wxT("dataviewctrl") || + type == wxT("dataviewtreectrl") || type == wxT("dataviewlistctrl") || type == wxT("dataviewlistcolumn") || + type == wxT("dataviewcolumn") || type == wxT("notebook") || type == wxT("flatnotebook") || + type == wxT("listbook") || type == wxT("simplebook") || type == wxT("choicebook") || type == wxT("auinotebook") || + type == wxT("widget") || type == wxT("expanded_widget") || type == wxT("propgrid") || + type == wxT("propgridman") || type == wxT("propgridpage") || type == wxT("propgriditem") || + type == wxT("statusbar") || type == wxT("component") || type == wxT("container") || type == wxT("menubar") || + type == wxT("treelistctrl") || type == wxT("treelistctrlcolumn") || type == wxT("toolbar") || + type == wxT("nonvisual") || type == wxT("splitter")); } -void ObjectDatabase::ImportComponentLibrary( wxString libfile, PwxFBManager manager ) +void ObjectDatabase::ImportComponentLibrary(wxString libfile, PwxFBManager manager) { - wxString path; - auto pluginLibrary = m_pluginLibraries.emplace(std::piecewise_construct, std::forward_as_tuple(libfile), std::forward_as_tuple()).first; - try { - pluginLibrary->second.sharedLibrary.load(libfile.ToStdString(), - boost::dll::load_mode::default_mode | // Use platform default parameters - boost::dll::load_mode::append_decorations | // Only the library base name is supplied, it needs to be decorated for the platform - boost::dll::load_mode::search_system_folders // This enables usage of RPATH - ); - path = pluginLibrary->second.sharedLibrary.location().native(); - } catch (const std::system_error& ex) { - THROW_WXFBEX("Error loading library " << libfile << ": " << ex.what()) - } - try { - pluginLibrary->second.getComponentLibrary = pluginLibrary->second.sharedLibrary.get("GetComponentLibrary"); - pluginLibrary->second.freeComponentLibrary = pluginLibrary->second.sharedLibrary.get("FreeComponentLibrary"); - } catch (const std::system_error& ex) { - THROW_WXFBEX(path << " is not a valid component library: " << ex.what()) - } - - LogDebug("[Database::ImportComponentLibrary] Importing " + path + " library"); - pluginLibrary->second.componentLibrary = pluginLibrary->second.getComponentLibrary(manager.get()); - auto* comp_lib = pluginLibrary->second.componentLibrary; - - // Import all of the components - for ( unsigned int i = 0; i < comp_lib->GetComponentCount(); i++ ) - { - wxString class_name = comp_lib->GetComponentName( i ); - IComponent* comp = comp_lib->GetComponent( i ); - - // Look for the class in the data read from the .xml files - PObjectInfo class_info = GetObjectInfo( class_name ); - if ( class_info ) - { - class_info->SetComponent(comp); - } - else - { + wxString path; + auto pluginLibrary = + m_pluginLibraries.emplace(std::piecewise_construct, std::forward_as_tuple(libfile), std::forward_as_tuple()) + .first; + try { + pluginLibrary->second.sharedLibrary.load( + libfile.ToStdString(), + boost::dll::load_mode::default_mode | // Use platform default parameters + boost::dll::load_mode::append_decorations | // Only the library base name is supplied, it needs to be + // decorated for the platform + boost::dll::load_mode::search_system_folders // This enables usage of RPATH + ); + path = pluginLibrary->second.sharedLibrary.location().native(); + } catch (const std::system_error& ex) { + THROW_WXFBEX("Error loading library " << libfile << ": " << ex.what()) + } + try { + pluginLibrary->second.getComponentLibrary = + pluginLibrary->second.sharedLibrary.get("GetComponentLibrary"); + pluginLibrary->second.freeComponentLibrary = + pluginLibrary->second.sharedLibrary.get("FreeComponentLibrary"); + } catch (const std::system_error& ex) { + THROW_WXFBEX(path << " is not a valid component library: " << ex.what()) + } + + LogDebug("[Database::ImportComponentLibrary] Importing " + path + " library"); + pluginLibrary->second.componentLibrary = pluginLibrary->second.getComponentLibrary(manager.get()); + auto* comp_lib = pluginLibrary->second.componentLibrary; + + // Import all of the components + for (unsigned int i = 0; i < comp_lib->GetComponentCount(); i++) { + wxString class_name = comp_lib->GetComponentName(i); + IComponent* comp = comp_lib->GetComponent(i); + + // Look for the class in the data read from the .xml files + PObjectInfo class_info = GetObjectInfo(class_name); + if (class_info) { + class_info->SetComponent(comp); + } else { LogDebug("ObjectInfo for <" + class_name + "> not found while loading library <" + path + ">"); - } - } - - // Add all of the macros in the library to the macro dictionary - PMacroDictionary dic = MacroDictionary::GetInstance(); - for ( unsigned int i = 0; i < comp_lib->GetMacroCount(); i++ ) - { - wxString name = comp_lib->GetMacroName( i ); - int value = comp_lib->GetMacroValue( i ); - dic->AddMacro( name, value ); - m_macroSet.erase( name ); - } + } + } + + // Add all of the macros in the library to the macro dictionary + PMacroDictionary dic = MacroDictionary::GetInstance(); + for (unsigned int i = 0; i < comp_lib->GetMacroCount(); i++) { + wxString name = comp_lib->GetMacroName(i); + int value = comp_lib->GetMacroValue(i); + dic->AddMacro(name, value); + m_macroSet.erase(name); + } } -PropertyType ObjectDatabase::ParsePropertyType( wxString str ) +PropertyType ObjectDatabase::ParsePropertyType(wxString str) { - PropertyType result; - PTMap::iterator it = m_propTypes.find(str); - if (it != m_propTypes.end()) - result = it->second; - else - { - THROW_WXFBEX( wxString::Format( wxT("Unknown property type \"%s\""), str ) ); - } - - return result; + PropertyType result; + PTMap::iterator it = m_propTypes.find(str); + if (it != m_propTypes.end()) + result = it->second; + else { + THROW_WXFBEX(wxString::Format(wxT("Unknown property type \"%s\""), str)); + } + + return result; } -wxString ObjectDatabase::ParseObjectType( wxString str ) +wxString ObjectDatabase::ParseObjectType(wxString str) { - return str; + return str; } -#define PT(x,y) m_propTypes.insert(PTMap::value_type(x,y)) +#define PT(x, y) m_propTypes.insert(PTMap::value_type(x, y)) void ObjectDatabase::InitPropertyTypes() { - PT( wxT("bool"), PT_BOOL ); - PT( wxT("text"), PT_TEXT ); - PT( wxT("int"), PT_INT ); - PT( wxT("uint"), PT_UINT ); - PT( wxT("bitlist"), PT_BITLIST ); - PT( wxT("intlist"), PT_INTLIST ); - PT( wxT("uintlist"), PT_UINTLIST ); - PT(wxT("intpairlist"), PT_INTPAIRLIST); - PT(wxT("uintpairlist"), PT_UINTPAIRLIST); - PT( wxT("option"), PT_OPTION ); - PT( wxT("macro"), PT_MACRO ); - PT( wxT("path"), PT_PATH ); - PT( wxT("file"), PT_FILE ); - PT( wxT("wxString"), PT_WXSTRING ); - PT( wxT("wxPoint"), PT_WXPOINT ); - PT( wxT("wxSize"), PT_WXSIZE ); - PT( wxT("wxFont"), PT_WXFONT ); - PT( wxT("wxColour"), PT_WXCOLOUR ); - PT( wxT("bitmap"), PT_BITMAP ); - PT( wxT("wxString_i18n"),PT_WXSTRING_I18N); - PT( wxT("stringlist"), PT_STRINGLIST ); - PT( wxT("float"), PT_FLOAT ); - PT( wxT("parent"), PT_PARENT ); - PT( wxT("editoption"), PT_EDIT_OPTION ); + PT(wxT("bool"), PT_BOOL); + PT(wxT("text"), PT_TEXT); + PT(wxT("int"), PT_INT); + PT(wxT("uint"), PT_UINT); + PT(wxT("bitlist"), PT_BITLIST); + PT(wxT("intlist"), PT_INTLIST); + PT(wxT("uintlist"), PT_UINTLIST); + PT(wxT("intpairlist"), PT_INTPAIRLIST); + PT(wxT("uintpairlist"), PT_UINTPAIRLIST); + PT(wxT("option"), PT_OPTION); + PT(wxT("macro"), PT_MACRO); + PT(wxT("path"), PT_PATH); + PT(wxT("file"), PT_FILE); + PT(wxT("wxString"), PT_WXSTRING); + PT(wxT("wxPoint"), PT_WXPOINT); + PT(wxT("wxSize"), PT_WXSIZE); + PT(wxT("wxFont"), PT_WXFONT); + PT(wxT("wxColour"), PT_WXCOLOUR); + PT(wxT("bitmap"), PT_BITMAP); + PT(wxT("wxString_i18n"), PT_WXSTRING_I18N); + PT(wxT("stringlist"), PT_STRINGLIST); + PT(wxT("float"), PT_FLOAT); + PT(wxT("parent"), PT_PARENT); + PT(wxT("editoption"), PT_EDIT_OPTION); } bool ObjectDatabase::LoadObjectTypes() { - ticpp::Document doc; - wxString xmlPath = m_xmlPath + wxT("objtypes.xml"); - XMLUtils::LoadXMLFile( doc, true, xmlPath ); - - // First load the object types, then the children - try - { - ticpp::Element* root = doc.FirstChildElement("definitions"); - ticpp::Element* elem = root->FirstChildElement( "objtype" ); - while ( elem ) - { - bool hidden; - elem->GetAttributeOrDefault( "hidden", &hidden, false ); - - bool item; - elem->GetAttributeOrDefault( "item", &item, false ); - - wxString name = _WXSTR( elem->GetAttribute("name") ); - - PObjectType objType( new ObjectType( name, (int)m_types.size(), hidden, item ) ); - m_types.insert( ObjectTypeMap::value_type( name, objType ) ); - - elem = elem->NextSiblingElement( "objtype", false ); - } - - // now load the children - elem = root->FirstChildElement("objtype"); - while (elem) - { - wxString name = _WXSTR( elem->GetAttribute("name") ); - - // get the objType - PObjectType objType = GetObjectType( name ); - ticpp::Element* child = elem->FirstChildElement( "childtype", false ); - while ( child ) - { - int nmax = -1; // no limit - int aui_nmax = -1; // no limit - child->GetAttributeOrDefault( "nmax", &nmax, -1 ); - child->GetAttributeOrDefault( "aui_nmax", &aui_nmax, -1 ); - - wxString childname = _WXSTR( child->GetAttribute("name") ); - - PObjectType childType = GetObjectType( childname ); - if ( !childType ) - { - wxLogError( _("No Object Type found for \"%s\""), childname ); - continue; - } - - objType->AddChildType( childType, nmax, aui_nmax ); - - child = child->NextSiblingElement( "childtype", false ); - } - elem = elem->NextSiblingElement( "objtype", false ); - } - } - catch( ticpp::Exception& ex ) - { - wxLogError( _WXSTR( ex.m_details ) ); - return false; - } - - return true; + ticpp::Document doc; + wxString xmlPath = m_xmlPath + wxT("objtypes.xml"); + XMLUtils::LoadXMLFile(doc, true, xmlPath); + + // First load the object types, then the children + try { + ticpp::Element* root = doc.FirstChildElement("definitions"); + ticpp::Element* elem = root->FirstChildElement("objtype"); + while (elem) { + bool hidden; + elem->GetAttributeOrDefault("hidden", &hidden, false); + + bool item; + elem->GetAttributeOrDefault("item", &item, false); + + wxString name = _WXSTR(elem->GetAttribute("name")); + + PObjectType objType(new ObjectType(name, (int)m_types.size(), hidden, item)); + m_types.insert(ObjectTypeMap::value_type(name, objType)); + + elem = elem->NextSiblingElement("objtype", false); + } + + // now load the children + elem = root->FirstChildElement("objtype"); + while (elem) { + wxString name = _WXSTR(elem->GetAttribute("name")); + + // get the objType + PObjectType objType = GetObjectType(name); + ticpp::Element* child = elem->FirstChildElement("childtype", false); + while (child) { + int nmax = -1; // no limit + int aui_nmax = -1; // no limit + child->GetAttributeOrDefault("nmax", &nmax, -1); + child->GetAttributeOrDefault("aui_nmax", &aui_nmax, -1); + + wxString childname = _WXSTR(child->GetAttribute("name")); + + PObjectType childType = GetObjectType(childname); + if (!childType) { + wxLogError(_("No Object Type found for \"%s\""), childname); + continue; + } + + objType->AddChildType(childType, nmax, aui_nmax); + + child = child->NextSiblingElement("childtype", false); + } + elem = elem->NextSiblingElement("objtype", false); + } + } catch (ticpp::Exception& ex) { + wxLogError(_WXSTR(ex.m_details)); + return false; + } + + return true; } PObjectType ObjectDatabase::GetObjectType(wxString name) { - PObjectType type; - ObjectTypeMap::iterator it = m_types.find(name); - if (it != m_types.end()) - type = it->second; + PObjectType type; + ObjectTypeMap::iterator it = m_types.find(name); + if (it != m_types.end()) + type = it->second; - return type; + return type; } diff --git a/src/model/database.h b/src/model/database.h index 33ef63f7f..f175d6e87 100644 --- a/src/model/database.h +++ b/src/model/database.h @@ -22,16 +22,18 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef MODEL_DATABASE_H #define MODEL_DATABASE_H -#include "utils/wxfbdefs.h" -#include "model/types.h" - -#include #include +#include + #include +#include "model/types.h" +#include "utils/wxfbdefs.h" + class ObjectDatabase; class ObjectTypeDictionary; @@ -41,65 +43,65 @@ typedef std::shared_ptr PObjectDatabase; namespace ticpp { - class Element; +class Element; } + /** * Paquete de clases de objetos. * Determinará la agrupación en la paleta de componentes. */ class ObjectPackage { - private: - wxString m_name; // nombre del paquete - wxString m_desc; // breve descripción del paquete - wxBitmap m_icon; // The icon for the notebook page - - // Vector con los objetos que están contenidos en el paquete - std::vector< PObjectInfo > m_objs; - - public: - /** - * Constructor. - */ - ObjectPackage(wxString name, wxString desc, wxBitmap icon); - - /** - * Incluye en el paquete la información de un objeto. - */ - void Add(PObjectInfo obj) { m_objs.push_back(obj); } - - /** - * Obtiene el nombre del paquete. - */ - wxString GetPackageName() { return m_name; } - - /** - * Obtiene el texto que describe el paquete. - */ - wxString GetPackageDescription() { return m_desc; } - - /** - * Get Package Icon - */ - wxBitmap GetPackageIcon() { return m_icon; } - - /** - * Obtiene el número de objetos incluidos en el paquete. - */ - unsigned int GetObjectCount() { return (unsigned int)m_objs.size(); } - - /** - * Obtiene la información de un objeto incluido en el paquete. - */ - PObjectInfo GetObjectInfo(unsigned int idx); - - /** - If two xml files specify the same package name, then they merged to one package with this. - This allows one package to be split across multiple xml files. - */ - void AppendPackage( PObjectPackage package ); - +private: + wxString m_name; // nombre del paquete + wxString m_desc; // breve descripción del paquete + wxBitmap m_icon; // The icon for the notebook page + + // Vector con los objetos que están contenidos en el paquete + std::vector m_objs; + +public: + /** + * Constructor. + */ + ObjectPackage(wxString name, wxString desc, wxBitmap icon); + + /** + * Incluye en el paquete la información de un objeto. + */ + void Add(PObjectInfo obj) { m_objs.push_back(obj); } + + /** + * Obtiene el nombre del paquete. + */ + wxString GetPackageName() { return m_name; } + + /** + * Obtiene el texto que describe el paquete. + */ + wxString GetPackageDescription() { return m_desc; } + + /** + * Get Package Icon + */ + wxBitmap GetPackageIcon() { return m_icon; } + + /** + * Obtiene el número de objetos incluidos en el paquete. + */ + unsigned int GetObjectCount() { return (unsigned int)m_objs.size(); } + + /** + * Obtiene la información de un objeto incluido en el paquete. + */ + PObjectInfo GetObjectInfo(unsigned int idx); + + /** + If two xml files specify the same package name, then they merged to one package with this. + This allows one package to be split across multiple xml files. + */ + void AppendPackage(PObjectPackage package); }; class IComponentLibrary; @@ -112,172 +114,172 @@ class IManager; */ class ObjectDatabase { - public: - static bool HasCppProperties(wxString type); - private: - typedef std::vector PackageVector; - - // Map the property type string to the property type number - typedef std::map PTMap; - typedef std::map ObjectTypeMap; - typedef std::set MacroSet; - typedef std::map< wxString, PCodeInfo > LangTemplateMap; - typedef std::map< PropertyType, LangTemplateMap > PTLangTemplateMap; - - struct PluginLibrary { - boost::dll::shared_library sharedLibrary; - std::function getComponentLibrary; - std::function freeComponentLibrary; - IComponentLibrary* componentLibrary = nullptr; - }; - - wxString m_xmlPath; - wxString m_iconPath; - wxString m_pluginPath; - std::map< wxString, PObjectInfo > m_objs; - PackageVector m_pkgs; - PTMap m_propTypes; - ObjectTypeMap m_types; // register object types - - // para comprobar que no se nos han quedado macros sin añadir en las - // liberias de componentes, vamos a crear un conjunto con las macros - // definidas en los XML, y al importar las librerías vamos a ir eliminando - // dichas macros del conjunto, quedando al final las macros que faltan - // por registrar en la librería. - MacroSet m_macroSet; - - PTLangTemplateMap m_propertyTypeTemplates; - - std::map m_pluginLibraries; - - /** - * Initialize the property type map. - */ - void InitPropertyTypes(); - - /** - * Carga las plantillas de generación de código de un fichero - * xml de código dado - */ - void LoadCodeGen( const wxString& file ); - - /** - * Carga los objetos de un paquete con todas sus propiedades salvo - * los objetos heredados - */ - PObjectPackage LoadPackage( const wxString& file, const wxString& iconPath = wxEmptyString ); - - void ParseProperties( ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category, std::set< PropertyType >* types ); - void ParseEvents ( ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category ); - - /** - * Importa una librería de componentes y lo asocia a cada clase. - * @throw wxFBException If the library could not be imported. - */ - void ImportComponentLibrary( wxString libfile, PwxFBManager manager ); - - /** - * Incluye la información heredada de los objetos de un paquete. - * En la segunda pasada configura cada paquete con sus objetos base. - */ - void SetupPackage( const wxString& file, const wxString& path, PwxFBManager manager ); - - /** - * Determina si el tipo de objeto hay que incluirlo en la paleta de - * componentes. - */ - bool ShowInPalette(wxString type); - - // rutinas de conversión - PropertyType ParsePropertyType (wxString str); - wxString ParseObjectType (wxString str); - - - PObjectType GetObjectType(wxString name); - - int CountChildrenWithSameType(PObjectBase parent,PObjectType type); - int CountChildrenWithSameType(PObjectBase parent, const std::set& types); - - void SetDefaultLayoutProperties(PObjectBase obj); - - public: - ObjectDatabase(); - ~ObjectDatabase(); - - PObjectBase NewObject(PObjectInfo obj_info); - - /** - * Obtiene la información de un objeto a partir del nombre de la clase. - */ - PObjectInfo GetObjectInfo(wxString class_name); - - /** - * Configura la ruta donde se encuentran los ficheros con la descripción. - */ - void SetXmlPath( const wxString& path ) { m_xmlPath = path; } - - /** - * Configura la ruta donde se encuentran los iconos asociados a los objetos. - */ - void SetIconPath( const wxString& path) { m_iconPath = path; } - void SetPluginPath( const wxString& path ) { m_pluginPath = path; } - - /** - * Obtiene la ruta donde se encuentran los ficheros con la descripción de - * objetos. - */ - wxString GetXmlPath() { return m_xmlPath; } - wxString GetIconPath() { return m_iconPath; } - wxString GetPluginPath() { return m_pluginPath; } - - /** - * Carga las definiciones de tipos de objetos. - */ - bool LoadObjectTypes(); - - /** - * Find and load plugins from the plugins directory - */ - void LoadPlugins( PwxFBManager manager ); - - /** - * Fabrica de objetos. - * A partir del nombre de la clase se crea una nueva instancia de un objeto. - */ - PObjectBase CreateObject( std::string class_name, PObjectBase parent = PObjectBase()); - - /** - * Fábrica de objetos a partir de un objeto XML. - * Este método se usará para cargar un proyecto almacenado. - */ - PObjectBase CreateObject( ticpp::Element* obj, PObjectBase parent = PObjectBase()); - - /** - * Crea un objeto como copia de otro. - */ - - PObjectBase CopyObject(PObjectBase obj); - - /** - * Obtiene un paquete de objetos. - */ - PObjectPackage GetPackage(unsigned int idx); - - /** - * Obtiene el número de paquetes registrados. - */ - unsigned int GetPackageCount() { return (unsigned int)m_pkgs.size(); } - - /** - * Resetea los contadores que acompañan al nombre. - * La propiedad "name" es una propiedad especial, reservada para el nombre - * de la instancia del objeto. Cada clase de objeto tiene asociado un contador - * para no duplicar nombre en la creación de nuevos objetos - * (p.e. m_button1, m_button2 ...) - */ - void ResetObjectCounters(); +public: + static bool HasCppProperties(wxString type); + +private: + typedef std::vector PackageVector; + + // Map the property type string to the property type number + typedef std::map PTMap; + typedef std::map ObjectTypeMap; + typedef std::set MacroSet; + typedef std::map LangTemplateMap; + typedef std::map PTLangTemplateMap; + + struct PluginLibrary { + boost::dll::shared_library sharedLibrary; + std::function getComponentLibrary; + std::function freeComponentLibrary; + IComponentLibrary* componentLibrary = nullptr; + }; + + wxString m_xmlPath; + wxString m_iconPath; + wxString m_pluginPath; + std::map m_objs; + PackageVector m_pkgs; + PTMap m_propTypes; + ObjectTypeMap m_types; // register object types + + // para comprobar que no se nos han quedado macros sin añadir en las + // liberias de componentes, vamos a crear un conjunto con las macros + // definidas en los XML, y al importar las librerías vamos a ir eliminando + // dichas macros del conjunto, quedando al final las macros que faltan + // por registrar en la librería. + MacroSet m_macroSet; + + PTLangTemplateMap m_propertyTypeTemplates; + + std::map m_pluginLibraries; + + /** + * Initialize the property type map. + */ + void InitPropertyTypes(); + + /** + * Carga las plantillas de generación de código de un fichero + * xml de código dado + */ + void LoadCodeGen(const wxString& file); + + /** + * Carga los objetos de un paquete con todas sus propiedades salvo + * los objetos heredados + */ + PObjectPackage LoadPackage(const wxString& file, const wxString& iconPath = wxEmptyString); + + void ParseProperties( + ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category, std::set* types); + void ParseEvents(ticpp::Element* elem_obj, PObjectInfo obj_info, PPropertyCategory category); + + /** + * Importa una librería de componentes y lo asocia a cada clase. + * @throw wxFBException If the library could not be imported. + */ + void ImportComponentLibrary(wxString libfile, PwxFBManager manager); + + /** + * Incluye la información heredada de los objetos de un paquete. + * En la segunda pasada configura cada paquete con sus objetos base. + */ + void SetupPackage(const wxString& file, const wxString& path, PwxFBManager manager); + + /** + * Determina si el tipo de objeto hay que incluirlo en la paleta de + * componentes. + */ + bool ShowInPalette(wxString type); + + // rutinas de conversión + PropertyType ParsePropertyType(wxString str); + wxString ParseObjectType(wxString str); + + + PObjectType GetObjectType(wxString name); + + int CountChildrenWithSameType(PObjectBase parent, PObjectType type); + int CountChildrenWithSameType(PObjectBase parent, const std::set& types); + + void SetDefaultLayoutProperties(PObjectBase obj); + +public: + ObjectDatabase(); + ~ObjectDatabase(); + + PObjectBase NewObject(PObjectInfo obj_info); + + /** + * Obtiene la información de un objeto a partir del nombre de la clase. + */ + PObjectInfo GetObjectInfo(wxString class_name); + + /** + * Configura la ruta donde se encuentran los ficheros con la descripción. + */ + void SetXmlPath(const wxString& path) { m_xmlPath = path; } + + /** + * Configura la ruta donde se encuentran los iconos asociados a los objetos. + */ + void SetIconPath(const wxString& path) { m_iconPath = path; } + void SetPluginPath(const wxString& path) { m_pluginPath = path; } + + /** + * Obtiene la ruta donde se encuentran los ficheros con la descripción de + * objetos. + */ + wxString GetXmlPath() { return m_xmlPath; } + wxString GetIconPath() { return m_iconPath; } + wxString GetPluginPath() { return m_pluginPath; } + + /** + * Carga las definiciones de tipos de objetos. + */ + bool LoadObjectTypes(); + + /** + * Find and load plugins from the plugins directory + */ + void LoadPlugins(PwxFBManager manager); + + /** + * Fabrica de objetos. + * A partir del nombre de la clase se crea una nueva instancia de un objeto. + */ + PObjectBase CreateObject(std::string class_name, PObjectBase parent = PObjectBase()); + + /** + * Fábrica de objetos a partir de un objeto XML. + * Este método se usará para cargar un proyecto almacenado. + */ + PObjectBase CreateObject(ticpp::Element* obj, PObjectBase parent = PObjectBase()); + + /** + * Crea un objeto como copia de otro. + */ + + PObjectBase CopyObject(PObjectBase obj); + + /** + * Obtiene un paquete de objetos. + */ + PObjectPackage GetPackage(unsigned int idx); + + /** + * Obtiene el número de paquetes registrados. + */ + unsigned int GetPackageCount() { return (unsigned int)m_pkgs.size(); } + + /** + * Resetea los contadores que acompañan al nombre. + * La propiedad "name" es una propiedad especial, reservada para el nombre + * de la instancia del objeto. Cada clase de objeto tiene asociado un contador + * para no duplicar nombre en la creación de nuevos objetos + * (p.e. m_button1, m_button2 ...) + */ + void ResetObjectCounters(); }; - - -#endif // MODEL_DATABASE_H +#endif // MODEL_DATABASE_H diff --git a/src/model/objectbase.cpp b/src/model/objectbase.cpp index 6f54ad8cb..28736ea49 100644 --- a/src/model/objectbase.cpp +++ b/src/model/objectbase.cpp @@ -25,927 +25,884 @@ #include "objectbase.h" +#include +#include + #include "rad/appdata.h" #include "utils/debug.h" #include "utils/stringutils.h" #include "utils/typeconv.h" -#include -#include -PropertyInfo::PropertyInfo(wxString name, PropertyType type, wxString def_value, wxString description, wxString customEditor, - POptionList opt_list, const std::list< PropertyChild >& children ) +PropertyInfo::PropertyInfo( + wxString name, PropertyType type, wxString def_value, wxString description, wxString customEditor, + POptionList opt_list, const std::list& children) { - m_name = name; - m_type = type; - m_def_value = def_value; - m_opt_list = opt_list; - m_description = description; - m_children = children; - m_customEditor = customEditor; + m_name = name; + m_type = type; + m_def_value = def_value; + m_opt_list = opt_list; + m_description = description; + m_children = children; + m_customEditor = customEditor; } PropertyInfo::~PropertyInfo() { } -EventInfo::EventInfo(const wxString &name, const wxString &eventClass, - const wxString &defValue, const wxString &description) - : m_name(name), m_eventClass(eventClass), m_defaultValue(defValue), - m_description(description) +EventInfo::EventInfo( + const wxString& name, const wxString& eventClass, const wxString& defValue, const wxString& description) : + m_name(name), m_eventClass(eventClass), m_defaultValue(defValue), m_description(description) { } bool Property::IsDefaultValue() { - return (m_info->GetDefaultValue() == m_value); + return (m_info->GetDefaultValue() == m_value); } bool Property::IsNull() { - switch ( m_info->GetType() ) - { - case PT_BITMAP: - { - wxString path; - size_t semicolonIndex = m_value.find_first_of( wxT(";") ); - if ( semicolonIndex != m_value.npos ) - { - path = m_value.substr( 0, semicolonIndex ); - } - else - { - path = m_value; - } - - return path.empty(); - } - case PT_WXSIZE: - { - return ( wxDefaultSize == TypeConv::StringToSize( m_value ) ); - } - default: - { - return m_value.empty(); - } - } + switch (m_info->GetType()) { + case PT_BITMAP: { + wxString path; + size_t semicolonIndex = m_value.find_first_of(wxT(";")); + if (semicolonIndex != m_value.npos) { + path = m_value.substr(0, semicolonIndex); + } else { + path = m_value; + } + + return path.empty(); + } + case PT_WXSIZE: { + return (wxDefaultSize == TypeConv::StringToSize(m_value)); + } + default: { + return m_value.empty(); + } + } } void Property::SetDefaultValue() { - m_value = m_info->GetDefaultValue(); + m_value = m_info->GetDefaultValue(); } -void Property::SetValue(const wxFontContainer &font) +void Property::SetValue(const wxFontContainer& font) { - m_value = TypeConv::FontToString( font ); + m_value = TypeConv::FontToString(font); } -void Property::SetValue(const wxColour &colour) +void Property::SetValue(const wxColour& colour) { - m_value = TypeConv::ColourToString( colour ); + m_value = TypeConv::ColourToString(colour); } -void Property::SetValue(const wxString &str, bool format) +void Property::SetValue(const wxString& str, bool format) { - m_value = (format ? TypeConv::TextToString(str) : str ); + m_value = (format ? TypeConv::TextToString(str) : str); } -void Property::SetValue(const wxPoint &point) +void Property::SetValue(const wxPoint& point) { - m_value = TypeConv::PointToString(point); + m_value = TypeConv::PointToString(point); } -void Property::SetValue(const wxSize &size) +void Property::SetValue(const wxSize& size) { - m_value = TypeConv::SizeToString(size); + m_value = TypeConv::SizeToString(size); } void Property::SetValue(const int integer) { - m_value = StringUtils::IntToStr(integer); + m_value = StringUtils::IntToStr(integer); } -void Property::SetValue(const double val ) +void Property::SetValue(const double val) { - m_value = TypeConv::FloatToString( val ); + m_value = TypeConv::FloatToString(val); } wxFontContainer Property::GetValueAsFont() { - return TypeConv::StringToFont( m_value ); + return TypeConv::StringToFont(m_value); } wxColour Property::GetValueAsColour() { - return TypeConv::StringToColour(m_value); + return TypeConv::StringToColour(m_value); } wxPoint Property::GetValueAsPoint() { - return TypeConv::StringToPoint(m_value); + return TypeConv::StringToPoint(m_value); } wxSize Property::GetValueAsSize() { - return TypeConv::StringToSize(m_value); + return TypeConv::StringToSize(m_value); } wxBitmap Property::GetValueAsBitmap() { - return TypeConv::StringToBitmap( m_value ); + return TypeConv::StringToBitmap(m_value); } int Property::GetValueAsInteger() { - int result = 0; - - switch (GetType()) - { - case PT_EDIT_OPTION: - case PT_OPTION: - case PT_MACRO: - result = TypeConv::GetMacroValue(m_value); - break; - case PT_BITLIST: - result = TypeConv::BitlistToInt(m_value); - break; - default: - result = TypeConv::StringToInt(m_value); - break; - } - return result; + int result = 0; + + switch (GetType()) { + case PT_EDIT_OPTION: + case PT_OPTION: + case PT_MACRO: + result = TypeConv::GetMacroValue(m_value); + break; + case PT_BITLIST: + result = TypeConv::BitlistToInt(m_value); + break; + default: + result = TypeConv::StringToInt(m_value); + break; + } + return result; } wxString Property::GetValueAsString() { - return m_value; + return m_value; } wxString Property::GetValueAsText() { - return TypeConv::StringToText(m_value); + return TypeConv::StringToText(m_value); } wxArrayString Property::GetValueAsArrayString() { - return TypeConv::StringToArrayString(m_value); + return TypeConv::StringToArrayString(m_value); } double Property::GetValueAsFloat() { - return TypeConv::StringToFloat(m_value); + return TypeConv::StringToFloat(m_value); } -void Property::SplitParentProperty( std::map< wxString, wxString >* children ) +void Property::SplitParentProperty(std::map* children) { - children->clear(); - if ( m_info->GetType() != PT_PARENT ) - { - return; - } + children->clear(); + if (m_info->GetType() != PT_PARENT) { + return; + } - std::list< PropertyChild >* myChildren = m_info->GetChildren(); - std::list< PropertyChild >::iterator it = myChildren->begin(); + std::list* myChildren = m_info->GetChildren(); + std::list::iterator it = myChildren->begin(); - wxStringTokenizer tkz( m_value, wxT(";"), wxTOKEN_RET_EMPTY_ALL ); - while ( tkz.HasMoreTokens() ) - { - if ( myChildren->end() == it ) - { - return; - } - wxString child = tkz.GetNextToken(); - child.Trim( false ); - child.Trim( true ); - children->insert( std::map< wxString, wxString >::value_type( it->m_name, child ) ); - it++; - } + wxStringTokenizer tkz(m_value, wxT(";"), wxTOKEN_RET_EMPTY_ALL); + while (tkz.HasMoreTokens()) { + if (myChildren->end() == it) { + return; + } + wxString child = tkz.GetNextToken(); + child.Trim(false); + child.Trim(true); + children->insert(std::map::value_type(it->m_name, child)); + it++; + } } -wxString Property::GetChildFromParent( const wxString& childName ) +wxString Property::GetChildFromParent(const wxString& childName) { - std::map< wxString, wxString > children; - SplitParentProperty( &children ); + std::map children; + SplitParentProperty(&children); - std::map< wxString, wxString >::iterator child; - child = children.find( childName ); + std::map::iterator child; + child = children.find(childName); - if ( children.end() == child ) - { - return wxEmptyString; - } - else - { - return child->second; - } + if (children.end() == child) { + return wxEmptyString; + } else { + return child->second; + } } /////////////////////////////////////////////////////////////////////////////// const int ObjectBase::INDENT = 2; -ObjectBase::ObjectBase (wxString class_name) -: -m_expanded( true ) +ObjectBase::ObjectBase(wxString class_name) : m_expanded(true) { - m_class = class_name; + m_class = class_name; - LogDebug(wxT("new ObjectBase")); + LogDebug(wxT("new ObjectBase")); } ObjectBase::~ObjectBase() { - // remove the reference in the parent - PObjectBase parent = m_parent.lock(); + // remove the reference in the parent + PObjectBase parent = m_parent.lock(); - if (parent) - { - PObjectBase pobj(GetThis()); - parent->RemoveChild(pobj); - } + if (parent) { + PObjectBase pobj(GetThis()); + parent->RemoveChild(pobj); + } - LogDebug(wxT("delete ObjectBase")); + LogDebug(wxT("delete ObjectBase")); } wxString ObjectBase::GetIndentString(int indent) { - int i; - wxString s; + int i; + wxString s; - for (i=0;iGetParent() ) && - ( current->GetObjectInfo()->IsSubclassOf( wxT( "sizeritem" ) ) || - current->GetObjectInfo()->IsSubclassOf( wxT( "sizer" ) ) ) ) - ; + while ((current = current->GetParent()) && (current->GetObjectInfo()->IsSubclassOf(wxT("sizeritem")) || + current->GetObjectInfo()->IsSubclassOf(wxT("sizer")))) + ; - return current; + return current; } -PProperty ObjectBase::GetProperty (wxString name) +PProperty ObjectBase::GetProperty(wxString name) { - PropertyMap::iterator it = m_properties.find( name ); - if ( it != m_properties.end() ) - return it->second; + PropertyMap::iterator it = m_properties.find(name); + if (it != m_properties.end()) + return it->second; - //LogDebug(wxT("[ObjectBase::GetProperty] Property %s not found!"),name); - // este aserto falla siempre que se crea un sizeritem - // assert(false); - return PProperty(); + // LogDebug(wxT("[ObjectBase::GetProperty] Property %s not found!"),name); + // este aserto falla siempre que se crea un sizeritem + // assert(false); + return PProperty(); } -PProperty ObjectBase::GetProperty (unsigned int idx) +PProperty ObjectBase::GetProperty(unsigned int idx) { - assert (idx < m_properties.size()); + assert(idx < m_properties.size()); - PropertyMap::iterator it = m_properties.begin(); - unsigned int i = 0; - while (i < idx && it != m_properties.end()) - { - i++; - it++; - } + PropertyMap::iterator it = m_properties.begin(); + unsigned int i = 0; + while (i < idx && it != m_properties.end()) { + i++; + it++; + } - if (it != m_properties.end()) - return it->second; + if (it != m_properties.end()) + return it->second; - return PProperty(); + return PProperty(); } -PEvent ObjectBase::GetEvent (wxString name) +PEvent ObjectBase::GetEvent(wxString name) { - EventMap::iterator it = m_events.find( name ); - if ( it != m_events.end() ) - return it->second; + EventMap::iterator it = m_events.find(name); + if (it != m_events.end()) + return it->second; LogDebug("[ObjectBase::GetEvent] Event " + name + " not found!"); - return PEvent(); + return PEvent(); } -PEvent ObjectBase::GetEvent (unsigned int idx) +PEvent ObjectBase::GetEvent(unsigned int idx) { - assert (idx < m_events.size()); + assert(idx < m_events.size()); - EventMap::iterator it = m_events.begin(); - unsigned int i = 0; - while (i < idx && it != m_events.end()) - { - i++; - it++; - } + EventMap::iterator it = m_events.begin(); + unsigned int i = 0; + while (i < idx && it != m_events.end()) { + i++; + it++; + } - if (it != m_events.end()) - return it->second; + if (it != m_events.end()) + return it->second; - return PEvent(); + return PEvent(); } -void ObjectBase::AddProperty (PProperty prop) +void ObjectBase::AddProperty(PProperty prop) { - m_properties.insert( PropertyMap::value_type( prop->GetName(), prop ) ); + m_properties.insert(PropertyMap::value_type(prop->GetName(), prop)); } void ObjectBase::AddEvent(PEvent event) { - m_events.insert( EventMap::value_type( event->GetName(), event ) ); + m_events.insert(EventMap::value_type(event->GetName(), event)); } PObjectBase ObjectBase::FindNearAncestor(wxString type) { - PObjectBase result; - PObjectBase parent = GetParent(); - if (parent) - { - if (parent->GetObjectTypeName() == type) - result = parent; - else - result = parent->FindNearAncestor(type); - } + PObjectBase result; + PObjectBase parent = GetParent(); + if (parent) { + if (parent->GetObjectTypeName() == type) + result = parent; + else + result = parent->FindNearAncestor(type); + } - return result; + return result; } PObjectBase ObjectBase::FindNearAncestorByBaseClass(wxString type) { - PObjectBase result; - PObjectBase parent = GetParent(); - if (parent) - { - if ( parent->GetObjectInfo()->IsSubclassOf( type ) ) - result = parent; - else - result = parent->FindNearAncestorByBaseClass( type ); - } + PObjectBase result; + PObjectBase parent = GetParent(); + if (parent) { + if (parent->GetObjectInfo()->IsSubclassOf(type)) + result = parent; + else + result = parent->FindNearAncestorByBaseClass(type); + } - return result; + return result; } PObjectBase ObjectBase::FindParentForm() { - PObjectBase retObj = this->FindNearAncestor( wxT( "form" ) ); - if( retObj == NULL ) retObj = this->FindNearAncestor( wxT( "menubar_form" ) ); - if( retObj == NULL ) retObj = this->FindNearAncestor( wxT( "toolbar_form" ) ); - if( retObj == NULL ) retObj = this->FindNearAncestor( wxT("wizard") ); + PObjectBase retObj = this->FindNearAncestor(wxT("form")); + if (retObj == NULL) + retObj = this->FindNearAncestor(wxT("menubar_form")); + if (retObj == NULL) + retObj = this->FindNearAncestor(wxT("toolbar_form")); + if (retObj == NULL) + retObj = this->FindNearAncestor(wxT("wizard")); - return retObj; + return retObj; } -bool ObjectBase::AddChild (PObjectBase obj) +bool ObjectBase::AddChild(PObjectBase obj) { - bool result = false; - if (ChildTypeOk(obj->GetObjectInfo()->GetObjectType())) - //if (ChildTypeOk(obj->GetObjectTypeName())) - { - m_children.push_back(obj); - result = true; - } + bool result = false; + if (ChildTypeOk(obj->GetObjectInfo()->GetObjectType())) + // if (ChildTypeOk(obj->GetObjectTypeName())) + { + m_children.push_back(obj); + result = true; + } - return result; + return result; } -bool ObjectBase::AddChild (unsigned int idx, PObjectBase obj) +bool ObjectBase::AddChild(unsigned int idx, PObjectBase obj) { - bool result = false; - if (ChildTypeOk(obj->GetObjectInfo()->GetObjectType()) && idx <= m_children.size()) - //if (ChildTypeOk(obj->GetObjectTypeName()) && idx <= m_children.size()) - { - m_children.insert(m_children.begin() + idx,obj); - result = true; - } + bool result = false; + if (ChildTypeOk(obj->GetObjectInfo()->GetObjectType()) && idx <= m_children.size()) + // if (ChildTypeOk(obj->GetObjectTypeName()) && idx <= m_children.size()) + { + m_children.insert(m_children.begin() + idx, obj); + result = true; + } - return result; + return result; } -bool ObjectBase::ChildTypeOk (PObjectType type) +bool ObjectBase::ChildTypeOk(PObjectType type) { - // buscamos si puede haber objectos del tipo "type" como hijos - // del actual objeto tipo. - - int nmax = 0; + // buscamos si puede haber objectos del tipo "type" como hijos + // del actual objeto tipo. - // check allowed child count - if( GetObjectInfo()->GetObjectType()->GetName() == wxT("form") ) - { - nmax = GetObjectInfo()->GetObjectType()->FindChildType( - type, this->GetPropertyAsInteger(wxT("aui_managed")) != 0); - } - else - nmax = GetObjectInfo()->GetObjectType()->FindChildType(type, false); + int nmax = 0; - if (nmax == 0) - return false; + // check allowed child count + if (GetObjectInfo()->GetObjectType()->GetName() == wxT("form")) { + nmax = + GetObjectInfo()->GetObjectType()->FindChildType(type, this->GetPropertyAsInteger(wxT("aui_managed")) != 0); + } else + nmax = GetObjectInfo()->GetObjectType()->FindChildType(type, false); - if (nmax < 0) - return true; + if (nmax == 0) + return false; - // llegados aquí hay que comprobar el número de hijos del tipo pasado - int count = 0; - for (unsigned int i=0; i < GetChildCount() && count <= nmax; i++) - { - if (GetChild(i)->GetObjectInfo()->GetObjectType() == type) - count++; - } + if (nmax < 0) + return true; - if (count > nmax) - return false; + // llegados aquí hay que comprobar el número de hijos del tipo pasado + int count = 0; + for (unsigned int i = 0; i < GetChildCount() && count <= nmax; i++) { + if (GetChild(i)->GetObjectInfo()->GetObjectType() == type) + count++; + } - return true; + if (count > nmax) + return false; + return true; } PObjectBase ObjectBase::GetLayout() { - PObjectBase result; + PObjectBase result; - if (GetParent() && GetParent()->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") )) - result = GetParent(); + if (GetParent() && GetParent()->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) + result = GetParent(); - return result; + return result; } -void ObjectBase::RemoveChild (PObjectBase obj) +void ObjectBase::RemoveChild(PObjectBase obj) { - std::vector< PObjectBase >::iterator it = m_children.begin(); - while (it != m_children.end() && *it != obj) - it++; + std::vector::iterator it = m_children.begin(); + while (it != m_children.end() && *it != obj) it++; - if (it != m_children.end()) - m_children.erase(it); + if (it != m_children.end()) + m_children.erase(it); } -void ObjectBase::RemoveChild (unsigned int idx) +void ObjectBase::RemoveChild(unsigned int idx) { - assert (idx < m_children.size()); + assert(idx < m_children.size()); - std::vector< PObjectBase >::iterator it = m_children.begin() + idx; - m_children.erase(it); + std::vector::iterator it = m_children.begin() + idx; + m_children.erase(it); } -PObjectBase ObjectBase::GetChild (unsigned int idx) +PObjectBase ObjectBase::GetChild(unsigned int idx) { - assert (idx < m_children.size()); + assert(idx < m_children.size()); - return m_children[idx]; + return m_children[idx]; } -PObjectBase ObjectBase::GetChild (unsigned int idx, const wxString& type) +PObjectBase ObjectBase::GetChild(unsigned int idx, const wxString& type) { - //assert (idx < m_children.size()); + // assert (idx < m_children.size()); - unsigned int cnt = 0; + unsigned int cnt = 0; - for( std::vector< PObjectBase >::iterator it = m_children.begin(); it != m_children.end(); ++it ) - { - if( (*it)->GetObjectInfo()->GetObjectTypeName() == type && ++cnt == idx ) return *it; - } + for (std::vector::iterator it = m_children.begin(); it != m_children.end(); ++it) { + if ((*it)->GetObjectInfo()->GetObjectTypeName() == type && ++cnt == idx) + return *it; + } - return PObjectBase(); + return PObjectBase(); } int ObjectBase::Deep() { - int deep = 0; - PObjectBase obj(GetParent()); - while (obj) - { - obj = obj->GetParent(); - deep++; + int deep = 0; + PObjectBase obj(GetParent()); + while (obj) { + obj = obj->GetParent(); + deep++; - if (deep > 1000) - assert(false); - } - return deep; + if (deep > 1000) + assert(false); + } + return deep; } -//void ObjectBase::PrintOut(ostream &s, int indent) +// void ObjectBase::PrintOut(ostream &s, int indent) //{ -// wxString ind_str = GetIndentString(indent); +// wxString ind_str = GetIndentString(indent); // -// s << ind_str << "[ " << GetClassName() << " ] " << GetObjectType() << endl; -// map< wxString, PProperty >::const_iterator it_prop; -// for (it_prop = m_properties.begin(); it_prop!= m_properties.end(); it_prop++) -// { -// s << ind_str << "property '" << it_prop->first << "' = '" << -// it_prop->second->GetValue() << "'" << endl; -// } +// s << ind_str << "[ " << GetClassName() << " ] " << GetObjectType() << endl; +// map< wxString, PProperty >::const_iterator it_prop; +// for (it_prop = m_properties.begin(); it_prop!= m_properties.end(); it_prop++) +// { +// s << ind_str << "property '" << it_prop->first << "' = '" << +// it_prop->second->GetValue() << "'" << endl; +// } // -// vector< PObjectBase >::const_iterator it_ch; -// for (it_ch = m_children.begin() ; it_ch != m_children.end(); it_ch++) -// { -// (*it_ch)->PrintOut(s,INDENT + indent); -// } -//} +// vector< PObjectBase >::const_iterator it_ch; +// for (it_ch = m_children.begin() ; it_ch != m_children.end(); it_ch++) +// { +// (*it_ch)->PrintOut(s,INDENT + indent); +// } +// } // -//ostream& operator << (ostream &s, PObjectBase obj) +// ostream& operator << (ostream &s, PObjectBase obj) //{ -// obj->PrintOut(s,0); -// return s; -//} +// obj->PrintOut(s,0); +// return s; +// } -void ObjectBase::SerializeObject( ticpp::Element* serializedElement ) +void ObjectBase::SerializeObject(ticpp::Element* serializedElement) { - ticpp::Element element( "object" ); - element.SetAttribute( "class", _STDSTR( GetClassName() ) ); - element.SetAttribute( "expanded", GetExpanded() ); + ticpp::Element element("object"); + element.SetAttribute("class", _STDSTR(GetClassName())); + element.SetAttribute("expanded", GetExpanded()); - for ( unsigned int i = 0; i < GetPropertyCount(); i++ ) - { - PProperty prop = GetProperty( i ); - ticpp::Element prop_element( "property" ); - prop_element.SetAttribute( "name", _STDSTR( prop->GetName() ) ); - prop_element.SetText( _STDSTR( prop->GetValue() ) ); - element.LinkEndChild( &prop_element ); - } + for (unsigned int i = 0; i < GetPropertyCount(); i++) { + PProperty prop = GetProperty(i); + ticpp::Element prop_element("property"); + prop_element.SetAttribute("name", _STDSTR(prop->GetName())); + prop_element.SetText(_STDSTR(prop->GetValue())); + element.LinkEndChild(&prop_element); + } - for ( unsigned int i = 0; i < GetEventCount(); i++ ) - { - PEvent event = GetEvent( i ); - const std::string callback(event->GetValue().ToUTF8()); - if (callback.empty()) { - continue; // skip, because there's no event attached (see issue #467) - } - ticpp::Element event_element( "event" ); - event_element.SetAttribute( "name", _STDSTR( event->GetName() ) ); - event_element.SetText(callback); - element.LinkEndChild( &event_element ); - } + for (unsigned int i = 0; i < GetEventCount(); i++) { + PEvent event = GetEvent(i); + const std::string callback(event->GetValue().ToUTF8()); + if (callback.empty()) { + continue; // skip, because there's no event attached (see issue #467) + } + ticpp::Element event_element("event"); + event_element.SetAttribute("name", _STDSTR(event->GetName())); + event_element.SetText(callback); + element.LinkEndChild(&event_element); + } - for ( unsigned int i = 0 ; i < GetChildCount(); i++ ) - { - PObjectBase child = GetChild( i ); - ticpp::Element child_element; - child->SerializeObject( &child_element ); - element.LinkEndChild( &child_element ); - } + for (unsigned int i = 0; i < GetChildCount(); i++) { + PObjectBase child = GetChild(i); + ticpp::Element child_element; + child->SerializeObject(&child_element); + element.LinkEndChild(&child_element); + } - *serializedElement = element; + *serializedElement = element; } -void ObjectBase::Serialize( ticpp::Document* serializedDocument ) +void ObjectBase::Serialize(ticpp::Document* serializedDocument) { - ticpp::Document document( "document" ); + ticpp::Document document("document"); - ticpp::Declaration dec( "1.0", "UTF-8", "yes" ); - document.LinkEndChild( &dec ); + ticpp::Declaration dec("1.0", "UTF-8", "yes"); + document.LinkEndChild(&dec); - ticpp::Element root( "wxFormBuilder_Project" ); + ticpp::Element root("wxFormBuilder_Project"); - ticpp::Element fileVersion( "FileVersion" ); - fileVersion.SetAttribute( "major", AppData()->m_fbpVerMajor ); - fileVersion.SetAttribute( "minor", AppData()->m_fbpVerMinor ); + ticpp::Element fileVersion("FileVersion"); + fileVersion.SetAttribute("major", AppData()->m_fbpVerMajor); + fileVersion.SetAttribute("minor", AppData()->m_fbpVerMinor); - root.LinkEndChild( &fileVersion ); + root.LinkEndChild(&fileVersion); - ticpp::Element element; - SerializeObject( &element ); + ticpp::Element element; + SerializeObject(&element); - root.LinkEndChild( &element ); - document.LinkEndChild( &root ); + root.LinkEndChild(&element); + document.LinkEndChild(&root); - *serializedDocument = document; + *serializedDocument = document; } unsigned int ObjectBase::GetChildPosition(PObjectBase obj) { - unsigned int pos = 0; - while (pos < GetChildCount() && m_children[pos] != obj) - pos++; + unsigned int pos = 0; + while (pos < GetChildCount() && m_children[pos] != obj) pos++; - return pos; + return pos; } -bool ObjectBase::ChangeChildPosition( PObjectBase obj, unsigned int pos) +bool ObjectBase::ChangeChildPosition(PObjectBase obj, unsigned int pos) { - unsigned int obj_pos = GetChildPosition(obj); + unsigned int obj_pos = GetChildPosition(obj); - if (obj_pos == GetChildCount() || pos >= GetChildCount()) - return false; + if (obj_pos == GetChildCount() || pos >= GetChildCount()) + return false; - if (pos == obj_pos) - return true; + if (pos == obj_pos) + return true; - // Procesamos el cambio de posición - RemoveChild(obj); - AddChild(pos,obj); - return true; + // Procesamos el cambio de posición + RemoveChild(obj); + AddChild(pos, obj); + return true; } /////////////////////////////////////////////////////////////////////////////// -bool ObjectBase::IsNull (const wxString& pname) +bool ObjectBase::IsNull(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->IsNull(); - else - return true; + PProperty property = GetProperty(pname); + if (property) + return property->IsNull(); + else + return true; } -int ObjectBase::GetPropertyAsInteger (const wxString& pname) +int ObjectBase::GetPropertyAsInteger(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsInteger(); - else - return 0; + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsInteger(); + else + return 0; } wxFontContainer ObjectBase::GetPropertyAsFont(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsFont(); - else - return wxFontContainer(); + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsFont(); + else + return wxFontContainer(); } -wxColour ObjectBase::GetPropertyAsColour (const wxString& pname) +wxColour ObjectBase::GetPropertyAsColour(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsColour(); - else - return wxColour(); + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsColour(); + else + return wxColour(); } -wxString ObjectBase::GetPropertyAsString (const wxString& pname) +wxString ObjectBase::GetPropertyAsString(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsString(); - else - return wxString(); + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsString(); + else + return wxString(); } -wxPoint ObjectBase::GetPropertyAsPoint (const wxString& pname) +wxPoint ObjectBase::GetPropertyAsPoint(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsPoint(); - else - return wxPoint(); + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsPoint(); + else + return wxPoint(); } -wxSize ObjectBase::GetPropertyAsSize (const wxString& pname) +wxSize ObjectBase::GetPropertyAsSize(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsSize(); - else - return wxDefaultSize; + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsSize(); + else + return wxDefaultSize; } -wxBitmap ObjectBase::GetPropertyAsBitmap (const wxString& pname) +wxBitmap ObjectBase::GetPropertyAsBitmap(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsBitmap(); - else - return wxBitmap(); + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsBitmap(); + else + return wxBitmap(); } -double ObjectBase::GetPropertyAsFloat( const wxString& pname ) +double ObjectBase::GetPropertyAsFloat(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsFloat(); - else - return 0; + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsFloat(); + else + return 0; } wxArrayInt ObjectBase::GetPropertyAsArrayInt(const wxString& pname) { - wxArrayInt array; - PProperty property = GetProperty( pname ); - if (property) - { - IntList il(property->GetValue(), property->GetType() == PT_UINTLIST, (property->GetType() == PT_INTPAIRLIST || property->GetType() == PT_UINTPAIRLIST)); - for (unsigned int i=0; i < il.GetSize() ; i++) - array.Add(il.GetValue(i)); - } + wxArrayInt array; + PProperty property = GetProperty(pname); + if (property) { + IntList il( + property->GetValue(), property->GetType() == PT_UINTLIST, + (property->GetType() == PT_INTPAIRLIST || property->GetType() == PT_UINTPAIRLIST)); + for (unsigned int i = 0; i < il.GetSize(); i++) array.Add(il.GetValue(i)); + } - return array; + return array; } wxArrayString ObjectBase::GetPropertyAsArrayString(const wxString& pname) { - PProperty property = GetProperty( pname ); - if (property) - return property->GetValueAsArrayString(); - else - return wxArrayString(); + PProperty property = GetProperty(pname); + if (property) + return property->GetValueAsArrayString(); + else + return wxArrayString(); } std::vector> ObjectBase::GetPropertyAsVectorIntPair(const wxString& pname) { - std::vector> result; - - auto property = GetProperty(pname); - if (property) - { - IntList il(property->GetValue(), property->GetType() == PT_UINTLIST, (property->GetType() == PT_INTPAIRLIST || property->GetType() == PT_UINTPAIRLIST)); - result.reserve(il.GetSize()); - for (unsigned int i = 0; i < il.GetSize(); ++i) - { - result.emplace_back(il.GetPair(i)); - } - } + std::vector> result; - return result; + auto property = GetProperty(pname); + if (property) { + IntList il( + property->GetValue(), property->GetType() == PT_UINTLIST, + (property->GetType() == PT_INTPAIRLIST || property->GetType() == PT_UINTPAIRLIST)); + result.reserve(il.GetSize()); + for (unsigned int i = 0; i < il.GetSize(); ++i) { result.emplace_back(il.GetPair(i)); } + } + + return result; } -wxString ObjectBase::GetChildFromParentProperty( const wxString& parentName, const wxString& childName ) +wxString ObjectBase::GetChildFromParentProperty(const wxString& parentName, const wxString& childName) { - PProperty property = GetProperty( parentName ); - if (property) - return property->GetChildFromParent( childName ); - else - return wxEmptyString; + PProperty property = GetProperty(parentName); + if (property) + return property->GetChildFromParent(childName); + else + return wxEmptyString; } /////////////////////////////////////////////////////////////////////////////// -ObjectInfo::ObjectInfo(wxString class_name, PObjectType type, WPObjectPackage package, bool startGroup ) +ObjectInfo::ObjectInfo(wxString class_name, PObjectType type, WPObjectPackage package, bool startGroup) { - m_class = class_name; - m_type = type; - m_numIns = 0; - m_component = NULL; - m_package = package; - m_category = PPropertyCategory( new PropertyCategory( m_class ) ); - m_startGroup = startGroup; + m_class = class_name; + m_type = type; + m_numIns = 0; + m_component = NULL; + m_package = package; + m_category = PPropertyCategory(new PropertyCategory(m_class)); + m_startGroup = startGroup; } PObjectPackage ObjectInfo::GetPackage() { - return m_package.lock(); + return m_package.lock(); } PPropertyInfo ObjectInfo::GetPropertyInfo(wxString name) { - PPropertyInfo result; + PPropertyInfo result; - std::map< wxString, PPropertyInfo >::iterator it = m_properties.find(name); - if (it != m_properties.end()) - result = it->second; + std::map::iterator it = m_properties.find(name); + if (it != m_properties.end()) + result = it->second; - return result; + return result; } PPropertyInfo ObjectInfo::GetPropertyInfo(unsigned int idx) { - PPropertyInfo result; + PPropertyInfo result; - assert (idx < m_properties.size()); + assert(idx < m_properties.size()); - std::map< wxString, PPropertyInfo >::iterator it = m_properties.begin(); - unsigned int i = 0; - while (i < idx && it != m_properties.end()) - { - i++; - it++; - } + std::map::iterator it = m_properties.begin(); + unsigned int i = 0; + while (i < idx && it != m_properties.end()) { + i++; + it++; + } - if (it != m_properties.end()) - result = it->second; + if (it != m_properties.end()) + result = it->second; - return result; + return result; } PEventInfo ObjectInfo::GetEventInfo(wxString name) { - PEventInfo result; + PEventInfo result; - EventInfoMap::iterator it = m_events.find(name); - if (it != m_events.end()) - result = it->second; + EventInfoMap::iterator it = m_events.find(name); + if (it != m_events.end()) + result = it->second; - return result; + return result; } PEventInfo ObjectInfo::GetEventInfo(unsigned int idx) { - PEventInfo result; + PEventInfo result; - assert (idx < m_events.size()); + assert(idx < m_events.size()); - EventInfoMap::iterator it = m_events.begin(); - unsigned int i = 0; - while (i < idx && it != m_events.end()) - { - i++; - it++; - } + EventInfoMap::iterator it = m_events.begin(); + unsigned int i = 0; + while (i < idx && it != m_events.end()) { + i++; + it++; + } - if (it != m_events.end()) - result = it->second; + if (it != m_events.end()) + result = it->second; - return result; + return result; } -void ObjectInfo::AddPropertyInfo( PPropertyInfo prop ) +void ObjectInfo::AddPropertyInfo(PPropertyInfo prop) { - m_properties.insert( PropertyInfoMap::value_type(prop->GetName(), prop) ); + m_properties.insert(PropertyInfoMap::value_type(prop->GetName(), prop)); } void ObjectInfo::AddEventInfo(PEventInfo evtInfo) { - m_events.insert( EventInfoMap::value_type(evtInfo->GetName(), evtInfo) ); + m_events.insert(EventInfoMap::value_type(evtInfo->GetName(), evtInfo)); } -void ObjectInfo::AddBaseClassDefaultPropertyValue( size_t baseIndex, const wxString& propertyName, const wxString& defaultValue ) +void ObjectInfo::AddBaseClassDefaultPropertyValue( + size_t baseIndex, const wxString& propertyName, const wxString& defaultValue) { - std::map< size_t, std::map< wxString, wxString > >::iterator baseClassMap = m_baseClassDefaultPropertyValues.find( baseIndex ); - if ( baseClassMap != m_baseClassDefaultPropertyValues.end() ) - { - baseClassMap->second.insert( std::map< wxString, wxString >::value_type( propertyName, defaultValue ) ); - } - else - { - std::map< wxString, wxString > propertyDefaultValues; - propertyDefaultValues[ propertyName ] = defaultValue; - m_baseClassDefaultPropertyValues[ baseIndex ] = propertyDefaultValues; - } + std::map>::iterator baseClassMap = + m_baseClassDefaultPropertyValues.find(baseIndex); + if (baseClassMap != m_baseClassDefaultPropertyValues.end()) { + baseClassMap->second.insert(std::map::value_type(propertyName, defaultValue)); + } else { + std::map propertyDefaultValues; + propertyDefaultValues[propertyName] = defaultValue; + m_baseClassDefaultPropertyValues[baseIndex] = propertyDefaultValues; + } } -wxString ObjectInfo::GetBaseClassDefaultPropertyValue( size_t baseIndex, const wxString& propertyName ) +wxString ObjectInfo::GetBaseClassDefaultPropertyValue(size_t baseIndex, const wxString& propertyName) { - std::map< size_t, std::map< wxString, wxString > >::iterator baseClassMap = m_baseClassDefaultPropertyValues.find( baseIndex ); - if ( baseClassMap != m_baseClassDefaultPropertyValues.end() ) - { - std::map< wxString, wxString >::iterator defaultValue = baseClassMap->second.find( propertyName ); - if ( defaultValue != baseClassMap->second.end() ) - { - return defaultValue->second; - } - } - return wxString(); + std::map>::iterator baseClassMap = + m_baseClassDefaultPropertyValues.find(baseIndex); + if (baseClassMap != m_baseClassDefaultPropertyValues.end()) { + std::map::iterator defaultValue = baseClassMap->second.find(propertyName); + if (defaultValue != baseClassMap->second.end()) { + return defaultValue->second; + } + } + return wxString(); } PObjectInfo ObjectInfo::GetBaseClass(unsigned int idx, bool inherited) { - if( inherited ) - { - std::vector classes; - GetBaseClasses( classes ); + if (inherited) { + std::vector classes; + GetBaseClasses(classes); - assert (idx < classes.size()); - return classes[idx]; - } - else - { - assert (idx < m_base.size()); - return m_base[idx]; - } + assert(idx < classes.size()); + return classes[idx]; + } else { + assert(idx < m_base.size()); + return m_base[idx]; + } } unsigned int ObjectInfo::GetBaseClassCount(bool inherited) { - if( inherited ) - { - std::vector classes; - GetBaseClasses( classes ); + if (inherited) { + std::vector classes; + GetBaseClasses(classes); - return (unsigned int)classes.size(); - } - else - return (unsigned int)m_base.size(); + return (unsigned int)classes.size(); + } else + return (unsigned int)m_base.size(); } -void ObjectInfo::GetBaseClasses(std::vector &classes, bool inherited) +void ObjectInfo::GetBaseClasses(std::vector& classes, bool inherited) { - for ( std::vector::iterator it = m_base.begin(); it != m_base.end(); ++it ) - { - PObjectInfo base_info = *it;; - classes.push_back( base_info ); + for (std::vector::iterator it = m_base.begin(); it != m_base.end(); ++it) { + PObjectInfo base_info = *it; + ; + classes.push_back(base_info); - if( inherited ) base_info->GetBaseClasses( classes ); - } + if (inherited) + base_info->GetBaseClasses(classes); + } } bool ObjectInfo::IsSubclassOf(wxString classname) { - bool found = false; + bool found = false; - if (GetClassName() == classname) - { - found = true; - } - else - { - for (unsigned int i=0; !found && i < GetBaseClassCount() ; i++) - { - PObjectInfo base = GetBaseClass(i); - found = base->IsSubclassOf(classname); - } - } - return found; + if (GetClassName() == classname) { + found = true; + } else { + for (unsigned int i = 0; !found && i < GetBaseClassCount(); i++) { + PObjectInfo base = GetBaseClass(i); + found = base->IsSubclassOf(classname); + } + } + return found; } // -//void ObjectInfo::PrintOut(ostream &s, int indent) +// void ObjectInfo::PrintOut(ostream &s, int indent) //{ // wxString ind_str = ""; // for (int i=0;i::iterator templates = m_codeTemp.find( lang ); - if ( templates == m_codeTemp.end() ) - { - // First code info is a clean copy - m_codeTemp[ lang ] = PCodeInfo( new CodeInfo( *codeinfo ) ); - } - else - { - // If code info already existed for the language, merge code info - templates->second->Merge( codeinfo ); - } + std::map::iterator templates = m_codeTemp.find(lang); + if (templates == m_codeTemp.end()) { + // First code info is a clean copy + m_codeTemp[lang] = PCodeInfo(new CodeInfo(*codeinfo)); + } else { + // If code info already existed for the language, merge code info + templates->second->Merge(codeinfo); + } } PCodeInfo ObjectInfo::GetCodeInfo(wxString lang) { - PCodeInfo result; - std::map< wxString, PCodeInfo >::iterator it = m_codeTemp.find(lang); - if (it != m_codeTemp.end()) - result = it->second; + PCodeInfo result; + std::map::iterator it = m_codeTemp.find(lang); + if (it != m_codeTemp.end()) + result = it->second; - return result; + return result; } -//ostream& operator << (ostream &s, PObjectInfo obj) +// ostream& operator << (ostream &s, PObjectInfo obj) //{ -// obj->PrintOut(s,0); -// return s; -//} +// obj->PrintOut(s,0); +// return s; +// } /////////////////////////////////////////////////////////////////////////////// wxString CodeInfo::GetTemplate(wxString name) { - wxString result; + wxString result; - TemplateMap::iterator it = m_templates.find(name); - if (it != m_templates.end()) - result = it->second; + TemplateMap::iterator it = m_templates.find(name); + if (it != m_templates.end()) + result = it->second; - return result; + return result; } void CodeInfo::AddTemplate(wxString name, wxString _template) { - m_templates.insert(TemplateMap::value_type(name,_template)); + m_templates.insert(TemplateMap::value_type(name, _template)); } -void CodeInfo::Merge( PCodeInfo merger ) +void CodeInfo::Merge(PCodeInfo merger) { - TemplateMap::iterator mergerTemplate; - for ( mergerTemplate = merger->m_templates.begin(); mergerTemplate != merger->m_templates.end(); ++mergerTemplate ) - { - std::pair< TemplateMap::iterator, bool > mine = m_templates.insert( TemplateMap::value_type( mergerTemplate->first, mergerTemplate->second ) ); - if ( !mine.second ) - { - mine.first->second += mergerTemplate->second; - } - } + TemplateMap::iterator mergerTemplate; + for (mergerTemplate = merger->m_templates.begin(); mergerTemplate != merger->m_templates.end(); ++mergerTemplate) { + std::pair mine = + m_templates.insert(TemplateMap::value_type(mergerTemplate->first, mergerTemplate->second)); + if (!mine.second) { + mine.first->second += mergerTemplate->second; + } + } } diff --git a/src/model/objectbase.h b/src/model/objectbase.h index 12d7aea18..8bdbc1f6d 100644 --- a/src/model/objectbase.h +++ b/src/model/objectbase.h @@ -33,34 +33,23 @@ #ifndef MODEL_OBJECTBASE_H #define MODEL_OBJECTBASE_H -#include "utils/wxfbdefs.h" -#include "model/types.h" +#include #include -#include -/////////////////////////////////////////////////////////////////////////////// +#include "model/types.h" +#include "utils/wxfbdefs.h" + class OptionList { private: - - std::map< wxString, wxString > m_options; + std::map m_options; public: - - void AddOption( wxString option, wxString description = wxString() ) - { - m_options[option] = description; - } - unsigned int GetOptionCount() - { - return (unsigned int)m_options.size(); - } - const std::map< wxString, wxString >& GetOptions() - { - return m_options; - } + void AddOption(wxString option, wxString description = wxString()) { m_options[option] = description; } + unsigned int GetOptionCount() { return (unsigned int)m_options.size(); } + const std::map& GetOptions() { return m_options; } }; /////////////////////////////////////////////////////////////////////////////// @@ -72,61 +61,58 @@ Data Container for children of a Parent property class PropertyChild { public: - wxString m_name; - wxString m_defaultValue; - wxString m_description; - PropertyType m_type; + wxString m_name; + wxString m_defaultValue; + wxString m_description; + PropertyType m_type; }; /////////////////////////////////////////////////////////////////////////////// class PropertyInfo { - friend class Property; + friend class Property; private: - wxString m_name; - PropertyType m_type; - wxString m_def_value; - POptionList m_opt_list; - std::list< PropertyChild > m_children; // Only used for parent properties - wxString m_description; - wxString m_customEditor; // an optional custom editor for the property grid + wxString m_name; + PropertyType m_type; + wxString m_def_value; + POptionList m_opt_list; + std::list m_children; // Only used for parent properties + wxString m_description; + wxString m_customEditor; // an optional custom editor for the property grid public: - - PropertyInfo(wxString name, PropertyType type, wxString def_value, wxString description, wxString customEditor, - POptionList opt_list, const std::list< PropertyChild >& children ); - - ~PropertyInfo(); - - wxString GetDefaultValue() { return m_def_value; } - PropertyType GetType() { return m_type; } - wxString GetName() { return m_name; } - POptionList GetOptionList () { return m_opt_list; } - std::list< PropertyChild >* GetChildren(){ return &m_children; } - wxString GetDescription () { return m_description;} - wxString GetCustomEditor() { return m_customEditor; } + PropertyInfo( + wxString name, PropertyType type, wxString def_value, wxString description, wxString customEditor, + POptionList opt_list, const std::list& children); + + ~PropertyInfo(); + + wxString GetDefaultValue() { return m_def_value; } + PropertyType GetType() { return m_type; } + wxString GetName() { return m_name; } + POptionList GetOptionList() { return m_opt_list; } + std::list* GetChildren() { return &m_children; } + wxString GetDescription() { return m_description; } + wxString GetCustomEditor() { return m_customEditor; } }; class EventInfo { private: - wxString m_name; - wxString m_eventClass; - wxString m_defaultValue; - wxString m_description; + wxString m_name; + wxString m_eventClass; + wxString m_defaultValue; + wxString m_description; public: - EventInfo(const wxString &name, - const wxString &eventClass, - const wxString &defValue, - const wxString &description); - - wxString GetName() { return m_name; } - wxString GetEventClassName() { return m_eventClass; } - wxString GetDefaultValue() { return m_defaultValue; } - wxString GetDescription() { return m_description; } + EventInfo(const wxString& name, const wxString& eventClass, const wxString& defValue, const wxString& description); + + wxString GetName() { return m_name; } + wxString GetEventClassName() { return m_eventClass; } + wxString GetDefaultValue() { return m_defaultValue; } + wxString GetDescription() { return m_description; } }; /////////////////////////////////////////////////////////////////////////////// @@ -134,569 +120,546 @@ class EventInfo class Property { private: - PPropertyInfo m_info; // pointer to its descriptor - WPObjectBase m_object; // pointer to the owner object + PPropertyInfo m_info; // pointer to its descriptor + WPObjectBase m_object; // pointer to the owner object - wxString m_value; + wxString m_value; public: - Property(PPropertyInfo info, PObjectBase obj = PObjectBase()) - { - m_object = obj; - m_info = info; - } - - PObjectBase GetObject() { return m_object.lock(); } - wxString GetName() { return m_info->GetName(); } - wxString GetValue() { return m_value; } - void SetValue( wxString& val ) { m_value = val; } - void SetValue( const wxChar* val ) { m_value = val; } - - PPropertyInfo GetPropertyInfo() { return m_info; } - PropertyType GetType() { return m_info->GetType(); } - - bool IsDefaultValue(); - bool IsNull(); - void SetDefaultValue(); - void ChangeDefaultValue( const wxString& value ) - { - m_info->m_def_value = value; - } - - //////////////////// - void SetValue(const wxFontContainer &font); - void SetValue(const wxColour &colour); - void SetValue(const wxString &str, bool format = false); - void SetValue(const wxPoint &point); - void SetValue(const wxSize &size); - void SetValue(const int integer); - void SetValue(const double val ); - - wxFontContainer GetValueAsFont(); - wxColour GetValueAsColour(); - wxPoint GetValueAsPoint(); - wxSize GetValueAsSize(); - int GetValueAsInteger(); - wxString GetValueAsString(); - wxBitmap GetValueAsBitmap(); - wxString GetValueAsText(); // sustituye los ('\n',...) por ("\\n",...) - - wxArrayString GetValueAsArrayString(); - double GetValueAsFloat(); - void SplitParentProperty( std::map< wxString, wxString >* children ); - wxString GetChildFromParent( const wxString& childName ); + Property(PPropertyInfo info, PObjectBase obj = PObjectBase()) + { + m_object = obj; + m_info = info; + } + + PObjectBase GetObject() { return m_object.lock(); } + wxString GetName() { return m_info->GetName(); } + wxString GetValue() { return m_value; } + void SetValue(wxString& val) { m_value = val; } + void SetValue(const wxChar* val) { m_value = val; } + + PPropertyInfo GetPropertyInfo() { return m_info; } + PropertyType GetType() { return m_info->GetType(); } + + bool IsDefaultValue(); + bool IsNull(); + void SetDefaultValue(); + void ChangeDefaultValue(const wxString& value) { m_info->m_def_value = value; } + + //////////////////// + void SetValue(const wxFontContainer& font); + void SetValue(const wxColour& colour); + void SetValue(const wxString& str, bool format = false); + void SetValue(const wxPoint& point); + void SetValue(const wxSize& size); + void SetValue(const int integer); + void SetValue(const double val); + + wxFontContainer GetValueAsFont(); + wxColour GetValueAsColour(); + wxPoint GetValueAsPoint(); + wxSize GetValueAsSize(); + int GetValueAsInteger(); + wxString GetValueAsString(); + wxBitmap GetValueAsBitmap(); + wxString GetValueAsText(); // sustituye los ('\n',...) por ("\\n",...) + + wxArrayString GetValueAsArrayString(); + double GetValueAsFloat(); + void SplitParentProperty(std::map* children); + wxString GetChildFromParent(const wxString& childName); }; class Event { private: - PEventInfo m_info; // pointer to its descriptor - WPObjectBase m_object; // pointer to the owner object - wxString m_value; // handler function name + PEventInfo m_info; // pointer to its descriptor + WPObjectBase m_object; // pointer to the owner object + wxString m_value; // handler function name public: - Event (PEventInfo info, PObjectBase obj) - : m_info(info), m_object(obj) - {} - - void SetValue(const wxString &value) { m_value = value; } - wxString GetValue() { return m_value; } - wxString GetName() { return m_info->GetName(); } - PObjectBase GetObject() { return m_object.lock(); } - PEventInfo GetEventInfo() { return m_info; } + Event(PEventInfo info, PObjectBase obj) : m_info(info), m_object(obj) {} + + void SetValue(const wxString& value) { m_value = value; } + wxString GetValue() { return m_value; } + wxString GetName() { return m_info->GetName(); } + PObjectBase GetObject() { return m_object.lock(); } + PEventInfo GetEventInfo() { return m_info; } }; class PropertyCategory { private: - wxString m_name; - std::vector< wxString > m_properties; - std::vector< wxString > m_events; - std::vector< PPropertyCategory > m_categories; + wxString m_name; + std::vector m_properties; + std::vector m_events; + std::vector m_categories; public: - - PropertyCategory( wxString name ) : m_name( name ){} - void AddProperty( wxString name ){ m_properties.push_back( name ); } - void AddEvent( wxString name ){ m_events.push_back( name ); } - void AddCategory( PPropertyCategory category ){ m_categories.push_back( category ); } - wxString GetName(){ return m_name; } - wxString GetPropertyName( size_t index ) - { - if ( index < m_properties.size() ) - { - return m_properties[ index ]; - } - else - { - return wxEmptyString; - } - } - - wxString GetEventName( size_t index ) - { - if ( index < m_events.size() ) - { - return m_events[ index ]; - } - else - { - return wxEmptyString; - } - } - - PPropertyCategory GetCategory( size_t index ) - { - if ( index < m_categories.size() ) - { - return m_categories[ index ]; - } - else - { - return PPropertyCategory(); - } - } - - size_t GetPropertyCount() { return m_properties.size(); } - size_t GetEventCount() { return m_events.size(); } - size_t GetCategoryCount() { return m_categories.size(); } + PropertyCategory(wxString name) : m_name(name) {} + void AddProperty(wxString name) { m_properties.push_back(name); } + void AddEvent(wxString name) { m_events.push_back(name); } + void AddCategory(PPropertyCategory category) { m_categories.push_back(category); } + wxString GetName() { return m_name; } + wxString GetPropertyName(size_t index) + { + if (index < m_properties.size()) { + return m_properties[index]; + } else { + return wxEmptyString; + } + } + + wxString GetEventName(size_t index) + { + if (index < m_events.size()) { + return m_events[index]; + } else { + return wxEmptyString; + } + } + + PPropertyCategory GetCategory(size_t index) + { + if (index < m_categories.size()) { + return m_categories[index]; + } else { + return PPropertyCategory(); + } + } + + size_t GetPropertyCount() { return m_properties.size(); } + size_t GetEventCount() { return m_events.size(); } + size_t GetCategoryCount() { return m_categories.size(); } }; /////////////////////////////////////////////////////////////////////////////// namespace ticpp { - class Document; - class Element; -} +class Document; +class Element; +} // namespace ticpp class ObjectBase : public IObject, public std::enable_shared_from_this { - friend class wxFBDataObject; + friend class wxFBDataObject; + private: - wxString m_class; // class name - wxString m_type; // type of object - WPObjectBase m_parent; // weak pointer, no reference loops please! + wxString m_class; // class name + wxString m_type; // type of object + WPObjectBase m_parent; // weak pointer, no reference loops please! - ObjectBaseVector m_children; - PropertyMap m_properties; - EventMap m_events; - PObjectInfo m_info; - bool m_expanded; // is expanded in the object tree, allows for saving to file + ObjectBaseVector m_children; + PropertyMap m_properties; + EventMap m_events; + PObjectInfo m_info; + bool m_expanded; // is expanded in the object tree, allows for saving to file protected: - // utilities for implementing the tree - static const int INDENT; // size of indent - wxString GetIndentString(int indent); // obtiene la cadena con el indentado + // utilities for implementing the tree + static const int INDENT; // size of indent + wxString GetIndentString(int indent); // obtiene la cadena con el indentado - ObjectBaseVector& GetChildren() { return m_children; } - PropertyMap& GetProperties() { return m_properties; } + ObjectBaseVector& GetChildren() { return m_children; } + PropertyMap& GetProperties() { return m_properties; } - // Crea un elemento del objeto - void SerializeObject( ticpp::Element* serializedElement ); + // Crea un elemento del objeto + void SerializeObject(ticpp::Element* serializedElement); - // devuelve el puntero "this" - PObjectBase GetThis() { return shared_from_this(); } + // devuelve el puntero "this" + PObjectBase GetThis() { return shared_from_this(); } public: - - /// Constructor. - ObjectBase (wxString class_name); - - ~ObjectBase() override; - - /** - Sets whether the object is expanded in the object tree or not. - */ - void SetExpanded( bool expanded ){ m_expanded = expanded; } - - /** - Gets whether the object is expanded in the object tree or not. - */ - bool GetExpanded(){ return m_expanded; } - - /** - * Obtiene el nombre del objeto. - * - * @note No confundir con la propiedad nombre que tienen algunos objetos. - * Cada objeto tiene un nombre, el cual será el mismo que el usado - * como clave en el registro de descriptores. - */ - wxString GetClassName() override { - return m_class; - } - - /// Gets the parent object - PObjectBase GetParent () { return m_parent.lock(); } - - PObjectBase GetNonSizerParent (); - - /// Links the object to a parent - void SetParent(PObjectBase parent) { m_parent = parent; } - - /** - * Obtiene la propiedad identificada por el nombre. - * - * @note Notar que no existe el método SetProperty, ya que la modificación - * se hace a través de la referencia. - */ - PProperty GetProperty (wxString name); - - PEvent GetEvent(wxString name); - - /** - * Añade una propiedad al objeto. - * - * Este método será usado por el registro de descriptores para crear la - * instancia del objeto. - * Los objetos siempre se crearán a través del registro de descriptores. - */ - void AddProperty (PProperty value); - - void AddEvent(PEvent event); - - /** - * Obtiene el número de propiedades del objeto. - */ - unsigned int GetPropertyCount() { return (unsigned int)m_properties.size(); } - - unsigned int GetEventCount() { return m_events.size(); } - - /** - * Obtiene una propiedad del objeto. - * @todo esta función deberá lanzar una excepción en caso de no encontrarse - * dicha propiedad, así se simplifica el código al no tener que hacer - * tantas comprobaciones. - * Por ejemplo, el código sin excepciones sería algo así: - * - * @code - * - * PProperty plabel = obj->GetProperty("label"); - * PProperty ppos = obj->GetProperty("pos"); - * PProperty psize = obj->GetProperty("size"); - * PProperty pstyle = obj->GetProperty("style"); - * - * if (plabel && ppos && psize && pstyle) - * { - * wxButton *button = new wxButton(parent,wxID_ANY, - * plabel->GetValueAsString(), - * ppos->GetValueAsPoint(), - * psize->GetValueAsSize(), - * pstyle->GetValueAsInteger()); - * } - * else - * { - * // manejo del error - * } - * - * @endcode - * - * y con excepciones: - * - * @code - * - * try - * { - * wxButton *button = new wxButton(parent,wxID_ANY, - * obj->GetProperty("label")->GetValueAsString(), - * obj->GetProperty("pos")->GetValueAsPoint(), - * obj->GetProperty("size")->GetValueAsSize(), - * obj->GetProperty("style")->GetValueAsInteger()); - * } - * catch (...) - * { - * // manejo del error - * } - * - * @endcode - * - */ - PProperty GetProperty (unsigned int idx); // throws ...; - - PEvent GetEvent (unsigned int idx); // throws ...; - - /** - * Devuelve el primer antecesor cuyo tipo coincida con el que se pasa - * como parámetro. - * - * Será útil para encontrar el widget padre. - */ - PObjectBase FindNearAncestor(wxString type); - PObjectBase FindNearAncestorByBaseClass(wxString type); - PObjectBase FindParentForm(); - - /** - * Obtiene el documento xml del arbol tomando como raíz el nodo actual. - */ - void Serialize( ticpp::Document* serializedDocument ); - - /** - * Añade un hijo al objeto. - * Esta función es virtual, debido a que puede variar el comportamiento - * según el tipo de objeto. - * - * @return true si se añadió el hijo con éxito y false en caso contrario. - */ - virtual bool AddChild (PObjectBase); - virtual bool AddChild (unsigned int idx, PObjectBase obj); - - /** - * Devuelve la posicion del hijo o GetChildCount() en caso de no encontrarlo - */ - unsigned int GetChildPosition(PObjectBase obj); - bool ChangeChildPosition(PObjectBase obj, unsigned int pos); - - /** - * devuelve la posición entre sus hermanos - */ - /* unsigned int GetPosition(); - bool ChangePosition(unsigned int pos);*/ - - - /** - * Elimina un hijo del objeto. - */ - void RemoveChild (PObjectBase obj); - void RemoveChild (unsigned int idx); - void RemoveAllChildren(){ m_children.clear(); } - - /** - * Obtiene un hijo del objeto. - */ - PObjectBase GetChild (unsigned int idx); - - PObjectBase GetChild (unsigned int idx, const wxString& type); - - /** - * Obtiene el número de hijos del objeto. - */ - unsigned int GetChildCount() override { - return (unsigned int)m_children.size(); - } - - /** - * Comprueba si el tipo de objeto pasado es válido como hijo del objeto. - * Esta rutina es importante, ya que define las restricciónes de ubicación. - */ - //bool ChildTypeOk (wxString type); - bool ChildTypeOk (PObjectType type); - - bool IsContainer() { return (GetObjectTypeName() == wxT("container") ); } - - PObjectBase GetLayout(); - - /** - * Devuelve el tipo de objeto. - * - * Deberá ser redefinida en cada clase derivada. - */ - wxString GetObjectTypeName() override { - return m_type; - } - void SetObjectTypeName(wxString type) { m_type = type; } - - /** - * Devuelve el descriptor del objeto. - */ - PObjectInfo GetObjectInfo() { return m_info; } - void SetObjectInfo(PObjectInfo info) { m_info = info; } - - /** - * Devuelve la profundidad del objeto en el arbol. - */ - int Deep(); - - /** - * Imprime el arbol en un stream. - */ - //virtual void PrintOut(ostream &s, int indent); - - /** - * Sobrecarga del operador inserción. - */ - friend std::ostream& operator << (std::ostream &s, PObjectBase obj); - - ///////////////////////// - // Implementación de la interfaz IObject para su uso dentro de los - // plugins - bool IsNull(const wxString& pname) override; - int GetPropertyAsInteger(const wxString& pname) override; - wxFontContainer GetPropertyAsFont(const wxString& pname) override; - wxColour GetPropertyAsColour(const wxString& pname) override; - wxString GetPropertyAsString(const wxString& pname) override; - wxPoint GetPropertyAsPoint(const wxString& pname) override; - wxSize GetPropertyAsSize(const wxString& pname) override; - wxBitmap GetPropertyAsBitmap(const wxString& pname) override; - double GetPropertyAsFloat(const wxString& pname) override; - - wxArrayInt GetPropertyAsArrayInt(const wxString& pname) override; - wxArrayString GetPropertyAsArrayString(const wxString& pname) override; - std::vector> GetPropertyAsVectorIntPair(const wxString& pname) override; - wxString GetChildFromParentProperty(const wxString& parentName, - const wxString& childName) override; - - IObject* GetChildPtr(unsigned int idx) override { - return GetChild(idx).get(); - } + /// Constructor. + ObjectBase(wxString class_name); + + ~ObjectBase() override; + + /** + Sets whether the object is expanded in the object tree or not. + */ + void SetExpanded(bool expanded) { m_expanded = expanded; } + + /** + Gets whether the object is expanded in the object tree or not. + */ + bool GetExpanded() { return m_expanded; } + + /** + * Obtiene el nombre del objeto. + * + * @note No confundir con la propiedad nombre que tienen algunos objetos. + * Cada objeto tiene un nombre, el cual será el mismo que el usado + * como clave en el registro de descriptores. + */ + wxString GetClassName() override { return m_class; } + + /// Gets the parent object + PObjectBase GetParent() { return m_parent.lock(); } + + PObjectBase GetNonSizerParent(); + + /// Links the object to a parent + void SetParent(PObjectBase parent) { m_parent = parent; } + + /** + * Obtiene la propiedad identificada por el nombre. + * + * @note Notar que no existe el método SetProperty, ya que la modificación + * se hace a través de la referencia. + */ + PProperty GetProperty(wxString name); + + PEvent GetEvent(wxString name); + + /** + * Añade una propiedad al objeto. + * + * Este método será usado por el registro de descriptores para crear la + * instancia del objeto. + * Los objetos siempre se crearán a través del registro de descriptores. + */ + void AddProperty(PProperty value); + + void AddEvent(PEvent event); + + /** + * Obtiene el número de propiedades del objeto. + */ + unsigned int GetPropertyCount() { return (unsigned int)m_properties.size(); } + + unsigned int GetEventCount() { return m_events.size(); } + + /** + * Obtiene una propiedad del objeto. + * @todo esta función deberá lanzar una excepción en caso de no encontrarse + * dicha propiedad, así se simplifica el código al no tener que hacer + * tantas comprobaciones. + * Por ejemplo, el código sin excepciones sería algo así: + * + * @code + * + * PProperty plabel = obj->GetProperty("label"); + * PProperty ppos = obj->GetProperty("pos"); + * PProperty psize = obj->GetProperty("size"); + * PProperty pstyle = obj->GetProperty("style"); + * + * if (plabel && ppos && psize && pstyle) + * { + * wxButton *button = new wxButton(parent,wxID_ANY, + * plabel->GetValueAsString(), + * ppos->GetValueAsPoint(), + * psize->GetValueAsSize(), + * pstyle->GetValueAsInteger()); + * } + * else + * { + * // manejo del error + * } + * + * @endcode + * + * y con excepciones: + * + * @code + * + * try + * { + * wxButton *button = new wxButton(parent,wxID_ANY, + * obj->GetProperty("label")->GetValueAsString(), + * obj->GetProperty("pos")->GetValueAsPoint(), + * obj->GetProperty("size")->GetValueAsSize(), + * obj->GetProperty("style")->GetValueAsInteger()); + * } + * catch (...) + * { + * // manejo del error + * } + * + * @endcode + * + */ + PProperty GetProperty(unsigned int idx); // throws ...; + + PEvent GetEvent(unsigned int idx); // throws ...; + + /** + * Devuelve el primer antecesor cuyo tipo coincida con el que se pasa + * como parámetro. + * + * Será útil para encontrar el widget padre. + */ + PObjectBase FindNearAncestor(wxString type); + PObjectBase FindNearAncestorByBaseClass(wxString type); + PObjectBase FindParentForm(); + + /** + * Obtiene el documento xml del arbol tomando como raíz el nodo actual. + */ + void Serialize(ticpp::Document* serializedDocument); + + /** + * Añade un hijo al objeto. + * Esta función es virtual, debido a que puede variar el comportamiento + * según el tipo de objeto. + * + * @return true si se añadió el hijo con éxito y false en caso contrario. + */ + virtual bool AddChild(PObjectBase); + virtual bool AddChild(unsigned int idx, PObjectBase obj); + + /** + * Devuelve la posicion del hijo o GetChildCount() en caso de no encontrarlo + */ + unsigned int GetChildPosition(PObjectBase obj); + bool ChangeChildPosition(PObjectBase obj, unsigned int pos); + + /** + * devuelve la posición entre sus hermanos + */ + /* unsigned int GetPosition(); + bool ChangePosition(unsigned int pos);*/ + + + /** + * Elimina un hijo del objeto. + */ + void RemoveChild(PObjectBase obj); + void RemoveChild(unsigned int idx); + void RemoveAllChildren() { m_children.clear(); } + + /** + * Obtiene un hijo del objeto. + */ + PObjectBase GetChild(unsigned int idx); + + PObjectBase GetChild(unsigned int idx, const wxString& type); + + /** + * Obtiene el número de hijos del objeto. + */ + unsigned int GetChildCount() override { return (unsigned int)m_children.size(); } + + /** + * Comprueba si el tipo de objeto pasado es válido como hijo del objeto. + * Esta rutina es importante, ya que define las restricciónes de ubicación. + */ + // bool ChildTypeOk (wxString type); + bool ChildTypeOk(PObjectType type); + + bool IsContainer() { return (GetObjectTypeName() == wxT("container")); } + + PObjectBase GetLayout(); + + /** + * Devuelve el tipo de objeto. + * + * Deberá ser redefinida en cada clase derivada. + */ + wxString GetObjectTypeName() override { return m_type; } + void SetObjectTypeName(wxString type) { m_type = type; } + + /** + * Devuelve el descriptor del objeto. + */ + PObjectInfo GetObjectInfo() { return m_info; } + void SetObjectInfo(PObjectInfo info) { m_info = info; } + + /** + * Devuelve la profundidad del objeto en el arbol. + */ + int Deep(); + + /** + * Imprime el arbol en un stream. + */ + // virtual void PrintOut(ostream &s, int indent); + + /** + * Sobrecarga del operador inserción. + */ + friend std::ostream& operator<<(std::ostream& s, PObjectBase obj); + + ///////////////////////// + // Implementación de la interfaz IObject para su uso dentro de los + // plugins + bool IsNull(const wxString& pname) override; + int GetPropertyAsInteger(const wxString& pname) override; + wxFontContainer GetPropertyAsFont(const wxString& pname) override; + wxColour GetPropertyAsColour(const wxString& pname) override; + wxString GetPropertyAsString(const wxString& pname) override; + wxPoint GetPropertyAsPoint(const wxString& pname) override; + wxSize GetPropertyAsSize(const wxString& pname) override; + wxBitmap GetPropertyAsBitmap(const wxString& pname) override; + double GetPropertyAsFloat(const wxString& pname) override; + + wxArrayInt GetPropertyAsArrayInt(const wxString& pname) override; + wxArrayString GetPropertyAsArrayString(const wxString& pname) override; + std::vector> GetPropertyAsVectorIntPair(const wxString& pname) override; + wxString GetChildFromParentProperty(const wxString& parentName, const wxString& childName) override; + + IObject* GetChildPtr(unsigned int idx) override { return GetChild(idx).get(); } }; /////////////////////////////////////////////////////////////////////////////// /** -* Clase que guarda un conjunto de plantillas de código. -*/ + * Clase que guarda un conjunto de plantillas de código. + */ class CodeInfo { private: - typedef std::map TemplateMap; - TemplateMap m_templates; + typedef std::map TemplateMap; + TemplateMap m_templates; + public: - wxString GetTemplate(wxString name); - void AddTemplate(wxString name, wxString _template); - void Merge( PCodeInfo merger ); + wxString GetTemplate(wxString name); + void AddTemplate(wxString name, wxString _template); + void Merge(PCodeInfo merger); }; /////////////////////////////////////////////////////////////////////////////// /** -* Información de objeto o MetaObjeto. -*/ + * Información de objeto o MetaObjeto. + */ class ObjectInfo { public: - /** - * Constructor. - */ - ObjectInfo(wxString class_name, PObjectType type, WPObjectPackage package, bool startGroup = false ); - - virtual ~ObjectInfo() = default; - - PPropertyCategory GetCategory(){ return m_category; } - - unsigned int GetPropertyCount() { return (unsigned int)m_properties.size(); } - unsigned int GetEventCount() { return (unsigned int)m_events.size(); } - - /** - * Obtiene el descriptor de la propiedad. - */ - PPropertyInfo GetPropertyInfo(wxString name); - PPropertyInfo GetPropertyInfo(unsigned int idx); - - PEventInfo GetEventInfo(wxString name); - PEventInfo GetEventInfo(unsigned int idx); - - /** - * Añade un descriptor de propiedad al descriptor de objeto. - */ - void AddPropertyInfo(PPropertyInfo pinfo); - - /** - * Adds a event descriptor. - */ - void AddEventInfo(PEventInfo evtInfo); - - /** - * Add a default value for an inherited property. - * @param baseIndex Index of base class returned from AddBaseClass. - * @param propertyName Property of base class to assign a default value to. - * @param defaultValue Default value of the inherited property. - */ - void AddBaseClassDefaultPropertyValue( size_t baseIndex, const wxString& propertyName, const wxString& defaultValue ); - - /** - * Get a default value for an inherited property. - * @param baseIndex Index of base class in the base class vector - * @param propertName Name of the property to get the default value for - * @return The default value for the property - */ - wxString GetBaseClassDefaultPropertyValue( size_t baseIndex, const wxString& propertyName ); - - /** - * Devuelve el tipo de objeto, será util para que el constructor de objetos - * sepa la clase derivada de ObjectBase que ha de crear a partir del - * descriptor. - */ - wxString GetObjectTypeName() { return m_type->GetName(); } - - PObjectType GetObjectType() { return m_type; } - - wxString GetClassName () { return m_class; } - - /** - * Imprime el descriptor en un stream. - */ - //virtual void PrintOut(ostream &s, int indent); - - - /** - * Sobrecarga del operador inserción. - */ - friend std::ostream& operator << (std::ostream &s, PObjectInfo obj); - - // nos serán utiles para generar el nombre del objeto - unsigned int GetInstanceCount() { return m_numIns; } - void IncrementInstanceCount() { m_numIns++; } - void ResetInstanceCount() { m_numIns = 0; } - - /** - * Añade la información de un objeto al conjunto de clases base. - */ - size_t AddBaseClass(PObjectInfo base) - { - m_base.push_back(base); - return m_base.size() - 1; - } - - /** - * Comprueba si el tipo es derivado del que se pasa como parámetro. - */ - bool IsSubclassOf(wxString classname); - - PObjectInfo GetBaseClass(unsigned int idx, bool inherited = true); - void GetBaseClasses(std::vector &classes, bool inherited = true); - unsigned int GetBaseClassCount(bool inherited = true); - - void SetIconFile(wxBitmap icon) { m_icon = icon; } - wxBitmap GetIconFile() { return m_icon; } - - void SetSmallIconFile(wxBitmap icon) { m_smallIcon = icon; } - wxBitmap GetSmallIconFile() { return m_smallIcon; } - - void AddCodeInfo(wxString lang, PCodeInfo codeinfo); - PCodeInfo GetCodeInfo(wxString lang); - - PObjectPackage GetPackage(); - - bool IsStartOfGroup() { return m_startGroup; } + /** + * Constructor. + */ + ObjectInfo(wxString class_name, PObjectType type, WPObjectPackage package, bool startGroup = false); + + virtual ~ObjectInfo() = default; + + PPropertyCategory GetCategory() { return m_category; } + + unsigned int GetPropertyCount() { return (unsigned int)m_properties.size(); } + unsigned int GetEventCount() { return (unsigned int)m_events.size(); } + + /** + * Obtiene el descriptor de la propiedad. + */ + PPropertyInfo GetPropertyInfo(wxString name); + PPropertyInfo GetPropertyInfo(unsigned int idx); + + PEventInfo GetEventInfo(wxString name); + PEventInfo GetEventInfo(unsigned int idx); + + /** + * Añade un descriptor de propiedad al descriptor de objeto. + */ + void AddPropertyInfo(PPropertyInfo pinfo); + + /** + * Adds a event descriptor. + */ + void AddEventInfo(PEventInfo evtInfo); + + /** + * Add a default value for an inherited property. + * @param baseIndex Index of base class returned from AddBaseClass. + * @param propertyName Property of base class to assign a default value to. + * @param defaultValue Default value of the inherited property. + */ + void AddBaseClassDefaultPropertyValue(size_t baseIndex, const wxString& propertyName, const wxString& defaultValue); + + /** + * Get a default value for an inherited property. + * @param baseIndex Index of base class in the base class vector + * @param propertName Name of the property to get the default value for + * @return The default value for the property + */ + wxString GetBaseClassDefaultPropertyValue(size_t baseIndex, const wxString& propertyName); + + /** + * Devuelve el tipo de objeto, será util para que el constructor de objetos + * sepa la clase derivada de ObjectBase que ha de crear a partir del + * descriptor. + */ + wxString GetObjectTypeName() { return m_type->GetName(); } + + PObjectType GetObjectType() { return m_type; } + + wxString GetClassName() { return m_class; } + + /** + * Imprime el descriptor en un stream. + */ + // virtual void PrintOut(ostream &s, int indent); + + + /** + * Sobrecarga del operador inserción. + */ + friend std::ostream& operator<<(std::ostream& s, PObjectInfo obj); + + // nos serán utiles para generar el nombre del objeto + unsigned int GetInstanceCount() { return m_numIns; } + void IncrementInstanceCount() { m_numIns++; } + void ResetInstanceCount() { m_numIns = 0; } + + /** + * Añade la información de un objeto al conjunto de clases base. + */ + size_t AddBaseClass(PObjectInfo base) + { + m_base.push_back(base); + return m_base.size() - 1; + } + + /** + * Comprueba si el tipo es derivado del que se pasa como parámetro. + */ + bool IsSubclassOf(wxString classname); + + PObjectInfo GetBaseClass(unsigned int idx, bool inherited = true); + void GetBaseClasses(std::vector& classes, bool inherited = true); + unsigned int GetBaseClassCount(bool inherited = true); + + void SetIconFile(wxBitmap icon) { m_icon = icon; } + wxBitmap GetIconFile() { return m_icon; } + + void SetSmallIconFile(wxBitmap icon) { m_smallIcon = icon; } + wxBitmap GetSmallIconFile() { return m_smallIcon; } + + void AddCodeInfo(wxString lang, PCodeInfo codeinfo); + PCodeInfo GetCodeInfo(wxString lang); + + PObjectPackage GetPackage(); + + bool IsStartOfGroup() { return m_startGroup; } - /** - * Le asigna un componente a la clase. - */ - void SetComponent(IComponent *c) { m_component = c; } - IComponent* GetComponent() { return m_component; } + /** + * Le asigna un componente a la clase. + */ + void SetComponent(IComponent* c) { m_component = c; } + IComponent* GetComponent() { return m_component; } private: - wxString m_class; // nombre de la clase (tipo de objeto) + wxString m_class; // nombre de la clase (tipo de objeto) - PObjectType m_type; // tipo del objeto - WPObjectPackage m_package; // Package that the object comes from + PObjectType m_type; // tipo del objeto + WPObjectPackage m_package; // Package that the object comes from - PPropertyCategory m_category; + PPropertyCategory m_category; - wxBitmap m_icon; - wxBitmap m_smallIcon; // The icon for the property grid toolbar - bool m_startGroup; // Place a separator in the palette toolbar just before this widget + wxBitmap m_icon; + wxBitmap m_smallIcon; // The icon for the property grid toolbar + bool m_startGroup; // Place a separator in the palette toolbar just before this widget - std::map< wxString, PCodeInfo > m_codeTemp; // plantillas de codigo K=language_name T=PCodeInfo + std::map m_codeTemp; // plantillas de codigo K=language_name T=PCodeInfo - unsigned int m_numIns; // número de instancias del objeto + unsigned int m_numIns; // número de instancias del objeto - std::map< wxString, PPropertyInfo > m_properties; - std::map< wxString, PEventInfo > m_events; + std::map m_properties; + std::map m_events; - std::vector< PObjectInfo > m_base; // base classes - std::map< size_t, std::map< wxString, wxString > > m_baseClassDefaultPropertyValues; - IComponent* m_component; // componente asociado a la clase los objetos del - // designer + std::vector m_base; // base classes + std::map> m_baseClassDefaultPropertyValues; + IComponent* m_component; // componente asociado a la clase los objetos del + // designer }; -#endif // MODEL_OBJECTBASE_H +#endif // MODEL_OBJECTBASE_H diff --git a/src/model/types.cpp b/src/model/types.cpp index a1aebcec0..2aafb0a99 100644 --- a/src/model/types.cpp +++ b/src/model/types.cpp @@ -25,156 +25,145 @@ #include "types.h" +#include + #include "utils/stringutils.h" -#include ObjectType::ObjectType(wxString name, int id, bool hidden, bool item) { - m_id = id; - m_name = name; - m_hidden = hidden; - m_item = item; + m_id = id; + m_name = name; + m_hidden = hidden; + m_item = item; } void ObjectType::AddChildType(PObjectType type, int max, int aui_max) { - /*assert(max != 0); - assert(aui_max != 0);*/ - m_childTypes.insert(ChildTypeMap::value_type(type,ChildCount(max, aui_max))); + /*assert(max != 0); + assert(aui_max != 0);*/ + m_childTypes.insert(ChildTypeMap::value_type(type, ChildCount(max, aui_max))); } int ObjectType::FindChildType(int type_id, bool aui) { - int max = 0; - ChildTypeMap::iterator it; - for (it = m_childTypes.begin(); it != m_childTypes.end() && max == 0; it++) - { - PObjectType type(it->first); - if (type && type_id == type->GetId()) - { - if( aui ) max = it->second.aui_max; - else - max = it->second.max; - } - } - return max; + int max = 0; + ChildTypeMap::iterator it; + for (it = m_childTypes.begin(); it != m_childTypes.end() && max == 0; it++) { + PObjectType type(it->first); + if (type && type_id == type->GetId()) { + if (aui) + max = it->second.aui_max; + else + max = it->second.max; + } + } + return max; } int ObjectType::FindChildType(PObjectType type, bool aui) { - int type_id = type->GetId(); - return FindChildType(type_id, aui); + int type_id = type->GetId(); + return FindChildType(type_id, aui); } unsigned int ObjectType::GetChildTypeCount() { - return (unsigned int)m_childTypes.size(); + return (unsigned int)m_childTypes.size(); } PObjectType ObjectType::GetChildType(unsigned int idx) { - PObjectType result; + PObjectType result; - assert (idx < GetChildTypeCount()); + assert(idx < GetChildTypeCount()); - unsigned int i = 0; - ChildTypeMap::iterator it = m_childTypes.begin(); + unsigned int i = 0; + ChildTypeMap::iterator it = m_childTypes.begin(); - while (i < idx && it != m_childTypes.end()) - { - i++; - it++; - } + while (i < idx && it != m_childTypes.end()) { + i++; + it++; + } - if (i == idx) - result = PObjectType(it->first); + if (i == idx) + result = PObjectType(it->first); - return result; + return result; } /////////////////////////////////////////////////////////////////////////////// -IntList::IntList(bool absolute_value, bool pair_value) - : m_abs(absolute_value) - , m_pairs(pair_value) +IntList::IntList(bool absolute_value, bool pair_value) : m_abs(absolute_value), m_pairs(pair_value) { } -IntList::IntList(const wxString& value, bool absolute_value, bool pair_value) - : IntList(absolute_value, pair_value) +IntList::IntList(const wxString& value, bool absolute_value, bool pair_value) : IntList(absolute_value, pair_value) { - SetList(value); + SetList(value); } void IntList::Add(int value) { - Add(value, 0); + Add(value, 0); } void IntList::Add(int first, int second) { - if (m_abs) - { - m_ints.emplace_back(std::abs(first), (m_pairs ? std::abs(second) : 0)); - } - else - { - m_ints.emplace_back(first, (m_pairs ? second : 0)); - } + if (m_abs) { + m_ints.emplace_back(std::abs(first), (m_pairs ? std::abs(second) : 0)); + } else { + m_ints.emplace_back(first, (m_pairs ? second : 0)); + } } void IntList::DeleteList() { - m_ints.clear(); + m_ints.clear(); } void IntList::SetList(const wxString& str) { - DeleteList(); - - wxStringTokenizer tkz(str, wxT(",")); - m_ints.reserve(tkz.CountTokens()); - while (tkz.HasMoreTokens()) - { - wxString secondToken; - wxString firstToken = tkz.GetNextToken().BeforeFirst(wxT(':'), &secondToken); - firstToken.Trim(true); - firstToken.Trim(false); - secondToken.Trim(true); - secondToken.Trim(false); - - long first; - long second = 0; - if (firstToken.ToLong(&first) && (!m_pairs || secondToken.empty() || secondToken.ToLong(&second))) - { - Add(static_cast(first), static_cast(second)); - } - } + DeleteList(); + + wxStringTokenizer tkz(str, wxT(",")); + m_ints.reserve(tkz.CountTokens()); + while (tkz.HasMoreTokens()) { + wxString secondToken; + wxString firstToken = tkz.GetNextToken().BeforeFirst(wxT(':'), &secondToken); + firstToken.Trim(true); + firstToken.Trim(false); + secondToken.Trim(true); + secondToken.Trim(false); + + long first; + long second = 0; + if (firstToken.ToLong(&first) && (!m_pairs || secondToken.empty() || secondToken.ToLong(&second))) { + Add(static_cast(first), static_cast(second)); + } + } } wxString IntList::ToString(bool skip_zero_second) { - wxString result; - // Reserve some space to avoid many reallocations, assume one digit numbers - result.reserve(m_pairs ? m_ints.size() * 3 : m_ints.size() * 2); - - for (const auto& entry : m_ints) - { - if (!result.empty()) { - result.append(wxT(",")); - } - - result.append(StringUtils::IntToStr(entry.first)); - if (m_pairs && !(skip_zero_second && entry.second == 0)) - { - result.append(wxT(":")); - result.append(StringUtils::IntToStr(entry.second)); - } - } - - return result; + wxString result; + // Reserve some space to avoid many reallocations, assume one digit numbers + result.reserve(m_pairs ? m_ints.size() * 3 : m_ints.size() * 2); + + for (const auto& entry : m_ints) { + if (!result.empty()) { + result.append(wxT(",")); + } + + result.append(StringUtils::IntToStr(entry.first)); + if (m_pairs && !(skip_zero_second && entry.second == 0)) { + result.append(wxT(":")); + result.append(StringUtils::IntToStr(entry.second)); + } + } + + return result; } diff --git a/src/model/types.h b/src/model/types.h index e6b3481b7..abb6ae5f5 100644 --- a/src/model/types.h +++ b/src/model/types.h @@ -22,20 +22,24 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef MODEL_TYPES_H #define MODEL_TYPES_H +#include + #include #include #include #include -#include + class ObjectType; typedef std::shared_ptr PObjectType; typedef std::weak_ptr WPObjectType; + /** * Representa el tipo de objeto. * @@ -63,103 +67,92 @@ typedef std::weak_ptr WPObjectType; class ObjectType { public: + ObjectType(wxString name, int id, bool hidden = false, bool item = false); + + int GetId() { return m_id; } + wxString GetName() { return m_name; } + // bool IsHidden() { return m_hidden; } + bool IsItem() { return m_item; } + - ObjectType(wxString name, int id, bool hidden = false, bool item = false); - - int GetId() - { - return m_id; - } - wxString GetName() - { - return m_name; - } - //bool IsHidden() { return m_hidden; } - bool IsItem() - { - return m_item; - } - - - /** - * Añade el tipo de objeto a la lista de posibles hijos. - */ - void AddChildType(PObjectType type, int max = -1, int aui_max = -1); - - /** - * Busca si el tipo pasado como parámetros está entre sus posibles - * hijos. - * @return numero máximo de ocurrencias del objeto como hijo. - * -1 = numero ilimitado, 0 = ninguna - */ - int FindChildType(int type_id, bool aui); - int FindChildType(PObjectType type, bool aui); - - unsigned int GetChildTypeCount(); - PObjectType GetChildType(unsigned int idx); + /** + * Añade el tipo de objeto a la lista de posibles hijos. + */ + void AddChildType(PObjectType type, int max = -1, int aui_max = -1); + + /** + * Busca si el tipo pasado como parámetros está entre sus posibles + * hijos. + * @return numero máximo de ocurrencias del objeto como hijo. + * -1 = numero ilimitado, 0 = ninguna + */ + int FindChildType(int type_id, bool aui); + int FindChildType(PObjectType type, bool aui); + + unsigned int GetChildTypeCount(); + PObjectType GetChildType(unsigned int idx); private: - class ChildCount - { - public: - ChildCount(int m, int am) : max(m), aui_max(am) {;} - int max; - int aui_max; - }; - - /** - * Registro con los tipos de los hijos posibles y el número máximo - * de estos. - * @note vamos a usar smart-pointers de tipo "weak" ya que puede haber muchas - * referencias cruzadas. - */ - typedef std::map> ChildTypeMap; - - int m_id; /**< identificador numérico del tipo de objeto */ - wxString m_name; /**< cadena de texto asociado al tipo */ - bool m_hidden; /**< indica si está oculto en el ObjectTree */ - bool m_item; /**< indica si es un "item". Los objetos contenidos en - * en un item, muestran las propiedades de éste junto - * con las propias del objeto. - */ - - ChildTypeMap m_childTypes; /**< registro de posibles hijos */ + class ChildCount + { + public: + ChildCount(int m, int am) : max(m), aui_max(am) { ; } + int max; + int aui_max; + }; + + /** + * Registro con los tipos de los hijos posibles y el número máximo + * de estos. + * @note vamos a usar smart-pointers de tipo "weak" ya que puede haber muchas + * referencias cruzadas. + */ + typedef std::map> ChildTypeMap; + + int m_id; /**< identificador numérico del tipo de objeto */ + wxString m_name; /**< cadena de texto asociado al tipo */ + bool m_hidden; /**< indica si está oculto en el ObjectTree */ + bool m_item; /**< indica si es un "item". Los objetos contenidos en + * en un item, muestran las propiedades de éste junto + * con las propias del objeto. + */ + + ChildTypeMap m_childTypes; /**< registro de posibles hijos */ }; /** * Tipos de propiedades. */ -typedef enum -{ - PT_ERROR, - PT_BOOL, - PT_TEXT, - PT_INT, - PT_UINT, - PT_BITLIST, - PT_INTLIST, - PT_UINTLIST, - PT_INTPAIRLIST, - PT_UINTPAIRLIST, - PT_OPTION, - PT_MACRO, - PT_WXSTRING, - PT_WXPOINT, - PT_WXSIZE, - PT_WXFONT, - PT_WXCOLOUR, - PT_WXPARENT, - PT_WXPARENT_SB, - PT_WXPARENT_CP, - PT_PATH, - PT_FILE, - PT_BITMAP, - PT_STRINGLIST, - PT_FLOAT, - PT_WXSTRING_I18N, - PT_PARENT, - PT_CLASS, - PT_EDIT_OPTION +typedef enum { + PT_ERROR, + PT_BOOL, + PT_TEXT, + PT_INT, + PT_UINT, + PT_BITLIST, + PT_INTLIST, + PT_UINTLIST, + PT_INTPAIRLIST, + PT_UINTPAIRLIST, + PT_OPTION, + PT_MACRO, + PT_WXSTRING, + PT_WXPOINT, + PT_WXSIZE, + PT_WXFONT, + PT_WXCOLOUR, + PT_WXPARENT, + PT_WXPARENT_SB, + PT_WXPARENT_CP, + PT_PATH, + PT_FILE, + PT_BITMAP, + PT_STRINGLIST, + PT_FLOAT, + PT_WXSTRING_I18N, + PT_PARENT, + PT_CLASS, + PT_EDIT_OPTION } PropertyType; /* typedef enum @@ -188,33 +181,24 @@ typedef enum class IntList { private: - std::vector> m_ints; - bool m_abs; - bool m_pairs; + std::vector> m_ints; + bool m_abs; + bool m_pairs; public: - explicit IntList(bool absolute_value = false, bool pair_value = false); - explicit IntList(const wxString& value, bool absolute_value = false, bool pair_value = false); - - unsigned int GetSize() const - { - return static_cast(m_ints.size()); - } - int GetValue(unsigned int idx) const - { - return m_ints[idx].first; - } - std::pair GetPair(unsigned int idx) const - { - return m_ints[idx]; - } - - void Add(int value); - void Add(int first, int second); - void DeleteList(); - void SetList(const wxString& str); - - wxString ToString(bool skip_zero_second = false); + explicit IntList(bool absolute_value = false, bool pair_value = false); + explicit IntList(const wxString& value, bool absolute_value = false, bool pair_value = false); + + unsigned int GetSize() const { return static_cast(m_ints.size()); } + int GetValue(unsigned int idx) const { return m_ints[idx].first; } + std::pair GetPair(unsigned int idx) const { return m_ints[idx]; } + + void Add(int value); + void Add(int first, int second); + void DeleteList(); + void SetList(const wxString& str); + + wxString ToString(bool skip_zero_second = false); }; -#endif // MODEL_TYPES_H +#endif // MODEL_TYPES_H diff --git a/src/model/xrcfilter.cpp b/src/model/xrcfilter.cpp index 004889c1a..c081d90b8 100644 --- a/src/model/xrcfilter.cpp +++ b/src/model/xrcfilter.cpp @@ -25,194 +25,165 @@ #include "xrcfilter.h" +#include "model/objectbase.h" #include "utils/debug.h" #include "utils/typeconv.h" -#include "model/objectbase.h" -PObjectBase XrcLoader::GetProject( ticpp::Document* xrcDoc ) + +PObjectBase XrcLoader::GetProject(ticpp::Document* xrcDoc) { - assert( m_objDb ); - LogDebug( wxT( "[XrcFilter::GetProject]" ) ); + assert(m_objDb); + LogDebug(wxT("[XrcFilter::GetProject]")); - PObjectBase project( m_objDb->CreateObject( "Project" ) ); + PObjectBase project(m_objDb->CreateObject("Project")); - ticpp::Element *root = xrcDoc->FirstChildElement( "resource", false ); - if ( !root ) - { - wxLogError( _( "Missing root element \"resource\"" ) ); - return project; - } + ticpp::Element* root = xrcDoc->FirstChildElement("resource", false); + if (!root) { + wxLogError(_("Missing root element \"resource\"")); + return project; + } - ticpp::Element *element = root->FirstChildElement( "object", false ); - while ( element ) - { - PObjectBase obj = GetObject( element, project ); - element = element->NextSiblingElement( "object", false ); - } + ticpp::Element* element = root->FirstChildElement("object", false); + while (element) { + PObjectBase obj = GetObject(element, project); + element = element->NextSiblingElement("object", false); + } - return project; + return project; } -PObjectBase XrcLoader::GetObject( ticpp::Element *xrcObj, PObjectBase parent ) +PObjectBase XrcLoader::GetObject(ticpp::Element* xrcObj, PObjectBase parent) { - // First, create the object by the name, the modify the properties - - std::string className = xrcObj->GetAttribute( "class" ); - if ( parent->GetObjectTypeName() == wxT( "project" ) ) - { - if ( className == "wxBitmap" ) - { - PProperty bitmapsProp = parent->GetProperty( _( "bitmaps" ) ); - if ( bitmapsProp ) - { - wxString value = bitmapsProp->GetValue(); - wxString text = _WXSTR( xrcObj->GetText() ); - text.Replace( wxT( "\'" ), wxT( "\'\'" ), true ); - value << wxT( "\'" ) << text << wxT( "\' " ); - bitmapsProp->SetValue( value ); - return PObjectBase(); - } - } - if ( className == "wxIcon" ) - { - PProperty iconsProp = parent->GetProperty( _( "icons" ) ); - if ( iconsProp ) - { - wxString value = iconsProp->GetValue(); - wxString text = _WXSTR( xrcObj->GetText() ); - text.Replace( wxT( "\'" ), wxT( "\'\'" ), true ); - value << wxT( "\'" ) << text << wxT( "\' " ); - iconsProp->SetValue( value ); - return PObjectBase(); - } - } - - // Forms wxPanel, wxFrame, wxDialog are stored internally as Panel, Frame, and Dialog - // to prevent conflicts with wxPanel as a container - className = className.substr( 2, className.size() - 2 ); - } - - // Well, this is not nice. wxMenu class name is ambiguous, so we'll get the - // correct class by the context. If the parent of a wxMenu is another wxMenu - // then the class name will be "submenu" - else if ( className == "wxMenu" && ( parent->GetClassName() == wxT( "wxMenu" ) || parent->GetClassName() == wxT( "submenu" ) ) ) - { - className = "submenu"; - } - - // "separator" is also ambiguous - could be a toolbar separator or a menu separator - else if ( className == "separator" ) - { - if ( parent->GetClassName() == wxT( "wxToolBar" ) || parent->GetClassName() == wxT( "ToolBar" ) ) - { - className = "toolSeparator"; - } - } - - // replace "spacer" with "sizeritem" so it will be imported as a "sizeritem" - // "sizeritem" is ambiguous - could also be a grid bag sizeritem - else if ( className == "spacer" || className == "sizeritem" ) - { - if ( parent->GetClassName() == wxT( "wxGridBagSizer" ) ) - { - className = "gbsizeritem"; - } - else - { - className = "sizeritem"; - } - } - - PObjectBase object; - PObjectInfo objInfo = m_objDb->GetObjectInfo( _WXSTR( className ) ); - if ( objInfo ) - { - IComponent *comp = objInfo->GetComponent(); - if ( !comp ) - { - wxLogError( _("No component found for class \"%s\", found on line %i."), _WXSTR( className ), xrcObj->Row() ); - } - else - { - ticpp::Element *fbObj = comp->ImportFromXrc( xrcObj ); - if ( !fbObj ) - { - wxLogError( _("ImportFromXrc returned NULL for class \"%s\", found on line %i."), _WXSTR( className ), xrcObj->Row() ); - } - else - { - object = m_objDb->CreateObject( fbObj, parent ); - if ( !object ) - { - // Unable to create the object and add it to the parent - probably needs a sizer - PObjectBase newsizer = m_objDb->CreateObject( "wxBoxSizer", parent ); - if ( newsizer ) - { - // It is possible the CreateObject returns an "item" containing the object, e.g. SizerItem or SplitterItem - // If that is the case, reassign "object" to the actual object - PObjectBase sizer = newsizer; - if ( sizer->GetChildCount() > 0 ) - { - sizer = sizer->GetChild( 0 ); - } - - if ( sizer ) - { - object = m_objDb->CreateObject( fbObj, sizer ); - if ( object ) - { - parent->AddChild( newsizer ); - newsizer->SetParent( parent ); - } - } - } - } - - if ( !object ) - { - wxLogError( wxT( "CreateObject failed for class \"%s\", with parent \"%s\", found on line %i" ), _WXSTR( className ), parent->GetClassName(), xrcObj->Row() ); - } - else - { - // It is possible the CreateObject returns an "item" containing the object, e.g. SizerItem or SplitterItem - // If that is the case, reassign "object" to the actual object - if ( object && object->GetChildCount() > 0 ) - object = object->GetChild( 0 ); - - if ( object ) - { - // Recursively import the children - ticpp::Element *element = xrcObj->FirstChildElement( "object", false ); - while ( element ) - { - GetObject( element, object ); - element = element->NextSiblingElement( "object", false ); - } - } - } - } - } - } - else - { - // Create a wxPanel to represent unknown classes - object = m_objDb->CreateObject( "wxPanel", parent ); - if ( object ) - { - parent->AddChild( object ); - object->SetParent( parent ); - wxLogError( wxT( "Unknown class \"%s\" found on line %i, replaced with a wxPanel" ), _WXSTR( className ), xrcObj->Row() ); - } - else - { - wxString msg( wxString::Format( - wxT( "Unknown class \"%s\" found on line %i, and could not replace with a wxPanel as child of \"%s:%s\"" ), - _WXSTR( className ), xrcObj->Row(), parent->GetPropertyAsString( wxT( "name" ) ), parent->GetClassName() ) ); - - wxLogError( msg ); - } - } - - return object; + // First, create the object by the name, the modify the properties + + std::string className = xrcObj->GetAttribute("class"); + if (parent->GetObjectTypeName() == wxT("project")) { + if (className == "wxBitmap") { + PProperty bitmapsProp = parent->GetProperty(_("bitmaps")); + if (bitmapsProp) { + wxString value = bitmapsProp->GetValue(); + wxString text = _WXSTR(xrcObj->GetText()); + text.Replace(wxT("\'"), wxT("\'\'"), true); + value << wxT("\'") << text << wxT("\' "); + bitmapsProp->SetValue(value); + return PObjectBase(); + } + } + if (className == "wxIcon") { + PProperty iconsProp = parent->GetProperty(_("icons")); + if (iconsProp) { + wxString value = iconsProp->GetValue(); + wxString text = _WXSTR(xrcObj->GetText()); + text.Replace(wxT("\'"), wxT("\'\'"), true); + value << wxT("\'") << text << wxT("\' "); + iconsProp->SetValue(value); + return PObjectBase(); + } + } + + // Forms wxPanel, wxFrame, wxDialog are stored internally as Panel, Frame, and Dialog + // to prevent conflicts with wxPanel as a container + className = className.substr(2, className.size() - 2); + } + + // Well, this is not nice. wxMenu class name is ambiguous, so we'll get the + // correct class by the context. If the parent of a wxMenu is another wxMenu + // then the class name will be "submenu" + else if ( + className == "wxMenu" && (parent->GetClassName() == wxT("wxMenu") || parent->GetClassName() == wxT("submenu"))) { + className = "submenu"; + } + + // "separator" is also ambiguous - could be a toolbar separator or a menu separator + else if (className == "separator") { + if (parent->GetClassName() == wxT("wxToolBar") || parent->GetClassName() == wxT("ToolBar")) { + className = "toolSeparator"; + } + } + + // replace "spacer" with "sizeritem" so it will be imported as a "sizeritem" + // "sizeritem" is ambiguous - could also be a grid bag sizeritem + else if (className == "spacer" || className == "sizeritem") { + if (parent->GetClassName() == wxT("wxGridBagSizer")) { + className = "gbsizeritem"; + } else { + className = "sizeritem"; + } + } + + PObjectBase object; + PObjectInfo objInfo = m_objDb->GetObjectInfo(_WXSTR(className)); + if (objInfo) { + IComponent* comp = objInfo->GetComponent(); + if (!comp) { + wxLogError(_("No component found for class \"%s\", found on line %i."), _WXSTR(className), xrcObj->Row()); + } else { + ticpp::Element* fbObj = comp->ImportFromXrc(xrcObj); + if (!fbObj) { + wxLogError( + _("ImportFromXrc returned NULL for class \"%s\", found on line %i."), _WXSTR(className), + xrcObj->Row()); + } else { + object = m_objDb->CreateObject(fbObj, parent); + if (!object) { + // Unable to create the object and add it to the parent - probably needs a sizer + PObjectBase newsizer = m_objDb->CreateObject("wxBoxSizer", parent); + if (newsizer) { + // It is possible the CreateObject returns an "item" containing the object, e.g. SizerItem or + // SplitterItem If that is the case, reassign "object" to the actual object + PObjectBase sizer = newsizer; + if (sizer->GetChildCount() > 0) { + sizer = sizer->GetChild(0); + } + + if (sizer) { + object = m_objDb->CreateObject(fbObj, sizer); + if (object) { + parent->AddChild(newsizer); + newsizer->SetParent(parent); + } + } + } + } + + if (!object) { + wxLogError( + wxT("CreateObject failed for class \"%s\", with parent \"%s\", found on line %i"), + _WXSTR(className), parent->GetClassName(), xrcObj->Row()); + } else { + // It is possible the CreateObject returns an "item" containing the object, e.g. SizerItem or + // SplitterItem If that is the case, reassign "object" to the actual object + if (object && object->GetChildCount() > 0) + object = object->GetChild(0); + + if (object) { + // Recursively import the children + ticpp::Element* element = xrcObj->FirstChildElement("object", false); + while (element) { + GetObject(element, object); + element = element->NextSiblingElement("object", false); + } + } + } + } + } + } else { + // Create a wxPanel to represent unknown classes + object = m_objDb->CreateObject("wxPanel", parent); + if (object) { + parent->AddChild(object); + object->SetParent(parent); + wxLogError( + wxT("Unknown class \"%s\" found on line %i, replaced with a wxPanel"), _WXSTR(className), xrcObj->Row()); + } else { + wxString msg(wxString::Format( + wxT("Unknown class \"%s\" found on line %i, and could not replace with a wxPanel as child of \"%s:%s\""), + _WXSTR(className), xrcObj->Row(), parent->GetPropertyAsString(wxT("name")), parent->GetClassName())); + + wxLogError(msg); + } + } + + return object; } diff --git a/src/model/xrcfilter.h b/src/model/xrcfilter.h index 706d98b34..30158f6e4 100644 --- a/src/model/xrcfilter.h +++ b/src/model/xrcfilter.h @@ -26,28 +26,28 @@ #ifndef MODEL_XRCFILTER_H #define MODEL_XRCFILTER_H +#include + #include "model/database.h" -#include /** * Filtro de importación de un fichero XRC. */ class XrcLoader { - private: - PObjectDatabase m_objDb; - - PObjectBase GetObject(ticpp::Element *xrcObj, PObjectBase parent); +private: + PObjectDatabase m_objDb; - public: + PObjectBase GetObject(ticpp::Element* xrcObj, PObjectBase parent); - void SetObjectDatabase(PObjectDatabase db) { m_objDb = db; } +public: + void SetObjectDatabase(PObjectDatabase db) { m_objDb = db; } - /** - * Dado un árbol XML en formato XRC, crea el arbol de objetos asociado. - */ - PObjectBase GetProject(ticpp::Document* xrcDoc); + /** + * Dado un árbol XML en formato XRC, crea el arbol de objetos asociado. + */ + PObjectBase GetProject(ticpp::Document* xrcDoc); }; -#endif // MODEL_XRCFILTER_H +#endif // MODEL_XRCFILTER_H diff --git a/src/rad/about.cpp b/src/rad/about.cpp index b56b5fd37..2678a494a 100644 --- a/src/rad/about.cpp +++ b/src/rad/about.cpp @@ -25,110 +25,111 @@ #include "about.h" -#include "rad/appdata.h" - #include #include +#include "rad/appdata.h" + + #if 0 -#define ID_OK 1000 + #define ID_OK 1000 BEGIN_EVENT_TABLE(AboutDialog,wxDialog) EVT_BUTTON(ID_OK,AboutDialog::OnButtonEvent) END_EVENT_TABLE() #endif + class HtmlWindow : public wxHtmlWindow { - public: - HtmlWindow(wxWindow *parent) : wxHtmlWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, - wxHW_SCROLLBAR_NEVER | wxHW_NO_SELECTION | wxRAISED_BORDER) +public: + HtmlWindow(wxWindow* parent) : + wxHtmlWindow( + parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHW_SCROLLBAR_NEVER | wxHW_NO_SELECTION | wxRAISED_BORDER) { } void LaunchBrowser(const wxString& url) { - wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(wxT("html")); - if (!ft) { - wxLogError(wxT("Impossible to determine the file type for extension html.\nPlease edit your MIME types.")); - return; - } - - wxString cmd; - bool ok = ft->GetOpenCommand(&cmd, wxFileType::MessageParameters(url, wxT(""))); - delete ft; - - if (ok) - wxExecute(cmd, wxEXEC_ASYNC); + wxFileType* ft = wxTheMimeTypesManager->GetFileTypeFromExtension(wxT("html")); + if (!ft) { + wxLogError(wxT("Impossible to determine the file type for extension html.\nPlease edit your MIME types.")); + return; + } + + wxString cmd; + bool ok = ft->GetOpenCommand(&cmd, wxFileType::MessageParameters(url, wxT(""))); + delete ft; + + if (ok) + wxExecute(cmd, wxEXEC_ASYNC); } - void OnLinkClicked(const wxHtmlLinkInfo& link) override { - ::wxLaunchDefaultBrowser(link.GetHref()); - } + void OnLinkClicked(const wxHtmlLinkInfo& link) override { ::wxLaunchDefaultBrowser(link.GetHref()); } }; -AboutDialog::AboutDialog(wxWindow *parent, int id) : wxDialog(parent,id,wxT("About...")) +AboutDialog::AboutDialog(wxWindow* parent, int id) : wxDialog(parent, id, wxT("About...")) { #if 0 - wxBoxSizer *sizer2; - sizer2 = new wxBoxSizer(wxVERTICAL); - m_staticText2 = new wxStaticText(this,wxID_ANY,wxT("wxFormBuilder"),wxDefaultPosition,wxDefaultSize,0); - m_staticText2->SetFont(wxFont(12,74,90,92,false,wxT("Arial"))); - sizer2->Add(m_staticText2, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); - m_staticText3 = new wxStaticText(this,wxID_ANY,wxT("a RAD tool for wxWidgets framework"),wxDefaultPosition,wxDefaultSize,0); - sizer2->Add(m_staticText3, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); - m_staticText6 = new wxStaticText(this,wxID_ANY,wxT("(C) 2005 José Antonio Hurtado"),wxDefaultPosition,wxDefaultSize,0); - sizer2->Add(m_staticText6, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); - window1 = new wxStaticLine(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxLI_HORIZONTAL); - sizer2->Add(window1, 0, wxALL|wxEXPAND, 5); - m_panel1 = new wxPanel(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER|wxTAB_TRAVERSAL); - wxBoxSizer *sizer3; - sizer3 = new wxBoxSizer(wxVERTICAL); - m_staticText8 = new wxStaticText(m_panel1,wxID_ANY,wxT("Developed by:"),wxDefaultPosition,wxDefaultSize,0); - sizer3->Add(m_staticText8, 0, wxALL, 5); - m_staticText9 = new wxStaticText(m_panel1,wxID_ANY,wxT("- José Antonio Hurtado"),wxDefaultPosition,wxDefaultSize,0); - sizer3->Add(m_staticText9, 0, wxALL, 5); - m_staticText10 = new wxStaticText(m_panel1,wxID_ANY,wxT("- Juan Antonio Ortega"),wxDefaultPosition,wxDefaultSize,0); - sizer3->Add(m_staticText10, 0, wxALL, 5); - m_panel1->SetSizer(sizer3); - m_panel1->SetAutoLayout(true); - m_panel1->Layout(); - sizer2->Add(m_panel1, 1, wxALL|wxEXPAND, 5); - window2 = new wxStaticLine(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxLI_HORIZONTAL); - sizer2->Add(window2, 0, wxALL|wxEXPAND, 5); - m_button1 = new wxButton(this,ID_OK,wxT("&OK"),wxDefaultPosition,wxDefaultSize,0); - sizer2->Add(m_button1, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); - this->SetSizer(sizer2); - this->SetAutoLayout(true); - this->Layout(); + wxBoxSizer *sizer2; + sizer2 = new wxBoxSizer(wxVERTICAL); + m_staticText2 = new wxStaticText(this,wxID_ANY,wxT("wxFormBuilder"),wxDefaultPosition,wxDefaultSize,0); + m_staticText2->SetFont(wxFont(12,74,90,92,false,wxT("Arial"))); + sizer2->Add(m_staticText2, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); + m_staticText3 = new wxStaticText(this,wxID_ANY,wxT("a RAD tool for wxWidgets framework"),wxDefaultPosition,wxDefaultSize,0); + sizer2->Add(m_staticText3, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); + m_staticText6 = new wxStaticText(this,wxID_ANY,wxT("(C) 2005 José Antonio Hurtado"),wxDefaultPosition,wxDefaultSize,0); + sizer2->Add(m_staticText6, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); + window1 = new wxStaticLine(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxLI_HORIZONTAL); + sizer2->Add(window1, 0, wxALL|wxEXPAND, 5); + m_panel1 = new wxPanel(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER|wxTAB_TRAVERSAL); + wxBoxSizer *sizer3; + sizer3 = new wxBoxSizer(wxVERTICAL); + m_staticText8 = new wxStaticText(m_panel1,wxID_ANY,wxT("Developed by:"),wxDefaultPosition,wxDefaultSize,0); + sizer3->Add(m_staticText8, 0, wxALL, 5); + m_staticText9 = new wxStaticText(m_panel1,wxID_ANY,wxT("- José Antonio Hurtado"),wxDefaultPosition,wxDefaultSize,0); + sizer3->Add(m_staticText9, 0, wxALL, 5); + m_staticText10 = new wxStaticText(m_panel1,wxID_ANY,wxT("- Juan Antonio Ortega"),wxDefaultPosition,wxDefaultSize,0); + sizer3->Add(m_staticText10, 0, wxALL, 5); + m_panel1->SetSizer(sizer3); + m_panel1->SetAutoLayout(true); + m_panel1->Layout(); + sizer2->Add(m_panel1, 1, wxALL|wxEXPAND, 5); + window2 = new wxStaticLine(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxLI_HORIZONTAL); + sizer2->Add(window2, 0, wxALL|wxEXPAND, 5); + m_button1 = new wxButton(this,ID_OK,wxT("&OK"),wxDefaultPosition,wxDefaultSize,0); + sizer2->Add(m_button1, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); + this->SetSizer(sizer2); + this->SetAutoLayout(true); + this->Layout(); #endif - wxBoxSizer *mainSizer = new wxBoxSizer(wxVERTICAL); - wxHtmlWindow *htmlWin = new HtmlWindow(this); + wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL); + wxHtmlWindow* htmlWin = new HtmlWindow(this); - // I don't know where is the problem, but if you call SetBorders(b) with - // 'b' between 0..6 it works, but if you use a bigger border, it doesn't fit - // correctly. - htmlWin->SetBorders(5); + // I don't know where is the problem, but if you call SetBorders(b) with + // 'b' between 0..6 it works, but if you use a bigger border, it doesn't fit + // correctly. + htmlWin->SetBorders(5); - htmlWin->LoadFile(wxFileName(AppData()->GetApplicationPath() + wxFILE_SEP_PATH + wxT("resources/about.html"))); + htmlWin->LoadFile(wxFileName(AppData()->GetApplicationPath() + wxFILE_SEP_PATH + wxT("resources/about.html"))); #ifdef __WXMAC__ - // work around a wxMac bug - htmlWin->SetSize(450, 650); + // work around a wxMac bug + htmlWin->SetSize(450, 650); #else - htmlWin->SetMinSize(wxSize(450, 650)); + htmlWin->SetMinSize(wxSize(450, 650)); #endif - mainSizer->Add(htmlWin, 1, wxEXPAND | wxALL, 5); - mainSizer->Add(new wxButton(this, wxID_OK, wxT("OK")), 0, wxALIGN_CENTER | wxBOTTOM, 5); + mainSizer->Add(htmlWin, 1, wxEXPAND | wxALL, 5); + mainSizer->Add(new wxButton(this, wxID_OK, wxT("OK")), 0, wxALIGN_CENTER | wxBOTTOM, 5); - SetSizerAndFit(mainSizer); - Center(); + SetSizerAndFit(mainSizer); + Center(); } -void AboutDialog::OnButtonEvent (wxCommandEvent &) +void AboutDialog::OnButtonEvent(wxCommandEvent&) { - Close(); + Close(); } diff --git a/src/rad/about.h b/src/rad/about.h index 85640dcd2..d92169e87 100644 --- a/src/rad/about.h +++ b/src/rad/about.h @@ -26,25 +26,27 @@ #ifndef RAD_ABOUT_H #define RAD_ABOUT_H -#include #include +#include + -class AboutDialog : public wxDialog { +class AboutDialog : public wxDialog +{ public: - AboutDialog(wxWindow* parent, int id = wxID_ANY); - void OnButtonEvent(wxCommandEvent&); + AboutDialog(wxWindow* parent, int id = wxID_ANY); + void OnButtonEvent(wxCommandEvent&); protected: - wxStaticText* m_staticText2; - wxStaticText* m_staticText3; - wxStaticText* m_staticText6; - wxStaticLine* window1; - wxPanel* m_panel1; - wxStaticText* m_staticText8; - wxStaticText* m_staticText9; - wxStaticText* m_staticText10; - wxStaticLine* window2; - wxButton* m_button1; + wxStaticText* m_staticText2; + wxStaticText* m_staticText3; + wxStaticText* m_staticText6; + wxStaticLine* window1; + wxPanel* m_panel1; + wxStaticText* m_staticText8; + wxStaticText* m_staticText9; + wxStaticText* m_staticText10; + wxStaticLine* window2; + wxButton* m_button1; }; -#endif // RAD_ABOUT_H +#endif // RAD_ABOUT_H diff --git a/src/rad/appdata.cpp b/src/rad/appdata.cpp index 17f0e277b..9b8fb6bd5 100644 --- a/src/rad/appdata.cpp +++ b/src/rad/appdata.cpp @@ -25,9 +25,14 @@ #include "appdata.h" -#include "rad/bitmaps.h" -#include "rad/wxfbevent.h" -#include "rad/wxfbmanager.h" +#include +#include +#include +#include +#include +#include +#include +#include #include "codegen/codewriter.h" #include "codegen/cppcg.h" @@ -35,22 +40,16 @@ #include "codegen/phpcg.h" #include "codegen/pythoncg.h" #include "model/objectbase.h" +#include "rad/bitmaps.h" +#include "rad/dataobject/dataobject.h" +#include "rad/wxfbevent.h" +#include "rad/wxfbmanager.h" +#include "rad/xrcpreview/xrcpreview.h" #include "utils/stringutils.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" #include "utils/wxfbipc.h" -#include "rad/dataobject/dataobject.h" -#include "rad/xrcpreview/xrcpreview.h" -#include - -#include -#include -#include -#include -#include -#include -#include using namespace TypeConv; @@ -64,373 +63,364 @@ using namespace TypeConv; class ExpandObjectCmd : public Command { - private: - PObjectBase m_object; - bool m_expand; +private: + PObjectBase m_object; + bool m_expand; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - ExpandObjectCmd( PObjectBase object, bool expand ); +public: + ExpandObjectCmd(PObjectBase object, bool expand); }; /** -* Comando para insertar un objeto en el árbol. -*/ + * Comando para insertar un objeto en el árbol. + */ class InsertObjectCmd : public Command { - private: - ApplicationData *m_data; - PObjectBase m_parent; - PObjectBase m_object; - int m_pos; - PObjectBase m_oldSelected; +private: + ApplicationData* m_data; + PObjectBase m_parent; + PObjectBase m_object; + int m_pos; + PObjectBase m_oldSelected; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - InsertObjectCmd( ApplicationData *data, PObjectBase object, PObjectBase parent, int pos = -1 ); +public: + InsertObjectCmd(ApplicationData* data, PObjectBase object, PObjectBase parent, int pos = -1); }; /** -* Comando para borrar un objeto. -*/ + * Comando para borrar un objeto. + */ class RemoveObjectCmd : public Command { - private: - ApplicationData *m_data; - PObjectBase m_parent; - PObjectBase m_object; - int m_oldPos; - PObjectBase m_oldSelected; +private: + ApplicationData* m_data; + PObjectBase m_parent; + PObjectBase m_object; + int m_oldPos; + PObjectBase m_oldSelected; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - RemoveObjectCmd( ApplicationData *data, PObjectBase object ); +public: + RemoveObjectCmd(ApplicationData* data, PObjectBase object); }; /** -* Comando para modificar una propiedad. -*/ + * Comando para modificar una propiedad. + */ class ModifyPropertyCmd : public Command { - private: - PProperty m_property; - wxString m_oldValue, m_newValue; +private: + PProperty m_property; + wxString m_oldValue, m_newValue; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - ModifyPropertyCmd( PProperty prop, wxString value ); +public: + ModifyPropertyCmd(PProperty prop, wxString value); }; /** -* Command for modifying an event -*/ + * Command for modifying an event + */ class ModifyEventHandlerCmd : public Command { - private: - PEvent m_event; - wxString m_oldValue, m_newValue; +private: + PEvent m_event; + wxString m_oldValue, m_newValue; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - ModifyEventHandlerCmd( PEvent event, wxString value ); +public: + ModifyEventHandlerCmd(PEvent event, wxString value); }; /** -* Comando para mover de posición un objeto. -*/ + * Comando para mover de posición un objeto. + */ class ShiftChildCmd : public Command { - private: - PObjectBase m_object; - int m_oldPos, m_newPos; - - protected: - void DoExecute() override; - void DoRestore() override; +private: + PObjectBase m_object; + int m_oldPos, m_newPos; - public: - ShiftChildCmd( PObjectBase object, int pos ); +protected: + void DoExecute() override; + void DoRestore() override; +public: + ShiftChildCmd(PObjectBase object, int pos); }; /** -* CutObjectCmd ademas de eliminar el objeto del árbol se asegura -* de eliminar la referencia "clipboard" deshacer el cambio. -*/ + * CutObjectCmd ademas de eliminar el objeto del árbol se asegura + * de eliminar la referencia "clipboard" deshacer el cambio. + */ class CutObjectCmd : public Command { - private: - // necesario para consultar/modificar el objeto "clipboard" - ApplicationData *m_data; - //PObjectBase m_clipboard; - PObjectBase m_parent; - PObjectBase m_object; - int m_oldPos; - PObjectBase m_oldSelected; +private: + // necesario para consultar/modificar el objeto "clipboard" + ApplicationData* m_data; + // PObjectBase m_clipboard; + PObjectBase m_parent; + PObjectBase m_object; + int m_oldPos; + PObjectBase m_oldSelected; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - CutObjectCmd( ApplicationData *data, PObjectBase object ); +public: + CutObjectCmd(ApplicationData* data, PObjectBase object); }; /** -* Cambia el padre. -*/ + * Cambia el padre. + */ class ReparentObjectCmd : public Command { - private: - PObjectBase m_sizeritem; - PObjectBase m_sizer; - PObjectBase m_oldSizer; - int m_oldPosition; +private: + PObjectBase m_sizeritem; + PObjectBase m_sizer; + PObjectBase m_oldSizer; + int m_oldPosition; - protected: - void DoExecute() override; - void DoRestore() override; +protected: + void DoExecute() override; + void DoRestore() override; - public: - ReparentObjectCmd ( PObjectBase sizeritem, PObjectBase sizer ); +public: + ReparentObjectCmd(PObjectBase sizeritem, PObjectBase sizer); }; /////////////////////////////////////////////////////////////////////////////// // Implementación de los Comandos /////////////////////////////////////////////////////////////////////////////// -ExpandObjectCmd::ExpandObjectCmd( PObjectBase object, bool expand ) - : m_object( object ), m_expand( expand ) +ExpandObjectCmd::ExpandObjectCmd(PObjectBase object, bool expand) : m_object(object), m_expand(expand) { } void ExpandObjectCmd::DoExecute() { - m_object->SetExpanded( m_expand ); + m_object->SetExpanded(m_expand); } void ExpandObjectCmd::DoRestore() { - m_object->SetExpanded( !m_expand ); + m_object->SetExpanded(!m_expand); } -InsertObjectCmd::InsertObjectCmd( ApplicationData *data, PObjectBase object, - PObjectBase parent, int pos ) - : m_data( data ), m_parent( parent ), m_object( object ), m_pos( pos ) +InsertObjectCmd::InsertObjectCmd(ApplicationData* data, PObjectBase object, PObjectBase parent, int pos) : + m_data(data), m_parent(parent), m_object(object), m_pos(pos) { - m_oldSelected = data->GetSelectedObject(); + m_oldSelected = data->GetSelectedObject(); } void InsertObjectCmd::DoExecute() { - m_parent->AddChild( m_object ); - m_object->SetParent( m_parent ); + m_parent->AddChild(m_object); + m_object->SetParent(m_parent); - if ( m_pos >= 0 ) - m_parent->ChangeChildPosition( m_object, m_pos ); + if (m_pos >= 0) + m_parent->ChangeChildPosition(m_object, m_pos); - PObjectBase obj = m_object; - while ( obj && obj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - if ( obj->GetChildCount() > 0 ) - obj = obj->GetChild( 0 ); - else - return; - } - m_data->SelectObject( obj, false, false ); + PObjectBase obj = m_object; + while (obj && obj->GetObjectInfo()->GetObjectType()->IsItem()) { + if (obj->GetChildCount() > 0) + obj = obj->GetChild(0); + else + return; + } + m_data->SelectObject(obj, false, false); } void InsertObjectCmd::DoRestore() { - m_parent->RemoveChild( m_object ); - m_object->SetParent( PObjectBase() ); - m_data->SelectObject( m_oldSelected ); + m_parent->RemoveChild(m_object); + m_object->SetParent(PObjectBase()); + m_data->SelectObject(m_oldSelected); } //----------------------------------------------------------------------------- -RemoveObjectCmd::RemoveObjectCmd( ApplicationData *data, PObjectBase object ) +RemoveObjectCmd::RemoveObjectCmd(ApplicationData* data, PObjectBase object) { - m_data = data; - m_object = object; - m_parent = object->GetParent(); - m_oldPos = m_parent->GetChildPosition( object ); - m_oldSelected = data->GetSelectedObject(); + m_data = data; + m_object = object; + m_parent = object->GetParent(); + m_oldPos = m_parent->GetChildPosition(object); + m_oldSelected = data->GetSelectedObject(); } void RemoveObjectCmd::DoExecute() { - m_parent->RemoveChild( m_object ); - m_object->SetParent( PObjectBase() ); - m_data->DetermineObjectToSelect( m_parent, m_oldPos ); + m_parent->RemoveChild(m_object); + m_object->SetParent(PObjectBase()); + m_data->DetermineObjectToSelect(m_parent, m_oldPos); } void RemoveObjectCmd::DoRestore() { - m_parent->AddChild( m_object ); - m_object->SetParent( m_parent ); + m_parent->AddChild(m_object); + m_object->SetParent(m_parent); - // restauramos la posición - m_parent->ChangeChildPosition( m_object, m_oldPos ); - m_data->SelectObject( m_oldSelected, true, false ); + // restauramos la posición + m_parent->ChangeChildPosition(m_object, m_oldPos); + m_data->SelectObject(m_oldSelected, true, false); } //----------------------------------------------------------------------------- -ModifyPropertyCmd::ModifyPropertyCmd( PProperty prop, wxString value ) - : m_property( prop ), m_newValue( value ) +ModifyPropertyCmd::ModifyPropertyCmd(PProperty prop, wxString value) : m_property(prop), m_newValue(value) { - m_oldValue = prop->GetValue(); + m_oldValue = prop->GetValue(); } void ModifyPropertyCmd::DoExecute() { - m_property->SetValue( m_newValue ); + m_property->SetValue(m_newValue); } void ModifyPropertyCmd::DoRestore() { - m_property->SetValue( m_oldValue ); + m_property->SetValue(m_oldValue); } //----------------------------------------------------------------------------- -ModifyEventHandlerCmd::ModifyEventHandlerCmd( PEvent event, wxString value ) - : m_event( event ), m_newValue( value ) +ModifyEventHandlerCmd::ModifyEventHandlerCmd(PEvent event, wxString value) : m_event(event), m_newValue(value) { - m_oldValue = event->GetValue(); + m_oldValue = event->GetValue(); } void ModifyEventHandlerCmd::DoExecute() { - m_event->SetValue( m_newValue ); + m_event->SetValue(m_newValue); } void ModifyEventHandlerCmd::DoRestore() { - m_event->SetValue( m_oldValue ); + m_event->SetValue(m_oldValue); } //----------------------------------------------------------------------------- -ShiftChildCmd::ShiftChildCmd( PObjectBase object, int pos ) +ShiftChildCmd::ShiftChildCmd(PObjectBase object, int pos) { - m_object = object; - PObjectBase parent = object->GetParent(); + m_object = object; + PObjectBase parent = object->GetParent(); - assert( parent ); + assert(parent); - m_oldPos = parent->GetChildPosition( object ); - m_newPos = pos; + m_oldPos = parent->GetChildPosition(object); + m_newPos = pos; } void ShiftChildCmd::DoExecute() { - if ( m_oldPos != m_newPos ) - { - PObjectBase parent ( m_object->GetParent() ); - parent->ChangeChildPosition( m_object, m_newPos ); - } + if (m_oldPos != m_newPos) { + PObjectBase parent(m_object->GetParent()); + parent->ChangeChildPosition(m_object, m_newPos); + } } void ShiftChildCmd::DoRestore() { - if ( m_oldPos != m_newPos ) - { - PObjectBase parent ( m_object->GetParent() ); - parent->ChangeChildPosition( m_object, m_oldPos ); - } + if (m_oldPos != m_newPos) { + PObjectBase parent(m_object->GetParent()); + parent->ChangeChildPosition(m_object, m_oldPos); + } } //----------------------------------------------------------------------------- -CutObjectCmd::CutObjectCmd( ApplicationData *data, PObjectBase object ) +CutObjectCmd::CutObjectCmd(ApplicationData* data, PObjectBase object) { - m_data = data; - m_object = object; - m_parent = object->GetParent(); - m_oldPos = m_parent->GetChildPosition( object ); - m_oldSelected = data->GetSelectedObject(); + m_data = data; + m_object = object; + m_parent = object->GetParent(); + m_oldPos = m_parent->GetChildPosition(object); + m_oldSelected = data->GetSelectedObject(); } void CutObjectCmd::DoExecute() { - // guardamos el clipboard ??? - //m_clipboard = m_data->GetClipboardObject(); + // guardamos el clipboard ??? + // m_clipboard = m_data->GetClipboardObject(); - m_data->SetClipboardObject( m_object ); - m_parent->RemoveChild( m_object ); - m_object->SetParent( PObjectBase() ); - m_data->DetermineObjectToSelect( m_parent, m_oldPos ); + m_data->SetClipboardObject(m_object); + m_parent->RemoveChild(m_object); + m_object->SetParent(PObjectBase()); + m_data->DetermineObjectToSelect(m_parent, m_oldPos); } void CutObjectCmd::DoRestore() { - // reubicamos el objeto donde estaba - m_parent->AddChild( m_object ); - m_object->SetParent( m_parent ); - m_parent->ChangeChildPosition( m_object, m_oldPos ); - + // reubicamos el objeto donde estaba + m_parent->AddChild(m_object); + m_object->SetParent(m_parent); + m_parent->ChangeChildPosition(m_object, m_oldPos); - // restauramos el clipboard - //m_data->SetClipboardObject(m_clipboard); - m_data->SetClipboardObject( PObjectBase() ); - m_data->SelectObject( m_oldSelected, true, false ); + // restauramos el clipboard + // m_data->SetClipboardObject(m_clipboard); + m_data->SetClipboardObject(PObjectBase()); + m_data->SelectObject(m_oldSelected, true, false); } //----------------------------------------------------------------------------- -ReparentObjectCmd ::ReparentObjectCmd ( PObjectBase sizeritem, PObjectBase sizer ) +ReparentObjectCmd ::ReparentObjectCmd(PObjectBase sizeritem, PObjectBase sizer) { - m_sizeritem = sizeritem; - m_sizer = sizer; - m_oldSizer = m_sizeritem->GetParent(); - m_oldPosition = m_oldSizer->GetChildPosition(sizeritem); + m_sizeritem = sizeritem; + m_sizer = sizer; + m_oldSizer = m_sizeritem->GetParent(); + m_oldPosition = m_oldSizer->GetChildPosition(sizeritem); } void ReparentObjectCmd::DoExecute() { - m_oldSizer->RemoveChild( m_sizeritem ); - m_sizeritem->SetParent( m_sizer ); - m_sizer->AddChild( m_sizeritem ); + m_oldSizer->RemoveChild(m_sizeritem); + m_sizeritem->SetParent(m_sizer); + m_sizer->AddChild(m_sizeritem); } void ReparentObjectCmd::DoRestore() { - m_sizer->RemoveChild( m_sizeritem ); - m_sizeritem->SetParent( m_oldSizer ); - m_oldSizer->AddChild( m_sizeritem ); - m_oldSizer->ChangeChildPosition( m_sizeritem, m_oldPosition); + m_sizer->RemoveChild(m_sizeritem); + m_sizeritem->SetParent(m_oldSizer); + m_oldSizer->AddChild(m_sizeritem); + m_oldSizer->ChangeChildPosition(m_sizeritem, m_oldPosition); } /////////////////////////////////////////////////////////////////////////////// @@ -439,2795 +429,2532 @@ void ReparentObjectCmd::DoRestore() ApplicationData* ApplicationData::s_instance = NULL; -ApplicationData* ApplicationData::Get( const wxString &rootdir ) +ApplicationData* ApplicationData::Get(const wxString& rootdir) { - if ( !s_instance ) - s_instance = new ApplicationData( rootdir ); + if (!s_instance) + s_instance = new ApplicationData(rootdir); - return s_instance; + return s_instance; } void ApplicationData::Destroy() { - delete s_instance; + delete s_instance; - s_instance = NULL; + s_instance = NULL; } void ApplicationData::Initialize() { - ApplicationData* appData = ApplicationData::Get(); - appData->LoadApp(); - - // Use the color of a dominant text to determine if dark mode should be used. - // TODO: Depending on the used theme it is not clear which color that is, - // using the window text has given the best results so far. - const auto col = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT); - const auto lightness = (col.Red() * 299 + col.Green() * 587 + col.Blue() * 114) / 1000; - appData->SetDarkMode(lightness > 127); -} - -ApplicationData::ApplicationData( const wxString &rootdir ) - : - m_rootDir( rootdir ), - m_modFlag( false ), - m_warnOnAdditionsUpdate( true ), - m_darkMode(false), - m_objDb( new ObjectDatabase() ), - m_manager( new wxFBManager ), - m_ipc( new wxFBIPC ), - m_fbpVerMajor( 1 ), - m_fbpVerMinor(16) -{ - #ifdef __WXFB_DEBUG__ - //wxLog* log = wxLog::SetActiveTarget( NULL ); - m_debugLogTarget = new wxLogWindow( NULL, wxT( "Logging" ) ); - //wxLog::SetActiveTarget( log ); - #endif - m_objDb->SetXmlPath( m_rootDir + wxFILE_SEP_PATH + wxT( "resources" ) + wxFILE_SEP_PATH + wxT( "xml" ) + wxFILE_SEP_PATH ) ; - m_objDb->SetIconPath( m_rootDir + wxFILE_SEP_PATH + wxT( "resources" ) + wxFILE_SEP_PATH + wxT( "icons" ) + wxFILE_SEP_PATH ); - m_objDb->SetPluginPath( m_rootDir + wxFILE_SEP_PATH + wxT( "plugins" ) + wxFILE_SEP_PATH ) ; - - // Support loading files from memory - // Used to load the XRC preview, but could be useful elsewhere - wxFileSystem::AddHandler( new wxMemoryFSHandler ); - - // Support for loading files from archives - wxFileSystem::AddHandler( new wxArchiveFSHandler ); - wxFileSystem::AddHandler( new wxFilterFSHandler ); + ApplicationData* appData = ApplicationData::Get(); + appData->LoadApp(); + + // Use the color of a dominant text to determine if dark mode should be used. + // TODO: Depending on the used theme it is not clear which color that is, + // using the window text has given the best results so far. + const auto col = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT); + const auto lightness = (col.Red() * 299 + col.Green() * 587 + col.Blue() * 114) / 1000; + appData->SetDarkMode(lightness > 127); +} + +ApplicationData::ApplicationData(const wxString& rootdir) : + m_rootDir(rootdir), + m_modFlag(false), + m_warnOnAdditionsUpdate(true), + m_darkMode(false), + m_objDb(new ObjectDatabase()), + m_manager(new wxFBManager), + m_ipc(new wxFBIPC), + m_fbpVerMajor(1), + m_fbpVerMinor(16) +{ +#ifdef __WXFB_DEBUG__ + // wxLog* log = wxLog::SetActiveTarget( NULL ); + m_debugLogTarget = new wxLogWindow(NULL, wxT("Logging")); +// wxLog::SetActiveTarget( log ); +#endif + m_objDb->SetXmlPath( + m_rootDir + wxFILE_SEP_PATH + wxT("resources") + wxFILE_SEP_PATH + wxT("xml") + wxFILE_SEP_PATH); + m_objDb->SetIconPath( + m_rootDir + wxFILE_SEP_PATH + wxT("resources") + wxFILE_SEP_PATH + wxT("icons") + wxFILE_SEP_PATH); + m_objDb->SetPluginPath(m_rootDir + wxFILE_SEP_PATH + wxT("plugins") + wxFILE_SEP_PATH); + + // Support loading files from memory + // Used to load the XRC preview, but could be useful elsewhere + wxFileSystem::AddHandler(new wxMemoryFSHandler); + + // Support for loading files from archives + wxFileSystem::AddHandler(new wxArchiveFSHandler); + wxFileSystem::AddHandler(new wxFilterFSHandler); } ApplicationData::~ApplicationData() { - #ifdef __WXFB_DEBUG__ - delete m_debugLogTarget; - m_debugLogTarget = 0; - #endif +#ifdef __WXFB_DEBUG__ + delete m_debugLogTarget; + m_debugLogTarget = 0; +#endif } void ApplicationData::LoadApp() { - wxString bitmapPath = m_objDb->GetXmlPath() + wxT( "icons.xml" ); - AppBitmaps::LoadBitmaps( bitmapPath, m_objDb->GetIconPath() ); - m_objDb->LoadObjectTypes(); - m_objDb->LoadPlugins( m_manager ); + wxString bitmapPath = m_objDb->GetXmlPath() + wxT("icons.xml"); + AppBitmaps::LoadBitmaps(bitmapPath, m_objDb->GetIconPath()); + m_objDb->LoadObjectTypes(); + m_objDb->LoadPlugins(m_manager); } PwxFBManager ApplicationData::GetManager() { - return m_manager; + return m_manager; } PObjectBase ApplicationData::GetSelectedObject() { - return m_selObj; + return m_selObj; } PObjectBase ApplicationData::GetSelectedForm() { - if( ( m_selObj->GetObjectTypeName() == wxT( "form" ) ) || - ( m_selObj->GetObjectTypeName() == wxT("wizard") ) || - ( m_selObj->GetObjectTypeName() == wxT( "menubar_form" ) ) || - ( m_selObj->GetObjectTypeName() == wxT( "toolbar_form" ) ) ) - return m_selObj; - else - return m_selObj->FindParentForm(); + if ( + (m_selObj->GetObjectTypeName() == wxT("form")) || (m_selObj->GetObjectTypeName() == wxT("wizard")) || + (m_selObj->GetObjectTypeName() == wxT("menubar_form")) || (m_selObj->GetObjectTypeName() == wxT("toolbar_form"))) + return m_selObj; + else + return m_selObj->FindParentForm(); } PObjectBase ApplicationData::GetProjectData() { - return m_project; + return m_project; } -void ApplicationData::BuildNameSet( PObjectBase obj, PObjectBase top, std::set< wxString >& name_set ) +void ApplicationData::BuildNameSet(PObjectBase obj, PObjectBase top, std::set& name_set) { - if ( obj != top ) - { - PProperty nameProp = top->GetProperty( wxT( "name" ) ); + if (obj != top) { + PProperty nameProp = top->GetProperty(wxT("name")); - if ( nameProp ) - name_set.insert( nameProp->GetValue() ); - } + if (nameProp) + name_set.insert(nameProp->GetValue()); + } - for ( unsigned int i = 0; i < top->GetChildCount(); i++ ) - BuildNameSet( obj, top->GetChild( i ), name_set ); + for (unsigned int i = 0; i < top->GetChildCount(); i++) BuildNameSet(obj, top->GetChild(i), name_set); } -void ApplicationData::ResolveNameConflict( PObjectBase obj ) +void ApplicationData::ResolveNameConflict(PObjectBase obj) { - while ( obj && obj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - if ( obj->GetChildCount() > 0 ) - obj = obj->GetChild( 0 ); - else - return; - } + while (obj && obj->GetObjectInfo()->GetObjectType()->IsItem()) { + if (obj->GetChildCount() > 0) + obj = obj->GetChild(0); + else + return; + } - PProperty nameProp = obj->GetProperty( wxT( "name" ) ); + PProperty nameProp = obj->GetProperty(wxT("name")); - if ( !nameProp ) - return; + if (!nameProp) + return; - // Save the original name for use later. - wxString originalName = nameProp->GetValue(); + // Save the original name for use later. + wxString originalName = nameProp->GetValue(); - // el nombre no puede estar repetido dentro del mismo form - /*PObjectBase top = obj->FindNearAncestor( wxT( "form" ) );*/ - PObjectBase top = obj->FindParentForm(); + // el nombre no puede estar repetido dentro del mismo form + /*PObjectBase top = obj->FindNearAncestor( wxT( "form" ) );*/ + PObjectBase top = obj->FindParentForm(); - if ( !top ) - top = m_project; // el objeto es un form. + if (!top) + top = m_project; // el objeto es un form. - // construimos el conjunto de nombres - std::set name_set; + // construimos el conjunto de nombres + std::set name_set; - BuildNameSet( obj, top, name_set ); + BuildNameSet(obj, top, name_set); - // comprobamos si hay conflicto - std::set::iterator it = name_set.find( originalName ); + // comprobamos si hay conflicto + std::set::iterator it = name_set.find(originalName); - int i = 0; + int i = 0; - wxString name = originalName; // The name that gets incremented. + wxString name = originalName; // The name that gets incremented. - while ( it != name_set.end() ) - { - i++; - name = wxString::Format( wxT( "%s%i" ), originalName, i ); - it = name_set.find( name ); - } + while (it != name_set.end()) { + i++; + name = wxString::Format(wxT("%s%i"), originalName, i); + it = name_set.find(name); + } - nameProp->SetValue( name ); + nameProp->SetValue(name); } -void ApplicationData::ResolveSubtreeNameConflicts( PObjectBase obj, PObjectBase topObj ) +void ApplicationData::ResolveSubtreeNameConflicts(PObjectBase obj, PObjectBase topObj) { - if ( !topObj ) - { - /*topObj = obj->FindNearAncestor( wxT( "form" ) );*/ - topObj = obj->FindParentForm(); + if (!topObj) { + /*topObj = obj->FindNearAncestor( wxT( "form" ) );*/ + topObj = obj->FindParentForm(); - if ( !topObj ) - topObj = m_project; // object is the project - } + if (!topObj) + topObj = m_project; // object is the project + } - // Ignore item objects - while ( obj && obj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - if ( obj->GetChildCount() > 0 ) - obj = obj->GetChild( 0 ); - else - return; // error - } + // Ignore item objects + while (obj && obj->GetObjectInfo()->GetObjectType()->IsItem()) { + if (obj->GetChildCount() > 0) + obj = obj->GetChild(0); + else + return; // error + } - // Resolve a possible name conflict - ResolveNameConflict( obj ); + // Resolve a possible name conflict + ResolveNameConflict(obj); - // Recurse through all children - for ( unsigned int i = 0 ; i < obj->GetChildCount() ; i++ ) - ResolveSubtreeNameConflicts( obj->GetChild( i ), topObj ); + // Recurse through all children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) ResolveSubtreeNameConflicts(obj->GetChild(i), topObj); } -int ApplicationData::CalcPositionOfInsertion( PObjectBase selected, PObjectBase parent ) +int ApplicationData::CalcPositionOfInsertion(PObjectBase selected, PObjectBase parent) { - int pos = -1; + int pos = -1; - if ( parent && selected ) - { - PObjectBase parentSelected = selected->GetParent(); + if (parent && selected) { + PObjectBase parentSelected = selected->GetParent(); - while ( parentSelected && parentSelected != parent ) - { - selected = parentSelected; - parentSelected = selected->GetParent(); - } + while (parentSelected && parentSelected != parent) { + selected = parentSelected; + parentSelected = selected->GetParent(); + } - if ( parentSelected && parentSelected == parent ) - pos = parent->GetChildPosition( selected ) + 1; - } + if (parentSelected && parentSelected == parent) + pos = parent->GetChildPosition(selected) + 1; + } - return pos; + return pos; } -void ApplicationData::RemoveEmptyItems( PObjectBase obj ) +void ApplicationData::RemoveEmptyItems(PObjectBase obj) { - if ( !obj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - bool emptyItem = true; + if (!obj->GetObjectInfo()->GetObjectType()->IsItem()) { + bool emptyItem = true; - // esto es un algoritmo ineficiente pero "seguro" con los índices + // esto es un algoritmo ineficiente pero "seguro" con los índices - while ( emptyItem ) - { - emptyItem = false; + while (emptyItem) { + emptyItem = false; - for ( unsigned int i = 0; !emptyItem && i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); + for (unsigned int i = 0; !emptyItem && i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); - if ( child->GetObjectInfo()->GetObjectType()->IsItem() && - child->GetChildCount() == 0 ) - { - obj->RemoveChild( child ); // borramos el item - child->SetParent( PObjectBase() ); + if (child->GetObjectInfo()->GetObjectType()->IsItem() && child->GetChildCount() == 0) { + obj->RemoveChild(child); // borramos el item + child->SetParent(PObjectBase()); - emptyItem = true; // volvemos a recorrer - wxString msg; - msg.Printf( wxT( "Empty item removed under %s" ), obj->GetPropertyAsString( wxT( "name" ) ) ); - wxLogWarning( msg ); - } - } - } - } + emptyItem = true; // volvemos a recorrer + wxString msg; + msg.Printf(wxT("Empty item removed under %s"), obj->GetPropertyAsString(wxT("name"))); + wxLogWarning(msg); + } + } + } + } - for ( unsigned int i = 0; i < obj->GetChildCount() ; i++ ) - RemoveEmptyItems( obj->GetChild( i ) ); + for (unsigned int i = 0; i < obj->GetChildCount(); i++) RemoveEmptyItems(obj->GetChild(i)); } -PObjectBase ApplicationData::SearchSizerInto( PObjectBase obj ) +PObjectBase ApplicationData::SearchSizerInto(PObjectBase obj) { - PObjectBase theSizer; + PObjectBase theSizer; - if ( obj->GetObjectInfo()->IsSubclassOf( wxT("sizer") ) || obj->GetObjectInfo()->IsSubclassOf( wxT("gbsizer") ) ) - theSizer = obj; - else - { - for ( unsigned int i = 0; !theSizer && i < obj->GetChildCount(); i++ ) - theSizer = SearchSizerInto( obj->GetChild( i ) ); - } + if (obj->GetObjectInfo()->IsSubclassOf(wxT("sizer")) || obj->GetObjectInfo()->IsSubclassOf(wxT("gbsizer"))) + theSizer = obj; + else { + for (unsigned int i = 0; !theSizer && i < obj->GetChildCount(); i++) + theSizer = SearchSizerInto(obj->GetChild(i)); + } - return theSizer; + return theSizer; } /////////////////////////////////////////////////////////////////////////////// -void ApplicationData::ExpandObject( PObjectBase obj, bool expand ) +void ApplicationData::ExpandObject(PObjectBase obj, bool expand) { - PCommand command( new ExpandObjectCmd( obj, expand ) ); - Execute( command ); + PCommand command(new ExpandObjectCmd(obj, expand)); + Execute(command); - // collapse also all children ... - PropagateExpansion( obj, expand, !expand ); + // collapse also all children ... + PropagateExpansion(obj, expand, !expand); - NotifyObjectExpanded( obj ); + NotifyObjectExpanded(obj); } -void ApplicationData::PropagateExpansion( PObjectBase obj, bool expand, bool up ) +void ApplicationData::PropagateExpansion(PObjectBase obj, bool expand, bool up) { - if( obj ) - { - if( up ) - { - PObjectBase child; - - for( size_t i = 0; i < obj->GetChildCount(); i++ ) - { - child = obj->GetChild(i); + if (obj) { + if (up) { + PObjectBase child; + + for (size_t i = 0; i < obj->GetChildCount(); i++) { + child = obj->GetChild(i); + + PCommand command(new ExpandObjectCmd(child, expand)); + Execute(command); + + PropagateExpansion(child, expand, up); + } + } else { + PropagateExpansion(obj->GetParent(), expand, up); + + PCommand command(new ExpandObjectCmd(obj, expand)); + Execute(command); + } + } +} - PCommand command( new ExpandObjectCmd( child, expand ) ); - Execute( command ); +bool ApplicationData::SelectObject(PObjectBase obj, bool force /*= false*/, bool notify /*= true */) +{ + if ((obj == m_selObj) && !force) { + return false; + } - PropagateExpansion( child, expand, up ); - } - } - else - { - PropagateExpansion( obj->GetParent(), expand, up ); + m_selObj = obj; - PCommand command( new ExpandObjectCmd( obj, expand ) ); - Execute( command ); - } - } + if (notify) { + NotifyObjectSelected(obj, force); + } + return true; } -bool ApplicationData::SelectObject( PObjectBase obj, bool force /*= false*/, bool notify /*= true */ ) +void ApplicationData::CreateObject(wxString name) { - if ( ( obj == m_selObj ) && !force ) - { - return false; - } + try { + LogDebug("[ApplicationData::CreateObject] New " + name); + PObjectBase old_selected = GetSelectedObject(); + PObjectBase parent = old_selected; + PObjectBase obj; + + if (parent) { + bool created = false; + + // Para que sea más práctico, si el objeto no se puede crear debajo + // del objeto seleccionado vamos a intentarlo en el padre del seleccionado + // y seguiremos subiendo hasta que ya no podamos crear el objeto. - m_selObj = obj; + while (parent && !created) { + // además, el objeto se insertará a continuación del objeto seleccionado + obj = m_objDb->CreateObject(_STDSTR(name), parent); - if ( notify ) - { - NotifyObjectSelected( obj, force ); - } - return true; + if (obj) { + int pos = CalcPositionOfInsertion(GetSelectedObject(), parent); + + PCommand command(new InsertObjectCmd(this, obj, parent, pos)); + Execute(command); // m_cmdProc.Execute(command); + created = true; + ResolveNameConflict(obj); + } else { + // lo vamos a seguir intentando con el padre, pero cuidado, el padre + // no puede ser un item! + parent = parent->GetParent(); + + while (parent && parent->GetObjectInfo()->GetObjectType()->IsItem()) parent = parent->GetParent(); + } + } + } + + // Seleccionamos el objeto, si este es un item entonces se selecciona + // el objeto contenido. ¿Tiene sentido tener un item debajo de un item? + + while (obj && obj->GetObjectInfo()->GetObjectType()->IsItem()) + obj = (obj->GetChildCount() > 0 ? obj->GetChild(0) : PObjectBase()); + + NotifyObjectCreated(obj); + + if (obj) { + SelectObject(obj, true, true); + } else { + SelectObject(old_selected, true, true); + } + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } } -void ApplicationData::CreateObject( wxString name ) +void ApplicationData::RemoveObject(PObjectBase obj) { - try - { - LogDebug("[ApplicationData::CreateObject] New " + name ); - PObjectBase old_selected = GetSelectedObject(); - PObjectBase parent = old_selected; - PObjectBase obj; + DoRemoveObject(obj, false); +} - if ( parent ) - { - bool created = false; - - // Para que sea más práctico, si el objeto no se puede crear debajo - // del objeto seleccionado vamos a intentarlo en el padre del seleccionado - // y seguiremos subiendo hasta que ya no podamos crear el objeto. +void ApplicationData::CutObject(PObjectBase obj) +{ + DoRemoveObject(obj, true); +} - while ( parent && !created ) - { - // además, el objeto se insertará a continuación del objeto seleccionado - obj = m_objDb->CreateObject( _STDSTR( name ), parent ); +void ApplicationData::DoRemoveObject(PObjectBase obj, bool cutObject) +{ + // Note: + // When removing an object it is important that the "item" objects + // are not left behind + PObjectBase parent = obj->GetParent(); + PObjectBase deleted_obj = obj; - if ( obj ) - { - int pos = CalcPositionOfInsertion( GetSelectedObject(), parent ); + if (parent) { + // Get the top item + while (parent && parent->GetObjectInfo()->GetObjectType()->IsItem()) { + obj = parent; + parent = obj->GetParent(); + } - PCommand command( new InsertObjectCmd( this, obj, parent, pos ) ); - Execute( command ); //m_cmdProc.Execute(command); - created = true; - ResolveNameConflict( obj ); - } - else - { - // lo vamos a seguir intentando con el padre, pero cuidado, el padre - // no puede ser un item! - parent = parent->GetParent(); - - while ( parent && parent->GetObjectInfo()->GetObjectType()->IsItem() ) - parent = parent->GetParent(); - } - } - } + if (cutObject) { + m_copyOnPaste = false; + PCommand command(new CutObjectCmd(this, obj)); + Execute(command); + } else { + PCommand command(new RemoveObjectCmd(this, obj)); + Execute(command); + } + + NotifyObjectRemoved(deleted_obj); + SelectObject(GetSelectedObject(), true, true); + } else { + if (obj->GetObjectTypeName() != wxT("project")) + assert(false); + } - // Seleccionamos el objeto, si este es un item entonces se selecciona - // el objeto contenido. ¿Tiene sentido tener un item debajo de un item? + CheckProjectTree(m_project); +} - while ( obj && obj->GetObjectInfo()->GetObjectType()->IsItem() ) - obj = ( obj->GetChildCount() > 0 ? obj->GetChild( 0 ) : PObjectBase() ); - - NotifyObjectCreated( obj ); - - if ( obj ) - { - SelectObject( obj, true, true ); - } - else - { - SelectObject( old_selected, true, true ); - } - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } -} - -void ApplicationData::RemoveObject( PObjectBase obj ) -{ - DoRemoveObject( obj, false ); -} - -void ApplicationData::CutObject( PObjectBase obj ) -{ - DoRemoveObject( obj, true ); -} - -void ApplicationData::DoRemoveObject( PObjectBase obj, bool cutObject ) -{ - // Note: - // When removing an object it is important that the "item" objects - // are not left behind - PObjectBase parent = obj->GetParent(); - PObjectBase deleted_obj = obj; - - if ( parent ) - { - // Get the top item - while ( parent && parent->GetObjectInfo()->GetObjectType()->IsItem() ) - { - obj = parent; - parent = obj->GetParent(); - } - - if ( cutObject ) - { - m_copyOnPaste = false; - PCommand command( new CutObjectCmd( this, obj ) ); - Execute( command ); - } - else - { - PCommand command( new RemoveObjectCmd( this, obj ) ); - Execute( command ); - } - - NotifyObjectRemoved( deleted_obj ); - SelectObject( GetSelectedObject(), true, true ); - } - else - { - if ( obj->GetObjectTypeName() != wxT( "project" ) ) - assert( false ); - } - - CheckProjectTree( m_project ); -} - -void ApplicationData::DetermineObjectToSelect( PObjectBase parent, unsigned int pos ) -{ - // get position of next control or last control - PObjectBase objToSelect; - unsigned int count = parent->GetChildCount(); - if ( 0 == count ) - { - objToSelect = parent; - } - else - { - pos = ( pos < count ? pos : count - 1 ); - objToSelect = parent->GetChild( pos ); - } - - while ( objToSelect && objToSelect->GetObjectInfo()->GetObjectType()->IsItem() ) - { - objToSelect = objToSelect->GetChild( 0 ); - } - - SelectObject( objToSelect ); -} - -void ApplicationData::CopyObjectToClipboard( PObjectBase obj ) +void ApplicationData::DetermineObjectToSelect(PObjectBase parent, unsigned int pos) { - // Write some text to the clipboard - - // Do not call Open() when the clipboard is opened - if( !wxTheClipboard->IsOpened() ) - { - if ( !wxTheClipboard->Open() ) - { + // get position of next control or last control + PObjectBase objToSelect; + unsigned int count = parent->GetChildCount(); + if (0 == count) { + objToSelect = parent; + } else { + pos = (pos < count ? pos : count - 1); + objToSelect = parent->GetChild(pos); + } + + while (objToSelect && objToSelect->GetObjectInfo()->GetObjectType()->IsItem()) { + objToSelect = objToSelect->GetChild(0); + } + + SelectObject(objToSelect); +} + +void ApplicationData::CopyObjectToClipboard(PObjectBase obj) +{ + // Write some text to the clipboard + + // Do not call Open() when the clipboard is opened + if (!wxTheClipboard->IsOpened()) { + if (!wxTheClipboard->Open()) { return; } - } + } // This data objects are held by the clipboard, // so do not delete them in the app. - wxTheClipboard->SetData( new wxFBDataObject( obj ) ); + wxTheClipboard->SetData(new wxFBDataObject(obj)); wxTheClipboard->Close(); } -bool ApplicationData::PasteObjectFromClipboard( PObjectBase parent ) +bool ApplicationData::PasteObjectFromClipboard(PObjectBase parent) { - // Do not call Open() when the clipboard is opened - if( !wxTheClipboard->IsOpened() ) - { - if ( !wxTheClipboard->Open() ) - { + // Do not call Open() when the clipboard is opened + if (!wxTheClipboard->IsOpened()) { + if (!wxTheClipboard->Open()) { return false; } - } + } - if ( wxTheClipboard->IsSupported( wxFBDataObjectFormat ) ) - { + if (wxTheClipboard->IsSupported(wxFBDataObjectFormat)) { wxFBDataObject data; - if ( wxTheClipboard->GetData( data ) ) - { + if (wxTheClipboard->GetData(data)) { PObjectBase obj = data.GetObj(); - if ( obj ) - { + if (obj) { wxTheClipboard->Close(); - return PasteObject( parent, obj ); + return PasteObject(parent, obj); } } } wxTheClipboard->Close(); - return false; + return false; } bool ApplicationData::CanPasteObjectFromClipboard() { - // Do not call Open() when the clipboard is opened - if( !wxTheClipboard->IsOpened() ) - { - if ( !wxTheClipboard->Open() ) - { + // Do not call Open() when the clipboard is opened + if (!wxTheClipboard->IsOpened()) { + if (!wxTheClipboard->Open()) { + return false; + } + } + + bool canPaste = wxTheClipboard->IsSupported(wxFBDataObjectFormat); + + if (wxTheClipboard->IsOpened()) + wxTheClipboard->Close(); + + return canPaste; +} + +void ApplicationData::CopyObject(PObjectBase obj) +{ + m_copyOnPaste = true; + + // Make a copy of the object on the clipboard, otherwise + // modifications to the object after the copy will also + // be made on the clipboard. + m_clipboard = m_objDb->CopyObject(obj); + + CheckProjectTree(m_project); +} + +bool ApplicationData::PasteObject(PObjectBase parent, PObjectBase objToPaste) +{ + try { + PObjectBase clipboard; + if (objToPaste) { + clipboard = objToPaste; + } else if (m_clipboard) { + if (m_copyOnPaste) { + clipboard = m_objDb->CopyObject(m_clipboard); + } else { + clipboard = m_clipboard; + } + } + + if (!clipboard) { + return false; + } + + // Remove parent/child relationship from clipboard object + PObjectBase clipParent = clipboard->GetParent(); + if (clipParent) { + clipParent->RemoveChild(clipboard); + clipboard->SetParent(PObjectBase()); + } + + // Vamos a hacer un pequeño truco, intentaremos crear un objeto nuevo + // del mismo tipo que el guardado en m_clipboard debajo de parent. + // El objeto devuelto quizá no sea de la misma clase que m_clipboard debido + // a que esté incluido dentro de un "item". + // Por tanto, si el objeto devuelto es no-nulo, entonces vamos a descender + // en el arbol hasta que el objeto sea de la misma clase que m_clipboard, + // momento en que cambiaremos dicho objeto por m_clipboard. + // + // Ejemplo: + // + // m_clipboard :: wxButton + // parent :: wxBoxSizer + // + // obj = CreateObject(m_clipboard->GetObjectInfo()->GetClassName(), parent) + // + // obj :: sizeritem + // / + // wxButton <- Cambiamos este por m_clipboard + PObjectBase old_parent = parent; + + PObjectBase obj = m_objDb->CreateObject(_STDSTR(clipboard->GetObjectInfo()->GetClassName()), parent); + + // If the object is already contained in an item, we may need to get the object out of the first + // item before pasting + if (!obj) { + + PObjectBase tempItem = clipboard; + while (tempItem->GetObjectInfo()->GetObjectType()->IsItem()) { + tempItem = tempItem->GetChild(0); + if (!tempItem) { + break; + } + + obj = m_objDb->CreateObject(_STDSTR(tempItem->GetObjectInfo()->GetClassName()), parent); + if (obj) { + clipboard = tempItem; + break; + } + } + } + + int pos = -1; + + if (!obj) { + // si no se ha podido crear el objeto vamos a intentar crearlo colgado + // del padre de "parent" y además vamos a insertarlo en la posición + // siguiente a "parent" + PObjectBase selected = parent; + parent = selected->GetParent(); + + while (parent && parent->GetObjectInfo()->GetObjectType()->IsItem()) { + selected = parent; + parent = selected->GetParent(); + } + + if (parent) { + obj = m_objDb->CreateObject(_STDSTR(clipboard->GetObjectInfo()->GetClassName()), parent); + if (obj) { + pos = CalcPositionOfInsertion(selected, parent); + } + } + } + + if (!obj) { return false; } - } - - bool canPaste = wxTheClipboard->IsSupported( wxFBDataObjectFormat ); - - if( wxTheClipboard->IsOpened() ) - wxTheClipboard->Close(); - - return canPaste; -} - -void ApplicationData::CopyObject( PObjectBase obj ) -{ - m_copyOnPaste = true; - - // Make a copy of the object on the clipboard, otherwise - // modifications to the object after the copy will also - // be made on the clipboard. - m_clipboard = m_objDb->CopyObject( obj ); - - CheckProjectTree( m_project ); -} - -bool ApplicationData::PasteObject( PObjectBase parent, PObjectBase objToPaste ) -{ - try - { - PObjectBase clipboard; - if ( objToPaste ) - { - clipboard = objToPaste; - } - else if ( m_clipboard ) - { - if ( m_copyOnPaste ) - { - clipboard = m_objDb->CopyObject( m_clipboard ); - } - else - { - clipboard = m_clipboard; - } - } - - if ( !clipboard ) - { - return false; - } - - // Remove parent/child relationship from clipboard object - PObjectBase clipParent = clipboard->GetParent(); - if ( clipParent ) - { - clipParent->RemoveChild( clipboard ); - clipboard->SetParent( PObjectBase() ); - } - - // Vamos a hacer un pequeño truco, intentaremos crear un objeto nuevo - // del mismo tipo que el guardado en m_clipboard debajo de parent. - // El objeto devuelto quizá no sea de la misma clase que m_clipboard debido - // a que esté incluido dentro de un "item". - // Por tanto, si el objeto devuelto es no-nulo, entonces vamos a descender - // en el arbol hasta que el objeto sea de la misma clase que m_clipboard, - // momento en que cambiaremos dicho objeto por m_clipboard. - // - // Ejemplo: - // - // m_clipboard :: wxButton - // parent :: wxBoxSizer - // - // obj = CreateObject(m_clipboard->GetObjectInfo()->GetClassName(), parent) - // - // obj :: sizeritem - // / - // wxButton <- Cambiamos este por m_clipboard - PObjectBase old_parent = parent; - - PObjectBase obj = m_objDb->CreateObject( _STDSTR( clipboard->GetObjectInfo()->GetClassName() ), parent ); - - // If the object is already contained in an item, we may need to get the object out of the first - // item before pasting - if ( !obj ) - { - - PObjectBase tempItem = clipboard; - while ( tempItem->GetObjectInfo()->GetObjectType()->IsItem() ) - { - tempItem = tempItem->GetChild( 0 ); - if ( !tempItem ) - { - break; - } - - obj = m_objDb->CreateObject( _STDSTR( tempItem->GetObjectInfo()->GetClassName() ), parent ); - if ( obj ) - { - clipboard = tempItem; - break; - } - } - } - - int pos = -1; - - if ( !obj ) - { - // si no se ha podido crear el objeto vamos a intentar crearlo colgado - // del padre de "parent" y además vamos a insertarlo en la posición - // siguiente a "parent" - PObjectBase selected = parent; - parent = selected->GetParent(); - - while ( parent && parent->GetObjectInfo()->GetObjectType()->IsItem() ) - { - selected = parent; - parent = selected->GetParent(); - } - - if ( parent ) - { - obj = m_objDb->CreateObject( _STDSTR( clipboard->GetObjectInfo()->GetClassName() ), parent ); - if ( obj ) - { - pos = CalcPositionOfInsertion( selected, parent ); - } - } - } - - if ( !obj ) - { - return false; - } - - PObjectBase aux = obj; - - while ( aux && aux->GetObjectInfo() != clipboard->GetObjectInfo() ) - aux = ( aux->GetChildCount() > 0 ? aux->GetChild( 0 ) : PObjectBase() ); - - if ( aux && aux != obj ) - { - // sustituimos aux por clipboard - PObjectBase auxParent = aux->GetParent(); - auxParent->RemoveChild( aux ); - aux->SetParent( PObjectBase() ); - - auxParent->AddChild( clipboard ); - clipboard->SetParent( auxParent ); - } - else - obj = clipboard; - - // y finalmente insertamos en el arbol - PCommand command( new InsertObjectCmd( this, obj, parent, pos ) ); - - Execute( command ); - - if ( !m_copyOnPaste ) - m_clipboard.reset(); - - ResolveSubtreeNameConflicts( obj ); - - NotifyProjectRefresh(); - - // vamos a mantener seleccionado el nuevo objeto creado - // pero hay que tener en cuenta que es muy probable que el objeto creado - // sea un "item" - while ( obj && obj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - assert( obj->GetChildCount() > 0 ); - obj = obj->GetChild( 0 ); - } - - SelectObject( obj, true, true ); - - CheckProjectTree( m_project ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - return false; - } - - return true; -} - -void ApplicationData::InsertObject( PObjectBase obj, PObjectBase parent ) -{ - // FIXME! comprobar obj se puede colgar de parent - // if (parent->GetObjectInfo()->GetObjectType()->FindChildType( - // obj->GetObjectInfo()->GetObjectType())) - // { - PCommand command( new InsertObjectCmd( this, obj, parent ) ); - Execute( command ); //m_cmdProc.Execute(command); - NotifyProjectRefresh(); - // } -} - -void ApplicationData::MergeProject( PObjectBase project ) -{ - // FIXME! comprobar obj se puede colgar de parent - for ( unsigned int i = 0; i < project->GetChildCount(); i++ ) - { - //m_project->AddChild(project->GetChild(i)); - //project->GetChild(i)->SetParent(m_project); + PObjectBase aux = obj; + + while (aux && aux->GetObjectInfo() != clipboard->GetObjectInfo()) + aux = (aux->GetChildCount() > 0 ? aux->GetChild(0) : PObjectBase()); + + if (aux && aux != obj) { + // sustituimos aux por clipboard + PObjectBase auxParent = aux->GetParent(); + auxParent->RemoveChild(aux); + aux->SetParent(PObjectBase()); + + auxParent->AddChild(clipboard); + clipboard->SetParent(auxParent); + } else + obj = clipboard; + + // y finalmente insertamos en el arbol + PCommand command(new InsertObjectCmd(this, obj, parent, pos)); + + Execute(command); + + if (!m_copyOnPaste) + m_clipboard.reset(); + + ResolveSubtreeNameConflicts(obj); + + NotifyProjectRefresh(); + + // vamos a mantener seleccionado el nuevo objeto creado + // pero hay que tener en cuenta que es muy probable que el objeto creado + // sea un "item" + while (obj && obj->GetObjectInfo()->GetObjectType()->IsItem()) { + assert(obj->GetChildCount() > 0); + obj = obj->GetChild(0); + } + + SelectObject(obj, true, true); + + CheckProjectTree(m_project); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + return false; + } + + return true; +} + +void ApplicationData::InsertObject(PObjectBase obj, PObjectBase parent) +{ + // FIXME! comprobar obj se puede colgar de parent + // if (parent->GetObjectInfo()->GetObjectType()->FindChildType( + // obj->GetObjectInfo()->GetObjectType())) + // { + PCommand command(new InsertObjectCmd(this, obj, parent)); + Execute(command); // m_cmdProc.Execute(command); + NotifyProjectRefresh(); + // } +} + +void ApplicationData::MergeProject(PObjectBase project) +{ + // FIXME! comprobar obj se puede colgar de parent + + for (unsigned int i = 0; i < project->GetChildCount(); i++) { + // m_project->AddChild(project->GetChild(i)); + // project->GetChild(i)->SetParent(m_project); + + PObjectBase child = project->GetChild(i); + RemoveEmptyItems(child); - PObjectBase child = project->GetChild( i ); - RemoveEmptyItems( child ); + InsertObject(child, m_project); + } + + // Merge bitmaps and icons properties + PObjectBase thisProject = GetProjectData(); + PProperty prop = thisProject->GetProperty(_("bitmaps")); + if (prop) { + wxString value = prop->GetValue(); + value.Trim(); + value << wxT(" ") << project->GetPropertyAsString(_("bitmaps")); + prop->SetValue(value); + } + prop = thisProject->GetProperty(_("icons")); + if (prop) { + wxString value = prop->GetValue(); + value.Trim(); + value << wxT(" ") << project->GetPropertyAsString(_("icons")); + prop->SetValue(value); + } - InsertObject( child, m_project ); - } + NotifyProjectRefresh(); +} + +void ApplicationData::ModifyProperty(PProperty prop, wxString str) +{ + PObjectBase object = prop->GetObject(); - // Merge bitmaps and icons properties - PObjectBase thisProject = GetProjectData(); - PProperty prop = thisProject->GetProperty( _("bitmaps") ); - if ( prop ) - { - wxString value = prop->GetValue(); - value.Trim(); - value << wxT(" ") << project->GetPropertyAsString( _("bitmaps") ); - prop->SetValue( value ); - } - prop = thisProject->GetProperty( _("icons") ); - if ( prop ) - { - wxString value = prop->GetValue(); - value.Trim(); - value << wxT(" ") << project->GetPropertyAsString( _("icons") ); - prop->SetValue( value ); - } + if (str != prop->GetValue()) { + PCommand command(new ModifyPropertyCmd(prop, str)); + Execute(command); // m_cmdProc.Execute(command); - NotifyProjectRefresh(); + NotifyPropertyModified(prop); + } } -void ApplicationData::ModifyProperty( PProperty prop, wxString str ) +void ApplicationData::ModifyEventHandler(PEvent evt, wxString value) { - PObjectBase object = prop->GetObject(); + PObjectBase object = evt->GetObject(); - if ( str != prop->GetValue() ) - { - PCommand command( new ModifyPropertyCmd( prop, str ) ); - Execute( command ); //m_cmdProc.Execute(command); + if (value != evt->GetValue()) { + PCommand command(new ModifyEventHandlerCmd(evt, value)); + Execute(command); // m_cmdProc.Execute(command); - NotifyPropertyModified( prop ); - } + NotifyEventHandlerModified(evt); + } } -void ApplicationData::ModifyEventHandler( PEvent evt, wxString value ) +void ApplicationData::SaveProject(const wxString& filename) { - PObjectBase object = evt->GetObject(); + // Make sure this file is not already open + + if (!m_ipc->VerifySingleInstance(filename, false)) { + if ( + wxYES == wxMessageBox( + wxT("You cannot save over a file that is currently open in another instance.\nWould you like to " + "switch to that instance?"), + wxT("Open in Another Instance"), wxICON_QUESTION | wxYES_NO, wxTheApp->GetTopWindow())) { + m_ipc->VerifySingleInstance(filename, true); + } - if ( value != evt->GetValue() ) - { - PCommand command( new ModifyEventHandlerCmd( evt, value ) ); - Execute( command ); //m_cmdProc.Execute(command); + return; + } - NotifyEventHandlerModified( evt ); - } + try { + ticpp::Document doc; + m_project->Serialize(&doc); + doc.SaveFile(std::string(filename.mb_str(wxConvFile))); + + m_projectFile = filename; + SetProjectPath(::wxPathOnly(filename)); + m_modFlag = false; + m_cmdProc.SetSavePoint(); + NotifyProjectSaved(); + } catch (ticpp::Exception& ex) { + wxString message = _WXSTR(ex.m_details); + + if (message.empty()) { + message = wxString(ex.m_details.c_str(), wxConvFile); + } + + THROW_WXFBEX(message) + } } - -void ApplicationData::SaveProject( const wxString& filename ) -{ - // Make sure this file is not already open - - if ( !m_ipc->VerifySingleInstance( filename, false ) ) - { - if ( wxYES == wxMessageBox( wxT( "You cannot save over a file that is currently open in another instance.\nWould you like to switch to that instance?" ), - wxT( "Open in Another Instance" ), wxICON_QUESTION | wxYES_NO, wxTheApp->GetTopWindow() ) ) - { - m_ipc->VerifySingleInstance( filename, true ); - } - - return; - } - - try - { - ticpp::Document doc; - m_project->Serialize( &doc ); - doc.SaveFile( std::string( filename.mb_str( wxConvFile ) ) ); - - m_projectFile = filename; - SetProjectPath( ::wxPathOnly( filename ) ); - m_modFlag = false; - m_cmdProc.SetSavePoint(); - NotifyProjectSaved(); - } - catch ( ticpp::Exception& ex ) - { - wxString message = _WXSTR( ex.m_details ); - - if ( message.empty() ) - { - message = wxString( ex.m_details.c_str(), wxConvFile ); - } - - THROW_WXFBEX( message ) - } -} - -bool ApplicationData::LoadProject( const wxString &file, bool justGenerate ) - -{ - LogDebug( wxT( "LOADING" ) ); - - if ( !wxFileName::FileExists( file ) ) - { - wxLogError( wxT( "This file does not exist: %s" ), file ); - return false; - } - - if ( !justGenerate) - { - if ( !m_ipc->VerifySingleInstance( file ) ) - { - return false; - } - } - - try - { - ticpp::Document doc; - XMLUtils::LoadXMLFile( doc, false, file ); - - ticpp::Element* root = doc.FirstChildElement(); - - m_objDb->ResetObjectCounters(); - - int fbpVerMajor = 0; - int fbpVerMinor = 0; - - if ( root->Value() != std::string( "object" ) ) - { - try - { - ticpp::Element* fileVersion = root->FirstChildElement( "FileVersion" ); - fileVersion->GetAttributeOrDefault( "major", &fbpVerMajor, 0 ); - fileVersion->GetAttributeOrDefault( "minor", &fbpVerMinor, 0 ); - } - catch( ticpp::Exception& ) - { - } - } - - bool older = false; - bool newer = false; - - if ( m_fbpVerMajor == fbpVerMajor ) - { - older = ( fbpVerMinor < m_fbpVerMinor ); - newer = ( fbpVerMinor > m_fbpVerMinor ); - } - else - { - older = ( fbpVerMajor < m_fbpVerMajor ); - newer = ( fbpVerMajor > m_fbpVerMajor ); - } - - if ( newer ) - { - if( justGenerate ){ - wxLogError( wxT( "This project file is newer than this version of wxFormBuilder.\n" ) ); - }else{ - wxMessageBox( wxT( "This project file is newer than this version of wxFormBuilder.\n" ) - wxT( "It cannot be opened.\n\n" ) - wxT( "Please download an updated version from http://www.wxFormBuilder.org" ), _( "New Version" ), wxICON_ERROR ); - } - return false; - } - - if ( older ) - { - if( justGenerate ){ - wxLogError( wxT( "This project file is out of date. Update your .fbp before using --generate" ) ); - return false; - } - - wxMessageBox( - _("This project file is using an older file format, it will be updated during loading.\n\n" - "WARNING: Saving the project will update the format of the project file on disk!"), - _("Older file format")); - - if (ConvertProject(doc, file, fbpVerMajor, fbpVerMinor)) - { - // Document has changed -- reacquire the root node - root = doc.FirstChildElement(); - } - else - { - wxLogError(wxT("Unable to convert project")); - return false; - } - } - - ticpp::Element* object = root->FirstChildElement( "object" ); - PObjectBase proj; - - try - { - proj = m_objDb->CreateObject( object ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - return false; - } - - if ( proj && proj->GetObjectTypeName() == wxT( "project" ) ) - { - PObjectBase old_proj = m_project; - m_project = proj; - m_selObj = m_project; - // Set the modification to true if the project was older and has been converted - m_modFlag = older; - m_cmdProc.Reset(); - m_projectFile = file; - SetProjectPath( ::wxPathOnly( file ) ); - NotifyProjectLoaded(); - NotifyProjectRefresh(); - } - } - catch( ticpp::Exception& ex ) - { - wxLogError( _WXSTR( ex.m_details ) ); - return false; - } - - return true; + +bool ApplicationData::LoadProject(const wxString& file, bool justGenerate) + +{ + LogDebug(wxT("LOADING")); + + if (!wxFileName::FileExists(file)) { + wxLogError(wxT("This file does not exist: %s"), file); + return false; + } + + if (!justGenerate) { + if (!m_ipc->VerifySingleInstance(file)) { + return false; + } + } + + try { + ticpp::Document doc; + XMLUtils::LoadXMLFile(doc, false, file); + + ticpp::Element* root = doc.FirstChildElement(); + + m_objDb->ResetObjectCounters(); + + int fbpVerMajor = 0; + int fbpVerMinor = 0; + + if (root->Value() != std::string("object")) { + try { + ticpp::Element* fileVersion = root->FirstChildElement("FileVersion"); + fileVersion->GetAttributeOrDefault("major", &fbpVerMajor, 0); + fileVersion->GetAttributeOrDefault("minor", &fbpVerMinor, 0); + } catch (ticpp::Exception&) { + } + } + + bool older = false; + bool newer = false; + + if (m_fbpVerMajor == fbpVerMajor) { + older = (fbpVerMinor < m_fbpVerMinor); + newer = (fbpVerMinor > m_fbpVerMinor); + } else { + older = (fbpVerMajor < m_fbpVerMajor); + newer = (fbpVerMajor > m_fbpVerMajor); + } + + if (newer) { + if (justGenerate) { + wxLogError(wxT("This project file is newer than this version of wxFormBuilder.\n")); + } else { + wxMessageBox( + wxT("This project file is newer than this version of wxFormBuilder.\n") + wxT("It cannot be opened.\n\n") + wxT("Please download an updated version from http://www.wxFormBuilder.org"), + _("New Version"), wxICON_ERROR); + } + return false; + } + + if (older) { + if (justGenerate) { + wxLogError(wxT("This project file is out of date. Update your .fbp before using --generate")); + return false; + } + + wxMessageBox( + _("This project file is using an older file format, it will be updated during loading.\n\n" + "WARNING: Saving the project will update the format of the project file on disk!"), + _("Older file format")); + + if (ConvertProject(doc, file, fbpVerMajor, fbpVerMinor)) { + // Document has changed -- reacquire the root node + root = doc.FirstChildElement(); + } else { + wxLogError(wxT("Unable to convert project")); + return false; + } + } + + ticpp::Element* object = root->FirstChildElement("object"); + PObjectBase proj; + + try { + proj = m_objDb->CreateObject(object); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + return false; + } + + if (proj && proj->GetObjectTypeName() == wxT("project")) { + PObjectBase old_proj = m_project; + m_project = proj; + m_selObj = m_project; + // Set the modification to true if the project was older and has been converted + m_modFlag = older; + m_cmdProc.Reset(); + m_projectFile = file; + SetProjectPath(::wxPathOnly(file)); + NotifyProjectLoaded(); + NotifyProjectRefresh(); + } + } catch (ticpp::Exception& ex) { + wxLogError(_WXSTR(ex.m_details)); + return false; + } + + return true; } bool ApplicationData::ConvertProject(ticpp::Document& doc, const wxString& path, int fileMajor, int fileMinor) { - try - { - XMLUtils::LoadXMLFile( doc, false, path ); - - ticpp::Element* root = doc.FirstChildElement(); - if ( root->Value() == std::string( "object" ) ) - { - ConvertProjectProperties( root, path, fileMajor, fileMinor ); - ConvertObject( root, fileMajor, fileMinor ); - - // Create a clone of now-converted object tree, so it can be linked - // underneath the root element - std::unique_ptr objectTree = root->Clone(); - - // Clear the document to add the declaration and the root element - doc.Clear(); - - // Add the declaration - doc.LinkEndChild( new ticpp::Declaration( "1.0", "UTF-8", "yes" ) ); - - // Add the root element, with file version - ticpp::Element* newRoot = new ticpp::Element( "wxFormBuilder_Project" ); - - ticpp::Element* fileVersion = new ticpp::Element( "FileVersion" ); - fileVersion->SetAttribute( "major", m_fbpVerMajor ); - fileVersion->SetAttribute( "minor", m_fbpVerMinor ); - - newRoot->LinkEndChild( fileVersion ); - - // Add the object tree - newRoot->LinkEndChild( objectTree.release() ); - - doc.LinkEndChild( newRoot ); - } - else - { - // Handle project separately because it only occurs once - ticpp::Element* project = root->FirstChildElement( "object" ); - ConvertProjectProperties( project, path, fileMajor, fileMinor ); - ConvertObject( project, fileMajor, fileMinor ); - ticpp::Element* fileVersion = root->FirstChildElement( "FileVersion" ); - fileVersion->SetAttribute( "major", m_fbpVerMajor ); - fileVersion->SetAttribute( "minor", m_fbpVerMinor ); - } - } - catch ( ticpp::Exception& ex ) - { - wxLogError( _WXSTR( ex.m_details ) ); - return false; - } - - return true; -} - -void ApplicationData::ConvertProjectProperties( ticpp::Element* project, const wxString& path, int fileMajor, int fileMinor ) - -{ - // Ensure that this is the "project" element - std::string objClass; - project->GetAttribute( "class", &objClass ); - - if ( objClass != "Project" ) - { - return; - } - - // Reusable sets for finding properties - std::set< std::string > oldProps; - std::set< ticpp::Element* > newProps; - - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 5 ) ) - { - // Find the user_headers property - - oldProps.insert( "user_headers" ); - GetPropertiesToConvert( project, oldProps, &newProps ); - - std::string user_headers; - if ( !newProps.empty() ) - { - user_headers = ( *newProps.begin() )->GetText( false ); - project->RemoveChild( *newProps.begin() ); - } - - if ( !user_headers.empty() ) - { - wxString msg = _( "The \"user_headers\" property has been removed.\n" ); - msg += _( "Its purpose was to provide a place to include precompiled headers or\n" ); - msg += _( "headers for subclasses.\n" ); - msg += _( "There is now a \"precompiled_header\" property and a \"header\" subitem\n" ); - msg += _( "on the subclass property.\n\n" ); - msg += _( "Would you like the current value of the \"user_headers\" property to be saved\n" ); - msg += _( "to a file so that you can distribute the headers among the \"precompiled_header\"\n" ); - msg += _( "and \"subclass\" properties\?" ); - - if ( wxYES == wxMessageBox( msg, _( "The \"user_headers\" property has been removed" ), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) ) - { - wxString name; - wxFileName::SplitPath( path, NULL, NULL, &name, NULL ); - wxFileDialog dialog( wxTheApp->GetTopWindow(), _( "Save \"user_headers\"" ), ::wxPathOnly( path ), - name + wxT( "_user_headers.txt" ), wxT( "All files (*.*)|*.*" ), wxFD_SAVE ); - - if ( dialog.ShowModal() == wxID_OK ) - { - wxString wxuser_headers = _WXSTR( user_headers ); - wxString filename = dialog.GetPath(); - bool success = false; - wxFFile output( filename, wxT( "w" ) ); - - if ( output.IsOpened() ) - { - if ( output.Write( wxuser_headers ) ) - { - output.Close(); - success = true; - } - } - - if ( !success ) - { - wxLogError( _( "Unable to open %s for writing.\nUser Headers:\n%s" ), filename, wxuser_headers ); - } - } - } - } - } - - - // The pch property is now the exact code to be generated, not just the header filename - // The goal of this conversion block is to determine which of two possible pch blocks to use - // The pch block that wxFB generated changed in version 1.6 - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 8 ) ) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert( "precompiled_header" ); - GetPropertiesToConvert( project, oldProps, &newProps ); - - if ( !newProps.empty() ) - { - std::string pch = ( *newProps.begin() )->GetText( false ); - if ( !pch.empty() ) - { - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 6 ) ) - { - // use the older block - ( *newProps.begin() )->SetText( - "#include \"" + pch + "\"" - "\n" - "\n#ifdef __BORLANDC__" - "\n#pragma hdrstop" - "\n#endif //__BORLANDC__" - "\n" - "\n#ifndef WX_PRECOMP" - "\n#include " - "\n#endif //WX_PRECOMP" - ); - } - else - { - // use the newer block - ( *newProps.begin() )->SetText( - "#ifdef WX_PRECOMP" - "\n" - "\n#include \"" + pch + "\"" - "\n" - "\n#ifdef __BORLANDC__" - "\n#pragma hdrstop" - "\n#endif //__BORLANDC__" - "\n" - "\n#else" - "\n#include " - "\n#endif //WX_PRECOMP" - ); - } - } - } - } - - // The format of string list properties changed in version 1.9 - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 9 ) ) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert( "namespace" ); - oldProps.insert( "bitmaps" ); - oldProps.insert( "icons" ); - GetPropertiesToConvert( project, oldProps, &newProps ); - - std::set< ticpp::Element* >::iterator prop; - for ( prop = newProps.begin(); prop != newProps.end(); ++prop ) - { - std::string value = ( *prop )->GetText( false ); - if ( !value.empty() ) - { - wxArrayString array = TypeConv::OldStringToArrayString( _WXSTR( value ) ); - ( *prop )->SetText( _STDSTR( TypeConv::ArrayStringToString( array ) ) ); - } - } - } - - // event_handler moved to the forms in version 1.10 - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 10 ) ) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert( "event_handler" ); - GetPropertiesToConvert( project, oldProps, &newProps ); - - - if ( !newProps.empty() ) - { - ticpp::Iterator< ticpp::Element > object( "object" ); - for ( object = project->FirstChildElement( "object", false ); object != object.end(); ++object ) - { - object->LinkEndChild( ( *newProps.begin() )->Clone().get() ); - } - - project->RemoveChild( *newProps.begin() ); - } - } -} - -void ApplicationData::ConvertObject( ticpp::Element* parent, int fileMajor, int fileMinor ) -{ - ticpp::Iterator< ticpp::Element > object( "object" ); - - for ( object = parent->FirstChildElement( "object", false ); object != object.end(); ++object ) - { - ConvertObject( object.Get(), fileMajor, fileMinor ); - } - - // Reusable sets to find properties with - std::set< std::string > oldProps; - - std::set< ticpp::Element* > newProps; - - std::set< ticpp::Element* >::iterator newProp; - - // Get the class of the object - std::string objClass; - - parent->GetAttribute( "class", &objClass ); - - /* The changes below will convert an unversioned file to version 1.3 */ - - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 3 ) ) - { - // The property 'option' became 'proportion' - - if ( objClass == "sizeritem" || objClass == "gbsizeritem" || objClass == "spacer" ) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert( "option" ); - GetPropertiesToConvert( parent, oldProps, &newProps ); - - if ( !newProps.empty() ) - { - // One in, one out - ( *newProps.begin() )->SetAttribute( "name", "proportion" ); - } - } - - // The 'style' property used to have both wxWindow styles and the styles of the specific controls - // now it only has the styles of the specific controls, and wxWindow styles are saved in window_style - // This also applies to 'extra_style', which was once combined with 'style'. - // And they were named 'WindowStyle' and one point, too... - - std::set< wxString > windowStyles; - windowStyles.insert( wxT( "wxSIMPLE_BORDER" ) ); - windowStyles.insert( wxT( "wxDOUBLE_BORDER" ) ); - windowStyles.insert( wxT( "wxSUNKEN_BORDER" ) ); - windowStyles.insert( wxT( "wxRAISED_BORDER" ) ); - windowStyles.insert( wxT( "wxSTATIC_BORDER" ) ); - windowStyles.insert( wxT( "wxNO_BORDER" ) ); - windowStyles.insert( wxT( "wxTRANSPARENT_WINDOW" ) ); - windowStyles.insert( wxT( "wxTAB_TRAVERSAL" ) ); - windowStyles.insert( wxT( "wxWANTS_CHARS" ) ); - windowStyles.insert( wxT( "wxVSCROLL" ) ); - windowStyles.insert( wxT( "wxHSCROLL" ) ); - windowStyles.insert( wxT( "wxALWAYS_SHOW_SB" ) ); - windowStyles.insert( wxT( "wxCLIP_CHILDREN" ) ); - windowStyles.insert( wxT( "wxFULL_REPAINT_ON_RESIZE" ) ); - - // Transfer the window styles - oldProps.clear(); - newProps.clear(); - - oldProps.insert( "style" ); - - oldProps.insert( "WindowStyle" ); - - GetPropertiesToConvert( parent, oldProps, &newProps ); - - for ( newProp = newProps.begin(); newProp != newProps.end(); ++newProp ) - { - TransferOptionList( *newProp, &windowStyles, "window_style" ); - } - - - std::set< wxString > extraWindowStyles; - extraWindowStyles.insert( wxT( "wxWS_EX_VALIDATE_RECURSIVELY" ) ); - extraWindowStyles.insert( wxT( "wxWS_EX_BLOCK_EVENTS" ) ); - extraWindowStyles.insert( wxT( "wxWS_EX_TRANSIENT" ) ); - extraWindowStyles.insert( wxT( "wxWS_EX_PROCESS_IDLE" ) ); - extraWindowStyles.insert( wxT( "wxWS_EX_PROCESS_UI_UPDATES" ) ); - - // Transfer the window extra styles - oldProps.clear(); - newProps.clear(); - - oldProps.insert( "style" ); - - oldProps.insert( "extra_style" ); - - oldProps.insert( "WindowStyle" ); - - GetPropertiesToConvert( parent, oldProps, &newProps ); - - for ( newProp = newProps.begin(); newProp != newProps.end(); ++newProp ) - { - TransferOptionList( *newProp, &extraWindowStyles, "window_extra_style" ); - } - } - - /* The file is now at least version 1.3 */ - - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 4 ) ) - { - if ( objClass == "wxCheckList" ) - { - // The class we once named "wxCheckList" really represented a "wxCheckListBox", now that we use the #class macro in - // code generation, it generates the wrong code - parent->SetAttribute( "class", "wxCheckListBox" ); - } - } - - /* The file is now at least version 1.4 */ - - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 6 ) ) - { - if ( objClass == "spacer" ) - { - // spacer used to be represented by its own class, it is now under a sizeritem like everything else. - // no need to check for a wxGridBagSizer, because it was introduced at the same time. - - // the goal is to change the class to sizeritem, then create a spacer child, then move "width" and "height" to the spacer - parent->SetAttribute( "class", "sizeritem" ); - ticpp::Element spacer( "object" ); - spacer.SetAttribute( "class", "spacer" ); - - oldProps.clear(); - newProps.clear(); - oldProps.insert( "width" ); - GetPropertiesToConvert( parent, oldProps, &newProps ); - - if ( !newProps.empty() ) - { - // One in, one out - ticpp::Element* width = *newProps.begin(); - spacer.LinkEndChild( width->Clone().release() ); - parent->RemoveChild( width ); - } - - oldProps.clear(); - newProps.clear(); - oldProps.insert( "height" ); - GetPropertiesToConvert( parent, oldProps, &newProps ); - - if ( !newProps.empty() ) - { - // One in, one out - ticpp::Element* height = *newProps.begin(); - spacer.LinkEndChild( height->Clone().release() ); - parent->RemoveChild( height ); - } - parent->LinkEndChild( &spacer ); - } - } - - /* The file is now at least version 1.6 */ - - // Version 1.7 now stores all font properties. - // The font property conversion is automatic because it is just an extension of the old values. - - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 7 ) ) - { - // Remove deprecated 2.6 things - - // wxDialog styles wxTHICK_FRAME and wxNO_3D - if ( objClass == "Dialog" ) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert( "style" ); - GetPropertiesToConvert( parent, oldProps, &newProps ); - - if ( !newProps.empty() ) - { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR( style->GetText( false ) ); - if ( !styles.empty() ) - { - if ( TypeConv::FlagSet( wxT("wxTHICK_FRAME"), styles ) ) - { - styles = TypeConv::ClearFlag( wxT("wxTHICK_FRAME"), styles ); - styles = TypeConv::SetFlag( wxT("wxRESIZE_BORDER"), styles ); - } - - styles = TypeConv::ClearFlag( wxT("wxNO_3D"), styles ); - style->SetText( _STDSTR( styles ) ); - } - } - } - } - - /* The file is now at least version 1.7 */ - - // The update to 1.8 only affected project properties - // See ConvertProjectProperties - - /* The file is now at least version 1.8 */ - - // stringlist properties are stored in a different format as of version 1.9 - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 9 ) ) - { - oldProps.clear(); - newProps.clear(); - - if ( objClass == "wxComboBox" || - objClass == "wxChoice" || - objClass == "wxListBox" || - objClass == "wxRadioBox" || - objClass == "wxCheckListBox" - ) - { - oldProps.insert( "choices" ); - } - else if ( objClass == "wxGrid" ) - { - oldProps.insert( "col_label_values" ); - oldProps.insert( "row_label_values" ); - } - - if ( !oldProps.empty() ) - { - GetPropertiesToConvert( parent, oldProps, &newProps ); - - std::set< ticpp::Element* >::iterator prop; - for ( prop = newProps.begin(); prop != newProps.end(); ++prop ) - { - std::string value = ( *prop )->GetText( false ); - if ( !value.empty() ) - { - wxArrayString array = TypeConv::OldStringToArrayString( _WXSTR( value ) ); - ( *prop )->SetText( _STDSTR( TypeConv::ArrayStringToString( array ) ) ); - } - } - } - } - - /* The file is now at least version 1.9 */ - - // Version 1.11 now stores bitmap property in the following format: - // 'source'; 'data' instead of old form 'data'; 'source'. - - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 11 ) ) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert( "bitmap" ); - GetPropertiesToConvert( parent, oldProps, &newProps ); - - std::set< ticpp::Element* >::iterator prop; - for ( prop = newProps.begin(); prop != newProps.end(); ++prop ) - { - ticpp::Element* bitmap = *prop; - - wxString image = _WXSTR( bitmap->GetText( false ) ); - if ( !image.empty() ) - { - if( image.AfterLast( ';' ).Contains( _("Load From") ) ) - { - wxString source = image.AfterLast( ';' ).Trim().Trim(false); - wxString data = image.BeforeLast( ';' ).Trim().Trim(false); - - bitmap->SetText( _STDSTR( source + wxT("; ") + data ) ); - } - } - } - - /* oldProps.clear(); - newProps.clear(); - oldProps.insert( "choices" ); - GetPropertiesToConvert( parent, oldProps, &newProps ); - - for ( prop = newProps.begin(); prop != newProps.end(); ++prop ) - { - ticpp::Element* choices = *prop; - - wxString content = _WXSTR( choices->GetText( false ) ); - if ( !content.empty() ) - { - content.Replace( wxT("\" \""), wxT(";") ); - content.Replace( wxT("\""), wxT("") ); - - choices->SetText( _STDSTR( content ) ); - } - }*/ - } - - /* The file is now at least version 1.11 */ - if ( fileMajor < 1 || ( 1 == fileMajor && fileMinor < 12 ) ) - { - bool classUpdated = false; - if( "wxScintilla" == objClass ) - { - objClass = "wxStyledTextCtrl"; - parent->SetAttribute( "class", objClass ); - classUpdated = true; - } - if( "wxTreeListCtrl" == objClass ) - { - objClass = "wxadditions::wxTreeListCtrl"; - parent->SetAttribute( "class", objClass ); - classUpdated = true; - } - if( "wxTreeListCtrlColumn" == objClass ) - { - objClass = "wxadditions::wxTreeListCtrlColumn"; - parent->SetAttribute( "class", objClass ); - classUpdated = true; - } - if( m_warnOnAdditionsUpdate && classUpdated ) - { - m_warnOnAdditionsUpdate = false; - wxLogWarning( _("Updated classes from wxAdditions. You must use the latest version of wxAdditions to continue.\nNote wxScintilla is now wxStyledListCtrl, wxTreeListCtrl is now wxadditions::wxTreeListCtrl, and wxTreeListCtrlColumn is now wxadditions::wxTreeListCtrlColumn") ); - } - - typedef std::map< std::string, std::set< std::string > > PropertiesToRemove; - - static std::set< std::string > propertyRemovalWarnings; - const PropertiesToRemove& propertiesToRemove = GetPropertiesToRemove_v1_12(); - PropertiesToRemove::const_iterator it = propertiesToRemove.find( objClass ); - if( it != propertiesToRemove.end() ) - { - RemoveProperties( parent, it->second ); - if( 0 == propertyRemovalWarnings.count( objClass ) ) - { - std::stringstream ss; - std::ostream_iterator< std::string > out_it (ss, ", "); - std::copy( it->second.begin(), it->second.end(), out_it ); - - wxLogMessage( _("Removed properties for class %s because they are no longer supported: %s"), objClass, ss.str() ); - propertyRemovalWarnings.insert( objClass ); - } - } - } - - /* The file is now at least version 1.12 */ - // TODO: Dont know where Version 1.13 comes from, so this is for Version 1.14 - if (fileMajor < 1 || (1 == fileMajor && fileMinor < 14)) { - // Rename all wx*_BORDER-Styles to wxBORDER_*-Styles and remove wxDOUBLE_BORDER - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - oldProps.insert("window_style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - for (newProp = newProps.begin(); newProp != newProps.end(); ++newProp) { - wxString styles = _WXSTR((*newProp)->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxSIMPLE_BORDER"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxSIMPLE_BORDER"), styles); - styles = TypeConv::SetFlag(wxT("wxBORDER_SIMPLE"), styles); - } - - if (TypeConv::FlagSet(wxT("wxDOUBLE_BORDER"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxDOUBLE_BORDER"), styles); - } - - if (TypeConv::FlagSet(wxT("wxSUNKEN_BORDER"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxSUNKEN_BORDER"), styles); - styles = TypeConv::SetFlag(wxT("wxBORDER_SUNKEN"), styles); - } - - if (TypeConv::FlagSet(wxT("wxRAISED_BORDER"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxRAISED_BORDER"), styles); - styles = TypeConv::SetFlag(wxT("wxBORDER_RAISED"), styles); - } - - if (TypeConv::FlagSet(wxT("wxSTATIC_BORDER"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxSTATIC_BORDER"), styles); - styles = TypeConv::SetFlag(wxT("wxBORDER_STATIC"), styles); - } - - if (TypeConv::FlagSet(wxT("wxNO_BORDER"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxNO_BORDER"), styles); - styles = TypeConv::SetFlag(wxT("wxBORDER_NONE"), styles); - } - - (*newProp)->SetText(_STDSTR(styles)); - } - } - - // wxBitmapButton: Remove wxBU_AUTODRAW and rename properties selected->pressed, - // hover->current - if ("wxBitmapButton" == objClass) { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxBU_AUTODRAW"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxBU_AUTODRAW"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - - oldProps.clear(); - newProps.clear(); - oldProps.insert("selected"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { (*newProps.begin())->SetAttribute("name", "pressed"); } - - oldProps.clear(); - newProps.clear(); - oldProps.insert("hover"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { (*newProps.begin())->SetAttribute("name", "current"); } - } - - // wxStaticText: Rename wxALIGN_CENTRE -> wxALIGN_CENTER_HORIZONTAL - else if ("wxStaticText" == objClass) { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxALIGN_CENTRE"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxALIGN_CENTRE"), styles); - styles = TypeConv::SetFlag(wxT("wxALIGN_CENTER_HORIZONTAL"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - - // wxRadioBox: Remove wxRA_USE_CHECKBOX - else if ("wxRadioBox" == objClass) { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxRA_USE_CHECKBOX"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxRA_USE_CHECKBOX"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - - // wxRadioButton: Remove wxRB_USE_CHECKBOX - else if ("wxRadioButton" == objClass) { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxRB_USE_CHECKBOX"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxRB_USE_CHECKBOX"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - - // wxStatusBar: Rename wxST_SIZEGRIP -> wxSTB_SIZEGRIP - else if ("wxStatusBar" == objClass) { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxST_SIZEGRIP"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxST_SIZEGRIP"), styles); - styles = TypeConv::SetFlag(wxT("wxSTB_SIZEGRIP"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - - // wxMenuBar: Remove wxMB_DOCKABLE - else if ("wxMenuBar" == objClass) { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) { - ticpp::Element* style = *newProps.begin(); - wxString styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) { - if (TypeConv::FlagSet(wxT("wxMB_DOCKABLE"), styles)) { - styles = TypeConv::ClearFlag(wxT("wxMB_DOCKABLE"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - } - - /* The file is now at least version 1.14 */ - if (fileMajor < 1 || (1 == fileMajor && fileMinor < 15)) - { - // Rename wxTE_CENTRE -> wxTE_CENTER - if ("wxTextCtrl" == objClass || "wxSearchCtrl" == objClass) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) - { - auto* style = *newProps.begin(); - auto styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) - { - if (TypeConv::FlagSet(wxT("wxTE_CENTRE"), styles)) - { - styles = TypeConv::ClearFlag(wxT("wxTE_CENTRE"), styles); - styles = TypeConv::SetFlag(wxT("wxTE_CENTER"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - // Rename wxALIGN_CENTRE -> wxALIGN_CENTER - else if ("wxGrid" == objClass) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert("col_label_horiz_alignment"); - oldProps.insert("col_label_vert_alignment"); - oldProps.insert("row_label_horiz_alignment"); - oldProps.insert("row_label_vert_alignment"); - oldProps.insert("cell_horiz_alignment"); - oldProps.insert("cell_vert_alignment"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - for (newProp = newProps.begin(); newProp != newProps.end(); ++newProp) - { - auto styles = _WXSTR((*newProp)->GetText(false)); - if (!styles.empty()) - { - if (TypeConv::FlagSet(wxT("wxALIGN_CENTRE"), styles)) - { - styles = TypeConv::ClearFlag(wxT("wxALIGN_CENTRE"), styles); - styles = TypeConv::SetFlag(wxT("wxALIGN_CENTER"), styles); - } - - (*newProp)->SetText(_STDSTR(styles)); - } - } - } - // wxNotebook: Remove wxNB_FLAT - else if ("wxNotebook" == objClass) - { - oldProps.clear(); - newProps.clear(); - oldProps.insert("style"); - GetPropertiesToConvert(parent, oldProps, &newProps); - - if (!newProps.empty()) - { - auto* style = *newProps.begin(); - auto styles = _WXSTR(style->GetText(false)); - if (!styles.empty()) - { - if (TypeConv::FlagSet(wxT("wxNB_FLAT"), styles)) - { - styles = TypeConv::ClearFlag(wxT("wxNB_FLAT"), styles); - } - - style->SetText(_STDSTR(styles)); - } - } - } - } - - /* The file is now at least version 1.15 */ - if (fileMajor < 1 || (fileMajor == 1 && fileMinor < 16)) - { - static bool showRemovalWarnings = true; - if (objClass == "wxMenuBar") - { - RemoveProperties(parent, std::set{"label"}); - if (showRemovalWarnings) - { - wxLogMessage(_("Removed property label for class wxMenuBar because it is no longer used")); - showRemovalWarnings = false; - } - } - } -} - -void ApplicationData::GetPropertiesToConvert( ticpp::Node* parent, const std::set< std::string >& names, std::set< ticpp::Element* >* properties ) -{ - // Clear result set - properties->clear(); - - ticpp::Iterator< ticpp::Element > prop( "property" ); - - for ( prop = parent->FirstChildElement( "property", false ); prop != prop.end(); ++prop ) - { - std::string name; - prop->GetAttribute( "name", &name ); - - if ( names.find( name ) != names.end() ) - { - properties->insert( prop.Get() ); - } - } -} - -void ApplicationData::RemoveProperties( ticpp::Node* parent, const std::set< std::string >& names ) -{ - ticpp::Iterator< ticpp::Element > prop( "property" ); - - for ( prop = parent->FirstChildElement( "property", false ); prop != prop.end(); ) - { - ticpp::Element element = *prop; - ++prop; - - std::string name; - element.GetAttribute( "name", &name ); - - if ( names.find( name ) != names.end() ) - { - parent->RemoveChild( &element ); - } - } -} - -void ApplicationData::TransferOptionList( ticpp::Element* prop, std::set< wxString >* options, const std::string& newPropName ) - -{ - wxString value = _WXSTR( prop->GetText( false ) ); - - std::set< wxString > transfer; - - std::set< wxString > keep; - - // Sort options - if in the 'options' set, they should be transferred to a property named 'newPropName' - // otherwise, they should stay - wxStringTokenizer tkz( value, wxT( "|" ), wxTOKEN_RET_EMPTY_ALL ); - - while ( tkz.HasMoreTokens() ) - { - wxString option = tkz.GetNextToken(); - option.Trim( false ); - option.Trim( true ); - - if ( options->find( option ) != options->end() ) - { - // Needs to be transferred - transfer.insert( option ); - } - else - { - // Should be kept - keep.insert( option ); - } - } - - // Reusable sets to find properties with - std::set< std::string > oldProps; - - std::set< ticpp::Element* > newProps; + try { + XMLUtils::LoadXMLFile(doc, false, path); + + ticpp::Element* root = doc.FirstChildElement(); + if (root->Value() == std::string("object")) { + ConvertProjectProperties(root, path, fileMajor, fileMinor); + ConvertObject(root, fileMajor, fileMinor); + + // Create a clone of now-converted object tree, so it can be linked + // underneath the root element + std::unique_ptr objectTree = root->Clone(); + + // Clear the document to add the declaration and the root element + doc.Clear(); + + // Add the declaration + doc.LinkEndChild(new ticpp::Declaration("1.0", "UTF-8", "yes")); + + // Add the root element, with file version + ticpp::Element* newRoot = new ticpp::Element("wxFormBuilder_Project"); + + ticpp::Element* fileVersion = new ticpp::Element("FileVersion"); + fileVersion->SetAttribute("major", m_fbpVerMajor); + fileVersion->SetAttribute("minor", m_fbpVerMinor); + + newRoot->LinkEndChild(fileVersion); + + // Add the object tree + newRoot->LinkEndChild(objectTree.release()); + + doc.LinkEndChild(newRoot); + } else { + // Handle project separately because it only occurs once + ticpp::Element* project = root->FirstChildElement("object"); + ConvertProjectProperties(project, path, fileMajor, fileMinor); + ConvertObject(project, fileMajor, fileMinor); + ticpp::Element* fileVersion = root->FirstChildElement("FileVersion"); + fileVersion->SetAttribute("major", m_fbpVerMajor); + fileVersion->SetAttribute("minor", m_fbpVerMinor); + } + } catch (ticpp::Exception& ex) { + wxLogError(_WXSTR(ex.m_details)); + return false; + } + + return true; +} + +void ApplicationData::ConvertProjectProperties( + ticpp::Element* project, const wxString& path, int fileMajor, int fileMinor) + +{ + // Ensure that this is the "project" element + std::string objClass; + project->GetAttribute("class", &objClass); - // If there are any to transfer, add to the target property, or make a new one - ticpp::Node* parent = prop->Parent(); + if (objClass != "Project") { + return; + } - if ( !transfer.empty() ) - { - // Check for the target property - ticpp::Element* newProp; - wxString newOptionList; + // Reusable sets for finding properties + std::set oldProps; + std::set newProps; - oldProps.clear(); - oldProps.insert( newPropName ); - GetPropertiesToConvert( parent, oldProps, &newProps ); + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 5)) { + // Find the user_headers property - std::unique_ptr tmpProp; - if ( !newProps.empty() ) - { - newProp = *newProps.begin(); - newOptionList << wxT( "|" ) << _WXSTR( newProp->GetText( false ) ); - } - else - { - tmpProp = std::make_unique("property"); - newProp = tmpProp.get(); - newProp->SetAttribute( "name", newPropName ); - } + oldProps.insert("user_headers"); + GetPropertiesToConvert(project, oldProps, &newProps); - std::set< wxString >::iterator option; + std::string user_headers; + if (!newProps.empty()) { + user_headers = (*newProps.begin())->GetText(false); + project->RemoveChild(*newProps.begin()); + } - for ( option = transfer.begin(); option != transfer.end(); ++option ) - { - newOptionList << wxT( "|" ) << *option; - } + if (!user_headers.empty()) { + wxString msg = _("The \"user_headers\" property has been removed.\n"); + msg += _("Its purpose was to provide a place to include precompiled headers or\n"); + msg += _("headers for subclasses.\n"); + msg += _("There is now a \"precompiled_header\" property and a \"header\" subitem\n"); + msg += _("on the subclass property.\n\n"); + msg += _("Would you like the current value of the \"user_headers\" property to be saved\n"); + msg += _("to a file so that you can distribute the headers among the \"precompiled_header\"\n"); + msg += _("and \"subclass\" properties\?"); + + if ( + wxYES == wxMessageBox( + msg, _("The \"user_headers\" property has been removed"), + wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow())) { + wxString name; + wxFileName::SplitPath(path, NULL, NULL, &name, NULL); + wxFileDialog dialog( + wxTheApp->GetTopWindow(), _("Save \"user_headers\""), ::wxPathOnly(path), + name + wxT("_user_headers.txt"), wxT("All files (*.*)|*.*"), wxFD_SAVE); + + if (dialog.ShowModal() == wxID_OK) { + wxString wxuser_headers = _WXSTR(user_headers); + wxString filename = dialog.GetPath(); + bool success = false; + wxFFile output(filename, wxT("w")); + + if (output.IsOpened()) { + if (output.Write(wxuser_headers)) { + output.Close(); + success = true; + } + } + + if (!success) { + wxLogError(_("Unable to open %s for writing.\nUser Headers:\n%s"), filename, wxuser_headers); + } + } + } + } + } - newProp->SetText( _STDSTR( newOptionList.substr( 1 ) ) ); - if ( newProps.empty() ) - { - parent->InsertBeforeChild( prop, *newProp ); - } - } + // The pch property is now the exact code to be generated, not just the header filename + // The goal of this conversion block is to determine which of two possible pch blocks to use + // The pch block that wxFB generated changed in version 1.6 + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 8)) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("precompiled_header"); + GetPropertiesToConvert(project, oldProps, &newProps); + + if (!newProps.empty()) { + std::string pch = (*newProps.begin())->GetText(false); + if (!pch.empty()) { + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 6)) { + // use the older block + (*newProps.begin()) + ->SetText( + "#include \"" + pch + + "\"" + "\n" + "\n#ifdef __BORLANDC__" + "\n#pragma hdrstop" + "\n#endif //__BORLANDC__" + "\n" + "\n#ifndef WX_PRECOMP" + "\n#include " + "\n#endif //WX_PRECOMP"); + } else { + // use the newer block + (*newProps.begin()) + ->SetText( + "#ifdef WX_PRECOMP" + "\n" + "\n#include \"" + + pch + + "\"" + "\n" + "\n#ifdef __BORLANDC__" + "\n#pragma hdrstop" + "\n#endif //__BORLANDC__" + "\n" + "\n#else" + "\n#include " + "\n#endif //WX_PRECOMP"); + } + } + } + } - // Set the value of the property to whatever is left - if ( keep.empty() ) - { - parent->RemoveChild( prop ); - } - else - { + // The format of string list properties changed in version 1.9 + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 9)) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("namespace"); + oldProps.insert("bitmaps"); + oldProps.insert("icons"); + GetPropertiesToConvert(project, oldProps, &newProps); + + std::set::iterator prop; + for (prop = newProps.begin(); prop != newProps.end(); ++prop) { + std::string value = (*prop)->GetText(false); + if (!value.empty()) { + wxArrayString array = TypeConv::OldStringToArrayString(_WXSTR(value)); + (*prop)->SetText(_STDSTR(TypeConv::ArrayStringToString(array))); + } + } + } - std::set< wxString >::iterator option; + // event_handler moved to the forms in version 1.10 + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 10)) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("event_handler"); + GetPropertiesToConvert(project, oldProps, &newProps); - wxString newOptionList; - for ( option = keep.begin(); option != keep.end(); ++option ) - { - newOptionList << wxT( "|" ) << *option; - } + if (!newProps.empty()) { + ticpp::Iterator object("object"); + for (object = project->FirstChildElement("object", false); object != object.end(); ++object) { + object->LinkEndChild((*newProps.begin())->Clone().get()); + } - prop->SetText( _STDSTR( newOptionList.substr( 1 ) ) ); - } + project->RemoveChild(*newProps.begin()); + } + } +} + +void ApplicationData::ConvertObject(ticpp::Element* parent, int fileMajor, int fileMinor) +{ + ticpp::Iterator object("object"); + + for (object = parent->FirstChildElement("object", false); object != object.end(); ++object) { + ConvertObject(object.Get(), fileMajor, fileMinor); + } + + // Reusable sets to find properties with + std::set oldProps; + + std::set newProps; + + std::set::iterator newProp; + + // Get the class of the object + std::string objClass; + + parent->GetAttribute("class", &objClass); + + /* The changes below will convert an unversioned file to version 1.3 */ + + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 3)) { + // The property 'option' became 'proportion' + + if (objClass == "sizeritem" || objClass == "gbsizeritem" || objClass == "spacer") { + oldProps.clear(); + newProps.clear(); + oldProps.insert("option"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + // One in, one out + (*newProps.begin())->SetAttribute("name", "proportion"); + } + } + + // The 'style' property used to have both wxWindow styles and the styles of the specific controls + // now it only has the styles of the specific controls, and wxWindow styles are saved in window_style + // This also applies to 'extra_style', which was once combined with 'style'. + // And they were named 'WindowStyle' and one point, too... + + std::set windowStyles; + windowStyles.insert(wxT("wxSIMPLE_BORDER")); + windowStyles.insert(wxT("wxDOUBLE_BORDER")); + windowStyles.insert(wxT("wxSUNKEN_BORDER")); + windowStyles.insert(wxT("wxRAISED_BORDER")); + windowStyles.insert(wxT("wxSTATIC_BORDER")); + windowStyles.insert(wxT("wxNO_BORDER")); + windowStyles.insert(wxT("wxTRANSPARENT_WINDOW")); + windowStyles.insert(wxT("wxTAB_TRAVERSAL")); + windowStyles.insert(wxT("wxWANTS_CHARS")); + windowStyles.insert(wxT("wxVSCROLL")); + windowStyles.insert(wxT("wxHSCROLL")); + windowStyles.insert(wxT("wxALWAYS_SHOW_SB")); + windowStyles.insert(wxT("wxCLIP_CHILDREN")); + windowStyles.insert(wxT("wxFULL_REPAINT_ON_RESIZE")); + + // Transfer the window styles + oldProps.clear(); + newProps.clear(); + + oldProps.insert("style"); + + oldProps.insert("WindowStyle"); + + GetPropertiesToConvert(parent, oldProps, &newProps); + + for (newProp = newProps.begin(); newProp != newProps.end(); ++newProp) { + TransferOptionList(*newProp, &windowStyles, "window_style"); + } + + + std::set extraWindowStyles; + extraWindowStyles.insert(wxT("wxWS_EX_VALIDATE_RECURSIVELY")); + extraWindowStyles.insert(wxT("wxWS_EX_BLOCK_EVENTS")); + extraWindowStyles.insert(wxT("wxWS_EX_TRANSIENT")); + extraWindowStyles.insert(wxT("wxWS_EX_PROCESS_IDLE")); + extraWindowStyles.insert(wxT("wxWS_EX_PROCESS_UI_UPDATES")); + + // Transfer the window extra styles + oldProps.clear(); + newProps.clear(); + + oldProps.insert("style"); + + oldProps.insert("extra_style"); + + oldProps.insert("WindowStyle"); + + GetPropertiesToConvert(parent, oldProps, &newProps); + + for (newProp = newProps.begin(); newProp != newProps.end(); ++newProp) { + TransferOptionList(*newProp, &extraWindowStyles, "window_extra_style"); + } + } + + /* The file is now at least version 1.3 */ + + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 4)) { + if (objClass == "wxCheckList") { + // The class we once named "wxCheckList" really represented a "wxCheckListBox", now that we use the #class + // macro in code generation, it generates the wrong code + parent->SetAttribute("class", "wxCheckListBox"); + } + } + + /* The file is now at least version 1.4 */ + + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 6)) { + if (objClass == "spacer") { + // spacer used to be represented by its own class, it is now under a sizeritem like everything else. + // no need to check for a wxGridBagSizer, because it was introduced at the same time. + + // the goal is to change the class to sizeritem, then create a spacer child, then move "width" and "height" + // to the spacer + parent->SetAttribute("class", "sizeritem"); + ticpp::Element spacer("object"); + spacer.SetAttribute("class", "spacer"); + + oldProps.clear(); + newProps.clear(); + oldProps.insert("width"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + // One in, one out + ticpp::Element* width = *newProps.begin(); + spacer.LinkEndChild(width->Clone().release()); + parent->RemoveChild(width); + } + + oldProps.clear(); + newProps.clear(); + oldProps.insert("height"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + // One in, one out + ticpp::Element* height = *newProps.begin(); + spacer.LinkEndChild(height->Clone().release()); + parent->RemoveChild(height); + } + parent->LinkEndChild(&spacer); + } + } + + /* The file is now at least version 1.6 */ + + // Version 1.7 now stores all font properties. + // The font property conversion is automatic because it is just an extension of the old values. + + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 7)) { + // Remove deprecated 2.6 things + + // wxDialog styles wxTHICK_FRAME and wxNO_3D + if (objClass == "Dialog") { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxTHICK_FRAME"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxTHICK_FRAME"), styles); + styles = TypeConv::SetFlag(wxT("wxRESIZE_BORDER"), styles); + } + + styles = TypeConv::ClearFlag(wxT("wxNO_3D"), styles); + style->SetText(_STDSTR(styles)); + } + } + } + } + + /* The file is now at least version 1.7 */ + + // The update to 1.8 only affected project properties + // See ConvertProjectProperties + + /* The file is now at least version 1.8 */ + + // stringlist properties are stored in a different format as of version 1.9 + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 9)) { + oldProps.clear(); + newProps.clear(); + + if ( + objClass == "wxComboBox" || objClass == "wxChoice" || objClass == "wxListBox" || objClass == "wxRadioBox" || + objClass == "wxCheckListBox") { + oldProps.insert("choices"); + } else if (objClass == "wxGrid") { + oldProps.insert("col_label_values"); + oldProps.insert("row_label_values"); + } + + if (!oldProps.empty()) { + GetPropertiesToConvert(parent, oldProps, &newProps); + + std::set::iterator prop; + for (prop = newProps.begin(); prop != newProps.end(); ++prop) { + std::string value = (*prop)->GetText(false); + if (!value.empty()) { + wxArrayString array = TypeConv::OldStringToArrayString(_WXSTR(value)); + (*prop)->SetText(_STDSTR(TypeConv::ArrayStringToString(array))); + } + } + } + } + + /* The file is now at least version 1.9 */ + + // Version 1.11 now stores bitmap property in the following format: + // 'source'; 'data' instead of old form 'data'; 'source'. + + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 11)) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("bitmap"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + std::set::iterator prop; + for (prop = newProps.begin(); prop != newProps.end(); ++prop) { + ticpp::Element* bitmap = *prop; + + wxString image = _WXSTR(bitmap->GetText(false)); + if (!image.empty()) { + if (image.AfterLast(';').Contains(_("Load From"))) { + wxString source = image.AfterLast(';').Trim().Trim(false); + wxString data = image.BeforeLast(';').Trim().Trim(false); + + bitmap->SetText(_STDSTR(source + wxT("; ") + data)); + } + } + } + + /* oldProps.clear(); + newProps.clear(); + oldProps.insert( "choices" ); + GetPropertiesToConvert( parent, oldProps, &newProps ); + + for ( prop = newProps.begin(); prop != newProps.end(); ++prop ) + { + ticpp::Element* choices = *prop; + + wxString content = _WXSTR( choices->GetText( false ) ); + if ( !content.empty() ) + { + content.Replace( wxT("\" \""), wxT(";") ); + content.Replace( wxT("\""), wxT("") ); + + choices->SetText( _STDSTR( content ) ); + } + }*/ + } + + /* The file is now at least version 1.11 */ + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 12)) { + bool classUpdated = false; + if ("wxScintilla" == objClass) { + objClass = "wxStyledTextCtrl"; + parent->SetAttribute("class", objClass); + classUpdated = true; + } + if ("wxTreeListCtrl" == objClass) { + objClass = "wxadditions::wxTreeListCtrl"; + parent->SetAttribute("class", objClass); + classUpdated = true; + } + if ("wxTreeListCtrlColumn" == objClass) { + objClass = "wxadditions::wxTreeListCtrlColumn"; + parent->SetAttribute("class", objClass); + classUpdated = true; + } + if (m_warnOnAdditionsUpdate && classUpdated) { + m_warnOnAdditionsUpdate = false; + wxLogWarning( + _("Updated classes from wxAdditions. You must use the latest version of wxAdditions to continue.\nNote " + "wxScintilla is now wxStyledListCtrl, wxTreeListCtrl is now wxadditions::wxTreeListCtrl, and " + "wxTreeListCtrlColumn is now wxadditions::wxTreeListCtrlColumn")); + } + + typedef std::map > PropertiesToRemove; + + static std::set propertyRemovalWarnings; + const PropertiesToRemove& propertiesToRemove = GetPropertiesToRemove_v1_12(); + PropertiesToRemove::const_iterator it = propertiesToRemove.find(objClass); + if (it != propertiesToRemove.end()) { + RemoveProperties(parent, it->second); + if (0 == propertyRemovalWarnings.count(objClass)) { + std::stringstream ss; + std::ostream_iterator out_it(ss, ", "); + std::copy(it->second.begin(), it->second.end(), out_it); + + wxLogMessage( + _("Removed properties for class %s because they are no longer supported: %s"), objClass, ss.str()); + propertyRemovalWarnings.insert(objClass); + } + } + } + + /* The file is now at least version 1.12 */ + // TODO: Dont know where Version 1.13 comes from, so this is for Version 1.14 + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 14)) { + // Rename all wx*_BORDER-Styles to wxBORDER_*-Styles and remove wxDOUBLE_BORDER + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + oldProps.insert("window_style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + for (newProp = newProps.begin(); newProp != newProps.end(); ++newProp) { + wxString styles = _WXSTR((*newProp)->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxSIMPLE_BORDER"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxSIMPLE_BORDER"), styles); + styles = TypeConv::SetFlag(wxT("wxBORDER_SIMPLE"), styles); + } + + if (TypeConv::FlagSet(wxT("wxDOUBLE_BORDER"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxDOUBLE_BORDER"), styles); + } + + if (TypeConv::FlagSet(wxT("wxSUNKEN_BORDER"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxSUNKEN_BORDER"), styles); + styles = TypeConv::SetFlag(wxT("wxBORDER_SUNKEN"), styles); + } + + if (TypeConv::FlagSet(wxT("wxRAISED_BORDER"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxRAISED_BORDER"), styles); + styles = TypeConv::SetFlag(wxT("wxBORDER_RAISED"), styles); + } + + if (TypeConv::FlagSet(wxT("wxSTATIC_BORDER"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxSTATIC_BORDER"), styles); + styles = TypeConv::SetFlag(wxT("wxBORDER_STATIC"), styles); + } + + if (TypeConv::FlagSet(wxT("wxNO_BORDER"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxNO_BORDER"), styles); + styles = TypeConv::SetFlag(wxT("wxBORDER_NONE"), styles); + } + + (*newProp)->SetText(_STDSTR(styles)); + } + } + + // wxBitmapButton: Remove wxBU_AUTODRAW and rename properties selected->pressed, + // hover->current + if ("wxBitmapButton" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxBU_AUTODRAW"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxBU_AUTODRAW"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + + oldProps.clear(); + newProps.clear(); + oldProps.insert("selected"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + (*newProps.begin())->SetAttribute("name", "pressed"); + } + + oldProps.clear(); + newProps.clear(); + oldProps.insert("hover"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + (*newProps.begin())->SetAttribute("name", "current"); + } + } + + // wxStaticText: Rename wxALIGN_CENTRE -> wxALIGN_CENTER_HORIZONTAL + else if ("wxStaticText" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxALIGN_CENTRE"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxALIGN_CENTRE"), styles); + styles = TypeConv::SetFlag(wxT("wxALIGN_CENTER_HORIZONTAL"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + + // wxRadioBox: Remove wxRA_USE_CHECKBOX + else if ("wxRadioBox" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxRA_USE_CHECKBOX"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxRA_USE_CHECKBOX"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + + // wxRadioButton: Remove wxRB_USE_CHECKBOX + else if ("wxRadioButton" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxRB_USE_CHECKBOX"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxRB_USE_CHECKBOX"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + + // wxStatusBar: Rename wxST_SIZEGRIP -> wxSTB_SIZEGRIP + else if ("wxStatusBar" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxST_SIZEGRIP"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxST_SIZEGRIP"), styles); + styles = TypeConv::SetFlag(wxT("wxSTB_SIZEGRIP"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + + // wxMenuBar: Remove wxMB_DOCKABLE + else if ("wxMenuBar" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + ticpp::Element* style = *newProps.begin(); + wxString styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxMB_DOCKABLE"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxMB_DOCKABLE"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + } + + /* The file is now at least version 1.14 */ + if (fileMajor < 1 || (1 == fileMajor && fileMinor < 15)) { + // Rename wxTE_CENTRE -> wxTE_CENTER + if ("wxTextCtrl" == objClass || "wxSearchCtrl" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + auto* style = *newProps.begin(); + auto styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxTE_CENTRE"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxTE_CENTRE"), styles); + styles = TypeConv::SetFlag(wxT("wxTE_CENTER"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + // Rename wxALIGN_CENTRE -> wxALIGN_CENTER + else if ("wxGrid" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("col_label_horiz_alignment"); + oldProps.insert("col_label_vert_alignment"); + oldProps.insert("row_label_horiz_alignment"); + oldProps.insert("row_label_vert_alignment"); + oldProps.insert("cell_horiz_alignment"); + oldProps.insert("cell_vert_alignment"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + for (newProp = newProps.begin(); newProp != newProps.end(); ++newProp) { + auto styles = _WXSTR((*newProp)->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxALIGN_CENTRE"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxALIGN_CENTRE"), styles); + styles = TypeConv::SetFlag(wxT("wxALIGN_CENTER"), styles); + } + + (*newProp)->SetText(_STDSTR(styles)); + } + } + } + // wxNotebook: Remove wxNB_FLAT + else if ("wxNotebook" == objClass) { + oldProps.clear(); + newProps.clear(); + oldProps.insert("style"); + GetPropertiesToConvert(parent, oldProps, &newProps); + + if (!newProps.empty()) { + auto* style = *newProps.begin(); + auto styles = _WXSTR(style->GetText(false)); + if (!styles.empty()) { + if (TypeConv::FlagSet(wxT("wxNB_FLAT"), styles)) { + styles = TypeConv::ClearFlag(wxT("wxNB_FLAT"), styles); + } + + style->SetText(_STDSTR(styles)); + } + } + } + } + + /* The file is now at least version 1.15 */ + if (fileMajor < 1 || (fileMajor == 1 && fileMinor < 16)) { + static bool showRemovalWarnings = true; + if (objClass == "wxMenuBar") { + RemoveProperties(parent, std::set{"label"}); + if (showRemovalWarnings) { + wxLogMessage(_("Removed property label for class wxMenuBar because it is no longer used")); + showRemovalWarnings = false; + } + } + } +} + +void ApplicationData::GetPropertiesToConvert( + ticpp::Node* parent, const std::set& names, std::set* properties) +{ + // Clear result set + properties->clear(); + + ticpp::Iterator prop("property"); + + for (prop = parent->FirstChildElement("property", false); prop != prop.end(); ++prop) { + std::string name; + prop->GetAttribute("name", &name); + + if (names.find(name) != names.end()) { + properties->insert(prop.Get()); + } + } +} + +void ApplicationData::RemoveProperties(ticpp::Node* parent, const std::set& names) +{ + ticpp::Iterator prop("property"); + + for (prop = parent->FirstChildElement("property", false); prop != prop.end();) { + ticpp::Element element = *prop; + ++prop; + + std::string name; + element.GetAttribute("name", &name); + + if (names.find(name) != names.end()) { + parent->RemoveChild(&element); + } + } +} + +void ApplicationData::TransferOptionList( + ticpp::Element* prop, std::set* options, const std::string& newPropName) + +{ + wxString value = _WXSTR(prop->GetText(false)); + + std::set transfer; + + std::set keep; + + // Sort options - if in the 'options' set, they should be transferred to a property named 'newPropName' + // otherwise, they should stay + wxStringTokenizer tkz(value, wxT("|"), wxTOKEN_RET_EMPTY_ALL); + + while (tkz.HasMoreTokens()) { + wxString option = tkz.GetNextToken(); + option.Trim(false); + option.Trim(true); + + if (options->find(option) != options->end()) { + // Needs to be transferred + transfer.insert(option); + } else { + // Should be kept + keep.insert(option); + } + } + + // Reusable sets to find properties with + std::set oldProps; + + std::set newProps; + + // If there are any to transfer, add to the target property, or make a new one + ticpp::Node* parent = prop->Parent(); + + if (!transfer.empty()) { + // Check for the target property + ticpp::Element* newProp; + wxString newOptionList; + + oldProps.clear(); + oldProps.insert(newPropName); + GetPropertiesToConvert(parent, oldProps, &newProps); + + std::unique_ptr tmpProp; + if (!newProps.empty()) { + newProp = *newProps.begin(); + newOptionList << wxT("|") << _WXSTR(newProp->GetText(false)); + } else { + tmpProp = std::make_unique("property"); + newProp = tmpProp.get(); + newProp->SetAttribute("name", newPropName); + } + + std::set::iterator option; + + for (option = transfer.begin(); option != transfer.end(); ++option) { newOptionList << wxT("|") << *option; } + + newProp->SetText(_STDSTR(newOptionList.substr(1))); + + if (newProps.empty()) { + parent->InsertBeforeChild(prop, *newProp); + } + } + + // Set the value of the property to whatever is left + if (keep.empty()) { + parent->RemoveChild(prop); + } else { + + std::set::iterator option; + + wxString newOptionList; + + for (option = keep.begin(); option != keep.end(); ++option) { newOptionList << wxT("|") << *option; } + + prop->SetText(_STDSTR(newOptionList.substr(1))); + } } void ApplicationData::NewProject() { - m_project = m_objDb->CreateObject( "Project" ); - m_selObj = m_project; - m_modFlag = false; - m_cmdProc.Reset(); - m_projectFile = wxT( "" ); - SetProjectPath( wxT( "" ) ); - m_ipc->Reset(); - NotifyProjectRefresh(); + m_project = m_objDb->CreateObject("Project"); + m_selObj = m_project; + m_modFlag = false; + m_cmdProc.Reset(); + m_projectFile = wxT(""); + SetProjectPath(wxT("")); + m_ipc->Reset(); + NotifyProjectRefresh(); } -void ApplicationData::GenerateCode( bool panelOnly, bool noDelayed ) +void ApplicationData::GenerateCode(bool panelOnly, bool noDelayed) { - NotifyCodeGeneration( panelOnly, !noDelayed ); + NotifyCodeGeneration(panelOnly, !noDelayed); } -void ApplicationData::GenerateInheritedClass( PObjectBase form, wxString className, wxString path, wxString file ) +void ApplicationData::GenerateInheritedClass(PObjectBase form, wxString className, wxString path, wxString file) { - try - { - PObjectBase project = GetProjectData(); - if ( !project ) - { - wxLogWarning( _("No Project?!") ); - return; - } + try { + PObjectBase project = GetProjectData(); + if (!project) { + wxLogWarning(_("No Project?!")); + return; + } - if ( !::wxDirExists( path ) ) - { - wxLogWarning( _("Invalid Path: %s"), path ); - return; - } + if (!::wxDirExists(path)) { + wxLogWarning(_("Invalid Path: %s"), path); + return; + } - PObjectBase obj = m_objDb->CreateObject( "UserClasses", PObjectBase() ); + PObjectBase obj = m_objDb->CreateObject("UserClasses", PObjectBase()); - PProperty baseNameProp = obj->GetProperty( wxT( "basename" ) ); - PProperty nameProp = obj->GetProperty( wxT( "name" ) ); - PProperty fileProp = obj->GetProperty( wxT( "file" ) ); - PProperty genfileProp = obj->GetProperty( wxT( "gen_file" ) ); - PProperty typeProp = obj->GetProperty( wxT( "type" ) ); - PProperty pchProp = obj->GetProperty(wxT("precompiled_header")); + PProperty baseNameProp = obj->GetProperty(wxT("basename")); + PProperty nameProp = obj->GetProperty(wxT("name")); + PProperty fileProp = obj->GetProperty(wxT("file")); + PProperty genfileProp = obj->GetProperty(wxT("gen_file")); + PProperty typeProp = obj->GetProperty(wxT("type")); + PProperty pchProp = obj->GetProperty(wxT("precompiled_header")); - if (!(baseNameProp && nameProp && fileProp && typeProp && genfileProp && pchProp)) - { - wxLogWarning( wxT("Missing Property") ); - return; - } + if (!(baseNameProp && nameProp && fileProp && typeProp && genfileProp && pchProp)) { + wxLogWarning(wxT("Missing Property")); + return; + } - wxFileName inherFile( file ); - if ( !inherFile.MakeAbsolute( path ) ) - { - wxLogWarning( _("Unable to make \"%s\" absolute to \"%s\""), file, path ); + wxFileName inherFile(file); + if (!inherFile.MakeAbsolute(path)) { + wxLogWarning(_("Unable to make \"%s\" absolute to \"%s\""), file, path); return; } - const wxString& genFileValue = project->GetPropertyAsString( _("file") ); - wxFileName genFile( genFileValue ); - if ( !genFile.MakeAbsolute( path ) ) - { - wxLogWarning( _("Unable to make \"%s\" absolute to \"%s\""), genFileValue, path ); + const wxString& genFileValue = project->GetPropertyAsString(_("file")); + wxFileName genFile(genFileValue); + if (!genFile.MakeAbsolute(path)) { + wxLogWarning(_("Unable to make \"%s\" absolute to \"%s\""), genFileValue, path); return; } const wxString& genFileFullPath = genFile.GetFullPath(); - if ( !genFile.MakeRelativeTo( inherFile.GetPath( wxPATH_GET_VOLUME ) ) ) - { - wxLogWarning( _("Unable to make \"%s\" relative to \"%s\""), genFileFullPath, inherFile.GetPath( wxPATH_GET_VOLUME ) ); + if (!genFile.MakeRelativeTo(inherFile.GetPath(wxPATH_GET_VOLUME))) { + wxLogWarning( + _("Unable to make \"%s\" relative to \"%s\""), genFileFullPath, inherFile.GetPath(wxPATH_GET_VOLUME)); return; } - baseNameProp->SetValue( form->GetPropertyAsString( _("name") ) ); - nameProp->SetValue( className ); - fileProp->SetValue( inherFile.GetName() ); - genfileProp->SetValue( genFile.GetFullPath() ); - typeProp->SetValue( form->GetClassName() ); + baseNameProp->SetValue(form->GetPropertyAsString(_("name"))); + nameProp->SetValue(className); + fileProp->SetValue(inherFile.GetName()); + genfileProp->SetValue(genFile.GetFullPath()); + typeProp->SetValue(form->GetClassName()); auto pchValue = project->GetProperty(wxT("precompiled_header")); - if (pchValue) - { + if (pchValue) { pchProp->SetValue(pchValue->GetValue()); } - // Determine if Microsoft BOM should be used - bool useMicrosoftBOM = false; - PProperty pUseMicrosoftBOM = project->GetProperty( _("use_microsoft_bom") ); + // Determine if Microsoft BOM should be used + bool useMicrosoftBOM = false; + PProperty pUseMicrosoftBOM = project->GetProperty(_("use_microsoft_bom")); - if ( pUseMicrosoftBOM ) - { - useMicrosoftBOM = ( pUseMicrosoftBOM->GetValueAsInteger() != 0 ); - } + if (pUseMicrosoftBOM) { + useMicrosoftBOM = (pUseMicrosoftBOM->GetValueAsInteger() != 0); + } + + // Determine if Utf8 or Ansi is to be created + bool useUtf8 = false; + PProperty pUseUtf8 = project->GetProperty(_("encoding")); - // Determine if Utf8 or Ansi is to be created - bool useUtf8 = false; - PProperty pUseUtf8 = project->GetProperty( _("encoding") ); + if (pUseUtf8) { + useUtf8 = (pUseUtf8->GetValueAsString() != wxT("ANSI")); + } - if ( pUseUtf8 ) - { - useUtf8 = ( pUseUtf8->GetValueAsString() != wxT("ANSI") ); - } + PProperty pCodeGen = project->GetProperty(wxT("code_generation")); + if (pCodeGen && TypeConv::FlagSet(wxT("C++"), pCodeGen->GetValue())) { + CppCodeGenerator codegen; + const wxString& fullPath = inherFile.GetFullPath(); + codegen.ParseFiles(fullPath + wxT(".h"), fullPath + wxT(".cpp")); - PProperty pCodeGen = project->GetProperty( wxT( "code_generation" ) ); - if ( pCodeGen && TypeConv::FlagSet( wxT("C++"), pCodeGen->GetValue() ) ) - { - CppCodeGenerator codegen; - const wxString& fullPath = inherFile.GetFullPath(); - codegen.ParseFiles(fullPath + wxT(".h"), fullPath + wxT(".cpp")); + PCodeWriter h_cw(new FileCodeWriter(fullPath + wxT(".h"), useMicrosoftBOM, useUtf8)); + PCodeWriter cpp_cw(new FileCodeWriter(fullPath + wxT(".cpp"), useMicrosoftBOM, useUtf8)); - PCodeWriter h_cw( new FileCodeWriter( fullPath + wxT(".h"), useMicrosoftBOM, useUtf8 ) ); - PCodeWriter cpp_cw( new FileCodeWriter( fullPath + wxT(".cpp"), useMicrosoftBOM, useUtf8 ) ); + codegen.SetHeaderWriter(h_cw); + codegen.SetSourceWriter(cpp_cw); - codegen.SetHeaderWriter( h_cw ); - codegen.SetSourceWriter( cpp_cw ); + codegen.GenerateInheritedClass(obj, form); + } else if (pCodeGen && TypeConv::FlagSet(wxT("Python"), pCodeGen->GetValue())) { + PythonCodeGenerator codegen; - codegen.GenerateInheritedClass( obj, form ); - } - else if( pCodeGen && TypeConv::FlagSet( wxT("Python"), pCodeGen->GetValue() ) ) - { - PythonCodeGenerator codegen; + const wxString& fullPath = inherFile.GetFullPath(); + PCodeWriter python_cw(new FileCodeWriter(fullPath + wxT(".py"), useMicrosoftBOM, useUtf8)); - const wxString& fullPath = inherFile.GetFullPath(); - PCodeWriter python_cw( new FileCodeWriter( fullPath + wxT(".py"), useMicrosoftBOM, useUtf8 ) ); + codegen.SetSourceWriter(python_cw); - codegen.SetSourceWriter( python_cw ); + codegen.GenerateInheritedClass(obj, form); + } else if (pCodeGen && TypeConv::FlagSet(wxT("PHP"), pCodeGen->GetValue())) { + PHPCodeGenerator codegen; - codegen.GenerateInheritedClass( obj, form ); - } - else if( pCodeGen && TypeConv::FlagSet( wxT("PHP"), pCodeGen->GetValue() ) ) - { - PHPCodeGenerator codegen; + const wxString& fullPath = inherFile.GetFullPath(); + PCodeWriter php_cw(new FileCodeWriter(fullPath + wxT(".php"), useMicrosoftBOM, useUtf8)); - const wxString& fullPath = inherFile.GetFullPath(); - PCodeWriter php_cw( new FileCodeWriter( fullPath + wxT(".php"), useMicrosoftBOM, useUtf8 ) ); + codegen.SetSourceWriter(php_cw); - codegen.SetSourceWriter( php_cw ); + codegen.GenerateInheritedClass(obj, form); + } else if (pCodeGen && TypeConv::FlagSet(wxT("Lua"), pCodeGen->GetValue())) { + LuaCodeGenerator codegen; - codegen.GenerateInheritedClass( obj, form ); - } - else if( pCodeGen && TypeConv::FlagSet( wxT("Lua"), pCodeGen->GetValue() ) ) - { - LuaCodeGenerator codegen; - - const wxString& fullPath = inherFile.GetFullPath(); - PCodeWriter lua_cw( new FileCodeWriter( fullPath + wxT(".lua"), useMicrosoftBOM, useUtf8 ) ); + const wxString& fullPath = inherFile.GetFullPath(); + PCodeWriter lua_cw(new FileCodeWriter(fullPath + wxT(".lua"), useMicrosoftBOM, useUtf8)); - codegen.SetSourceWriter( lua_cw ); + codegen.SetSourceWriter(lua_cw); - codegen.GenerateInheritedClass( obj, form, genFileFullPath ); - } + codegen.GenerateInheritedClass(obj, form, genFileFullPath); + } - wxLogStatus( wxT( "Class generated at \'%s\'." ), path ); - } - catch( wxFBException& ex ) - { - wxLogError( ex.what() ); - } + wxLogStatus(wxT("Class generated at \'%s\'."), path); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } } -void ApplicationData::MovePosition( PObjectBase obj, bool right, unsigned int num ) +void ApplicationData::MovePosition(PObjectBase obj, bool right, unsigned int num) { - PObjectBase noItemObj = obj; - - PObjectBase parent = obj->GetParent(); - - if ( parent ) - { - // Si el objeto está incluido dentro de un item hay que desplazar - // el item + PObjectBase noItemObj = obj; - while ( parent && parent->GetObjectInfo()->GetObjectType()->IsItem() ) - { - obj = parent; - parent = obj->GetParent(); - } + PObjectBase parent = obj->GetParent(); - unsigned int pos = parent->GetChildPosition( obj ); + if (parent) { + // Si el objeto está incluido dentro de un item hay que desplazar + // el item - // nos aseguramos de que los límites son correctos - - unsigned int children_count = parent->GetChildCount(); + while (parent && parent->GetObjectInfo()->GetObjectType()->IsItem()) { + obj = parent; + parent = obj->GetParent(); + } - if ( ( right && num + pos < children_count ) || - ( !right && ( num <= pos ) ) ) - { - pos = ( right ? pos + num : pos - num ); - - PCommand command( new ShiftChildCmd( obj, pos ) ); - Execute( command ); //m_cmdProc.Execute(command); - NotifyProjectRefresh(); - SelectObject( noItemObj, true ); + unsigned int pos = parent->GetChildPosition(obj); - } - } -} + // nos aseguramos de que los límites son correctos -void ApplicationData::MoveHierarchy( PObjectBase obj, bool up ) -{ - PObjectBase sizeritem = obj->GetParent(); - if ( !( sizeritem && sizeritem->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) ) - { - return; - } + unsigned int children_count = parent->GetChildCount(); - PObjectBase nextSizer = sizeritem->GetParent(); // points to the object's sizer - if ( nextSizer ) - { - if ( up ) - { - do - { - nextSizer = nextSizer->GetParent(); - } - while ( nextSizer && !nextSizer->GetObjectInfo()->IsSubclassOf( wxT("sizer") ) && !nextSizer->GetObjectInfo()->IsSubclassOf( wxT("gbsizer") ) ); + if ((right && num + pos < children_count) || (!right && (num <= pos))) { + pos = (right ? pos + num : pos - num); - if ( nextSizer && ( nextSizer->GetObjectInfo()->IsSubclassOf( wxT("sizer") ) || nextSizer->GetObjectInfo()->IsSubclassOf( wxT("gbsizer") ) ) ) - { - PCommand cmdReparent( new ReparentObjectCmd( sizeritem, nextSizer ) ); - Execute( cmdReparent ); - NotifyProjectRefresh(); - SelectObject( obj, true ); - } - } - else - { - // object will be move to the top sizer of the next sibling object - // subtree. - unsigned int pos = nextSizer->GetChildPosition( sizeritem ) + 1; + PCommand command(new ShiftChildCmd(obj, pos)); + Execute(command); // m_cmdProc.Execute(command); + NotifyProjectRefresh(); + SelectObject(noItemObj, true); + } + } +} - if ( pos < nextSizer->GetChildCount() ) - { - nextSizer = SearchSizerInto( nextSizer->GetChild( pos ) ); +void ApplicationData::MoveHierarchy(PObjectBase obj, bool up) +{ + PObjectBase sizeritem = obj->GetParent(); + if (!(sizeritem && sizeritem->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase")))) { + return; + } - if ( nextSizer ) - { - PCommand cmdReparent( new ReparentObjectCmd( sizeritem, nextSizer ) ); - Execute( cmdReparent ); - NotifyProjectRefresh(); - SelectObject( obj, true ); - } - } - } - } + PObjectBase nextSizer = sizeritem->GetParent(); // points to the object's sizer + if (nextSizer) { + if (up) { + do { + nextSizer = nextSizer->GetParent(); + } while (nextSizer && !nextSizer->GetObjectInfo()->IsSubclassOf(wxT("sizer")) && + !nextSizer->GetObjectInfo()->IsSubclassOf(wxT("gbsizer"))); + + if ( + nextSizer && (nextSizer->GetObjectInfo()->IsSubclassOf(wxT("sizer")) || + nextSizer->GetObjectInfo()->IsSubclassOf(wxT("gbsizer")))) { + PCommand cmdReparent(new ReparentObjectCmd(sizeritem, nextSizer)); + Execute(cmdReparent); + NotifyProjectRefresh(); + SelectObject(obj, true); + } + } else { + // object will be move to the top sizer of the next sibling object + // subtree. + unsigned int pos = nextSizer->GetChildPosition(sizeritem) + 1; + + if (pos < nextSizer->GetChildCount()) { + nextSizer = SearchSizerInto(nextSizer->GetChild(pos)); + + if (nextSizer) { + PCommand cmdReparent(new ReparentObjectCmd(sizeritem, nextSizer)); + Execute(cmdReparent); + NotifyProjectRefresh(); + SelectObject(obj, true); + } + } + } + } } void ApplicationData::Undo() { - m_cmdProc.Undo(); - m_modFlag = !m_cmdProc.IsAtSavePoint(); - NotifyProjectRefresh(); - CheckProjectTree( m_project ); - NotifyObjectSelected( GetSelectedObject() ); + m_cmdProc.Undo(); + m_modFlag = !m_cmdProc.IsAtSavePoint(); + NotifyProjectRefresh(); + CheckProjectTree(m_project); + NotifyObjectSelected(GetSelectedObject()); } void ApplicationData::Redo() { - m_cmdProc.Redo(); - m_modFlag = !m_cmdProc.IsAtSavePoint(); - NotifyProjectRefresh(); - CheckProjectTree( m_project ); - NotifyObjectSelected( GetSelectedObject() ); + m_cmdProc.Redo(); + m_modFlag = !m_cmdProc.IsAtSavePoint(); + NotifyProjectRefresh(); + CheckProjectTree(m_project); + NotifyObjectSelected(GetSelectedObject()); } -void ApplicationData::ToggleExpandLayout( PObjectBase obj ) +void ApplicationData::ToggleExpandLayout(PObjectBase obj) { - if ( !obj ) - { - return; - } + if (!obj) { + return; + } - PObjectBase parent = obj->GetParent(); - if ( !parent ) - { - return; - } + PObjectBase parent = obj->GetParent(); + if (!parent) { + return; + } - if ( !parent->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - { - return; - } + if (!parent->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) { + return; + } - PProperty propFlag = parent->GetProperty( wxT("flag") ); + PProperty propFlag = parent->GetProperty(wxT("flag")); - if( !propFlag ) - { - return; - } + if (!propFlag) { + return; + } - wxString value; - wxString currentValue = propFlag->GetValueAsString(); + wxString value; + wxString currentValue = propFlag->GetValueAsString(); - value = - ( TypeConv::FlagSet( wxT("wxEXPAND"), currentValue ) ? - TypeConv::ClearFlag( wxT("wxEXPAND"), currentValue ) : - TypeConv::SetFlag( wxT("wxEXPAND"), currentValue ) ); + value = + (TypeConv::FlagSet(wxT("wxEXPAND"), currentValue) ? TypeConv::ClearFlag(wxT("wxEXPAND"), currentValue) + : TypeConv::SetFlag(wxT("wxEXPAND"), currentValue)); - ModifyProperty( propFlag, value ); + ModifyProperty(propFlag, value); } -void ApplicationData::ToggleStretchLayout( PObjectBase obj ) +void ApplicationData::ToggleStretchLayout(PObjectBase obj) { - if ( !obj ) - { - return; - } + if (!obj) { + return; + } - PObjectBase parent = obj->GetParent(); - if ( !parent ) - { - return; - } + PObjectBase parent = obj->GetParent(); + if (!parent) { + return; + } - if ( parent->GetObjectTypeName() != wxT("sizeritem") && parent->GetObjectTypeName() != wxT("gbsizeritem") ) - { - return; - } + if (parent->GetObjectTypeName() != wxT("sizeritem") && parent->GetObjectTypeName() != wxT("gbsizeritem")) { + return; + } - PProperty proportion = parent->GetProperty( wxT("proportion") ); - if ( !proportion ) - { - return; - } + PProperty proportion = parent->GetProperty(wxT("proportion")); + if (!proportion) { + return; + } - wxString value = ( proportion->GetValue() != wxT("0") ? wxT( "0" ) : wxT( "1" ) ); - ModifyProperty( proportion, value ); + wxString value = (proportion->GetValue() != wxT("0") ? wxT("0") : wxT("1")); + ModifyProperty(proportion, value); } -void ApplicationData::CheckProjectTree( PObjectBase obj ) +void ApplicationData::CheckProjectTree(PObjectBase obj) { - assert( obj ); + assert(obj); - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - PObjectBase child = obj->GetChild( i ); + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { + PObjectBase child = obj->GetChild(i); - if ( child->GetParent() != obj ) - { - wxLogError( wxString::Format("Parent of object \'" + child->GetPropertyAsString("name") + "\' is wrong!") ); - } - CheckProjectTree( child ); - } -} - -bool ApplicationData::GetLayoutSettings( PObjectBase obj, int *flag, int *option, int *border, int* orient ) -{ - if ( !obj ) - { - return false; - } + if (child->GetParent() != obj) { + wxLogError(wxString::Format("Parent of object \'" + child->GetPropertyAsString("name") + "\' is wrong!")); + } + CheckProjectTree(child); + } +} - PObjectBase parent = obj->GetParent(); - if ( !parent ) - { - return false; - } +bool ApplicationData::GetLayoutSettings(PObjectBase obj, int* flag, int* option, int* border, int* orient) +{ + if (!obj) { + return false; + } - if ( parent->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - { - PProperty propOption = parent->GetProperty( wxT("proportion") ); - if ( propOption ) - { - *option = propOption->GetValueAsInteger(); - } + PObjectBase parent = obj->GetParent(); + if (!parent) { + return false; + } - *flag = parent->GetPropertyAsInteger( wxT("flag") ); - *border = parent->GetPropertyAsInteger( wxT("border") ); + if (parent->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) { + PProperty propOption = parent->GetProperty(wxT("proportion")); + if (propOption) { + *option = propOption->GetValueAsInteger(); + } - PObjectBase sizer = parent->GetParent(); - if ( sizer ) - { - wxString parentName = sizer->GetClassName(); - if ( wxT("wxBoxSizer") == parentName || wxT("wxStaticBoxSizer") == parentName ) - { - PProperty propOrient = sizer->GetProperty( wxT("orient") ); - if ( propOrient ) - { - *orient = propOrient->GetValueAsInteger(); - } - } - } - return true; - } + *flag = parent->GetPropertyAsInteger(wxT("flag")); + *border = parent->GetPropertyAsInteger(wxT("border")); + + PObjectBase sizer = parent->GetParent(); + if (sizer) { + wxString parentName = sizer->GetClassName(); + if (wxT("wxBoxSizer") == parentName || wxT("wxStaticBoxSizer") == parentName) { + PProperty propOrient = sizer->GetProperty(wxT("orient")); + if (propOrient) { + *orient = propOrient->GetValueAsInteger(); + } + } + } + return true; + } - return false; + return false; } -void ApplicationData::ChangeAlignment ( PObjectBase obj, int align, bool vertical ) +void ApplicationData::ChangeAlignment(PObjectBase obj, int align, bool vertical) { - if ( !obj ) - { - return; - } + if (!obj) { + return; + } - PObjectBase parent = obj->GetParent(); - if ( !parent ) - { - return; - } + PObjectBase parent = obj->GetParent(); + if (!parent) { + return; + } - if ( !parent->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - { - return; - } + if (!parent->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) { + return; + } - PProperty propFlag = parent->GetProperty( wxT( "flag" ) ); + PProperty propFlag = parent->GetProperty(wxT("flag")); - if ( !propFlag ) - { - return; - } + if (!propFlag) { + return; + } - wxString value = propFlag->GetValueAsString(); + wxString value = propFlag->GetValueAsString(); - // Primero borramos los flags de la configuración previa, para así - // evitar conflictos de alineaciones. + // Primero borramos los flags de la configuración previa, para así + // evitar conflictos de alineaciones. - if ( vertical ) - { - value = TypeConv::ClearFlag( wxT( "wxALIGN_TOP" ), value ); - value = TypeConv::ClearFlag( wxT( "wxALIGN_BOTTOM" ), value ); - value = TypeConv::ClearFlag( wxT( "wxALIGN_CENTER_VERTICAL" ), value ); - } - else - { - value = TypeConv::ClearFlag( wxT( "wxALIGN_LEFT" ), value ); - value = TypeConv::ClearFlag( wxT( "wxALIGN_RIGHT" ), value ); - value = TypeConv::ClearFlag( wxT( "wxALIGN_CENTER_HORIZONTAL" ), value ); - } + if (vertical) { + value = TypeConv::ClearFlag(wxT("wxALIGN_TOP"), value); + value = TypeConv::ClearFlag(wxT("wxALIGN_BOTTOM"), value); + value = TypeConv::ClearFlag(wxT("wxALIGN_CENTER_VERTICAL"), value); + } else { + value = TypeConv::ClearFlag(wxT("wxALIGN_LEFT"), value); + value = TypeConv::ClearFlag(wxT("wxALIGN_RIGHT"), value); + value = TypeConv::ClearFlag(wxT("wxALIGN_CENTER_HORIZONTAL"), value); + } - wxString alignStr; + wxString alignStr; - switch ( align ) - { + switch (align) { - case wxALIGN_RIGHT: - alignStr = wxT( "wxALIGN_RIGHT" ); + case wxALIGN_RIGHT: + alignStr = wxT("wxALIGN_RIGHT"); - break; + break; - case wxALIGN_CENTER_HORIZONTAL: - alignStr = wxT( "wxALIGN_CENTER_HORIZONTAL" ); + case wxALIGN_CENTER_HORIZONTAL: + alignStr = wxT("wxALIGN_CENTER_HORIZONTAL"); - break; + break; - case wxALIGN_BOTTOM: - alignStr = wxT( "wxALIGN_BOTTOM" ); + case wxALIGN_BOTTOM: + alignStr = wxT("wxALIGN_BOTTOM"); - break; + break; - case wxALIGN_CENTER_VERTICAL: - alignStr = wxT( "wxALIGN_CENTER_VERTICAL" ); + case wxALIGN_CENTER_VERTICAL: + alignStr = wxT("wxALIGN_CENTER_VERTICAL"); - break; - } + break; + } - value = TypeConv::SetFlag( alignStr, value ); + value = TypeConv::SetFlag(alignStr, value); - ModifyProperty( propFlag, value ); + ModifyProperty(propFlag, value); } -void ApplicationData::ToggleBorderFlag( PObjectBase obj, int border ) +void ApplicationData::ToggleBorderFlag(PObjectBase obj, int border) { - if ( !obj ) - { - return; - } + if (!obj) { + return; + } - PObjectBase parent = obj->GetParent(); - if ( !parent ) - { - return; - } + PObjectBase parent = obj->GetParent(); + if (!parent) { + return; + } - if ( !parent->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - { - return; - } + if (!parent->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) { + return; + } - PProperty propFlag = parent->GetProperty( wxT( "flag" ) ); + PProperty propFlag = parent->GetProperty(wxT("flag")); - if ( !propFlag ) - { - return; - } + if (!propFlag) { + return; + } - wxString value = propFlag->GetValueAsString(); + wxString value = propFlag->GetValueAsString(); - value = TypeConv::ClearFlag( wxT( "wxALL" ), value ); - value = TypeConv::ClearFlag( wxT( "wxTOP" ), value ); - value = TypeConv::ClearFlag( wxT( "wxBOTTOM" ), value ); - value = TypeConv::ClearFlag( wxT( "wxRIGHT" ), value ); - value = TypeConv::ClearFlag( wxT( "wxLEFT" ), value ); + value = TypeConv::ClearFlag(wxT("wxALL"), value); + value = TypeConv::ClearFlag(wxT("wxTOP"), value); + value = TypeConv::ClearFlag(wxT("wxBOTTOM"), value); + value = TypeConv::ClearFlag(wxT("wxRIGHT"), value); + value = TypeConv::ClearFlag(wxT("wxLEFT"), value); - int intVal = propFlag->GetValueAsInteger(); - intVal ^= border; + int intVal = propFlag->GetValueAsInteger(); + intVal ^= border; - if ( ( intVal & wxALL ) == wxALL ) - value = TypeConv::SetFlag( wxT( "wxALL" ), value ); - else - { - if ( ( intVal & wxTOP ) != 0 ) value = TypeConv::SetFlag( wxT( "wxTOP" ), value ); + if ((intVal & wxALL) == wxALL) + value = TypeConv::SetFlag(wxT("wxALL"), value); + else { + if ((intVal & wxTOP) != 0) + value = TypeConv::SetFlag(wxT("wxTOP"), value); - if ( ( intVal & wxBOTTOM ) != 0 ) value = TypeConv::SetFlag( wxT( "wxBOTTOM" ), value ); + if ((intVal & wxBOTTOM) != 0) + value = TypeConv::SetFlag(wxT("wxBOTTOM"), value); - if ( ( intVal & wxRIGHT ) != 0 ) value = TypeConv::SetFlag( wxT( "wxRIGHT" ), value ); + if ((intVal & wxRIGHT) != 0) + value = TypeConv::SetFlag(wxT("wxRIGHT"), value); - if ( ( intVal & wxLEFT ) != 0 ) value = TypeConv::SetFlag( wxT( "wxLEFT" ), value ); - } + if ((intVal & wxLEFT) != 0) + value = TypeConv::SetFlag(wxT("wxLEFT"), value); + } - ModifyProperty( propFlag, value ); + ModifyProperty(propFlag, value); } -void ApplicationData::CreateBoxSizerWithObject( PObjectBase obj ) +void ApplicationData::CreateBoxSizerWithObject(PObjectBase obj) { - PObjectBase parent = obj->GetParent(); - if ( !parent ) - { - return; - } + PObjectBase parent = obj->GetParent(); + if (!parent) { + return; + } - PObjectBase grandParent = parent->GetParent(); - if ( !grandParent ) - { - return; - } + PObjectBase grandParent = parent->GetParent(); + if (!grandParent) { + return; + } - int childPos = -1; - if ( parent->GetObjectInfo()->IsSubclassOf( wxT("sizeritembase") ) ) - { - childPos = (int)grandParent->GetChildPosition( parent ); - parent = grandParent; - } + int childPos = -1; + if (parent->GetObjectInfo()->IsSubclassOf(wxT("sizeritembase"))) { + childPos = (int)grandParent->GetChildPosition(parent); + parent = grandParent; + } - // Must first cut the old object in case it is the only allowable object - PObjectBase clipboard = m_clipboard; - CutObject( obj ); + // Must first cut the old object in case it is the only allowable object + PObjectBase clipboard = m_clipboard; + CutObject(obj); - // Create the wxBoxSizer - PObjectBase newSizer = m_objDb->CreateObject( "wxBoxSizer", parent ); + // Create the wxBoxSizer + PObjectBase newSizer = m_objDb->CreateObject("wxBoxSizer", parent); - if ( newSizer ) - { - PCommand cmd( new InsertObjectCmd( this, newSizer, parent, childPos ) ); - Execute( cmd ); + if (newSizer) { + PCommand cmd(new InsertObjectCmd(this, newSizer, parent, childPos)); + Execute(cmd); - if ( newSizer->GetObjectTypeName() == wxT("sizeritem") ) - newSizer = newSizer->GetChild( 0 ); + if (newSizer->GetObjectTypeName() == wxT("sizeritem")) + newSizer = newSizer->GetChild(0); - PasteObject( newSizer ); - m_clipboard = clipboard; + PasteObject(newSizer); + m_clipboard = clipboard; - //NotifyProjectRefresh(); - } - else - { - Undo(); - m_clipboard = clipboard; - } + // NotifyProjectRefresh(); + } else { + Undo(); + m_clipboard = clipboard; + } } void ApplicationData::ShowXrcPreview() { - PObjectBase form = GetSelectedForm(); + PObjectBase form = GetSelectedForm(); - if ( form == NULL ) - { - wxMessageBox( wxT( "Please select a form and try again." ), wxT( "XRC Preview" ), wxICON_ERROR ); - return; - } else if (form->GetPropertyAsInteger(wxT("aui_managed")) != 0) { - wxMessageBox( wxT( "XRC preview doesn't support AUI-managed frames." ), wxT( "XRC Preview" ), wxICON_ERROR ); - return; - } + if (form == NULL) { + wxMessageBox(wxT("Please select a form and try again."), wxT("XRC Preview"), wxICON_ERROR); + return; + } else if (form->GetPropertyAsInteger(wxT("aui_managed")) != 0) { + wxMessageBox(wxT("XRC preview doesn't support AUI-managed frames."), wxT("XRC Preview"), wxICON_ERROR); + return; + } - XRCPreview::Show( form, GetProjectPath() ); + XRCPreview::Show(form, GetProjectPath()); } bool ApplicationData::CanPasteObject() { - PObjectBase obj = GetSelectedObject(); + PObjectBase obj = GetSelectedObject(); - if ( obj && obj->GetObjectTypeName() != wxT( "project" ) ) - return ( m_clipboard != NULL ); + if (obj && obj->GetObjectTypeName() != wxT("project")) + return (m_clipboard != NULL); - return false; + return false; } bool ApplicationData::CanCopyObject() { - PObjectBase obj = GetSelectedObject(); + PObjectBase obj = GetSelectedObject(); - if ( obj && obj->GetObjectTypeName() != wxT( "project" ) ) - return true; + if (obj && obj->GetObjectTypeName() != wxT("project")) + return true; - return false; + return false; } bool ApplicationData::IsModified() { - return m_modFlag; + return m_modFlag; } void ApplicationData::SetDarkMode(bool darkMode) { - m_darkMode = darkMode; + m_darkMode = darkMode; } bool ApplicationData::IsDarkMode() const { - return m_darkMode; + return m_darkMode; } -void ApplicationData::Execute(PCommand cmd) { - m_modFlag = true; - m_cmdProc.Execute( cmd ); +void ApplicationData::Execute(PCommand cmd) +{ + m_modFlag = true; + m_cmdProc.Execute(cmd); } ////////////////////////////////////////////////////////////////////////////// -void ApplicationData::AddHandler( wxEvtHandler* handler ) +void ApplicationData::AddHandler(wxEvtHandler* handler) { - m_handlers.push_back( handler ); + m_handlers.push_back(handler); } -void ApplicationData::RemoveHandler( wxEvtHandler* handler ) +void ApplicationData::RemoveHandler(wxEvtHandler* handler) { - for ( HandlerVector::iterator it = m_handlers.begin(); it != m_handlers.end(); ++it ) - { - if ( *it == handler ) - { - m_handlers.erase( it ); - break; - } - } + for (HandlerVector::iterator it = m_handlers.begin(); it != m_handlers.end(); ++it) { + if (*it == handler) { + m_handlers.erase(it); + break; + } + } } -void ApplicationData::NotifyEvent( wxFBEvent& event, bool forcedelayed ) +void ApplicationData::NotifyEvent(wxFBEvent& event, bool forcedelayed) { - if ( !forcedelayed ) - { - LogDebug( "event: %s", event.GetEventName() ); + if (!forcedelayed) { + LogDebug("event: %s", event.GetEventName()); - std::vector< wxEvtHandler* >::iterator handler; + std::vector::iterator handler; - for ( handler = m_handlers.begin(); handler != m_handlers.end(); handler++ ) - { - ( *handler )->ProcessEvent( event ); - } - } - else - { - LogDebug( "Pending event: %s", event.GetEventName() ); + for (handler = m_handlers.begin(); handler != m_handlers.end(); handler++) { (*handler)->ProcessEvent(event); } + } else { + LogDebug("Pending event: %s", event.GetEventName()); - std::vector< wxEvtHandler* >::iterator handler; + std::vector::iterator handler; - for ( handler = m_handlers.begin(); handler != m_handlers.end(); handler++ ) - { - ( *handler )->AddPendingEvent( event ); - } - } + for (handler = m_handlers.begin(); handler != m_handlers.end(); handler++) { + (*handler)->AddPendingEvent(event); + } + } } void ApplicationData::NotifyProjectLoaded() { - wxFBEvent event( wxEVT_FB_PROJECT_LOADED ); - NotifyEvent( event ); + wxFBEvent event(wxEVT_FB_PROJECT_LOADED); + NotifyEvent(event); } void ApplicationData::NotifyProjectSaved() { - wxFBEvent event( wxEVT_FB_PROJECT_SAVED ); - NotifyEvent( event ); + wxFBEvent event(wxEVT_FB_PROJECT_SAVED); + NotifyEvent(event); } -void ApplicationData::NotifyObjectExpanded( PObjectBase obj ) +void ApplicationData::NotifyObjectExpanded(PObjectBase obj) { - wxFBObjectEvent event( wxEVT_FB_OBJECT_EXPANDED, obj ); - NotifyEvent( event ); + wxFBObjectEvent event(wxEVT_FB_OBJECT_EXPANDED, obj); + NotifyEvent(event); } -void ApplicationData::NotifyObjectSelected( PObjectBase obj, bool force ) +void ApplicationData::NotifyObjectSelected(PObjectBase obj, bool force) { - wxFBObjectEvent event( wxEVT_FB_OBJECT_SELECTED, obj ); - if( force ) event.SetString( wxT("force") ); + wxFBObjectEvent event(wxEVT_FB_OBJECT_SELECTED, obj); + if (force) + event.SetString(wxT("force")); - NotifyEvent( event, false ); + NotifyEvent(event, false); } -void ApplicationData::NotifyObjectCreated( PObjectBase obj ) +void ApplicationData::NotifyObjectCreated(PObjectBase obj) { - wxFBObjectEvent event( wxEVT_FB_OBJECT_CREATED, obj ); - NotifyEvent( event, false ); + wxFBObjectEvent event(wxEVT_FB_OBJECT_CREATED, obj); + NotifyEvent(event, false); } -void ApplicationData::NotifyObjectRemoved( PObjectBase obj ) +void ApplicationData::NotifyObjectRemoved(PObjectBase obj) { - wxFBObjectEvent event( wxEVT_FB_OBJECT_REMOVED, obj ); - NotifyEvent( event, false ); + wxFBObjectEvent event(wxEVT_FB_OBJECT_REMOVED, obj); + NotifyEvent(event, false); } -void ApplicationData::NotifyPropertyModified( PProperty prop ) +void ApplicationData::NotifyPropertyModified(PProperty prop) { - wxFBPropertyEvent event( wxEVT_FB_PROPERTY_MODIFIED, prop ); - NotifyEvent( event ); + wxFBPropertyEvent event(wxEVT_FB_PROPERTY_MODIFIED, prop); + NotifyEvent(event); } -void ApplicationData::NotifyEventHandlerModified( PEvent evtHandler ) +void ApplicationData::NotifyEventHandlerModified(PEvent evtHandler) { - wxFBEventHandlerEvent event( wxEVT_FB_EVENT_HANDLER_MODIFIED, evtHandler ); - NotifyEvent( event ); + wxFBEventHandlerEvent event(wxEVT_FB_EVENT_HANDLER_MODIFIED, evtHandler); + NotifyEvent(event); } -void ApplicationData::NotifyCodeGeneration( bool panelOnly, bool forcedelayed ) +void ApplicationData::NotifyCodeGeneration(bool panelOnly, bool forcedelayed) { - wxFBEvent event( wxEVT_FB_CODE_GENERATION ); + wxFBEvent event(wxEVT_FB_CODE_GENERATION); - // Using the previously unused Id field in the event to carry a boolean - event.SetId( ( panelOnly ? 1 : 0 ) ); + // Using the previously unused Id field in the event to carry a boolean + event.SetId((panelOnly ? 1 : 0)); - NotifyEvent( event, forcedelayed ); + NotifyEvent(event, forcedelayed); } void ApplicationData::NotifyProjectRefresh() { - wxFBEvent event( wxEVT_FB_PROJECT_REFRESH ); - NotifyEvent( event ); + wxFBEvent event(wxEVT_FB_PROJECT_REFRESH); + NotifyEvent(event); } -bool ApplicationData::VerifySingleInstance( const wxString& file, bool switchTo ) +bool ApplicationData::VerifySingleInstance(const wxString& file, bool switchTo) { - return m_ipc->VerifySingleInstance( file, switchTo ); + return m_ipc->VerifySingleInstance(file, switchTo); } -wxString ApplicationData::GetPathProperty( const wxString& pathName ) +wxString ApplicationData::GetPathProperty(const wxString& pathName) { - PObjectBase project = GetProjectData(); - wxFileName path; - // Get the output path - PProperty ppath = project->GetProperty( pathName ); + PObjectBase project = GetProjectData(); + wxFileName path; + // Get the output path + PProperty ppath = project->GetProperty(pathName); - if ( ppath ) - { - wxString pathEntry = ppath->GetValue(); + if (ppath) { + wxString pathEntry = ppath->GetValue(); - if ( pathEntry.empty() ) - { - THROW_WXFBEX( wxT( "You must set the \"") + pathName + wxT("\" property of the project to a valid path for output files" ) ); - } + if (pathEntry.empty()) { + THROW_WXFBEX( + wxT("You must set the \"") + pathName + + wxT("\" property of the project to a valid path for output files")); + } - path = wxFileName::DirName( pathEntry ); + path = wxFileName::DirName(pathEntry); - if ( !path.IsAbsolute() ) - { - wxString projectPath = AppData()->GetProjectPath(); + if (!path.IsAbsolute()) { + wxString projectPath = AppData()->GetProjectPath(); - if ( projectPath.empty() ) - { - THROW_WXFBEX( wxT( "You must save the project when using a relative path for output files" ) ); - } + if (projectPath.empty()) { + THROW_WXFBEX(wxT("You must save the project when using a relative path for output files")); + } - path = wxFileName( projectPath + - wxFileName::GetPathSeparator() + - pathEntry + - wxFileName::GetPathSeparator() ); + path = + wxFileName(projectPath + wxFileName::GetPathSeparator() + pathEntry + wxFileName::GetPathSeparator()); - path.Normalize(wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS); + path.Normalize(wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS); - // this approach is probably incorrect if the fb project is located under a symlink - /*path.SetCwd( projectPath ); - path.MakeAbsolute();*/ - } - } + // this approach is probably incorrect if the fb project is located under a symlink + /*path.SetCwd( projectPath ); + path.MakeAbsolute();*/ + } + } - if ( !path.DirExists() ) - { - THROW_WXFBEX( wxT( "Invalid Path: " ) << path.GetPath() << wxT( "\nYou must set the \"") + pathName + wxT("\" property of the project to a valid path for output files" ) ); - } + if (!path.DirExists()) { + THROW_WXFBEX( + wxT("Invalid Path: ") << path.GetPath() + << wxT("\nYou must set the \"") + pathName + + wxT("\" property of the project to a valid path for output files")); + } - return path.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR ); + return path.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR); } wxString ApplicationData::GetOutputPath() { - return GetPathProperty( wxT("path") ); + return GetPathProperty(wxT("path")); } wxString ApplicationData::GetEmbeddedFilesOutputPath() { - return GetPathProperty( wxT("embedded_files_path") ); -} - -ApplicationData::PropertiesToRemove& ApplicationData::GetPropertiesToRemove_v1_12() const { - static PropertiesToRemove propertiesToRemove; - if( propertiesToRemove.empty() ) - { - propertiesToRemove[ "Dialog" ].insert( "BottomDockable" ); - propertiesToRemove[ "Dialog" ].insert( "LeftDockable" ); - propertiesToRemove[ "Dialog" ].insert( "RightDockable" ); - propertiesToRemove[ "Dialog" ].insert( "TopDockable" ); - propertiesToRemove[ "Dialog" ].insert( "caption_visible" ); - propertiesToRemove[ "Dialog" ].insert( "center_pane" ); - propertiesToRemove[ "Dialog" ].insert( "close_button" ); - propertiesToRemove[ "Dialog" ].insert( "default_pane" ); - propertiesToRemove[ "Dialog" ].insert( "dock" ); - propertiesToRemove[ "Dialog" ].insert( "dock_fixed" ); - propertiesToRemove[ "Dialog" ].insert( "docking" ); - propertiesToRemove[ "Dialog" ].insert( "floatable" ); - propertiesToRemove[ "Dialog" ].insert( "gripper" ); - propertiesToRemove[ "Dialog" ].insert( "maximize_button" ); - propertiesToRemove[ "Dialog" ].insert( "minimize_button" ); - propertiesToRemove[ "Dialog" ].insert( "moveable" ); - propertiesToRemove[ "Dialog" ].insert( "pane_border" ); - propertiesToRemove[ "Dialog" ].insert( "pin_button" ); - propertiesToRemove[ "Dialog" ].insert( "resize" ); - propertiesToRemove[ "Dialog" ].insert( "show" ); - propertiesToRemove[ "Dialog" ].insert( "toolbar_pane" ); - propertiesToRemove[ "Dialog" ].insert( "validator_style" ); - propertiesToRemove[ "Dialog" ].insert( "validator_type" ); - propertiesToRemove[ "Dialog" ].insert( "aui_name" ); - - propertiesToRemove[ "Panel" ].insert( "BottomDockable" ); - propertiesToRemove[ "Panel" ].insert( "LeftDockable" ); - propertiesToRemove[ "Panel" ].insert( "RightDockable" ); - propertiesToRemove[ "Panel" ].insert( "TopDockable" ); - propertiesToRemove[ "Panel" ].insert( "caption_visible" ); - propertiesToRemove[ "Panel" ].insert( "center_pane" ); - propertiesToRemove[ "Panel" ].insert( "close_button" ); - propertiesToRemove[ "Panel" ].insert( "default_pane" ); - propertiesToRemove[ "Panel" ].insert( "dock" ); - propertiesToRemove[ "Panel" ].insert( "dock_fixed" ); - propertiesToRemove[ "Panel" ].insert( "docking" ); - propertiesToRemove[ "Panel" ].insert( "floatable" ); - propertiesToRemove[ "Panel" ].insert( "gripper" ); - propertiesToRemove[ "Panel" ].insert( "maximize_button" ); - propertiesToRemove[ "Panel" ].insert( "minimize_button" ); - propertiesToRemove[ "Panel" ].insert( "moveable" ); - propertiesToRemove[ "Panel" ].insert( "pane_border" ); - propertiesToRemove[ "Panel" ].insert( "pin_button" ); - propertiesToRemove[ "Panel" ].insert( "resize" ); - propertiesToRemove[ "Panel" ].insert( "show" ); - propertiesToRemove[ "Panel" ].insert( "toolbar_pane" ); - propertiesToRemove[ "Panel" ].insert( "validator_style" ); - propertiesToRemove[ "Panel" ].insert( "validator_type" ); - - propertiesToRemove[ "wxStaticText" ].insert( "validator_style" ); - propertiesToRemove[ "wxStaticText" ].insert( "validator_type" ); - propertiesToRemove[ "CustomControl" ].insert( "validator_style" ); - propertiesToRemove[ "CustomControl" ].insert( "validator_type" ); - propertiesToRemove[ "wxAuiNotebook" ].insert( "validator_style" ); - propertiesToRemove[ "wxAuiNotebook" ].insert( "validator_type" ); - propertiesToRemove[ "wxPanel" ].insert( "validator_style" ); - propertiesToRemove[ "wxPanel" ].insert( "validator_type" ); - propertiesToRemove[ "wxToolBar" ].insert( "validator_style" ); - propertiesToRemove[ "wxToolBar" ].insert( "validator_type" ); - propertiesToRemove[ "wxStyledTextCtrl" ].insert( "use_wxAddition" ); - propertiesToRemove[ "wxStyledTextCtrl" ].insert( "validator_style" ); - propertiesToRemove[ "wxStyledTextCtrl" ].insert( "validator_type" ); - propertiesToRemove[ "wxPropertyGridManager" ].insert( "use_wxAddition" ); - propertiesToRemove[ "wxPropertyGridManager" ].insert( "validator_style" ); - propertiesToRemove[ "wxPropertyGridManager" ].insert( "validator_type" ); - - propertiesToRemove[ "wxadditions::wxTreeListCtrl" ].insert( "validator_style" ); - propertiesToRemove[ "wxadditions::wxTreeListCtrl" ].insert( "validator_type" ); - } - return propertiesToRemove; + return GetPathProperty(wxT("embedded_files_path")); +} + +ApplicationData::PropertiesToRemove& ApplicationData::GetPropertiesToRemove_v1_12() const +{ + static PropertiesToRemove propertiesToRemove; + if (propertiesToRemove.empty()) { + propertiesToRemove["Dialog"].insert("BottomDockable"); + propertiesToRemove["Dialog"].insert("LeftDockable"); + propertiesToRemove["Dialog"].insert("RightDockable"); + propertiesToRemove["Dialog"].insert("TopDockable"); + propertiesToRemove["Dialog"].insert("caption_visible"); + propertiesToRemove["Dialog"].insert("center_pane"); + propertiesToRemove["Dialog"].insert("close_button"); + propertiesToRemove["Dialog"].insert("default_pane"); + propertiesToRemove["Dialog"].insert("dock"); + propertiesToRemove["Dialog"].insert("dock_fixed"); + propertiesToRemove["Dialog"].insert("docking"); + propertiesToRemove["Dialog"].insert("floatable"); + propertiesToRemove["Dialog"].insert("gripper"); + propertiesToRemove["Dialog"].insert("maximize_button"); + propertiesToRemove["Dialog"].insert("minimize_button"); + propertiesToRemove["Dialog"].insert("moveable"); + propertiesToRemove["Dialog"].insert("pane_border"); + propertiesToRemove["Dialog"].insert("pin_button"); + propertiesToRemove["Dialog"].insert("resize"); + propertiesToRemove["Dialog"].insert("show"); + propertiesToRemove["Dialog"].insert("toolbar_pane"); + propertiesToRemove["Dialog"].insert("validator_style"); + propertiesToRemove["Dialog"].insert("validator_type"); + propertiesToRemove["Dialog"].insert("aui_name"); + + propertiesToRemove["Panel"].insert("BottomDockable"); + propertiesToRemove["Panel"].insert("LeftDockable"); + propertiesToRemove["Panel"].insert("RightDockable"); + propertiesToRemove["Panel"].insert("TopDockable"); + propertiesToRemove["Panel"].insert("caption_visible"); + propertiesToRemove["Panel"].insert("center_pane"); + propertiesToRemove["Panel"].insert("close_button"); + propertiesToRemove["Panel"].insert("default_pane"); + propertiesToRemove["Panel"].insert("dock"); + propertiesToRemove["Panel"].insert("dock_fixed"); + propertiesToRemove["Panel"].insert("docking"); + propertiesToRemove["Panel"].insert("floatable"); + propertiesToRemove["Panel"].insert("gripper"); + propertiesToRemove["Panel"].insert("maximize_button"); + propertiesToRemove["Panel"].insert("minimize_button"); + propertiesToRemove["Panel"].insert("moveable"); + propertiesToRemove["Panel"].insert("pane_border"); + propertiesToRemove["Panel"].insert("pin_button"); + propertiesToRemove["Panel"].insert("resize"); + propertiesToRemove["Panel"].insert("show"); + propertiesToRemove["Panel"].insert("toolbar_pane"); + propertiesToRemove["Panel"].insert("validator_style"); + propertiesToRemove["Panel"].insert("validator_type"); + + propertiesToRemove["wxStaticText"].insert("validator_style"); + propertiesToRemove["wxStaticText"].insert("validator_type"); + propertiesToRemove["CustomControl"].insert("validator_style"); + propertiesToRemove["CustomControl"].insert("validator_type"); + propertiesToRemove["wxAuiNotebook"].insert("validator_style"); + propertiesToRemove["wxAuiNotebook"].insert("validator_type"); + propertiesToRemove["wxPanel"].insert("validator_style"); + propertiesToRemove["wxPanel"].insert("validator_type"); + propertiesToRemove["wxToolBar"].insert("validator_style"); + propertiesToRemove["wxToolBar"].insert("validator_type"); + propertiesToRemove["wxStyledTextCtrl"].insert("use_wxAddition"); + propertiesToRemove["wxStyledTextCtrl"].insert("validator_style"); + propertiesToRemove["wxStyledTextCtrl"].insert("validator_type"); + propertiesToRemove["wxPropertyGridManager"].insert("use_wxAddition"); + propertiesToRemove["wxPropertyGridManager"].insert("validator_style"); + propertiesToRemove["wxPropertyGridManager"].insert("validator_type"); + + propertiesToRemove["wxadditions::wxTreeListCtrl"].insert("validator_style"); + propertiesToRemove["wxadditions::wxTreeListCtrl"].insert("validator_type"); + } + return propertiesToRemove; } diff --git a/src/rad/appdata.h b/src/rad/appdata.h index 4d4903bb1..5c1c3487b 100644 --- a/src/rad/appdata.h +++ b/src/rad/appdata.h @@ -29,379 +29,374 @@ #include "model/database.h" #include "rad/cmdproc.h" + namespace ticpp { class Document; - class Node; - class Element; -} +} // namespace ticpp class Property; - class wxFBEvent; - +class wxFBIPC; class wxFBManager; -class wxFBIPC; -#define AppData() (ApplicationData::Get()) +#define AppData() (ApplicationData::Get()) #define AppDataCreate(path) (ApplicationData::Get(path)) -#define AppDataInit() (ApplicationData::Initialize()) -#define AppDataDestroy() (ApplicationData::Destroy()) +#define AppDataInit() (ApplicationData::Initialize()) +#define AppDataDestroy() (ApplicationData::Destroy()) + // This class is a singleton class. class ApplicationData { - private: - - static ApplicationData *s_instance; - - wxString m_rootDir; // directorio raíz (mismo que el ejecutable) +private: + static ApplicationData* s_instance; - bool m_modFlag; // flag de proyecto modificado + wxString m_rootDir; // directorio raíz (mismo que el ejecutable) - bool m_warnOnAdditionsUpdate; // flag to warn on additions update / class renames + bool m_modFlag; // flag de proyecto modificado - bool m_darkMode; + bool m_warnOnAdditionsUpdate; // flag to warn on additions update / class renames - PObjectDatabase m_objDb; // Base de datos de objetos + bool m_darkMode; - PObjectBase m_project; // Proyecto + PObjectDatabase m_objDb; // Base de datos de objetos - PObjectBase m_selObj; // Objeto seleccionado + PObjectBase m_project; // Proyecto - PObjectBase m_clipboard; + PObjectBase m_selObj; // Objeto seleccionado - bool m_copyOnPaste; // flag que indica si hay que copiar el objeto al pegar + PObjectBase m_clipboard; - // Procesador de comandos Undo/Redo - CommandProcessor m_cmdProc; + bool m_copyOnPaste; // flag que indica si hay que copiar el objeto al pegar - wxString m_projectFile; + // Procesador de comandos Undo/Redo + CommandProcessor m_cmdProc; - wxString m_projectPath; + wxString m_projectFile; - PwxFBManager m_manager; + wxString m_projectPath; - // Prevent more than one instance of a project - std::shared_ptr< wxFBIPC > m_ipc; + PwxFBManager m_manager; + // Prevent more than one instance of a project + std::shared_ptr m_ipc; - typedef std::vector< wxEvtHandler* > HandlerVector; - HandlerVector m_handlers; + typedef std::vector HandlerVector; - void NotifyEvent( wxFBEvent& event, bool forcedelayed = false ); + HandlerVector m_handlers; - // Notifican a cada observador el evento correspondiente - void NotifyProjectLoaded(); + void NotifyEvent(wxFBEvent& event, bool forcedelayed = false); - void NotifyProjectSaved(); + // Notifican a cada observador el evento correspondiente + void NotifyProjectLoaded(); - void NotifyObjectExpanded( PObjectBase obj ); + void NotifyProjectSaved(); - void NotifyObjectSelected( PObjectBase obj, bool force = false ); + void NotifyObjectExpanded(PObjectBase obj); - void NotifyObjectCreated( PObjectBase obj ); + void NotifyObjectSelected(PObjectBase obj, bool force = false); - void NotifyObjectRemoved( PObjectBase obj ); + void NotifyObjectCreated(PObjectBase obj); - void NotifyPropertyModified( PProperty prop ); + void NotifyObjectRemoved(PObjectBase obj); - void NotifyEventHandlerModified( PEvent evtHandler ); + void NotifyPropertyModified(PProperty prop); - void NotifyProjectRefresh(); + void NotifyEventHandlerModified(PEvent evtHandler); - void NotifyCodeGeneration( bool panelOnly = false, bool forcedelayed = false ); + void NotifyProjectRefresh(); - /** - * Comprueba las referencias cruzadas de todos los nodos del árbol - */ - void CheckProjectTree( PObjectBase obj ); + void NotifyCodeGeneration(bool panelOnly = false, bool forcedelayed = false); - /** - * Resuelve un posible conflicto de nombres. - * @note el objeto a comprobar debe estar insertado en proyecto, por tanto - * no es válida para arboles "flotantes". - */ - void ResolveNameConflict( PObjectBase obj ); + /** + * Comprueba las referencias cruzadas de todos los nodos del árbol + */ + void CheckProjectTree(PObjectBase obj); - /** - * Rename all objects that have the same name than any object of a subtree. - */ - void ResolveSubtreeNameConflicts( PObjectBase obj, PObjectBase topObj = PObjectBase() ); + /** + * Resuelve un posible conflicto de nombres. + * @note el objeto a comprobar debe estar insertado en proyecto, por tanto + * no es válida para arboles "flotantes". + */ + void ResolveNameConflict(PObjectBase obj); - /** - * Rutina auxiliar de ResolveNameConflict - */ - void BuildNameSet( PObjectBase obj, PObjectBase top, std::set &name_set ); + /** + * Rename all objects that have the same name than any object of a subtree. + */ + void ResolveSubtreeNameConflicts(PObjectBase obj, PObjectBase topObj = PObjectBase()); - /** - * Calcula la posición donde deberá ser insertado el objeto. - * - * Dado un objeto "padre" y un objeto "seleccionado", esta rutina calcula la - * posición de inserción de un objeto debajo de "parent" de forma que el objeto - * quede a continuación del objeto "seleccionado". - * - * El algoritmo consiste ir subiendo en el arbol desde el objeto "selected" - * hasta encontrar un objeto cuyo padre sea el mismo que "parent" en cuyo - * caso se toma la posición siguiente a ese objeto. - * - * @param parent objeto "padre" - * @param selected objeto "seleccionado". - * @return posición de insercción (-1 si no se puede insertar). - */ - int CalcPositionOfInsertion( PObjectBase selected, PObjectBase parent ); + /** + * Rutina auxiliar de ResolveNameConflict + */ + void BuildNameSet(PObjectBase obj, PObjectBase top, std::set& name_set); + /** + * Calcula la posición donde deberá ser insertado el objeto. + * + * Dado un objeto "padre" y un objeto "seleccionado", esta rutina calcula la + * posición de inserción de un objeto debajo de "parent" de forma que el objeto + * quede a continuación del objeto "seleccionado". + * + * El algoritmo consiste ir subiendo en el arbol desde el objeto "selected" + * hasta encontrar un objeto cuyo padre sea el mismo que "parent" en cuyo + * caso se toma la posición siguiente a ese objeto. + * + * @param parent objeto "padre" + * @param selected objeto "seleccionado". + * @return posición de insercción (-1 si no se puede insertar). + */ + int CalcPositionOfInsertion(PObjectBase selected, PObjectBase parent); - /** - * Elimina aquellos items que no contengan hijos. - * - * Esta rutina se utiliza cuando el árbol que se carga de un fichero - * no está bien formado, o la importación no ha sido correcta. - */ - void RemoveEmptyItems( PObjectBase obj ); - /** - * Eliminar un objeto. - */ - void DoRemoveObject( PObjectBase object, bool cutObject ); + /** + * Elimina aquellos items que no contengan hijos. + * + * Esta rutina se utiliza cuando el árbol que se carga de un fichero + * no está bien formado, o la importación no ha sido correcta. + */ + void RemoveEmptyItems(PObjectBase obj); - void Execute( PCommand cmd ); + /** + * Eliminar un objeto. + */ + void DoRemoveObject(PObjectBase object, bool cutObject); - /** - * Search a size in the hierarchy of an object - */ - PObjectBase SearchSizerInto( PObjectBase obj ); + void Execute(PCommand cmd); + /** + * Search a size in the hierarchy of an object + */ + PObjectBase SearchSizerInto(PObjectBase obj); - /** - Convert the properties of the project element. Handle this separately because it does not repeat. - @param project The project element. - @param path The path to the project file. - @param fileMajor The major revision of the file. - @param fileMinor The minor revision of the file. - */ - void ConvertProjectProperties( ticpp::Element* project, const wxString& path, int fileMajor, int fileMinor ); - /** - Iterates through 'property' element children of @a parent. - Saves all properties with a 'name' attribute matching one of @a names into @a properties - @param parent Object element with child properties. - @param names Set of property names to search for. - @param properties Pointer to a set in which to store the result of the search. - */ - void GetPropertiesToConvert( ticpp::Node* parent, const std::set< std::string >& names, std::set< ticpp::Element* >* properties ); + /** + Convert the properties of the project element. Handle this separately because it does not repeat. + @param project The project element. + @param path The path to the project file. + @param fileMajor The major revision of the file. + @param fileMinor The minor revision of the file. + */ + void ConvertProjectProperties(ticpp::Element* project, const wxString& path, int fileMajor, int fileMinor); - /** - Iterates through 'property' element children of @a parent. - Removes all properties with a 'name' attribute matching one of @a names - @param parent Object element with child properties. - @param names Set of property names to search for. - */ - void RemoveProperties( ticpp::Node* parent, const std::set< std::string >& names ); + /** + Iterates through 'property' element children of @a parent. + Saves all properties with a 'name' attribute matching one of @a names into @a properties + @param parent Object element with child properties. + @param names Set of property names to search for. + @param properties Pointer to a set in which to store the result of the search. + */ + void GetPropertiesToConvert( + ticpp::Node* parent, const std::set& names, std::set* properties); - /** - Transfers @a options from the text of @a prop to the text of @a newPropName, which will be created if it doesn't exist. - @param prop Property containing the options to transfer. - @param options Set of options to search for and transfer. - @param newPropName Name of property to transfer to, will be created if non-existent. - */ - void TransferOptionList( ticpp::Element* prop, std::set< wxString >* options, const std::string& newPropName ); + /** + Iterates through 'property' element children of @a parent. + Removes all properties with a 'name' attribute matching one of @a names + @param parent Object element with child properties. + @param names Set of property names to search for. + */ + void RemoveProperties(ticpp::Node* parent, const std::set& names); - void PropagateExpansion(PObjectBase obj, bool expand, bool up); + /** + Transfers @a options from the text of @a prop to the text of @a newPropName, which will be created if it doesn't + exist. + @param prop Property containing the options to transfer. + @param options Set of options to search for and transfer. + @param newPropName Name of property to transfer to, will be created if non-existent. + */ + void TransferOptionList(ticpp::Element* prop, std::set* options, const std::string& newPropName); - // hidden constructor - ApplicationData( const wxString &rootdir = wxT( "." ) ); + void PropagateExpansion(PObjectBase obj, bool expand, bool up); - /** - * Helper for GetOutputPath and GetEmbeddedFilesOutputPath - */ - wxString GetPathProperty( const wxString& pathName ); + // hidden constructor + ApplicationData(const wxString& rootdir = wxT(".")); - #ifdef __WXFB_DEBUG__ - wxLog* m_debugLogTarget; - #endif + /** + * Helper for GetOutputPath and GetEmbeddedFilesOutputPath + */ + wxString GetPathProperty(const wxString& pathName); - typedef std::map< std::string, std::set< std::string > > PropertiesToRemove; - PropertiesToRemove& GetPropertiesToRemove_v1_12() const; +#ifdef __WXFB_DEBUG__ + wxLog* m_debugLogTarget; +#endif - public: + typedef std::map > PropertiesToRemove; + PropertiesToRemove& GetPropertiesToRemove_v1_12() const; - ~ApplicationData(); - ApplicationData(const ApplicationData&) = delete; - ApplicationData& operator=(const ApplicationData&) = delete; - ApplicationData(ApplicationData&&) = delete; - ApplicationData& operator=(ApplicationData&&) = delete; +public: + ~ApplicationData(); + ApplicationData(const ApplicationData&) = delete; + ApplicationData& operator=(const ApplicationData&) = delete; + ApplicationData(ApplicationData&&) = delete; + ApplicationData& operator=(ApplicationData&&) = delete; - #ifdef __WXFB_DEBUG__ - wxLog* GetDebugLogTarget(){ return m_debugLogTarget; } - #endif +#ifdef __WXFB_DEBUG__ + wxLog* GetDebugLogTarget() { return m_debugLogTarget; } +#endif - static ApplicationData* Get( const wxString &rootdir = wxT( "." ) ); + static ApplicationData* Get(const wxString& rootdir = wxT(".")); - // Force the static AppData instance to Init() - static void Initialize(); + // Force the static AppData instance to Init() + static void Initialize(); - static void Destroy(); + static void Destroy(); - // Initialize application - void LoadApp(); + // Initialize application + void LoadApp(); - // Hold a pointer to the wxFBManager - PwxFBManager GetManager(); + // Hold a pointer to the wxFBManager + PwxFBManager GetManager(); - // Procedures for register/unregister wxEvtHandlers to be notified of wxFBEvents - void AddHandler( wxEvtHandler* handler ); + // Procedures for register/unregister wxEvtHandlers to be notified of wxFBEvents + void AddHandler(wxEvtHandler* handler); - void RemoveHandler( wxEvtHandler* handler ); + void RemoveHandler(wxEvtHandler* handler); - // Operaciones sobre los datos - bool LoadProject( const wxString &file, bool justGenerate = false ); + // Operaciones sobre los datos + bool LoadProject(const wxString& file, bool justGenerate = false); - void SaveProject( const wxString &filename ); + void SaveProject(const wxString& filename); - void NewProject(); + void NewProject(); - /** - Convert a project from an older version. - @param path The path to the project file - @param fileMajor The major revision of the file - @param fileMinor The minor revision of the file - @return true if successful, false otherwise - */ + /** + Convert a project from an older version. + @param path The path to the project file + @param fileMajor The major revision of the file + @param fileMinor The minor revision of the file + @return true if successful, false otherwise + */ - bool ConvertProject(ticpp::Document& doc, const wxString& path, int fileMajor, int fileMinor); + bool ConvertProject(ticpp::Document& doc, const wxString& path, int fileMajor, int fileMinor); - /** - Recursive function used to convert the object tree in the project file to the latest version. - @param object A pointer to the object element - @param fileMajor The major revision of the file - @param fileMinor The minor revision of the file - */ - void ConvertObject( ticpp::Element* object, int fileMajor, int fileMinor ); + /** + Recursive function used to convert the object tree in the project file to the latest version. + @param object A pointer to the object element + @param fileMajor The major revision of the file + @param fileMinor The minor revision of the file + */ + void ConvertObject(ticpp::Element* object, int fileMajor, int fileMinor); - void ExpandObject( PObjectBase obj, bool expand ); + void ExpandObject(PObjectBase obj, bool expand); - void DetermineObjectToSelect( PObjectBase parent, unsigned int pos ); + void DetermineObjectToSelect(PObjectBase parent, unsigned int pos); - // Object will not be selected if it already is selected, unless force = true - // Returns true if selection changed, false if already selected - bool SelectObject( PObjectBase obj, bool force = false, bool notify = true ); + // Object will not be selected if it already is selected, unless force = true + // Returns true if selection changed, false if already selected + bool SelectObject(PObjectBase obj, bool force = false, bool notify = true); - void CreateObject( wxString name ); + void CreateObject(wxString name); - void RemoveObject( PObjectBase obj ); + void RemoveObject(PObjectBase obj); - void CutObject( PObjectBase obj ); + void CutObject(PObjectBase obj); - void CopyObject( PObjectBase obj ); + void CopyObject(PObjectBase obj); - bool PasteObject( PObjectBase parent, PObjectBase objToPaste = PObjectBase() ); + bool PasteObject(PObjectBase parent, PObjectBase objToPaste = PObjectBase()); - void CopyObjectToClipboard( PObjectBase obj ); + void CopyObjectToClipboard(PObjectBase obj); - bool PasteObjectFromClipboard( PObjectBase parent ); + bool PasteObjectFromClipboard(PObjectBase parent); - void InsertObject( PObjectBase obj, PObjectBase parent ); + void InsertObject(PObjectBase obj, PObjectBase parent); - void MergeProject( PObjectBase project ); + void MergeProject(PObjectBase project); - void ModifyProperty( PProperty prop, wxString value ); + void ModifyProperty(PProperty prop, wxString value); - void ModifyEventHandler( PEvent evt, wxString value ); + void ModifyEventHandler(PEvent evt, wxString value); - void GenerateCode( bool panelOnly = false, bool noDelayed = false ); + void GenerateCode(bool panelOnly = false, bool noDelayed = false); - void GenerateInheritedClass( PObjectBase form, wxString className, wxString path, wxString file ); + void GenerateInheritedClass(PObjectBase form, wxString className, wxString path, wxString file); - void MovePosition( PObjectBase, bool right, unsigned int num = 1 ); + void MovePosition(PObjectBase, bool right, unsigned int num = 1); - void MoveHierarchy( PObjectBase obj, bool up ); + void MoveHierarchy(PObjectBase obj, bool up); - void Undo(); + void Undo(); - void Redo(); + void Redo(); - void ToggleExpandLayout( PObjectBase obj ); + void ToggleExpandLayout(PObjectBase obj); - void ToggleStretchLayout( PObjectBase obj ); + void ToggleStretchLayout(PObjectBase obj); - void ChangeAlignment ( PObjectBase obj, int align, bool vertical ); + void ChangeAlignment(PObjectBase obj, int align, bool vertical); - void ToggleBorderFlag( PObjectBase obj, int border ); + void ToggleBorderFlag(PObjectBase obj, int border); - void CreateBoxSizerWithObject( PObjectBase obj ); + void CreateBoxSizerWithObject(PObjectBase obj); - void ShowXrcPreview(); + void ShowXrcPreview(); - // Servicios para los observadores - PObjectBase GetSelectedObject(); + // Servicios para los observadores + PObjectBase GetSelectedObject(); - PObjectBase GetProjectData(); + PObjectBase GetProjectData(); - PObjectBase GetSelectedForm(); + PObjectBase GetSelectedForm(); - bool CanUndo() { return m_cmdProc.CanUndo(); } + bool CanUndo() { return m_cmdProc.CanUndo(); } - bool CanRedo() { return m_cmdProc.CanRedo(); } + bool CanRedo() { return m_cmdProc.CanRedo(); } - bool GetLayoutSettings( PObjectBase obj, int *flag, int *option, int *border, int* orient ); - bool CanPasteObject(); - bool CanPasteObjectFromClipboard(); - bool CanCopyObject(); - bool IsModified(); + bool GetLayoutSettings(PObjectBase obj, int* flag, int* option, int* border, int* orient); + bool CanPasteObject(); + bool CanPasteObjectFromClipboard(); + bool CanCopyObject(); + bool IsModified(); - void SetDarkMode(bool darkMode); - bool IsDarkMode() const; + void SetDarkMode(bool darkMode); + bool IsDarkMode() const; - PObjectPackage GetPackage( unsigned int idx ) - { return m_objDb->GetPackage( idx );} + PObjectPackage GetPackage(unsigned int idx) { return m_objDb->GetPackage(idx); } - unsigned int GetPackageCount() - { return m_objDb->GetPackageCount(); } + unsigned int GetPackageCount() { return m_objDb->GetPackageCount(); } - PObjectDatabase GetObjectDatabase() - { return m_objDb; } + PObjectDatabase GetObjectDatabase() { return m_objDb; } - // Servicios específicos, no definidos en DataObservable - void SetClipboardObject( PObjectBase obj ) { m_clipboard = obj; } + // Servicios específicos, no definidos en DataObservable + void SetClipboardObject(PObjectBase obj) { m_clipboard = obj; } - PObjectBase GetClipboardObject() { return m_clipboard; } + PObjectBase GetClipboardObject() { return m_clipboard; } - wxString GetProjectFileName() { return m_projectFile; } + wxString GetProjectFileName() { return m_projectFile; } - const int m_fbpVerMajor; + const int m_fbpVerMajor; - const int m_fbpVerMinor; + const int m_fbpVerMinor; - /** Path to the fbp file that is opened. */ - const wxString &GetProjectPath() { return m_projectPath; } + /** Path to the fbp file that is opened. */ + const wxString& GetProjectPath() { return m_projectPath; } - /** - Path where the files will be generated. - */ - wxString GetOutputPath(); + /** + Path where the files will be generated. + */ + wxString GetOutputPath(); - /** - Path where the embedded bitmap files will be generated. - */ - wxString GetEmbeddedFilesOutputPath(); + /** + Path where the embedded bitmap files will be generated. + */ + wxString GetEmbeddedFilesOutputPath(); - void SetProjectPath( const wxString &path ) { m_projectPath = path; } + void SetProjectPath(const wxString& path) { m_projectPath = path; } - const wxString &GetApplicationPath() { return m_rootDir; } + const wxString& GetApplicationPath() { return m_rootDir; } - void SetApplicationPath( const wxString &path ) { m_rootDir = path; } + void SetApplicationPath(const wxString& path) { m_rootDir = path; } - // Allow a single instance check from outsid the AppData class - bool VerifySingleInstance( const wxString& file, bool switchTo = true ); + // Allow a single instance check from outsid the AppData class + bool VerifySingleInstance(const wxString& file, bool switchTo = true); }; -#endif // RAD_APPDATA_H +#endif // RAD_APPDATA_H diff --git a/src/rad/auitabart.h b/src/rad/auitabart.h index 8af4112a0..8936bc56c 100644 --- a/src/rad/auitabart.h +++ b/src/rad/auitabart.h @@ -3,15 +3,24 @@ #include -class AuiTabArt : public wxAuiGenericTabArt { + +class AuiTabArt : public wxAuiGenericTabArt +{ public: - #if wxCHECK_VERSION(3, 1, 6) - wxSize GetTabSize(wxDC& dc, wxWindow* wnd, const wxString& caption, const wxBitmapBundle& bitmap, bool active, int close_button_state, int* x_extent) override { - #else - wxSize GetTabSize(wxDC& dc, wxWindow* wnd, const wxString& caption, const wxBitmap& bitmap, bool active, int close_button_state, int* x_extent) override { - #endif - return wxAuiGenericTabArt::GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, x_extent) + wxSize(0, 2); - } -}; +#if wxCHECK_VERSION(3, 1, 6) + wxSize GetTabSize( + wxDC& dc, wxWindow* wnd, const wxString& caption, const wxBitmapBundle& bitmap, bool active, + int close_button_state, int* x_extent) override{ +#else + wxSize GetTabSize( + wxDC& dc, wxWindow* wnd, const wxString& caption, const wxBitmap& bitmap, bool active, int close_button_state, + int* x_extent) override + { +#endif + return wxAuiGenericTabArt::GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, x_extent) + + wxSize(0, 2); +} +} +; -#endif // RAD_AUITABART_H +#endif // RAD_AUITABART_H diff --git a/src/rad/bitmaps.cpp b/src/rad/bitmaps.cpp index 085e513b2..f1cd640e8 100644 --- a/src/rad/bitmaps.cpp +++ b/src/rad/bitmaps.cpp @@ -25,66 +25,58 @@ #include "bitmaps.h" +#include + +#include + #include "utils/stringutils.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include -#include -static std::map< wxString, wxBitmap > m_bitmaps; +static std::map m_bitmaps; + -wxBitmap AppBitmaps::GetBitmap( wxString iconname, unsigned int size ) +wxBitmap AppBitmaps::GetBitmap(wxString iconname, unsigned int size) { - std::map< wxString, wxBitmap >::iterator bitmap; - bitmap = m_bitmaps.find( iconname ); - wxBitmap bmp; - if ( bitmap != m_bitmaps.end() ) - { - bmp = m_bitmaps[iconname]; - } - else - { - bmp = m_bitmaps[ wxT("unknown") ]; - } - if ( size != 0 ) - { - // rescale it to requested size - if ( bmp.GetWidth() != (int)size || bmp.GetHeight() != (int)size ) - { - wxImage image = bmp.ConvertToImage(); - bmp = wxBitmap( image.Scale(size, size) ); - } - } - return bmp; + std::map::iterator bitmap; + bitmap = m_bitmaps.find(iconname); + wxBitmap bmp; + if (bitmap != m_bitmaps.end()) { + bmp = m_bitmaps[iconname]; + } else { + bmp = m_bitmaps[wxT("unknown")]; + } + if (size != 0) { + // rescale it to requested size + if (bmp.GetWidth() != (int)size || bmp.GetHeight() != (int)size) { + wxImage image = bmp.ConvertToImage(); + bmp = wxBitmap(image.Scale(size, size)); + } + } + return bmp; } -void AppBitmaps::LoadBitmaps( wxString filepath, wxString iconpath ) +void AppBitmaps::LoadBitmaps(wxString filepath, wxString iconpath) { - try - { - m_bitmaps[ wxT("unknown") ] = wxBitmap( default_xpm ); + try { + m_bitmaps[wxT("unknown")] = wxBitmap(default_xpm); - ticpp::Document doc; - XMLUtils::LoadXMLFile( doc, true, filepath ); + ticpp::Document doc; + XMLUtils::LoadXMLFile(doc, true, filepath); - ticpp::Element* root = doc.FirstChildElement( "icons" ); - ticpp::Element* elem = root->FirstChildElement( "icon", false ); - while ( elem ) - { - wxString name = _WXSTR( elem->GetAttribute("name") ); - wxString file = _WXSTR( elem->GetAttribute("file") ); - m_bitmaps[name] = wxBitmap( iconpath + file, wxBITMAP_TYPE_ANY ); + ticpp::Element* root = doc.FirstChildElement("icons"); + ticpp::Element* elem = root->FirstChildElement("icon", false); + while (elem) { + wxString name = _WXSTR(elem->GetAttribute("name")); + wxString file = _WXSTR(elem->GetAttribute("file")); + m_bitmaps[name] = wxBitmap(iconpath + file, wxBITMAP_TYPE_ANY); - elem = elem->NextSiblingElement( "icon", false ); - } - } - catch ( ticpp::Exception& ex ) - { - wxLogError( _("Error loading images: %s"), _WXSTR( ex.m_details ) ); - } - catch ( wxFBException& ex ) - { - wxLogError( _("Error loading images: %s"), ex.what() ); - } + elem = elem->NextSiblingElement("icon", false); + } + } catch (ticpp::Exception& ex) { + wxLogError(_("Error loading images: %s"), _WXSTR(ex.m_details)); + } catch (wxFBException& ex) { + wxLogError(_("Error loading images: %s"), ex.what()); + } } diff --git a/src/rad/bitmaps.h b/src/rad/bitmaps.h index f01a9b73d..52e4c319f 100644 --- a/src/rad/bitmaps.h +++ b/src/rad/bitmaps.h @@ -26,16 +26,19 @@ #ifndef RAD_BITMAPS_H #define RAD_BITMAPS_H +#include + + const int ICON_SIZE = 22; const int TOOL_SIZE = 22; const int SMALL_ICON_SIZE = 14; -#include -class AppBitmaps { +class AppBitmaps +{ public: - static wxBitmap GetBitmap(wxString iconname, unsigned int size = 0); - static void LoadBitmaps(wxString filepath, wxString iconpath); + static wxBitmap GetBitmap(wxString iconname, unsigned int size = 0); + static void LoadBitmaps(wxString filepath, wxString iconpath); }; -#endif // RAD_BITMAPS_H +#endif // RAD_BITMAPS_H diff --git a/src/rad/cmdproc.cpp b/src/rad/cmdproc.cpp index 3d8771e2f..f3d8612eb 100644 --- a/src/rad/cmdproc.cpp +++ b/src/rad/cmdproc.cpp @@ -25,95 +25,87 @@ #include "cmdproc.h" -CommandProcessor::CommandProcessor() -: -m_savePoint( 0 ) + +CommandProcessor::CommandProcessor() : m_savePoint(0) { } void CommandProcessor::Execute(PCommand command) { - command->Execute(); - m_undoStack.push(command); + command->Execute(); + m_undoStack.push(command); - while (!m_redoStack.empty()) - m_redoStack.pop(); + while (!m_redoStack.empty()) m_redoStack.pop(); } void CommandProcessor::Undo() { - if (!m_undoStack.empty()) - { - PCommand command = m_undoStack.top(); - m_undoStack.pop(); - - command->Restore(); - m_redoStack.push(command); - } + if (!m_undoStack.empty()) { + PCommand command = m_undoStack.top(); + m_undoStack.pop(); + + command->Restore(); + m_redoStack.push(command); + } } void CommandProcessor::Redo() { - if (!m_redoStack.empty()) - { - PCommand command = m_redoStack.top(); - m_redoStack.pop(); + if (!m_redoStack.empty()) { + PCommand command = m_redoStack.top(); + m_redoStack.pop(); - command->Execute(); - m_undoStack.push(command); - } + command->Execute(); + m_undoStack.push(command); + } } void CommandProcessor::Reset() { - while (!m_redoStack.empty()) - m_redoStack.pop(); + while (!m_redoStack.empty()) m_redoStack.pop(); - while (!m_undoStack.empty()) - m_undoStack.pop(); + while (!m_undoStack.empty()) m_undoStack.pop(); - m_savePoint = 0; + m_savePoint = 0; } bool CommandProcessor::CanUndo() { - return (!m_undoStack.empty()); + return (!m_undoStack.empty()); } bool CommandProcessor::CanRedo() { - return (!m_redoStack.empty()); + return (!m_redoStack.empty()); } void CommandProcessor::SetSavePoint() { - m_savePoint = m_undoStack.size(); + m_savePoint = m_undoStack.size(); } bool CommandProcessor::IsAtSavePoint() { - return m_undoStack.size() == m_savePoint; + return m_undoStack.size() == m_savePoint; } /////////////////////////////////////////////////////////////////////////////// Command::Command() { - m_executed = false; + m_executed = false; } void Command::Execute() { - if (!m_executed) - { - DoExecute(); - m_executed = true; - } + if (!m_executed) { + DoExecute(); + m_executed = true; + } } void Command::Restore() { - if (m_executed) - { - DoRestore(); - m_executed = false; - } + if (m_executed) { + DoRestore(); + m_executed = false; + } } diff --git a/src/rad/cmdproc.h b/src/rad/cmdproc.h index d4089feee..355995f51 100644 --- a/src/rad/cmdproc.h +++ b/src/rad/cmdproc.h @@ -26,59 +26,61 @@ #ifndef RAD_CMDPROC_H #define RAD_CMDPROC_H -#include #include +#include + class Command; typedef std::shared_ptr PCommand; + class CommandProcessor { - private: - typedef std::stack CommandStack; +private: + typedef std::stack CommandStack; - CommandStack m_undoStack; - CommandStack m_redoStack; - size_t m_savePoint; + CommandStack m_undoStack; + CommandStack m_redoStack; + size_t m_savePoint; - public: - CommandProcessor(); - void Execute(PCommand command); +public: + CommandProcessor(); + void Execute(PCommand command); - void Undo(); - void Redo(); - void Reset(); + void Undo(); + void Redo(); + void Reset(); - void SetSavePoint(); - bool IsAtSavePoint(); + void SetSavePoint(); + bool IsAtSavePoint(); - bool CanUndo(); - bool CanRedo(); + bool CanUndo(); + bool CanRedo(); }; class Command { - private: - bool m_executed; - - protected: - /** - * Ejecuta el comando. - */ - virtual void DoExecute() = 0; - - /** - * Restaura el estado previo a la ejecución del comando. - */ - virtual void DoRestore() = 0; - - public: - Command(); - virtual ~Command() = default; - - void Execute(); - void Restore(); +private: + bool m_executed; + +protected: + /** + * Ejecuta el comando. + */ + virtual void DoExecute() = 0; + + /** + * Restaura el estado previo a la ejecución del comando. + */ + virtual void DoRestore() = 0; + +public: + Command(); + virtual ~Command() = default; + + void Execute(); + void Restore(); }; -#endif // RAD_CMDPROC_H +#endif // RAD_CMDPROC_H diff --git a/src/rad/codeeditor/codeeditor.cpp b/src/rad/codeeditor/codeeditor.cpp index f4d80d937..a62ca1e17 100644 --- a/src/rad/codeeditor/codeeditor.cpp +++ b/src/rad/codeeditor/codeeditor.cpp @@ -28,115 +28,106 @@ #include #include #include - #include -BEGIN_EVENT_TABLE ( CodeEditor, wxPanel ) - EVT_STC_MARGINCLICK( wxID_ANY, CodeEditor::OnMarginClick ) - EVT_FIND( wxID_ANY, CodeEditor::OnFind ) - EVT_FIND_NEXT( wxID_ANY, CodeEditor::OnFind ) + +BEGIN_EVENT_TABLE(CodeEditor, wxPanel) +EVT_STC_MARGINCLICK(wxID_ANY, CodeEditor::OnMarginClick) +EVT_FIND(wxID_ANY, CodeEditor::OnFind) +EVT_FIND_NEXT(wxID_ANY, CodeEditor::OnFind) END_EVENT_TABLE() -CodeEditor::CodeEditor( wxWindow *parent, int id ) -: -wxPanel( parent, id ) + +CodeEditor::CodeEditor(wxWindow* parent, int id) : wxPanel(parent, id) { - wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); - m_code = new wxStyledTextCtrl( this ); + m_code = new wxStyledTextCtrl(this); // Line Numbers - m_code->SetMarginType( 0, wxSTC_MARGIN_NUMBER ); - m_code->SetMarginWidth( 0, m_code->TextWidth ( wxSTC_STYLE_LINENUMBER, wxT( "_99999" ) ) ); + m_code->SetMarginType(0, wxSTC_MARGIN_NUMBER); + m_code->SetMarginWidth(0, m_code->TextWidth(wxSTC_STYLE_LINENUMBER, wxT("_99999"))); // markers - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS ); - m_code->MarkerSetBackground ( wxSTC_MARKNUM_FOLDER, wxColour ( wxT( "BLACK" ) ) ); - m_code->MarkerSetForeground ( wxSTC_MARKNUM_FOLDER, wxColour ( wxT( "WHITE" ) ) ); - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS ); - m_code->MarkerSetBackground ( wxSTC_MARKNUM_FOLDEROPEN, wxColour ( wxT( "BLACK" ) ) ); - m_code->MarkerSetForeground ( wxSTC_MARKNUM_FOLDEROPEN, wxColour ( wxT( "WHITE" ) ) ); - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_EMPTY ); - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUS ); - m_code->MarkerSetBackground ( wxSTC_MARKNUM_FOLDEREND, wxColour ( wxT( "BLACK" ) ) ); - m_code->MarkerSetForeground ( wxSTC_MARKNUM_FOLDEREND, wxColour ( wxT( "WHITE" ) ) ); - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUS ); - m_code->MarkerSetBackground ( wxSTC_MARKNUM_FOLDEROPENMID, wxColour ( wxT( "BLACK" ) ) ); - m_code->MarkerSetForeground ( wxSTC_MARKNUM_FOLDEROPENMID, wxColour ( wxT( "WHITE" ) ) ); - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_EMPTY ); - m_code->MarkerDefine ( wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_EMPTY ); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDER, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDER, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDEROPEN, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDEROPEN, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_EMPTY); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDEREND, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDEREND, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUS); + m_code->MarkerSetBackground(wxSTC_MARKNUM_FOLDEROPENMID, wxColour(wxT("BLACK"))); + m_code->MarkerSetForeground(wxSTC_MARKNUM_FOLDEROPENMID, wxColour(wxT("WHITE"))); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_EMPTY); + m_code->MarkerDefine(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_EMPTY); // folding - m_code->SetMarginType ( 1, wxSTC_MARGIN_SYMBOL ); - m_code->SetMarginMask ( 1, wxSTC_MASK_FOLDERS ); - m_code->SetMarginWidth ( 1, 16 ); - m_code->SetMarginSensitive ( 1, true ); - - m_code->SetProperty( wxT( "fold" ), wxT( "1" ) ); - m_code->SetProperty( wxT( "fold.comment" ), wxT( "1" ) ); - m_code->SetProperty( wxT( "fold.compact" ), wxT( "1" ) ); - m_code->SetProperty( wxT( "fold.preprocessor" ), wxT( "1" ) ); - m_code->SetProperty( wxT( "fold.html" ), wxT( "1" ) ); - m_code->SetProperty( wxT( "fold.html.preprocessor" ), wxT( "1" ) ); - - m_code->SetFoldFlags( wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED ); - m_code->SetIndentationGuides(1); - - m_code->SetMarginWidth( 2, 0 ); - sizer->Add( m_code, 1, wxEXPAND | wxALL ); - SetSizer( sizer ); + m_code->SetMarginType(1, wxSTC_MARGIN_SYMBOL); + m_code->SetMarginMask(1, wxSTC_MASK_FOLDERS); + m_code->SetMarginWidth(1, 16); + m_code->SetMarginSensitive(1, true); + + m_code->SetProperty(wxT("fold"), wxT("1")); + m_code->SetProperty(wxT("fold.comment"), wxT("1")); + m_code->SetProperty(wxT("fold.compact"), wxT("1")); + m_code->SetProperty(wxT("fold.preprocessor"), wxT("1")); + m_code->SetProperty(wxT("fold.html"), wxT("1")); + m_code->SetProperty(wxT("fold.html.preprocessor"), wxT("1")); + + m_code->SetFoldFlags(wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED); + m_code->SetIndentationGuides(1); + + m_code->SetMarginWidth(2, 0); + sizer->Add(m_code, 1, wxEXPAND | wxALL); + SetSizer(sizer); } -void CodeEditor::OnMarginClick ( wxStyledTextEvent &event ) +void CodeEditor::OnMarginClick(wxStyledTextEvent& event) { - if ( event.GetMargin() == 1 ) - { - int lineClick = m_code->LineFromPosition ( event.GetPosition() ); - int levelClick = m_code->GetFoldLevel ( lineClick ); - - if ( ( levelClick & wxSTC_FOLDLEVELHEADERFLAG ) > 0 ) - { - m_code->ToggleFold ( lineClick ); - } - } + if (event.GetMargin() == 1) { + int lineClick = m_code->LineFromPosition(event.GetPosition()); + int levelClick = m_code->GetFoldLevel(lineClick); + + if ((levelClick & wxSTC_FOLDLEVELHEADERFLAG) > 0) { + m_code->ToggleFold(lineClick); + } + } } wxStyledTextCtrl* CodeEditor::GetTextCtrl() { - return m_code; + return m_code; } -void CodeEditor::OnFind( wxFindDialogEvent& event ) +void CodeEditor::OnFind(wxFindDialogEvent& event) { - int wxflags = event.GetFlags(); - int sciflags = 0; - if ( (wxflags & wxFR_WHOLEWORD) != 0 ) - { + int wxflags = event.GetFlags(); + int sciflags = 0; + if ((wxflags & wxFR_WHOLEWORD) != 0) { sciflags |= wxSTC_FIND_WHOLEWORD; - } - if ( (wxflags & wxFR_MATCHCASE) != 0 ) - { + } + if ((wxflags & wxFR_MATCHCASE) != 0) { sciflags |= wxSTC_FIND_MATCHCASE; - } - int result; - if ( (wxflags & wxFR_DOWN) != 0 ) - { - m_code->SetSelectionStart( m_code->GetSelectionEnd() ); - m_code->SearchAnchor(); - result = m_code->SearchNext( sciflags, event.GetFindString() ); - } - else - { - m_code->SetSelectionEnd( m_code->GetSelectionStart() ); - m_code->SearchAnchor(); - result = m_code->SearchPrev( sciflags, event.GetFindString() ); - } - if ( wxSTC_INVALID_POSITION == result ) - { - wxMessageBox( wxString::Format( _("\"%s\" not found!"), event.GetFindString() ), _("Not Found!"), wxICON_ERROR, (wxWindow*)event.GetClientData() ); - } - else - { - m_code->EnsureCaretVisible(); - } + } + int result; + if ((wxflags & wxFR_DOWN) != 0) { + m_code->SetSelectionStart(m_code->GetSelectionEnd()); + m_code->SearchAnchor(); + result = m_code->SearchNext(sciflags, event.GetFindString()); + } else { + m_code->SetSelectionEnd(m_code->GetSelectionStart()); + m_code->SearchAnchor(); + result = m_code->SearchPrev(sciflags, event.GetFindString()); + } + if (wxSTC_INVALID_POSITION == result) { + wxMessageBox( + wxString::Format(_("\"%s\" not found!"), event.GetFindString()), _("Not Found!"), wxICON_ERROR, + (wxWindow*)event.GetClientData()); + } else { + m_code->EnsureCaretVisible(); + } } diff --git a/src/rad/codeeditor/codeeditor.h b/src/rad/codeeditor/codeeditor.h index b38bca9bb..07854e57c 100644 --- a/src/rad/codeeditor/codeeditor.h +++ b/src/rad/codeeditor/codeeditor.h @@ -28,24 +28,25 @@ #include + +class wxFindDialogEvent; class wxStyledTextCtrl; class wxStyledTextEvent; -class wxFindDialogEvent; class CodeEditor : public wxPanel { private: wxStyledTextCtrl* m_code; - void OnMarginClick( wxStyledTextEvent& event ); - DECLARE_EVENT_TABLE() + void OnMarginClick(wxStyledTextEvent& event); + DECLARE_EVENT_TABLE() public: - CodeEditor( wxWindow *parent, int id ); + CodeEditor(wxWindow* parent, int id); wxStyledTextCtrl* GetTextCtrl(); - void OnFind( wxFindDialogEvent& event ); + void OnFind(wxFindDialogEvent& event); }; -#endif // RAD_CODEEDITOR_CODEEDITOR_H +#endif // RAD_CODEEDITOR_CODEEDITOR_H diff --git a/src/rad/cpppanel/cpppanel.cpp b/src/rad/cpppanel/cpppanel.cpp index 4811a238a..f872f08c1 100644 --- a/src/rad/cpppanel/cpppanel.cpp +++ b/src/rad/cpppanel/cpppanel.cpp @@ -27,405 +27,365 @@ #include "cpppanel.h" +#include +#include + +#include "codegen/codewriter.h" +#include "codegen/cppcg.h" +#include "model/objectbase.h" #include "rad/appdata.h" #include "rad/auitabart.h" #include "rad/bitmaps.h" #include "rad/codeeditor/codeeditor.h" #include "rad/wxfbevent.h" - #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "model/objectbase.h" - -#include "codegen/codewriter.h" -#include "codegen/cppcg.h" -#include -#include +BEGIN_EVENT_TABLE(CppPanel, wxPanel) +EVT_FB_CODE_GENERATION(CppPanel::OnCodeGeneration) +EVT_FB_PROJECT_REFRESH(CppPanel::OnProjectRefresh) +EVT_FB_PROPERTY_MODIFIED(CppPanel::OnPropertyModified) +EVT_FB_OBJECT_CREATED(CppPanel::OnObjectChange) +EVT_FB_OBJECT_REMOVED(CppPanel::OnObjectChange) +EVT_FB_OBJECT_SELECTED(CppPanel::OnObjectChange) +EVT_FB_EVENT_HANDLER_MODIFIED(CppPanel::OnEventHandlerModified) -BEGIN_EVENT_TABLE ( CppPanel, wxPanel ) - EVT_FB_CODE_GENERATION( CppPanel::OnCodeGeneration ) - EVT_FB_PROJECT_REFRESH( CppPanel::OnProjectRefresh ) - EVT_FB_PROPERTY_MODIFIED( CppPanel::OnPropertyModified ) - EVT_FB_OBJECT_CREATED( CppPanel::OnObjectChange ) - EVT_FB_OBJECT_REMOVED( CppPanel::OnObjectChange ) - EVT_FB_OBJECT_SELECTED( CppPanel::OnObjectChange ) - EVT_FB_EVENT_HANDLER_MODIFIED( CppPanel::OnEventHandlerModified ) - - EVT_FIND( wxID_ANY, CppPanel::OnFind ) - EVT_FIND_NEXT( wxID_ANY, CppPanel::OnFind ) +EVT_FIND(wxID_ANY, CppPanel::OnFind) +EVT_FIND_NEXT(wxID_ANY, CppPanel::OnFind) END_EVENT_TABLE() -CppPanel::CppPanel( wxWindow *parent, int id ) -: -wxPanel( parent, id ) + +CppPanel::CppPanel(wxWindow* parent, int id) : wxPanel(parent, id) { - AppData()->AddHandler( this->GetEventHandler() ); - wxBoxSizer *top_sizer = new wxBoxSizer( wxVERTICAL ); + AppData()->AddHandler(this->GetEventHandler()); + wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); - m_notebook = new wxAuiNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP ); - m_notebook->SetArtProvider( new AuiTabArt() ); + m_notebook = new wxAuiNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP); + m_notebook->SetArtProvider(new AuiTabArt()); - m_cppPanel = new CodeEditor( m_notebook, wxID_ANY); - InitStyledTextCtrl( m_cppPanel->GetTextCtrl() ); - m_notebook->InsertPage( 0, m_cppPanel, wxT( "cpp" ), false ); - m_notebook->SetPageBitmap( 0, AppBitmaps::GetBitmap( wxT( "cpp" ), 16 ) ); + m_cppPanel = new CodeEditor(m_notebook, wxID_ANY); + InitStyledTextCtrl(m_cppPanel->GetTextCtrl()); + m_notebook->InsertPage(0, m_cppPanel, wxT("cpp"), false); + m_notebook->SetPageBitmap(0, AppBitmaps::GetBitmap(wxT("cpp"), 16)); - m_hPanel = new CodeEditor( m_notebook, wxID_ANY); - InitStyledTextCtrl( m_hPanel->GetTextCtrl() ); - m_notebook->InsertPage( 1, m_hPanel, wxT( "h" ), false ); - m_notebook->SetPageBitmap( 1, AppBitmaps::GetBitmap( wxT( "h" ), 16 ) ); + m_hPanel = new CodeEditor(m_notebook, wxID_ANY); + InitStyledTextCtrl(m_hPanel->GetTextCtrl()); + m_notebook->InsertPage(1, m_hPanel, wxT("h"), false); + m_notebook->SetPageBitmap(1, AppBitmaps::GetBitmap(wxT("h"), 16)); - top_sizer->Add( m_notebook, 1, wxEXPAND, 0 ); + top_sizer->Add(m_notebook, 1, wxEXPAND, 0); - SetSizer( top_sizer ); - SetAutoLayout( true ); - //top_sizer->SetSizeHints( this ); - top_sizer->Fit( this ); - top_sizer->Layout(); + SetSizer(top_sizer); + SetAutoLayout(true); + // top_sizer->SetSizeHints( this ); + top_sizer->Fit(this); + top_sizer->Layout(); - m_hCW = PTCCodeWriter( new TCCodeWriter( m_hPanel->GetTextCtrl() ) ); - m_cppCW = PTCCodeWriter( new TCCodeWriter( m_cppPanel->GetTextCtrl() ) ); + m_hCW = PTCCodeWriter(new TCCodeWriter(m_hPanel->GetTextCtrl())); + m_cppCW = PTCCodeWriter(new TCCodeWriter(m_cppPanel->GetTextCtrl())); } CppPanel::~CppPanel() { - AppData()->RemoveHandler( this->GetEventHandler() ); + AppData()->RemoveHandler(this->GetEventHandler()); } -void CppPanel::InitStyledTextCtrl( wxStyledTextCtrl *stc ) +void CppPanel::InitStyledTextCtrl(wxStyledTextCtrl* stc) { - stc->SetLexer( wxSTC_LEX_CPP ); - stc->SetKeyWords( 0, wxT( "asm auto bool break case catch char class const const_cast \ + stc->SetLexer(wxSTC_LEX_CPP); + stc->SetKeyWords(0, wxT("asm auto bool break case catch char class const const_cast \ continue default delete do double dynamic_cast else enum explicit \ export extern false float for friend goto if inline int long \ mutable namespace new operator private protected public register \ reinterpret_cast return short signed sizeof static static_cast \ struct switch template this throw true try typedef typeid \ typename union unsigned using virtual void volatile wchar_t \ - while" ) ); + while")); #ifdef __WXGTK__ - // Debe haber un bug en wxGTK ya que la familia wxMODERN no es de ancho fijo. - wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - font.SetFaceName( wxT( "Monospace" ) ); + // Debe haber un bug en wxGTK ya que la familia wxMODERN no es de ancho fijo. + wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + font.SetFaceName(wxT("Monospace")); #else - wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); #endif - stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); - stc->StyleSetFont( wxSTC_STYLE_DEFAULT, font ); + stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); + stc->StyleSetFont(wxSTC_STYLE_DEFAULT, font); stc->StyleClearAll(); - stc->StyleSetBold( wxSTC_C_WORD, true ); - if (!AppData()->IsDarkMode()) - { - stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); - stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); - } - else - { - stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); - stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); - } - stc->SetUseTabs( true ); - stc->SetTabWidth( 4 ); - stc->SetTabIndents( true ); - stc->SetBackSpaceUnIndents( true ); - stc->SetIndent( 4 ); - stc->SetSelBackground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) ); - stc->SetSelForeground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) ); - - stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->SetCaretWidth( 2 ); - stc->SetReadOnly( true ); + stc->StyleSetBold(wxSTC_C_WORD, true); + if (!AppData()->IsDarkMode()) { + stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); + stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); + } else { + stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); + stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); + } + stc->SetUseTabs(true); + stc->SetTabWidth(4); + stc->SetTabIndents(true); + stc->SetBackSpaceUnIndents(true); + stc->SetIndent(4); + stc->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); + stc->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); + + stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->SetCaretWidth(2); + stc->SetReadOnly(true); } -void CppPanel::OnFind( wxFindDialogEvent& event ) +void CppPanel::OnFind(wxFindDialogEvent& event) { - wxAuiNotebook* languageBook = wxDynamicCast( this->GetParent(), wxAuiNotebook ); - if ( NULL == languageBook ) - { - return; - } - - int languageSelection = languageBook->GetSelection(); - if ( languageSelection < 0 ) - { - return; - } - - wxString languageText = languageBook->GetPageText( languageSelection ); - if ( wxT("C++") != languageText ) - { - return; - } - - wxAuiNotebook* notebook = wxDynamicCast( m_cppPanel->GetParent(), wxAuiNotebook ); - if ( NULL == notebook ) - { - return; - } - - int selection = notebook->GetSelection(); - if ( selection < 0 ) - { - return; - } - - wxString text = notebook->GetPageText( selection ); - if ( wxT("cpp") == text ) - { - m_cppPanel->GetEventHandler()->ProcessEvent( event ); - } - else if ( wxT("h") == text ) - { - m_hPanel->GetEventHandler()->ProcessEvent( event ); - } + wxAuiNotebook* languageBook = wxDynamicCast(this->GetParent(), wxAuiNotebook); + if (NULL == languageBook) { + return; + } + + int languageSelection = languageBook->GetSelection(); + if (languageSelection < 0) { + return; + } + + wxString languageText = languageBook->GetPageText(languageSelection); + if (wxT("C++") != languageText) { + return; + } + + wxAuiNotebook* notebook = wxDynamicCast(m_cppPanel->GetParent(), wxAuiNotebook); + if (NULL == notebook) { + return; + } + + int selection = notebook->GetSelection(); + if (selection < 0) { + return; + } + + wxString text = notebook->GetPageText(selection); + if (wxT("cpp") == text) { + m_cppPanel->GetEventHandler()->ProcessEvent(event); + } else if (wxT("h") == text) { + m_hPanel->GetEventHandler()->ProcessEvent(event); + } } -void CppPanel::OnPropertyModified( wxFBPropertyEvent& event ) +void CppPanel::OnPropertyModified(wxFBPropertyEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void CppPanel::OnProjectRefresh( wxFBEvent& event ) +void CppPanel::OnProjectRefresh(wxFBEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void CppPanel::OnObjectChange( wxFBObjectEvent& event ) +void CppPanel::OnObjectChange(wxFBObjectEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void CppPanel::OnEventHandlerModified( wxFBEventHandlerEvent& event ) +void CppPanel::OnEventHandlerModified(wxFBEventHandlerEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void CppPanel::OnCodeGeneration( wxFBEvent& event ) +void CppPanel::OnCodeGeneration(wxFBEvent& event) { PObjectBase objectToGenerate; - // Generate code in the panel if the panel is active - bool doPanel = IsShown(); - - // Using the previously unused Id field in the event to carry a boolean - bool panelOnly = ( event.GetId() != 0 ); - - // Only generate to panel + panel is not shown = do nothing - if ( panelOnly && !doPanel ) - { - return; - } - - // For code preview generate only code relevant to selected form, - // otherwise generate full project code. - - // Create copy of the original project due to possible temporary modifications - PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); - - if(panelOnly) - { - objectToGenerate = AppData()->GetSelectedForm(); - } - - if(!panelOnly || !objectToGenerate) - { - objectToGenerate = project; - } - - // If only one project item should be generated then remove the rest items - // from the temporary project - if(doPanel && panelOnly && (objectToGenerate != project)) - { - if( project->GetChildCount() > 0) - { - unsigned int i = 0; - while( project->GetChildCount() > 1 ) - { - if(project->GetChild( i ) != objectToGenerate) - { - project->RemoveChild( i ); - } - else + // Generate code in the panel if the panel is active + bool doPanel = IsShown(); + + // Using the previously unused Id field in the event to carry a boolean + bool panelOnly = (event.GetId() != 0); + + // Only generate to panel + panel is not shown = do nothing + if (panelOnly && !doPanel) { + return; + } + + // For code preview generate only code relevant to selected form, + // otherwise generate full project code. + + // Create copy of the original project due to possible temporary modifications + PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); + + if (panelOnly) { + objectToGenerate = AppData()->GetSelectedForm(); + } + + if (!panelOnly || !objectToGenerate) { + objectToGenerate = project; + } + + // If only one project item should be generated then remove the rest items + // from the temporary project + if (doPanel && panelOnly && (objectToGenerate != project)) { + if (project->GetChildCount() > 0) { + unsigned int i = 0; + while (project->GetChildCount() > 1) { + if (project->GetChild(i) != objectToGenerate) { + project->RemoveChild(i); + } else i++; } - } - } + } + } - if(!project || !objectToGenerate)return; + if (!project || !objectToGenerate) + return; // Get C++ properties from the project - // If C++ generation is not enabled, do not generate the file - bool doFile = false; - PProperty pCodeGen = project->GetProperty( wxT( "code_generation" ) ); - if ( pCodeGen ) - { - doFile = TypeConv::FlagSet( wxT("C++"), pCodeGen->GetValue() ) && !panelOnly; - } - - if ( !(doPanel || doFile ) ) - { - return; - } - - // Get First ID from Project File - unsigned int firstID = 1000; - PProperty pFirstID = project->GetProperty( wxT("first_id") ); - if ( pFirstID ) - { - firstID = pFirstID->GetValueAsInteger(); - } - - // Get the file name - wxString file; - PProperty pfile = project->GetProperty( wxT( "file" ) ); - if ( pfile ) - { - file = pfile->GetValue(); - } - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Determine if the path is absolute or relative - bool useRelativePath = false; - PProperty pRelPath = project->GetProperty( wxT( "relative_path" ) ); - if ( pRelPath ) - { - useRelativePath = ( pRelPath->GetValueAsInteger() ? true : false ); - } - - // Get the output path - wxString path; - try - { - path = AppData()->GetOutputPath(); - } - catch ( wxFBException& ex ) - { - if ( doFile ) - { - path = wxEmptyString; - wxLogWarning( ex.what() ); - return; - } - } - - // Generate code in the panel - if ( doPanel ) - { - CppCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - codegen.SetHeaderWriter( m_hCW ); - codegen.SetSourceWriter( m_cppCW ); - - Freeze(); + // If C++ generation is not enabled, do not generate the file + bool doFile = false; + PProperty pCodeGen = project->GetProperty(wxT("code_generation")); + if (pCodeGen) { + doFile = TypeConv::FlagSet(wxT("C++"), pCodeGen->GetValue()) && !panelOnly; + } + + if (!(doPanel || doFile)) { + return; + } + + // Get First ID from Project File + unsigned int firstID = 1000; + PProperty pFirstID = project->GetProperty(wxT("first_id")); + if (pFirstID) { + firstID = pFirstID->GetValueAsInteger(); + } + + // Get the file name + wxString file; + PProperty pfile = project->GetProperty(wxT("file")); + if (pfile) { + file = pfile->GetValue(); + } + if (file.empty()) { + file = wxT("noname"); + } + + // Determine if the path is absolute or relative + bool useRelativePath = false; + PProperty pRelPath = project->GetProperty(wxT("relative_path")); + if (pRelPath) { + useRelativePath = (pRelPath->GetValueAsInteger() ? true : false); + } + + // Get the output path + wxString path; + try { + path = AppData()->GetOutputPath(); + } catch (wxFBException& ex) { + if (doFile) { + path = wxEmptyString; + wxLogWarning(ex.what()); + return; + } + } + + // Generate code in the panel + if (doPanel) { + CppCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + codegen.SetHeaderWriter(m_hCW); + codegen.SetSourceWriter(m_cppCW); + + Freeze(); wxStyledTextCtrl* cppEditor = m_cppPanel->GetTextCtrl(); - wxStyledTextCtrl* hEditor = m_hPanel->GetTextCtrl(); - cppEditor->SetReadOnly( false ); - int cppLine = cppEditor->GetFirstVisibleLine() + cppEditor->LinesOnScreen() - 1; - int cppXOffset = cppEditor->GetXOffset(); - - hEditor->SetReadOnly( false ); - int hLine = hEditor->GetFirstVisibleLine() + hEditor->LinesOnScreen() - 1; - int hXOffset = hEditor->GetXOffset(); - - codegen.GenerateCode( project ); - - cppEditor->SetReadOnly( true ); - cppEditor->GotoLine( cppLine ); - cppEditor->SetXOffset( cppXOffset ); - cppEditor->SetAnchor( 0 ); - cppEditor->SetCurrentPos( 0 ); - - hEditor->SetReadOnly( true ); - hEditor->GotoLine( hLine ); - hEditor->SetXOffset( hXOffset ); - hEditor->SetAnchor( 0 ); - hEditor->SetCurrentPos( 0 ); - - Thaw(); - } - - // Generate code in the file - if ( doFile ) - { - try - { - CppCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - // Determine if Microsoft BOM should be used - bool useMicrosoftBOM = false; - - PProperty pUseMicrosoftBOM = project->GetProperty( wxT( "use_microsoft_bom" ) ); - - if ( pUseMicrosoftBOM ) - { - useMicrosoftBOM = ( pUseMicrosoftBOM->GetValueAsInteger() != 0 ); - } - - // Determine if Utf8 or Ansi is to be created - bool useUtf8 = false; - PProperty pUseUtf8 = project->GetProperty( _("encoding") ); - - if ( pUseUtf8 ) - { - useUtf8 = ( pUseUtf8->GetValueAsString() != wxT("ANSI") ); - } - - PCodeWriter h_cw( new FileCodeWriter( path + file + wxT( ".h" ), useMicrosoftBOM, useUtf8 ) ); - - PCodeWriter cpp_cw( new FileCodeWriter( path + file + wxT( ".cpp" ), useMicrosoftBOM, useUtf8 ) ); - - codegen.SetHeaderWriter( h_cw ); - codegen.SetSourceWriter( cpp_cw ); - codegen.GenerateCode( project ); - wxLogStatus( wxT( "Code generated on \'%s\'." ), path ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } + wxStyledTextCtrl* hEditor = m_hPanel->GetTextCtrl(); + cppEditor->SetReadOnly(false); + int cppLine = cppEditor->GetFirstVisibleLine() + cppEditor->LinesOnScreen() - 1; + int cppXOffset = cppEditor->GetXOffset(); + + hEditor->SetReadOnly(false); + int hLine = hEditor->GetFirstVisibleLine() + hEditor->LinesOnScreen() - 1; + int hXOffset = hEditor->GetXOffset(); + + codegen.GenerateCode(project); + + cppEditor->SetReadOnly(true); + cppEditor->GotoLine(cppLine); + cppEditor->SetXOffset(cppXOffset); + cppEditor->SetAnchor(0); + cppEditor->SetCurrentPos(0); + + hEditor->SetReadOnly(true); + hEditor->GotoLine(hLine); + hEditor->SetXOffset(hXOffset); + hEditor->SetAnchor(0); + hEditor->SetCurrentPos(0); + + Thaw(); + } + + // Generate code in the file + if (doFile) { + try { + CppCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + // Determine if Microsoft BOM should be used + bool useMicrosoftBOM = false; + + PProperty pUseMicrosoftBOM = project->GetProperty(wxT("use_microsoft_bom")); + + if (pUseMicrosoftBOM) { + useMicrosoftBOM = (pUseMicrosoftBOM->GetValueAsInteger() != 0); + } + + // Determine if Utf8 or Ansi is to be created + bool useUtf8 = false; + PProperty pUseUtf8 = project->GetProperty(_("encoding")); + + if (pUseUtf8) { + useUtf8 = (pUseUtf8->GetValueAsString() != wxT("ANSI")); + } + + PCodeWriter h_cw(new FileCodeWriter(path + file + wxT(".h"), useMicrosoftBOM, useUtf8)); + + PCodeWriter cpp_cw(new FileCodeWriter(path + file + wxT(".cpp"), useMicrosoftBOM, useUtf8)); + + codegen.SetHeaderWriter(h_cw); + codegen.SetSourceWriter(cpp_cw); + codegen.GenerateCode(project); + wxLogStatus(wxT("Code generated on \'%s\'."), path); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } } diff --git a/src/rad/cpppanel/cpppanel.h b/src/rad/cpppanel/cpppanel.h index 09634d635..a14868852 100644 --- a/src/rad/cpppanel/cpppanel.h +++ b/src/rad/cpppanel/cpppanel.h @@ -26,47 +26,45 @@ #ifndef RAD_CPPPANEL_CPPPANEL_H #define RAD_CPPPANEL_CPPPANEL_H -#include "utils/wxfbdefs.h" - #include -class CodeEditor; +#include "utils/wxfbdefs.h" -class wxStyledTextCtrl; +class CodeEditor; class wxAuiNotebook; - -class wxFindDialogEvent; - class wxFBEvent; -class wxFBPropertyEvent; -class wxFBObjectEvent; class wxFBEventHandlerEvent; +class wxFBObjectEvent; +class wxFBPropertyEvent; +class wxFindDialogEvent; +class wxStyledTextCtrl; + class CppPanel : public wxPanel { private: - CodeEditor* m_cppPanel; - CodeEditor* m_hPanel; - PTCCodeWriter m_hCW; - PTCCodeWriter m_cppCW; - wxAuiNotebook* m_notebook; + CodeEditor* m_cppPanel; + CodeEditor* m_hPanel; + PTCCodeWriter m_hCW; + PTCCodeWriter m_cppCW; + wxAuiNotebook* m_notebook; - void InitStyledTextCtrl( wxStyledTextCtrl* stc ); + void InitStyledTextCtrl(wxStyledTextCtrl* stc); public: - CppPanel( wxWindow *parent, int id ); - ~CppPanel() override; + CppPanel(wxWindow* parent, int id); + ~CppPanel() override; - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - void OnCodeGeneration( wxFBEvent& event ); - void OnObjectChange( wxFBObjectEvent& event ); - void OnEventHandlerModified( wxFBEventHandlerEvent& event ); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnCodeGeneration(wxFBEvent& event); + void OnObjectChange(wxFBObjectEvent& event); + void OnEventHandlerModified(wxFBEventHandlerEvent& event); - void OnFind( wxFindDialogEvent& event ); + void OnFind(wxFindDialogEvent& event); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; -#endif // RAD_CPPPANEL_CPPPANEL_H +#endif // RAD_CPPPANEL_CPPPANEL_H diff --git a/src/rad/customkeys.cpp b/src/rad/customkeys.cpp index 43d8655e2..3cdf5afb8 100644 --- a/src/rad/customkeys.cpp +++ b/src/rad/customkeys.cpp @@ -24,53 +24,51 @@ /////////////////////////////////////////////////////////////////////////////// #include "customkeys.h" -#include "utils/debug.h" + #include "codegen/cppcg.h" #include "model/objectbase.h" - #include "rad/appdata.h" +#include "utils/debug.h" + -BEGIN_EVENT_TABLE(CustomKeysEvtHandler,wxEvtHandler) - EVT_CHAR(CustomKeysEvtHandler::OnKeyPress) +BEGIN_EVENT_TABLE(CustomKeysEvtHandler, wxEvtHandler) +EVT_CHAR(CustomKeysEvtHandler::OnKeyPress) END_EVENT_TABLE() -void CustomKeysEvtHandler::OnKeyPress(wxKeyEvent &event) + +void CustomKeysEvtHandler::OnKeyPress(wxKeyEvent& event) { - LogDebug( wxT("%d"),event.GetKeyCode()); + LogDebug(wxT("%d"), event.GetKeyCode()); - if (event.GetKeyCode() == WXK_DELETE) - AppData()->RemoveObject(AppData()->GetSelectedObject()); - else if (event.GetKeyCode() == 'P') - { - ///// - // prueba del parser - ///// + if (event.GetKeyCode() == WXK_DELETE) + AppData()->RemoveObject(AppData()->GetSelectedObject()); + else if (event.GetKeyCode() == 'P') { + ///// + // prueba del parser + ///// - LogDebug( wxT("#### Prueba del parser ####") ); + LogDebug(wxT("#### Prueba del parser ####")); - PObjectBase obj = AppData()->GetSelectedObject(); - PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo( wxT("C++") ); + PObjectBase obj = AppData()->GetSelectedObject(); + PCodeInfo code_info = obj->GetObjectInfo()->GetCodeInfo(wxT("C++")); - LogDebug( wxT("#### Plantillas ####") ); + LogDebug(wxT("#### Plantillas ####")); - LogDebug( code_info->GetTemplate( wxT("construction") ) ); - LogDebug( code_info->GetTemplate( wxT("declaration") ) ); - LogDebug( wxT("#### Código ####") ); - { - CppTemplateParser parser(obj,code_info->GetTemplate( wxT("construction") ), false, false, wxEmptyString ); + LogDebug(code_info->GetTemplate(wxT("construction"))); + LogDebug(code_info->GetTemplate(wxT("declaration"))); + LogDebug(wxT("#### Código ####")); + { + CppTemplateParser parser(obj, code_info->GetTemplate(wxT("construction")), false, false, wxEmptyString); - LogDebug( parser.ParseTemplate() ); - } - { - CppTemplateParser parser(obj,code_info->GetTemplate( wxT("declaration") ), false, false, wxEmptyString ); + LogDebug(parser.ParseTemplate()); + } + { + CppTemplateParser parser(obj, code_info->GetTemplate(wxT("declaration")), false, false, wxEmptyString); - LogDebug( parser.ParseTemplate() ); - } - } - else if (event.GetKeyCode() == 'C') - { - AppData()->GenerateCode(); - } - else - event.Skip(); + LogDebug(parser.ParseTemplate()); + } + } else if (event.GetKeyCode() == 'C') { + AppData()->GenerateCode(); + } else + event.Skip(); } diff --git a/src/rad/customkeys.h b/src/rad/customkeys.h index 3ab355312..30034d187 100644 --- a/src/rad/customkeys.h +++ b/src/rad/customkeys.h @@ -28,16 +28,17 @@ #include + // This class is not needed because shortcuts are made through acceletors // of the MainFrame menubar. class CustomKeysEvtHandler : public wxEvtHandler { - private: - CustomKeysEvtHandler() {} +private: + CustomKeysEvtHandler() {} - DECLARE_EVENT_TABLE() - public: - void OnKeyPress(wxKeyEvent &event); + DECLARE_EVENT_TABLE() +public: + void OnKeyPress(wxKeyEvent& event); }; -#endif // RAD_CUSTOMKEYS_H +#endif // RAD_CUSTOMKEYS_H diff --git a/src/rad/dataobject/dataobject.cpp b/src/rad/dataobject/dataobject.cpp index 18d16cb65..c31ffd092 100644 --- a/src/rad/dataobject/dataobject.cpp +++ b/src/rad/dataobject/dataobject.cpp @@ -21,133 +21,128 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "dataobject.h" +#include + #include "model/objectbase.h" -#include "utils/typeconv.h" #include "rad/appdata.h" +#include "utils/typeconv.h" -#include -wxFBDataObject::wxFBDataObject(PObjectBase obj) { - if (obj) { - // create xml representation of ObjectBase - ticpp::Element element; - obj->SerializeObject( &element ); +wxFBDataObject::wxFBDataObject(PObjectBase obj) +{ + if (obj) { + // create xml representation of ObjectBase + ticpp::Element element; + obj->SerializeObject(&element); - // add version info to xml data, just in case it is pasted into a different version of wxFB - element.SetAttribute( "fbp_version_major", AppData()->m_fbpVerMajor ); - element.SetAttribute( "fbp_version_minor", AppData()->m_fbpVerMinor ); + // add version info to xml data, just in case it is pasted into a different version of wxFB + element.SetAttribute("fbp_version_major", AppData()->m_fbpVerMajor); + element.SetAttribute("fbp_version_minor", AppData()->m_fbpVerMinor); - ticpp::Document doc; - doc.LinkEndChild( &element ); - TiXmlPrinter printer; - printer.SetIndent( "\t" ); + ticpp::Document doc; + doc.LinkEndChild(&element); + TiXmlPrinter printer; + printer.SetIndent("\t"); - printer.SetLineBreak("\n"); + printer.SetLineBreak("\n"); - doc.Accept( &printer ); - m_data = printer.Str(); - } + doc.Accept(&printer); + m_data = printer.Str(); + } } -void wxFBDataObject::GetAllFormats( wxDataFormat* formats, Direction dir ) const +void wxFBDataObject::GetAllFormats(wxDataFormat* formats, Direction dir) const { - switch ( dir ) - { - case Get: - formats[0] = wxFBDataObjectFormat; - formats[1] = wxDF_TEXT; - break; - case Set: - formats[0] = wxFBDataObjectFormat; - break; - default: - break; - } + switch (dir) { + case Get: + formats[0] = wxFBDataObjectFormat; + formats[1] = wxDF_TEXT; + break; + case Set: + formats[0] = wxFBDataObjectFormat; + break; + default: + break; + } } -bool wxFBDataObject::GetDataHere( const wxDataFormat&, void* buf ) const +bool wxFBDataObject::GetDataHere(const wxDataFormat&, void* buf) const { - if ( NULL == buf ) - { - return false; - } + if (NULL == buf) { + return false; + } - memcpy( (char*)buf, m_data.c_str(), m_data.length() ); + memcpy((char*)buf, m_data.c_str(), m_data.length()); - return true; + return true; } -size_t wxFBDataObject::GetDataSize( const wxDataFormat& /*format*/ ) const +size_t wxFBDataObject::GetDataSize(const wxDataFormat& /*format*/) const { - return m_data.length(); + return m_data.length(); } -size_t wxFBDataObject::GetFormatCount( Direction dir ) const +size_t wxFBDataObject::GetFormatCount(Direction dir) const { - switch ( dir ) - { - case Get: - return 2; - case Set: - return 1; - default: - return 0; - } + switch (dir) { + case Get: + return 2; + case Set: + return 1; + default: + return 0; + } } -wxDataFormat wxFBDataObject::GetPreferredFormat( Direction /*dir*/ ) const +wxDataFormat wxFBDataObject::GetPreferredFormat(Direction /*dir*/) const { - return wxFBDataObjectFormat; + return wxFBDataObjectFormat; } -bool wxFBDataObject::SetData( const wxDataFormat& format, size_t len, const void *buf ) +bool wxFBDataObject::SetData(const wxDataFormat& format, size_t len, const void* buf) { - if ( format != wxFBDataObjectFormat ) - { - return false; - } + if (format != wxFBDataObjectFormat) { + return false; + } - m_data.assign( reinterpret_cast< const char* >( buf ), len ); - return true; + m_data.assign(reinterpret_cast(buf), len); + return true; } PObjectBase wxFBDataObject::GetObj() { - if ( m_data.empty() ) - { - return PObjectBase(); - } - - // Read Object from xml - try - { - ticpp::Document doc; - doc.Parse( m_data, true, TIXML_ENCODING_UTF8 ); - ticpp::Element* element = doc.FirstChildElement(); - - - int major, minor; - element->GetAttribute( "fbp_version_major", &major ); - element->GetAttribute( "fbp_version_minor", &minor ); - - if ( major > AppData()->m_fbpVerMajor || ( AppData()->m_fbpVerMajor == major && minor > AppData()->m_fbpVerMinor ) ) - { - wxLogError( _("This object cannot be pasted because it is from a newer version of wxFormBuilder") ); - } - - if ( major < AppData()->m_fbpVerMajor || ( AppData()->m_fbpVerMajor == major && minor < AppData()->m_fbpVerMinor ) ) - { - AppData()->ConvertObject( element, major, minor ); - } - - PObjectDatabase db = AppData()->GetObjectDatabase(); - return db->CreateObject( element ); - } - catch( ticpp::Exception& ex ) - { - wxLogError( _WXSTR( ex.m_details ) ); - return PObjectBase(); - } + if (m_data.empty()) { + return PObjectBase(); + } + + // Read Object from xml + try { + ticpp::Document doc; + doc.Parse(m_data, true, TIXML_ENCODING_UTF8); + ticpp::Element* element = doc.FirstChildElement(); + + + int major, minor; + element->GetAttribute("fbp_version_major", &major); + element->GetAttribute("fbp_version_minor", &minor); + + if ( + major > AppData()->m_fbpVerMajor || (AppData()->m_fbpVerMajor == major && minor > AppData()->m_fbpVerMinor)) { + wxLogError(_("This object cannot be pasted because it is from a newer version of wxFormBuilder")); + } + + if ( + major < AppData()->m_fbpVerMajor || (AppData()->m_fbpVerMajor == major && minor < AppData()->m_fbpVerMinor)) { + AppData()->ConvertObject(element, major, minor); + } + + PObjectDatabase db = AppData()->GetObjectDatabase(); + return db->CreateObject(element); + } catch (ticpp::Exception& ex) { + wxLogError(_WXSTR(ex.m_details)); + return PObjectBase(); + } } diff --git a/src/rad/dataobject/dataobject.h b/src/rad/dataobject/dataobject.h index dd234cc84..29016047c 100644 --- a/src/rad/dataobject/dataobject.h +++ b/src/rad/dataobject/dataobject.h @@ -21,28 +21,32 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_DATAOBJECT_DATAOBJECT_H #define RAD_DATAOBJECT_DATAOBJECT_H +#include + #include "utils/wxfbdefs.h" -#include #define wxFBDataObjectFormat wxDataFormat(wxT("wxFormBuilderDataFormat")) -class wxFBDataObject : public wxDataObject { + +class wxFBDataObject : public wxDataObject +{ public: - wxFBDataObject(PObjectBase obj = PObjectBase()); - void GetAllFormats(wxDataFormat* formats, Direction dir = Get) const override; - bool GetDataHere(const wxDataFormat& format, void* buf) const override; - size_t GetDataSize(const wxDataFormat& format) const override; - size_t GetFormatCount(Direction dir = Get) const override; - wxDataFormat GetPreferredFormat(Direction dir = Get) const override; - bool SetData(const wxDataFormat& format, size_t len, const void* buf) override; - PObjectBase GetObj(); + wxFBDataObject(PObjectBase obj = PObjectBase()); + void GetAllFormats(wxDataFormat* formats, Direction dir = Get) const override; + bool GetDataHere(const wxDataFormat& format, void* buf) const override; + size_t GetDataSize(const wxDataFormat& format) const override; + size_t GetFormatCount(Direction dir = Get) const override; + wxDataFormat GetPreferredFormat(Direction dir = Get) const override; + bool SetData(const wxDataFormat& format, size_t len, const void* buf) override; + PObjectBase GetObj(); private: - std::string m_data; + std::string m_data; }; -#endif // RAD_DATAOBJECT_DATAOBJECT_H +#endif // RAD_DATAOBJECT_DATAOBJECT_H diff --git a/src/rad/designer/innerframe.cpp b/src/rad/designer/innerframe.cpp index 53c3ab999..ac3663460 100644 --- a/src/rad/designer/innerframe.cpp +++ b/src/rad/designer/innerframe.cpp @@ -22,296 +22,283 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "innerframe.h" +#include + #include "rad/designer/window_buttons.h" -#include -DEFINE_EVENT_TYPE( wxEVT_INNER_FRAME_RESIZED ) +DEFINE_EVENT_TYPE(wxEVT_INNER_FRAME_RESIZED) + class wxInnerFrame::TitleBar : public wxPanel { private: - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() - void DrawTitleBar ( wxDC &dc ); + void DrawTitleBar(wxDC& dc); - wxBitmap m_minimize; - wxBitmap m_minimizeDisabled; - wxBitmap m_maximize; - wxBitmap m_maximizeDisabled; - wxBitmap m_close; - wxBitmap m_closeDisabled; - wxColour m_colour1, m_colour2; - wxString m_titleText; - long m_style; + wxBitmap m_minimize; + wxBitmap m_minimizeDisabled; + wxBitmap m_maximize; + wxBitmap m_maximizeDisabled; + wxBitmap m_close; + wxBitmap m_closeDisabled; + wxColour m_colour1, m_colour2; + wxString m_titleText; + long m_style; protected: - wxSize DoGetBestSize() const override { - return wxSize( 100, 19 ); - } + wxSize DoGetBestSize() const override { return wxSize(100, 19); } public: - TitleBar ( wxWindow *parent, wxWindowID id, - const wxPoint &pos = wxDefaultPosition, - const wxSize &size = wxDefaultSize, - long style = 0 ); - - void OnPaint( wxPaintEvent &event ); + TitleBar( + wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = 0); - void OnLeftClick ( wxMouseEvent &event ); - void SetTitle( const wxString &title ) { m_titleText = title; } - wxString GetTitle() { return m_titleText; } - void SetStyle( long style ) { m_style = style; } + void OnPaint(wxPaintEvent& event); + void OnLeftClick(wxMouseEvent& event); + void SetTitle(const wxString& title) { m_titleText = title; } + wxString GetTitle() { return m_titleText; } + void SetStyle(long style) { m_style = style; } }; -BEGIN_EVENT_TABLE( wxInnerFrame::TitleBar, wxPanel ) - EVT_LEFT_DOWN( wxInnerFrame::TitleBar::OnLeftClick ) - EVT_PAINT( wxInnerFrame::TitleBar::OnPaint ) +BEGIN_EVENT_TABLE(wxInnerFrame::TitleBar, wxPanel) +EVT_LEFT_DOWN(wxInnerFrame::TitleBar::OnLeftClick) +EVT_PAINT(wxInnerFrame::TitleBar::OnPaint) END_EVENT_TABLE() -wxInnerFrame::TitleBar::TitleBar ( wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style ) -: -wxPanel( parent, id, pos, size, 0/*wxFULL_REPAINT_ON_RESIZE*/ ), -m_minimize( minimize_xpm ), -m_minimizeDisabled( minimize_disabled_xpm ), -m_maximize( maximize_xpm ), -m_maximizeDisabled( maximize_disabled_xpm ), -m_close( close_xpm ), -m_closeDisabled( close_disabled_xpm ), -m_style( style ) +wxInnerFrame::TitleBar::TitleBar(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : + wxPanel(parent, id, pos, size, 0 /*wxFULL_REPAINT_ON_RESIZE*/), + m_minimize(minimize_xpm), + m_minimizeDisabled(minimize_disabled_xpm), + m_maximize(maximize_xpm), + m_maximizeDisabled(maximize_disabled_xpm), + m_close(close_xpm), + m_closeDisabled(close_disabled_xpm), + m_style(style) { - //m_colour1 = wxColour(10,36,106); - //m_colour2 = wxColour(166,202,240); + // m_colour1 = wxColour(10,36,106); + // m_colour2 = wxColour(166,202,240); - m_colour1 = wxSystemSettings::GetColour( wxSYS_COLOUR_ACTIVECAPTION ); + m_colour1 = wxSystemSettings::GetColour(wxSYS_COLOUR_ACTIVECAPTION); - int r, g, b; + int r, g, b; - r = wxMin( 255, m_colour1.Red() + 30 ); - g = wxMin( 255, m_colour1.Green() + 30 ); - b = wxMin( 255, m_colour1.Blue() + 30 ); + r = wxMin(255, m_colour1.Red() + 30); + g = wxMin(255, m_colour1.Green() + 30); + b = wxMin(255, m_colour1.Blue() + 30); - m_colour2 = wxColour( r, g, b ); - m_titleText = wxT( "wxFormBuilder rocks!" ); - SetMinSize( wxSize( 100, 19 ) ); + m_colour2 = wxColour(r, g, b); + m_titleText = wxT("wxFormBuilder rocks!"); + SetMinSize(wxSize(100, 19)); } -void wxInnerFrame::TitleBar::OnLeftClick ( wxMouseEvent &event ) +void wxInnerFrame::TitleBar::OnLeftClick(wxMouseEvent& event) { - LogDebug("OnLeftClick"); - GetParent()->GetEventHandler()->ProcessEvent( event ); + LogDebug("OnLeftClick"); + GetParent()->GetEventHandler()->ProcessEvent(event); } -void wxInnerFrame::TitleBar::OnPaint ( wxPaintEvent& ) +void wxInnerFrame::TitleBar::OnPaint(wxPaintEvent&) { - wxPaintDC dc( this ); - wxBufferedDC bdc( &dc, GetClientSize() ); - DrawTitleBar( bdc ); + wxPaintDC dc(this); + wxBufferedDC bdc(&dc, GetClientSize()); + DrawTitleBar(bdc); } -void wxInnerFrame::TitleBar::DrawTitleBar( wxDC &dc ) +void wxInnerFrame::TitleBar::DrawTitleBar(wxDC& dc) { - static const int margin = 2; - - int tbPosX, tbPosY; // title bar - int tbWidth, tbHeight; - - int wbPosX, wbPosY; // window buttons - int wbWidth /*, wbHeight*/; - - int txtPosX, txtPosY; // title text position - int /*txtWidth,*/ txtHeight; - - // setup all variables - - wxSize clientSize( GetClientSize() ); - //wxSize clientSize(500,100); - - tbPosX = tbPosY = 0; - tbHeight = m_close.GetHeight() + margin * 2; - tbWidth = clientSize.GetWidth(); - - /*wbHeight = m_close.GetHeight();*/ - wbWidth = m_close.GetWidth(); - wbPosX = tbPosX + tbWidth - wbWidth - 2 * margin; - wbPosY = tbPosX + margin; - - txtPosY = tbPosY + margin; - txtPosX = tbPosX + 15 + 2 * margin; - txtHeight = tbHeight - 2 * margin + 1; - /*txtWidth = wbPosX - 2 * margin - txtPosX;*/ - - // Draw title background with vertical gradient. - float incR = ( float )( m_colour2.Red() - m_colour1.Red() ) / tbWidth; - float incG = ( float )( m_colour2.Green() - m_colour1.Green() ) / tbWidth; - float incB = ( float )( m_colour2.Blue() - m_colour1.Blue() ) / tbWidth; - - float colourR = m_colour1.Red(); - float colourG = m_colour1.Green(); - float colourB = m_colour1.Blue(); - - wxColour colour; - wxPen pen; - for ( int i = 0; i < tbWidth; i++ ) - { - colour.Set( ( unsigned char )colourR, ( unsigned char )colourG, ( unsigned char )colourB ); - pen.SetColour( colour ); - dc.SetPen( pen ); - dc.DrawLine( tbPosX + i, tbPosY, tbPosX + i, tbPosY + tbHeight ); - - colourR += incR; - colourG += incG; - colourB += incB; - } - - // Draw title background with horizontal gradient. - /*float incR = (float)(m_colour2.Red() - m_colour1.Red()) / tbHeight; - float incG = (float)(m_colour2.Green() - m_colour1.Green()) / tbHeight; - float incB = (float)(m_colour2.Blue() - m_colour1.Blue()) / tbHeight; - - float colourR = m_colour1.Red(); - float colourG = m_colour1.Green(); - float colourB = m_colour1.Blue(); - - wxColour colour; - wxPen pen; - for (int i=0; i txtHeight ); - - dc.DrawLabel( m_titleText, wxRect( txtPosX, txtPosY, tw, th ) ); - - // Draw Buttons - bool hasClose = ( m_style & wxCLOSE_BOX ) != 0; - bool hasMinimize = ( m_style & wxMINIMIZE_BOX ) != 0; - bool hasMaximize = ( m_style & wxMAXIMIZE_BOX ) != 0; - - #ifdef __WXMSW__ - if ( ( m_style & wxSYSTEM_MENU ) == 0 ) - { - // On Windows, no buttons are drawn without System Menu - return; - } - - dc.DrawBitmap( hasClose ? m_close : m_closeDisabled, wbPosX, wbPosY, true ); - wbPosX -= m_close.GetWidth(); - - if ( hasMaximize ) - { - dc.DrawBitmap( m_maximize, wbPosX, wbPosY, true ); - } - else if ( hasMinimize ) - { - dc.DrawBitmap( m_maximizeDisabled, wbPosX, wbPosY, true ); - } - wbPosX -= m_maximize.GetWidth(); - - if ( hasMinimize ) - { - dc.DrawBitmap( m_minimize, wbPosX, wbPosY, true ); - } - else if ( hasMaximize ) - { - dc.DrawBitmap( m_minimizeDisabled, wbPosX, wbPosY, true ); - } - #else // GTK - if ( hasClose ) - { - dc.DrawBitmap( m_close, wbPosX, wbPosY, true ); - wbPosX -= m_close.GetWidth(); - } - - bool hasResizeBorder = ( m_style & wxRESIZE_BORDER ) != 0; - if ( hasMaximize && hasResizeBorder ) - { - dc.DrawBitmap( m_maximize, wbPosX, wbPosY, true ); - wbPosX -= m_maximize.GetWidth(); - } - - if ( hasMinimize ) - { - dc.DrawBitmap( m_minimize, wbPosX, wbPosY, true ); - } - #endif + static const int margin = 2; + + int tbPosX, tbPosY; // title bar + int tbWidth, tbHeight; + + int wbPosX, wbPosY; // window buttons + int wbWidth /*, wbHeight*/; + + int txtPosX, txtPosY; // title text position + int /*txtWidth,*/ txtHeight; + + // setup all variables + + wxSize clientSize(GetClientSize()); + // wxSize clientSize(500,100); + + tbPosX = tbPosY = 0; + tbHeight = m_close.GetHeight() + margin * 2; + tbWidth = clientSize.GetWidth(); + + /*wbHeight = m_close.GetHeight();*/ + wbWidth = m_close.GetWidth(); + wbPosX = tbPosX + tbWidth - wbWidth - 2 * margin; + wbPosY = tbPosX + margin; + + txtPosY = tbPosY + margin; + txtPosX = tbPosX + 15 + 2 * margin; + txtHeight = tbHeight - 2 * margin + 1; + /*txtWidth = wbPosX - 2 * margin - txtPosX;*/ + + // Draw title background with vertical gradient. + float incR = (float)(m_colour2.Red() - m_colour1.Red()) / tbWidth; + float incG = (float)(m_colour2.Green() - m_colour1.Green()) / tbWidth; + float incB = (float)(m_colour2.Blue() - m_colour1.Blue()) / tbWidth; + + float colourR = m_colour1.Red(); + float colourG = m_colour1.Green(); + float colourB = m_colour1.Blue(); + + wxColour colour; + wxPen pen; + for (int i = 0; i < tbWidth; i++) { + colour.Set((unsigned char)colourR, (unsigned char)colourG, (unsigned char)colourB); + pen.SetColour(colour); + dc.SetPen(pen); + dc.DrawLine(tbPosX + i, tbPosY, tbPosX + i, tbPosY + tbHeight); + + colourR += incR; + colourG += incG; + colourB += incB; + } + + // Draw title background with horizontal gradient. + /*float incR = (float)(m_colour2.Red() - m_colour1.Red()) / tbHeight; + float incG = (float)(m_colour2.Green() - m_colour1.Green()) / tbHeight; + float incB = (float)(m_colour2.Blue() - m_colour1.Blue()) / tbHeight; + + float colourR = m_colour1.Red(); + float colourG = m_colour1.Green(); + float colourB = m_colour1.Blue(); + + wxColour colour; + wxPen pen; + for (int i=0; i txtHeight); + + dc.DrawLabel(m_titleText, wxRect(txtPosX, txtPosY, tw, th)); + + // Draw Buttons + bool hasClose = (m_style & wxCLOSE_BOX) != 0; + bool hasMinimize = (m_style & wxMINIMIZE_BOX) != 0; + bool hasMaximize = (m_style & wxMAXIMIZE_BOX) != 0; + +#ifdef __WXMSW__ + if ((m_style & wxSYSTEM_MENU) == 0) { + // On Windows, no buttons are drawn without System Menu + return; + } + + dc.DrawBitmap(hasClose ? m_close : m_closeDisabled, wbPosX, wbPosY, true); + wbPosX -= m_close.GetWidth(); + + if (hasMaximize) { + dc.DrawBitmap(m_maximize, wbPosX, wbPosY, true); + } else if (hasMinimize) { + dc.DrawBitmap(m_maximizeDisabled, wbPosX, wbPosY, true); + } + wbPosX -= m_maximize.GetWidth(); + + if (hasMinimize) { + dc.DrawBitmap(m_minimize, wbPosX, wbPosY, true); + } else if (hasMaximize) { + dc.DrawBitmap(m_minimizeDisabled, wbPosX, wbPosY, true); + } +#else // GTK + if (hasClose) { + dc.DrawBitmap(m_close, wbPosX, wbPosY, true); + wbPosX -= m_close.GetWidth(); + } + + bool hasResizeBorder = (m_style & wxRESIZE_BORDER) != 0; + if (hasMaximize && hasResizeBorder) { + dc.DrawBitmap(m_maximize, wbPosX, wbPosY, true); + wbPosX -= m_maximize.GetWidth(); + } + + if (hasMinimize) { + dc.DrawBitmap(m_minimize, wbPosX, wbPosY, true); + } +#endif } ////////////////////////////////////////////////////////////////////////////// -BEGIN_EVENT_TABLE( wxInnerFrame, wxPanel ) - EVT_MOTION( wxInnerFrame::OnMouseMotion ) - EVT_LEFT_DOWN( wxInnerFrame::OnLeftDown ) - EVT_LEFT_UP( wxInnerFrame::OnLeftUp ) +BEGIN_EVENT_TABLE(wxInnerFrame, wxPanel) +EVT_MOTION(wxInnerFrame::OnMouseMotion) +EVT_LEFT_DOWN(wxInnerFrame::OnLeftDown) +EVT_LEFT_UP(wxInnerFrame::OnLeftUp) END_EVENT_TABLE() -wxInnerFrame::wxInnerFrame( wxWindow *parent, wxWindowID id, - const wxPoint &pos, const wxSize &size, long style ) +wxInnerFrame::wxInnerFrame(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) #ifdef __WXGTK__ - : wxPanel( parent, id, pos, size, wxNO_BORDER | wxFULL_REPAINT_ON_RESIZE ) + : + wxPanel(parent, id, pos, size, wxNO_BORDER | wxFULL_REPAINT_ON_RESIZE) #else - : wxPanel( parent, id, pos, size, wxRAISED_BORDER | wxFULL_REPAINT_ON_RESIZE ) + : + wxPanel(parent, id, pos, size, wxRAISED_BORDER | wxFULL_REPAINT_ON_RESIZE) #endif { - m_sizing = NONE; - m_curX = m_curY = -1; - m_resizeBorder = 10; - - m_titleBar = new TitleBar( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style ); - m_frameContent = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize ); - - // Use spacers to create a 1 pixel border on left and top of content panel - this is for drawing the selection box - // Use borders to create a 2 pixel border on right and bottom - this is so the back panel can catch mouse events for resizing - wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); - sizer->Add( m_titleBar, 0, wxGROW | wxRIGHT, 2 ); - sizer->AddSpacer( 1 ); - wxBoxSizer *horiSizer = new wxBoxSizer( wxHORIZONTAL ); - horiSizer->AddSpacer( 1 ); - horiSizer->Add( m_frameContent, 1, wxGROW ); - sizer->Add( horiSizer, 1, wxGROW | wxBOTTOM | wxRIGHT, 2 ); - - SetSizer( sizer ); - SetAutoLayout( true ); - Layout(); - - m_minSize = m_titleBar->GetMinSize(); - m_minSize.x += 8; - m_minSize.y += 10; - m_baseMinSize = m_minSize; - - if ( wxDefaultSize == size ) - { - SetSize( GetBestSize() ); - } + m_sizing = NONE; + m_curX = m_curY = -1; + m_resizeBorder = 10; + + m_titleBar = new TitleBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style); + m_frameContent = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize); + + // Use spacers to create a 1 pixel border on left and top of content panel - this is for drawing the selection box + // Use borders to create a 2 pixel border on right and bottom - this is so the back panel can catch mouse events for + // resizing + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(m_titleBar, 0, wxGROW | wxRIGHT, 2); + sizer->AddSpacer(1); + wxBoxSizer* horiSizer = new wxBoxSizer(wxHORIZONTAL); + horiSizer->AddSpacer(1); + horiSizer->Add(m_frameContent, 1, wxGROW); + sizer->Add(horiSizer, 1, wxGROW | wxBOTTOM | wxRIGHT, 2); + + SetSizer(sizer); + SetAutoLayout(true); + Layout(); + + m_minSize = m_titleBar->GetMinSize(); + m_minSize.x += 8; + m_minSize.y += 10; + m_baseMinSize = m_minSize; + + if (wxDefaultSize == size) { + SetSize(GetBestSize()); + } } wxSize wxInnerFrame::DoGetBestSize() const @@ -319,198 +306,191 @@ wxSize wxInnerFrame::DoGetBestSize() const wxSize best; best = m_titleBar->GetBestSize(); wxSize content = m_frameContent->GetBestSize(); - best.IncBy( 0, content.GetHeight() ); - int border = wxSystemSettings::GetMetric( wxSYS_BORDER_X ); - best.SetWidth( ( content.GetWidth() + 1 > best.GetWidth() ? content.GetWidth() + 1 : best.GetWidth() ) + 2 + 2 * ( border > 0 ? border : 2 ) ); + best.IncBy(0, content.GetHeight()); + int border = wxSystemSettings::GetMetric(wxSYS_BORDER_X); + best.SetWidth( + (content.GetWidth() + 1 > best.GetWidth() ? content.GetWidth() + 1 : best.GetWidth()) + 2 + + 2 * (border > 0 ? border : 2)); // spacers and borders - best.IncBy( 0, 3 ); + best.IncBy(0, 3); return best; } -void wxInnerFrame::OnMouseMotion( wxMouseEvent& e ) +void wxInnerFrame::OnMouseMotion(wxMouseEvent& e) { - if ( m_sizing != NONE ) - { - wxScreenDC dc; - wxPen pen(*wxBLACK, 1, wxPENSTYLE_DOT); - - dc.SetPen( pen ); - dc.SetBrush( *wxTRANSPARENT_BRUSH ); - dc.SetLogicalFunction( wxINVERT ); - - //wxPoint pos = ClientToScreen(wxPoint(0, 0)); - wxPoint pos = GetParent()->ClientToScreen( GetPosition() ); - - if ( m_curX >= 0 && m_curY >= 0 ) - dc.DrawRectangle( pos.x, pos.y, m_curX, m_curY ); - - if ( m_sizing == RIGHT || m_sizing == RIGHTBOTTOM ) - m_curX = e.GetX() + m_difX; - else - m_curX = GetSize().x; - - if ( m_sizing == BOTTOM || m_sizing == RIGHTBOTTOM ) - m_curY = e.GetY() + m_difY; - else - m_curY = GetSize().y; - - // User min size - wxSize minSize = GetMinSize(); - if ( m_curX < minSize.x ) m_curX = minSize.x; - if ( m_curY < minSize.y ) m_curY = minSize.y; - - // Internal min size - if ( m_curX < m_minSize.x ) m_curX = m_minSize.x; - if ( m_curY < m_minSize.y ) m_curY = m_minSize.y; - - wxSize maxSize = GetMaxSize(); - if ( m_curX > maxSize.x && maxSize.x != wxDefaultCoord ) m_curX = maxSize.x; - if ( m_curY > maxSize.y && maxSize.y != wxDefaultCoord ) m_curY = maxSize.y; - - dc.DrawRectangle( pos.x, pos.y, m_curX, m_curY ); - - dc.SetLogicalFunction( wxCOPY ); - dc.SetPen( wxNullPen ); - dc.SetBrush( wxNullBrush ); - } - - else - { - int x, y; - GetClientSize( &x, &y ); - - if ( ( e.GetX() >= x - m_resizeBorder && e.GetY() >= y - m_resizeBorder ) || - ( e.GetX() < m_resizeBorder && e.GetY() < m_resizeBorder ) ) - { - SetCursor( wxCursor( wxCURSOR_SIZENWSE ) ); - } - else if ( ( e.GetX() < m_resizeBorder && e.GetY() >= y - m_resizeBorder ) || - ( e.GetX() > x - m_resizeBorder && e.GetY() < m_resizeBorder ) ) - { - SetCursor( wxCursor( wxCURSOR_SIZENESW ) ); - } - else if ( e.GetX() >= x - m_resizeBorder || e.GetX() < m_resizeBorder ) - { - SetCursor( wxCursor( wxCURSOR_SIZEWE ) ); - } - else if ( e.GetY() >= y - m_resizeBorder || e.GetY() < m_resizeBorder ) - { - SetCursor( wxCursor( wxCURSOR_SIZENS ) ); - } - else - { - SetCursor( *wxSTANDARD_CURSOR ); - } - - m_titleBar->SetCursor( *wxSTANDARD_CURSOR ); - m_frameContent->SetCursor( *wxSTANDARD_CURSOR ); - } + if (m_sizing != NONE) { + wxScreenDC dc; + wxPen pen(*wxBLACK, 1, wxPENSTYLE_DOT); + + dc.SetPen(pen); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + dc.SetLogicalFunction(wxINVERT); + + // wxPoint pos = ClientToScreen(wxPoint(0, 0)); + wxPoint pos = GetParent()->ClientToScreen(GetPosition()); + + if (m_curX >= 0 && m_curY >= 0) + dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); + + if (m_sizing == RIGHT || m_sizing == RIGHTBOTTOM) + m_curX = e.GetX() + m_difX; + else + m_curX = GetSize().x; + + if (m_sizing == BOTTOM || m_sizing == RIGHTBOTTOM) + m_curY = e.GetY() + m_difY; + else + m_curY = GetSize().y; + + // User min size + wxSize minSize = GetMinSize(); + if (m_curX < minSize.x) + m_curX = minSize.x; + if (m_curY < minSize.y) + m_curY = minSize.y; + + // Internal min size + if (m_curX < m_minSize.x) + m_curX = m_minSize.x; + if (m_curY < m_minSize.y) + m_curY = m_minSize.y; + + wxSize maxSize = GetMaxSize(); + if (m_curX > maxSize.x && maxSize.x != wxDefaultCoord) + m_curX = maxSize.x; + if (m_curY > maxSize.y && maxSize.y != wxDefaultCoord) + m_curY = maxSize.y; + + dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); + + dc.SetLogicalFunction(wxCOPY); + dc.SetPen(wxNullPen); + dc.SetBrush(wxNullBrush); + } + + else { + int x, y; + GetClientSize(&x, &y); + + if ( + (e.GetX() >= x - m_resizeBorder && e.GetY() >= y - m_resizeBorder) || + (e.GetX() < m_resizeBorder && e.GetY() < m_resizeBorder)) { + SetCursor(wxCursor(wxCURSOR_SIZENWSE)); + } else if ( + (e.GetX() < m_resizeBorder && e.GetY() >= y - m_resizeBorder) || + (e.GetX() > x - m_resizeBorder && e.GetY() < m_resizeBorder)) { + SetCursor(wxCursor(wxCURSOR_SIZENESW)); + } else if (e.GetX() >= x - m_resizeBorder || e.GetX() < m_resizeBorder) { + SetCursor(wxCursor(wxCURSOR_SIZEWE)); + } else if (e.GetY() >= y - m_resizeBorder || e.GetY() < m_resizeBorder) { + SetCursor(wxCursor(wxCURSOR_SIZENS)); + } else { + SetCursor(*wxSTANDARD_CURSOR); + } + + m_titleBar->SetCursor(*wxSTANDARD_CURSOR); + m_frameContent->SetCursor(*wxSTANDARD_CURSOR); + } } -void wxInnerFrame::OnLeftDown( wxMouseEvent& e ) +void wxInnerFrame::OnLeftDown(wxMouseEvent& e) { - LogDebug(wxT("OnLeftDown")); - if ( m_sizing == NONE ) - { - if ( e.GetX() >= GetSize().x - m_resizeBorder && e.GetY() >= GetSize().y - m_resizeBorder ) - m_sizing = RIGHTBOTTOM; - else if ( e.GetX() >= GetSize().x - m_resizeBorder ) - m_sizing = RIGHT; - else if ( e.GetY() >= GetSize().y - m_resizeBorder ) - m_sizing = BOTTOM; - - if ( m_sizing != NONE ) - { - m_difX = GetSize().x - e.GetX(); - m_difY = GetSize().y - e.GetY(); - CaptureMouse(); - OnMouseMotion( e ); - } - } + LogDebug(wxT("OnLeftDown")); + if (m_sizing == NONE) { + if (e.GetX() >= GetSize().x - m_resizeBorder && e.GetY() >= GetSize().y - m_resizeBorder) + m_sizing = RIGHTBOTTOM; + else if (e.GetX() >= GetSize().x - m_resizeBorder) + m_sizing = RIGHT; + else if (e.GetY() >= GetSize().y - m_resizeBorder) + m_sizing = BOTTOM; + + if (m_sizing != NONE) { + m_difX = GetSize().x - e.GetX(); + m_difY = GetSize().y - e.GetY(); + CaptureMouse(); + OnMouseMotion(e); + } + } } -void wxInnerFrame::OnLeftUp( wxMouseEvent& ) +void wxInnerFrame::OnLeftUp(wxMouseEvent&) { - if ( m_sizing != NONE ) - { - m_sizing = NONE; - ReleaseMouse(); - - wxScreenDC dc; - wxPen pen(*wxBLACK, 1, wxPENSTYLE_DOT); - - dc.SetPen( pen ); - dc.SetBrush( *wxTRANSPARENT_BRUSH ); - dc.SetLogicalFunction( wxINVERT ); - - //wxPoint pos = ClientToScreen(wxPoint(0, 0)); - wxPoint pos = GetParent()->ClientToScreen( GetPosition() ); - - dc.DrawRectangle( pos.x, pos.y, m_curX, m_curY ); - - dc.SetLogicalFunction( wxCOPY ); - dc.SetPen( wxNullPen ); - dc.SetBrush( wxNullBrush ); - - wxScrolledWindow * VEditor = (wxScrolledWindow*)GetParent(); - int scrolledposX = 0; - int scrolledposY = 0; - VEditor->GetViewStart( &scrolledposX, &scrolledposY ); - SetSize( m_curX, m_curY ); - Freeze(); - VEditor->FitInside(); - VEditor->SetVirtualSize(GetSize().x + 20, GetSize().y + 20); - - wxCommandEvent event( wxEVT_INNER_FRAME_RESIZED, GetId() ); - event.SetEventObject( this ); - GetEventHandler()->AddPendingEvent( event ); - - VEditor->Scroll( scrolledposX, scrolledposY ); - Thaw(); - Update(); - - m_curX = m_curY = -1; - } + if (m_sizing != NONE) { + m_sizing = NONE; + ReleaseMouse(); + + wxScreenDC dc; + wxPen pen(*wxBLACK, 1, wxPENSTYLE_DOT); + + dc.SetPen(pen); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + dc.SetLogicalFunction(wxINVERT); + + // wxPoint pos = ClientToScreen(wxPoint(0, 0)); + wxPoint pos = GetParent()->ClientToScreen(GetPosition()); + + dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); + + dc.SetLogicalFunction(wxCOPY); + dc.SetPen(wxNullPen); + dc.SetBrush(wxNullBrush); + + wxScrolledWindow* VEditor = (wxScrolledWindow*)GetParent(); + int scrolledposX = 0; + int scrolledposY = 0; + VEditor->GetViewStart(&scrolledposX, &scrolledposY); + SetSize(m_curX, m_curY); + Freeze(); + VEditor->FitInside(); + VEditor->SetVirtualSize(GetSize().x + 20, GetSize().y + 20); + + wxCommandEvent event(wxEVT_INNER_FRAME_RESIZED, GetId()); + event.SetEventObject(this); + GetEventHandler()->AddPendingEvent(event); + + VEditor->Scroll(scrolledposX, scrolledposY); + Thaw(); + Update(); + + m_curX = m_curY = -1; + } } -void wxInnerFrame::ShowTitleBar( bool show ) +void wxInnerFrame::ShowTitleBar(bool show) { - m_titleBar->Show( show ); - m_minSize = ( show ? m_baseMinSize : wxSize( 10, 10 ) ); - Layout(); + m_titleBar->Show(show); + m_minSize = (show ? m_baseMinSize : wxSize(10, 10)); + Layout(); } void wxInnerFrame::SetToBaseSize() { - if ( m_titleBar->IsShown() ) - { - SetSize( m_baseMinSize ); - } - else - { - SetSize( wxSize( 10, 10 ) ); - } + if (m_titleBar->IsShown()) { + SetSize(m_baseMinSize); + } else { + SetSize(wxSize(10, 10)); + } } bool wxInnerFrame::IsTitleBarShown() { - return m_titleBar->IsShown(); + return m_titleBar->IsShown(); } -void wxInnerFrame::SetTitle( const wxString &title ) +void wxInnerFrame::SetTitle(const wxString& title) { - m_titleBar->SetTitle( title ); + m_titleBar->SetTitle(title); } wxString wxInnerFrame::GetTitle() { - return m_titleBar->GetTitle(); + return m_titleBar->GetTitle(); } -void wxInnerFrame::SetTitleStyle( long style ) +void wxInnerFrame::SetTitleStyle(long style) { - m_titleBar->SetStyle( style ); + m_titleBar->SetStyle(style); } diff --git a/src/rad/designer/innerframe.h b/src/rad/designer/innerframe.h index 3143c2607..bb99affba 100644 --- a/src/rad/designer/innerframe.h +++ b/src/rad/designer/innerframe.h @@ -22,75 +22,69 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_DESIGNER_INNERFRAME_H #define RAD_DESIGNER_INNERFRAME_H +#include +#include + #include "utils/debug.h" -#include -#include class wxInnerFrame : public wxPanel { private: + DECLARE_EVENT_TABLE() - DECLARE_EVENT_TABLE() - - enum{ - NONE, - RIGHTBOTTOM, - RIGHT, - BOTTOM - } m_sizing; + enum { NONE, RIGHTBOTTOM, RIGHT, BOTTOM } m_sizing; int m_curX, m_curY, m_difX, m_difY; int m_resizeBorder; wxSize m_minSize; wxSize m_baseMinSize; - class TitleBar; + class TitleBar; - TitleBar *m_titleBar; - wxPanel *m_frameContent; - //wxAuiManager m_mgr + TitleBar* m_titleBar; + wxPanel* m_frameContent; + // wxAuiManager m_mgr protected: - wxSize DoGetBestSize() const override; + wxSize DoGetBestSize() const override; public: - wxInnerFrame(wxWindow *parent, wxWindowID id, - const wxPoint &pos = wxDefaultPosition, - const wxSize &size = wxDefaultSize, - long style = 0); + wxInnerFrame( + wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = 0); - //virtual ~wxInnerFrame(){m_mgr.UnInit();} + // virtual ~wxInnerFrame(){m_mgr.UnInit();} - wxPanel *GetFrameContentPanel() { return m_frameContent; } - void OnMouseMotion(wxMouseEvent& e); - void OnLeftDown(wxMouseEvent& e); - void OnLeftUp(wxMouseEvent& e); + wxPanel* GetFrameContentPanel() { return m_frameContent; } + void OnMouseMotion(wxMouseEvent& e); + void OnLeftDown(wxMouseEvent& e); + void OnLeftUp(wxMouseEvent& e); - //wxAuiManager& GetAuiManager() {return m_mgr;} + // wxAuiManager& GetAuiManager() {return m_mgr;} - void SetTitle(const wxString &title); - wxString GetTitle(); + void SetTitle(const wxString& title); + wxString GetTitle(); - void SetTitleStyle( long style ); + void SetTitleStyle(long style); - void ShowTitleBar(bool show = true); - void SetToBaseSize(); - bool IsTitleBarShown(); + void ShowTitleBar(bool show = true); + void SetToBaseSize(); + bool IsTitleBarShown(); }; BEGIN_DECLARE_EVENT_TYPES() - DECLARE_LOCAL_EVENT_TYPE(wxEVT_INNER_FRAME_RESIZED, -1) +DECLARE_LOCAL_EVENT_TYPE(wxEVT_INNER_FRAME_RESIZED, -1) END_DECLARE_EVENT_TYPES() -#define EVT_INNER_FRAME_RESIZED(id, fn) \ - wx__DECLARE_EVT1(wxEVT_INNER_FRAME_RESIZED,id,wxCommandEventHandler(fn)) +#define EVT_INNER_FRAME_RESIZED(id, fn) wx__DECLARE_EVT1(wxEVT_INNER_FRAME_RESIZED, id, wxCommandEventHandler(fn)) /*wxDECLARE_EVENT(wxEVT_INNER_FRAME_RESIZED, wxCommandEvent); #define EVT_INNER_FRAME_RESIZED(id, func) \ wx__DECLARE_EVT1(wxEVT_INNER_FRAME_RESIZED, id, &func)*/ -#endif // RAD_DESIGNER_INNERFRAME_H +#endif // RAD_DESIGNER_INNERFRAME_H diff --git a/src/rad/designer/menubar.cpp b/src/rad/designer/menubar.cpp index b8f9f7f7c..475361c31 100644 --- a/src/rad/designer/menubar.cpp +++ b/src/rad/designer/menubar.cpp @@ -25,14 +25,16 @@ #include "menubar.h" -Menubar::Menubar() { - m_sizer = nullptr; + +Menubar::Menubar() +{ + m_sizer = nullptr; } -Menubar::Menubar(wxWindow *parent, int id, const wxPoint& pos, const wxSize &size, - long style, const wxString &name) : wxPanel(parent, id, pos, size, style, name) +Menubar::Menubar(wxWindow* parent, int id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : + wxPanel(parent, id, pos, size, style, name) { - wxBoxSizer *mainSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL); m_sizer = new wxBoxSizer(wxHORIZONTAL); m_sizer->Add(new wxStaticText(this, wxID_ANY, wxT(" ")), 0, wxRIGHT | wxLEFT, 0); mainSizer->Add(m_sizer, 1, wxTOP | wxBOTTOM, 3); @@ -42,31 +44,27 @@ Menubar::Menubar(wxWindow *parent, int id, const wxPoint& pos, const wxSize &siz Menubar::~Menubar() { - while (!m_menus.empty()) - { - wxMenu *menu = m_menus[0]; + while (!m_menus.empty()) { + wxMenu* menu = m_menus[0]; delete menu; m_menus.erase(m_menus.begin()); } // Delete spawned event handlers wxSizerItemList& labels = m_sizer->GetChildren(); - for ( wxSizerItemList::iterator label = labels.begin(); label != labels.end(); ++label ) - { - wxStaticText* text = dynamic_cast< wxStaticText* >( (*label)->GetWindow() ); - if ( text != 0 ) - { - if ( text->GetEventHandler() != text ) - { - text->PopEventHandler( true ); + for (wxSizerItemList::iterator label = labels.begin(); label != labels.end(); ++label) { + wxStaticText* text = dynamic_cast((*label)->GetWindow()); + if (text != 0) { + if (text->GetEventHandler() != text) { + text->PopEventHandler(true); } } } } -void Menubar::AppendMenu(const wxString& name, wxMenu *menu) +void Menubar::AppendMenu(const wxString& name, wxMenu* menu) { - wxStaticText *st = new wxStaticText(this, wxID_ANY, name); + wxStaticText* st = new wxStaticText(this, wxID_ANY, name); st->PushEventHandler(new MenuEvtHandler(st, menu)); m_sizer->Add(st, 0, wxALIGN_LEFT | wxRIGHT | wxLEFT, 5); Layout(); @@ -86,14 +84,14 @@ int Menubar::GetMenuCount() wxMenu* Menubar::Remove(int /*i*/) { - return NULL; //TODO: Implementar Menubar::Remove + return NULL; // TODO: Implementar Menubar::Remove } BEGIN_EVENT_TABLE(MenuEvtHandler, wxEvtHandler) - EVT_LEFT_DOWN(MenuEvtHandler::OnMouseEvent) +EVT_LEFT_DOWN(MenuEvtHandler::OnMouseEvent) END_EVENT_TABLE() -MenuEvtHandler::MenuEvtHandler(wxStaticText *st, wxMenu *menu) +MenuEvtHandler::MenuEvtHandler(wxStaticText* st, wxMenu* menu) { wxASSERT(menu != NULL && st != NULL); @@ -101,7 +99,7 @@ MenuEvtHandler::MenuEvtHandler(wxStaticText *st, wxMenu *menu) m_menu = menu; } -void MenuEvtHandler::OnMouseEvent(wxMouseEvent& ) +void MenuEvtHandler::OnMouseEvent(wxMouseEvent&) { m_label->PopupMenu(m_menu, 0, m_label->GetSize().y + 3); } diff --git a/src/rad/designer/menubar.h b/src/rad/designer/menubar.h index 1367ee6b8..f300ab1b8 100644 --- a/src/rad/designer/menubar.h +++ b/src/rad/designer/menubar.h @@ -27,38 +27,41 @@ #define RAD_DESIGNER_MENUBAR_H #include + #include + typedef std::vector MenuVector; + class Menubar : public wxPanel { - public: - Menubar(); - Menubar(wxWindow *parent, int id, const wxPoint& pos = wxDefaultPosition, - const wxSize &size = wxDefaultSize, - long style = 0, const wxString &name = wxT("fbmenubar")); - ~Menubar() override; - void AppendMenu(const wxString& name, wxMenu *menu); - wxMenu* GetMenu(int i); - int GetMenuCount(); - wxMenu* Remove(int i); +public: + Menubar(); + Menubar( + wxWindow* parent, int id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = 0, const wxString& name = wxT("fbmenubar")); + ~Menubar() override; + void AppendMenu(const wxString& name, wxMenu* menu); + wxMenu* GetMenu(int i); + int GetMenuCount(); + wxMenu* Remove(int i); - private: - MenuVector m_menus; - wxBoxSizer *m_sizer; +private: + MenuVector m_menus; + wxBoxSizer* m_sizer; }; class MenuEvtHandler : public wxEvtHandler { - public: - MenuEvtHandler(wxStaticText *st, wxMenu *menu); - void OnMouseEvent(wxMouseEvent& event); +public: + MenuEvtHandler(wxStaticText* st, wxMenu* menu); + void OnMouseEvent(wxMouseEvent& event); - DECLARE_EVENT_TABLE() - private: - wxStaticText *m_label; - wxMenu *m_menu; + DECLARE_EVENT_TABLE() +private: + wxStaticText* m_label; + wxMenu* m_menu; }; -#endif // RAD_DESIGNER_MENUBAR_H +#endif // RAD_DESIGNER_MENUBAR_H diff --git a/src/rad/designer/resizablepanel.cpp b/src/rad/designer/resizablepanel.cpp index 1580c85ee..8ebe58afa 100644 --- a/src/rad/designer/resizablepanel.cpp +++ b/src/rad/designer/resizablepanel.cpp @@ -25,149 +25,148 @@ #include "resizablepanel.h" + DEFINE_EVENT_TYPE(wxEVT_PANEL_RESIZED) BEGIN_EVENT_TABLE(ResizablePanel, wxPanel) - EVT_SET_CURSOR(ResizablePanel::OnSetCursor) - EVT_LEFT_DOWN(ResizablePanel::OnLeftDown) - EVT_LEFT_UP(ResizablePanel::OnLeftUp) - EVT_MOTION(ResizablePanel::OnMouseMotion) - //EVT_SIZE(ResizablePanel::OnSize) +EVT_SET_CURSOR(ResizablePanel::OnSetCursor) +EVT_LEFT_DOWN(ResizablePanel::OnLeftDown) +EVT_LEFT_UP(ResizablePanel::OnLeftUp) +EVT_MOTION(ResizablePanel::OnMouseMotion) +// EVT_SIZE(ResizablePanel::OnSize) END_EVENT_TABLE() -ResizablePanel::ResizablePanel(wxWindow *parent, const wxPoint& pos, const wxSize& size, - long style) : + +ResizablePanel::ResizablePanel(wxWindow* parent, const wxPoint& pos, const wxSize& size, long style) : wxPanel(parent, -1, pos, size, style) { - m_sizing = NONE; - m_curX = m_curY = -1; - m_minSize = wxSize(10, 10); - m_resizeBorder = 10; + m_sizing = NONE; + m_curX = m_curY = -1; + m_minSize = wxSize(10, 10); + m_resizeBorder = 10; } void ResizablePanel::SetResizeBorder(int border) { - wxASSERT(border > 0); - m_resizeBorder = border; + wxASSERT(border > 0); + m_resizeBorder = border; } int ResizablePanel::GetResizeBorder() { - return m_resizeBorder; + return m_resizeBorder; } void ResizablePanel::SetMinSize(const wxSize& size) { - m_minSize = size; + m_minSize = size; } wxSize ResizablePanel::GetMinSize() { - return m_minSize; + return m_minSize; } void ResizablePanel::OnSetCursor(wxSetCursorEvent& e) { - if (e.GetX() >= GetSize().x - m_resizeBorder && e.GetY() >= GetSize().y - m_resizeBorder) - e.SetCursor(wxCursor(wxCURSOR_SIZENWSE)); - else if (e.GetX() >= GetSize().x - m_resizeBorder) - e.SetCursor(wxCursor(wxCURSOR_SIZEWE)); - else if (e.GetY() >= GetSize().y - m_resizeBorder) - e.SetCursor(wxCursor(wxCURSOR_SIZENS)); - else - e.SetCursor(*wxSTANDARD_CURSOR); + if (e.GetX() >= GetSize().x - m_resizeBorder && e.GetY() >= GetSize().y - m_resizeBorder) + e.SetCursor(wxCursor(wxCURSOR_SIZENWSE)); + else if (e.GetX() >= GetSize().x - m_resizeBorder) + e.SetCursor(wxCursor(wxCURSOR_SIZEWE)); + else if (e.GetY() >= GetSize().y - m_resizeBorder) + e.SetCursor(wxCursor(wxCURSOR_SIZENS)); + else + e.SetCursor(*wxSTANDARD_CURSOR); } void ResizablePanel::OnMouseMotion(wxMouseEvent& e) { - if (m_sizing != NONE) - { - wxScreenDC dc; - wxPen pen(*wxBLACK, 1, wxDOT); - - dc.SetPen(pen); - dc.SetBrush(*wxTRANSPARENT_BRUSH); - dc.SetLogicalFunction(wxINVERT); - - //wxPoint pos = ClientToScreen(wxPoint(0, 0)); - wxPoint pos = GetParent()->ClientToScreen(GetPosition()); - - if (m_curX >= 0 && m_curY >= 0) - dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); - - if (m_sizing == RIGHT || m_sizing == RIGHTBOTTOM) - m_curX = e.GetX() + m_difX; - else - m_curX = GetSize().x; - - if (m_sizing == BOTTOM || m_sizing == RIGHTBOTTOM) - m_curY = e.GetY() + m_difY; - else - m_curY = GetSize().y; - - if (m_curX < m_minSize.x) m_curX = m_minSize.x; - if (m_curY < m_minSize.y) m_curY = m_minSize.y; - - dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); - - dc.SetLogicalFunction(wxCOPY); - dc.SetPen(wxNullPen); - dc.SetBrush(wxNullBrush); - } + if (m_sizing != NONE) { + wxScreenDC dc; + wxPen pen(*wxBLACK, 1, wxDOT); + + dc.SetPen(pen); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + dc.SetLogicalFunction(wxINVERT); + + // wxPoint pos = ClientToScreen(wxPoint(0, 0)); + wxPoint pos = GetParent()->ClientToScreen(GetPosition()); + + if (m_curX >= 0 && m_curY >= 0) + dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); + + if (m_sizing == RIGHT || m_sizing == RIGHTBOTTOM) + m_curX = e.GetX() + m_difX; + else + m_curX = GetSize().x; + + if (m_sizing == BOTTOM || m_sizing == RIGHTBOTTOM) + m_curY = e.GetY() + m_difY; + else + m_curY = GetSize().y; + + if (m_curX < m_minSize.x) + m_curX = m_minSize.x; + if (m_curY < m_minSize.y) + m_curY = m_minSize.y; + + dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); + + dc.SetLogicalFunction(wxCOPY); + dc.SetPen(wxNullPen); + dc.SetBrush(wxNullBrush); + } } void ResizablePanel::OnLeftDown(wxMouseEvent& e) { - if (m_sizing == NONE) - { - if (e.GetX() >= GetSize().x - m_resizeBorder && e.GetY() >= GetSize().y - m_resizeBorder) - m_sizing = RIGHTBOTTOM; - else if (e.GetX() >= GetSize().x - m_resizeBorder) - m_sizing = RIGHT; - else if (e.GetY() >= GetSize().y - m_resizeBorder) - m_sizing = BOTTOM; - - if (m_sizing != NONE) - { - m_difX = GetSize().x - e.GetX(); - m_difY = GetSize().y - e.GetY(); - CaptureMouse(); - OnMouseMotion(e); + if (m_sizing == NONE) { + if (e.GetX() >= GetSize().x - m_resizeBorder && e.GetY() >= GetSize().y - m_resizeBorder) + m_sizing = RIGHTBOTTOM; + else if (e.GetX() >= GetSize().x - m_resizeBorder) + m_sizing = RIGHT; + else if (e.GetY() >= GetSize().y - m_resizeBorder) + m_sizing = BOTTOM; + + if (m_sizing != NONE) { + m_difX = GetSize().x - e.GetX(); + m_difY = GetSize().y - e.GetY(); + CaptureMouse(); + OnMouseMotion(e); + } } - } } -void ResizablePanel::OnLeftUp(wxMouseEvent& ) +void ResizablePanel::OnLeftUp(wxMouseEvent&) { - if (m_sizing != NONE) - { - m_sizing = NONE; - ReleaseMouse(); - - wxScreenDC dc; - wxPen pen(*wxBLACK, 1, wxDOT); - - dc.SetPen(pen); - dc.SetBrush(*wxTRANSPARENT_BRUSH); - dc.SetLogicalFunction(wxINVERT); - - //wxPoint pos = ClientToScreen(wxPoint(0, 0)); - wxPoint pos = GetParent()->ClientToScreen(GetPosition()); - - dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); - - dc.SetLogicalFunction(wxCOPY); - dc.SetPen(wxNullPen); - dc.SetBrush(wxNullBrush); - - SetSize(m_curX, m_curY); - - wxCommandEvent event(wxEVT_PANEL_RESIZED, GetId()); - event.SetEventObject(this); - GetEventHandler()->ProcessEvent(event); - - m_curX = m_curY = -1; - } + if (m_sizing != NONE) { + m_sizing = NONE; + ReleaseMouse(); + + wxScreenDC dc; + wxPen pen(*wxBLACK, 1, wxDOT); + + dc.SetPen(pen); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + dc.SetLogicalFunction(wxINVERT); + + // wxPoint pos = ClientToScreen(wxPoint(0, 0)); + wxPoint pos = GetParent()->ClientToScreen(GetPosition()); + + dc.DrawRectangle(pos.x, pos.y, m_curX, m_curY); + + dc.SetLogicalFunction(wxCOPY); + dc.SetPen(wxNullPen); + dc.SetBrush(wxNullBrush); + + SetSize(m_curX, m_curY); + + wxCommandEvent event(wxEVT_PANEL_RESIZED, GetId()); + event.SetEventObject(this); + GetEventHandler()->ProcessEvent(event); + + m_curX = m_curY = -1; + } } /* diff --git a/src/rad/designer/resizablepanel.h b/src/rad/designer/resizablepanel.h index 92fb43e0b..5d3ed9376 100644 --- a/src/rad/designer/resizablepanel.h +++ b/src/rad/designer/resizablepanel.h @@ -27,49 +27,44 @@ #define RAD_DESIGNER_RESIZABLEPANEL_H #include - #include + class ResizablePanel : public wxPanel { - enum{ - NONE, - RIGHTBOTTOM, - RIGHT, - BOTTOM - } m_sizing; - + enum { NONE, RIGHTBOTTOM, RIGHT, BOTTOM } m_sizing; + int m_curX, m_curY, m_difX, m_difY; int m_resizeBorder; wxSize m_minSize; - public: - ResizablePanel(wxWindow *parent, const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL); - + +public: + ResizablePanel( + wxWindow* parent, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = wxTAB_TRAVERSAL); + void SetResizeBorder(int border); int GetResizeBorder(); void SetMinSize(const wxSize& size); wxSize GetMinSize(); - + void OnMouseMotion(wxMouseEvent& e); void OnLeftDown(wxMouseEvent& e); void OnSetCursor(wxSetCursorEvent& e); void OnLeftUp(wxMouseEvent& e); - //void OnSize(wxSizeEvent& e); - void OnPanelResized(wxSizeEvent &e); - + // void OnSize(wxSizeEvent& e); + void OnPanelResized(wxSizeEvent& e); + DECLARE_EVENT_TABLE() }; BEGIN_DECLARE_EVENT_TYPES() - DECLARE_LOCAL_EVENT_TYPE(wxEVT_PANEL_RESIZED, 6000) +DECLARE_LOCAL_EVENT_TYPE(wxEVT_PANEL_RESIZED, 6000) END_DECLARE_EVENT_TYPES() #define EVT_PANEL_RESIZED(id, fn) \ DECLARE_EVENT_TABLE_ENTRY( \ - wxEVT_PANEL_RESIZED, id, wxID_ANY, \ - (wxObjectEventFunction)(wxEventFunction) wxStaticCastEvent( wxCommandEventFunction, &fn ), \ - (wxObject *) NULL \ - ), + wxEVT_PANEL_RESIZED, id, wxID_ANY, \ + (wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxCommandEventFunction, &fn), (wxObject*)NULL), -#endif // RAD_DESIGNER_RESIZABLEPANEL_H +#endif // RAD_DESIGNER_RESIZABLEPANEL_H diff --git a/src/rad/designer/visualeditor.cpp b/src/rad/designer/visualeditor.cpp index 22f79f396..a88d916d5 100644 --- a/src/rad/designer/visualeditor.cpp +++ b/src/rad/designer/visualeditor.cpp @@ -25,1617 +25,1419 @@ #include "visualeditor.h" +#include + #include "model/objectbase.h" -#include "utils/typeconv.h" -#include "utils/wxfbexception.h" #include "rad/appdata.h" +#include "rad/designer/menubar.h" #include "rad/wxfbevent.h" #include "rad/wxfbmanager.h" -#include "rad/designer/menubar.h" - -#include +#include "utils/typeconv.h" +#include "utils/wxfbexception.h" static const int ID_TIMER_SCAN = wxWindow::NewControlId(); -BEGIN_EVENT_TABLE(VisualEditor,wxScrolledWindow) - //EVT_SASH_DRAGGED(wxID_ANY, VisualEditor::OnResizeBackPanel) - //EVT_COMMAND(wxID_ANY, wxEVT_PANEL_RESIZED, VisualEditor::OnResizeBackPanel) - EVT_INNER_FRAME_RESIZED(wxID_ANY, VisualEditor::OnResizeBackPanel) +BEGIN_EVENT_TABLE(VisualEditor, wxScrolledWindow) +// EVT_SASH_DRAGGED(wxID_ANY, VisualEditor::OnResizeBackPanel) +// EVT_COMMAND(wxID_ANY, wxEVT_PANEL_RESIZED, VisualEditor::OnResizeBackPanel) +EVT_INNER_FRAME_RESIZED(wxID_ANY, VisualEditor::OnResizeBackPanel) - EVT_FB_PROJECT_LOADED( VisualEditor::OnProjectLoaded ) - EVT_FB_PROJECT_SAVED( VisualEditor::OnProjectSaved ) - EVT_FB_OBJECT_SELECTED( VisualEditor::OnObjectSelected ) - EVT_FB_OBJECT_CREATED( VisualEditor::OnObjectCreated ) - EVT_FB_OBJECT_REMOVED( VisualEditor::OnObjectRemoved ) - EVT_FB_PROPERTY_MODIFIED( VisualEditor::OnPropertyModified ) - EVT_FB_PROJECT_REFRESH( VisualEditor::OnProjectRefresh ) - EVT_FB_CODE_GENERATION( VisualEditor::OnProjectRefresh ) +EVT_FB_PROJECT_LOADED(VisualEditor::OnProjectLoaded) +EVT_FB_PROJECT_SAVED(VisualEditor::OnProjectSaved) +EVT_FB_OBJECT_SELECTED(VisualEditor::OnObjectSelected) +EVT_FB_OBJECT_CREATED(VisualEditor::OnObjectCreated) +EVT_FB_OBJECT_REMOVED(VisualEditor::OnObjectRemoved) +EVT_FB_PROPERTY_MODIFIED(VisualEditor::OnPropertyModified) +EVT_FB_PROJECT_REFRESH(VisualEditor::OnProjectRefresh) +EVT_FB_CODE_GENERATION(VisualEditor::OnProjectRefresh) - EVT_TIMER( ID_TIMER_SCAN, VisualEditor::OnAuiScaner ) +EVT_TIMER(ID_TIMER_SCAN, VisualEditor::OnAuiScaner) END_EVENT_TABLE() -VisualEditor::VisualEditor(wxWindow *parent) -: -wxScrolledWindow(parent, wxID_ANY,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER), -m_stopSelectedEvent( false ), -m_stopModifiedEvent( false ) + +VisualEditor::VisualEditor(wxWindow* parent) : + wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER), + m_stopSelectedEvent(false), + m_stopModifiedEvent(false) { - SetExtraStyle( wxWS_EX_BLOCK_EVENTS ); + SetExtraStyle(wxWS_EX_BLOCK_EVENTS); - AppData()->AddHandler( this->GetEventHandler() ); + AppData()->AddHandler(this->GetEventHandler()); - if (!AppData()->IsDarkMode()) - { - SetOwnBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE).ChangeLightness(80)); - } - else - { - SetOwnBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE).ChangeLightness(120)); - } + if (!AppData()->IsDarkMode()) { + SetOwnBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE).ChangeLightness(80)); + } else { + SetOwnBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE).ChangeLightness(120)); + } - SetScrollRate(5, 5); + SetScrollRate(5, 5); - m_back = new DesignerWindow( this, wxID_ANY, wxPoint(10,10) ); - m_back->GetEventHandler()->Connect( wxID_ANY, wxEVT_LEFT_DOWN, wxMouseEventHandler( VisualEditor::OnClickBackPanel ), NULL, this ); + m_back = new DesignerWindow(this, wxID_ANY, wxPoint(10, 10)); + m_back->GetEventHandler()->Connect( + wxID_ANY, wxEVT_LEFT_DOWN, wxMouseEventHandler(VisualEditor::OnClickBackPanel), NULL, this); - m_auimgr = NULL; - m_auipanel = NULL; + m_auimgr = NULL; + m_auipanel = NULL; - // scan aui panes in run-time - m_AuiScaner.SetOwner( this, ID_TIMER_SCAN ); - m_AuiScaner.Start( 200 ); + // scan aui panes in run-time + m_AuiScaner.SetOwner(this, ID_TIMER_SCAN); + m_AuiScaner.Start(200); m_wizard = NULL; } void VisualEditor::DeleteAbstractObjects() { - wxObjectMap::iterator it; - for ( it = m_wxobjects.begin(); it != m_wxobjects.end(); ++it ) - { - // The abstract objects are stored as wxNoObject*'s - wxNoObject* noobject = dynamic_cast< wxNoObject* >( it->first ); - delete noobject; - if (noobject == nullptr) { - // Delete push'd visual object event handlers - if (auto* staticBoxSizer = wxDynamicCast(it->first, wxStaticBoxSizer)) - { - staticBoxSizer->GetStaticBox()->PopEventHandler(true); - } - else if (auto* window = wxDynamicCast(it->first, wxWindow)) - { - window->PopEventHandler(true); - } - } - } + wxObjectMap::iterator it; + for (it = m_wxobjects.begin(); it != m_wxobjects.end(); ++it) { + // The abstract objects are stored as wxNoObject*'s + wxNoObject* noobject = dynamic_cast(it->first); + delete noobject; + if (noobject == nullptr) { + // Delete push'd visual object event handlers + if (auto* staticBoxSizer = wxDynamicCast(it->first, wxStaticBoxSizer)) { + staticBoxSizer->GetStaticBox()->PopEventHandler(true); + } else if (auto* window = wxDynamicCast(it->first, wxWindow)) { + window->PopEventHandler(true); + } + } + } } VisualEditor::~VisualEditor() { - m_AuiScaner.Stop(); + m_AuiScaner.Stop(); - AppData()->RemoveHandler( this->GetEventHandler() ); - DeleteAbstractObjects(); + AppData()->RemoveHandler(this->GetEventHandler()); + DeleteAbstractObjects(); - ClearAui(); + ClearAui(); ClearWizard(); - ClearComponents( m_back->GetFrameContentPanel() ); + ClearComponents(m_back->GetFrameContentPanel()); } void VisualEditor::UpdateVirtualSize() { - int w, h, panelW, panelH; - GetVirtualSize(&w, &h); - m_back->GetSize(&panelW, &panelH); - panelW += 20; panelH += 20; - if (panelW != w || panelH != h) SetVirtualSize(panelW, panelH); + int w, h, panelW, panelH; + GetVirtualSize(&w, &h); + m_back->GetSize(&panelW, &panelH); + panelW += 20; + panelH += 20; + if (panelW != w || panelH != h) + SetVirtualSize(panelW, panelH); } -void VisualEditor::OnClickBackPanel( wxMouseEvent& event ) +void VisualEditor::OnClickBackPanel(wxMouseEvent& event) { - if ( m_form ) - { - AppData()->SelectObject(m_form); - } - event.Skip(); + if (m_form) { + AppData()->SelectObject(m_form); + } + event.Skip(); } -void VisualEditor::OnResizeBackPanel (wxCommandEvent &) //(wxSashEvent &event) +void VisualEditor::OnResizeBackPanel(wxCommandEvent&) //(wxSashEvent &event) { - /*wxRect rect(event.GetDragRect()); - LogDebug("VisualEditor::OnResizeBackPanel [%d,%d,%d,%d]",rect.x,rect.y,rect.width, rect.height); - m_back->SetSize(rect.width,rect.height); - m_back->Layout();*/ - LogDebug( "event: " + wxString("OnResizeBackPanel") ); - - PObjectBase form (AppData()->GetSelectedForm()); - - if (form) - { - PProperty prop(form->GetProperty( wxT("size") )); - if (prop) - { - wxString value(TypeConv::PointToString(wxPoint(m_back->GetSize().x, m_back->GetSize().y))); - AppData()->ModifyProperty(prop, value); - } - } - - /*event.Skip();*/ + /*wxRect rect(event.GetDragRect()); + LogDebug("VisualEditor::OnResizeBackPanel [%d,%d,%d,%d]",rect.x,rect.y,rect.width, rect.height); + m_back->SetSize(rect.width,rect.height); + m_back->Layout();*/ + LogDebug("event: " + wxString("OnResizeBackPanel")); + + PObjectBase form(AppData()->GetSelectedForm()); + + if (form) { + PProperty prop(form->GetProperty(wxT("size"))); + if (prop) { + wxString value(TypeConv::PointToString(wxPoint(m_back->GetSize().x, m_back->GetSize().y))); + AppData()->ModifyProperty(prop, value); + } + } + + /*event.Skip();*/ } -void VisualEditor::OnWizardPageChanged( WizardEvent &event ) +void VisualEditor::OnWizardPageChanged(WizardEvent& event) { int i = event.GetInt(); - if ( !i ) - { - AppData()->GetManager()->SelectObject( event.GetPage() ); + if (!i) { + AppData()->GetManager()->SelectObject(event.GetPage()); return; } event.Skip(); } -PObjectBase VisualEditor::GetObjectBase( wxObject* wxobject ) +PObjectBase VisualEditor::GetObjectBase(wxObject* wxobject) { - if ( NULL == wxobject ) - { - wxLogError( _("wxObject was NULL!") ); - return PObjectBase(); - } - - wxObjectMap::iterator obj = m_wxobjects.find( wxobject ); - if ( obj != m_wxobjects.end() ) - { - return obj->second; - } - else - { - wxLogError( _("No corresponding ObjectBase for wxObject. Name: %s"), wxobject->GetClassInfo()->GetClassName() ); - return PObjectBase(); - } + if (NULL == wxobject) { + wxLogError(_("wxObject was NULL!")); + return PObjectBase(); + } + + wxObjectMap::iterator obj = m_wxobjects.find(wxobject); + if (obj != m_wxobjects.end()) { + return obj->second; + } else { + wxLogError(_("No corresponding ObjectBase for wxObject. Name: %s"), wxobject->GetClassInfo()->GetClassName()); + return PObjectBase(); + } } -wxObject* VisualEditor::GetWxObject( PObjectBase baseobject ) +wxObject* VisualEditor::GetWxObject(PObjectBase baseobject) { - if ( !baseobject ) - { - wxLogError( _("baseobject was NULL!") ); - return NULL; - } - - ObjectBaseMap::iterator obj = m_baseobjects.find( baseobject.get() ); - if ( obj != m_baseobjects.end() ) - { - return obj->second; - } - else - { - wxLogError( _("No corresponding wxObject for ObjectBase. Name: %s"), baseobject->GetClassName() ); - return NULL; - } + if (!baseobject) { + wxLogError(_("baseobject was NULL!")); + return NULL; + } + + ObjectBaseMap::iterator obj = m_baseobjects.find(baseobject.get()); + if (obj != m_baseobjects.end()) { + return obj->second; + } else { + wxLogError(_("No corresponding wxObject for ObjectBase. Name: %s"), baseobject->GetClassName()); + return NULL; + } } -void VisualEditor::ScanPanes( wxWindow* parent) +void VisualEditor::ScanPanes(wxWindow* parent) { - bool updateNeeded; - - wxLogNull stopTheLogging; - const wxWindowList& children = parent->GetChildren(); - for ( wxWindowList::const_reverse_iterator child = children.rbegin(); child != children.rend(); ++child ) - { - ScanPanes(*child); - - PObjectBase obj = GetObjectBase( *child ); - - if ( obj ) - { - updateNeeded = false; - - PObjectInfo obj_info = obj->GetObjectInfo(); - wxString cname = obj_info->GetObjectType()->GetName(); - - if( cname == wxT("widget") || - cname == wxT("expanded_widget") || - cname == wxT("ribbonbar") || - cname == wxT("propgrid") || - cname == wxT("propgridman") || - cname == wxT("dataviewctrl") || - cname == wxT("dataviewtreectrl") || - cname == wxT("dataviewlistctrl") || - cname == wxT("toolbar") || - cname == wxT("container") ) - { - wxAuiPaneInfo inf = m_auimgr->GetPane(*child); - if(inf.IsOk()) - { - // scan position and docking mode - if (obj->GetPropertyAsInteger(wxT("center_pane")) == 0) { - wxString dock; - if( inf.IsDocked()) - { - wxString dockDir; - switch(inf.dock_direction) - { - case 1: - dockDir = wxT("Top"); - break; - - case 2: - dockDir = wxT("Right"); - break; - - case 3: - dockDir = wxT("Bottom"); - break; - - case 4: - dockDir = wxT("Left"); - break; - - case 5: - dockDir = wxT("Center"); - break; - - default: - dockDir = wxT("Left"); - break; - } - PProperty pdock = obj->GetProperty( wxT("docking") ); - - if( pdock->GetValue() != dockDir ) - { - pdock->SetValue( dockDir ); - updateNeeded = true; - } - - dock = wxT("Dock"); - } - else - { - // scan "floating position" - wxPoint pos = inf.floating_pos; - if ( pos.x != -1 && pos.y != -1 ) - { - PProperty pposition = obj->GetProperty( wxT("pane_position") ); - if( pposition->GetValue() != TypeConv::PointToString( pos ) ) - { - pposition->SetValue( TypeConv::PointToString( pos ) ); - updateNeeded = true; - } - } - - // scan "floating size" - wxSize paneSize = inf.floating_size; - if ( paneSize.x != -1 && paneSize.y != -1 ) - { - PProperty psize = obj->GetProperty( wxT("pane_size") ); - - if( psize->GetValue() != TypeConv::SizeToString( paneSize ) ) - { - psize->SetValue( TypeConv::SizeToString( paneSize ) ); - obj->GetProperty( wxT("resize") )->SetValue( wxT("Resizable") ); - - updateNeeded = true; - } - } - - dock = wxT("Float"); - } - PProperty pfloat = obj->GetProperty(wxT("dock") ); - if( pfloat->GetValue() != dock ) - { - pfloat->SetValue( dock ); - updateNeeded = true; - } - - // scan "best size" - /*wxSize bestSize = inf.best_size; - if ( bestSize.x != -1 && bestSize.y != -1 ) - { - PProperty psize = obj->GetProperty( wxT("best_size") ); - - if( psize->GetValue() != TypeConv::SizeToString( bestSize ) ) - { - psize->SetValue( TypeConv::SizeToString( bestSize ) ); - obj->GetProperty( wxT("resize") )->SetValue( wxT("Resizable") ); - - updateNeeded = true; - } - }*/ - - // scan "row" and "layer" - PProperty prop = obj->GetProperty(wxT("aui_row") ); - if( obj->GetPropertyAsInteger( wxT("aui_row") ) != inf.dock_row ) - { - prop->SetValue( inf.dock_row ); - updateNeeded = true; - } - prop = obj->GetProperty(wxT("aui_layer") ); - if( obj->GetPropertyAsInteger( wxT("aui_layer") ) != inf.dock_layer ) - { - prop->SetValue( inf.dock_layer ); - updateNeeded = true; - } - } - - // scan "show" property - PProperty pshow = obj->GetProperty(wxT("show") ); - if( obj->GetPropertyAsInteger( wxT("show") ) != (int) inf.IsShown() ) - { - pshow->SetValue(inf.IsShown() ? 1 : 0); - updateNeeded = true; - } - - if( updateNeeded ) AppData()->SelectObject( obj, true, true ); - } - } - } - } + bool updateNeeded; + + wxLogNull stopTheLogging; + const wxWindowList& children = parent->GetChildren(); + for (wxWindowList::const_reverse_iterator child = children.rbegin(); child != children.rend(); ++child) { + ScanPanes(*child); + + PObjectBase obj = GetObjectBase(*child); + + if (obj) { + updateNeeded = false; + + PObjectInfo obj_info = obj->GetObjectInfo(); + wxString cname = obj_info->GetObjectType()->GetName(); + + if ( + cname == wxT("widget") || cname == wxT("expanded_widget") || cname == wxT("ribbonbar") || + cname == wxT("propgrid") || cname == wxT("propgridman") || cname == wxT("dataviewctrl") || + cname == wxT("dataviewtreectrl") || cname == wxT("dataviewlistctrl") || cname == wxT("toolbar") || + cname == wxT("container")) { + wxAuiPaneInfo inf = m_auimgr->GetPane(*child); + if (inf.IsOk()) { + // scan position and docking mode + if (obj->GetPropertyAsInteger(wxT("center_pane")) == 0) { + wxString dock; + if (inf.IsDocked()) { + wxString dockDir; + switch (inf.dock_direction) { + case 1: + dockDir = wxT("Top"); + break; + + case 2: + dockDir = wxT("Right"); + break; + + case 3: + dockDir = wxT("Bottom"); + break; + + case 4: + dockDir = wxT("Left"); + break; + + case 5: + dockDir = wxT("Center"); + break; + + default: + dockDir = wxT("Left"); + break; + } + PProperty pdock = obj->GetProperty(wxT("docking")); + + if (pdock->GetValue() != dockDir) { + pdock->SetValue(dockDir); + updateNeeded = true; + } + + dock = wxT("Dock"); + } else { + // scan "floating position" + wxPoint pos = inf.floating_pos; + if (pos.x != -1 && pos.y != -1) { + PProperty pposition = obj->GetProperty(wxT("pane_position")); + if (pposition->GetValue() != TypeConv::PointToString(pos)) { + pposition->SetValue(TypeConv::PointToString(pos)); + updateNeeded = true; + } + } + + // scan "floating size" + wxSize paneSize = inf.floating_size; + if (paneSize.x != -1 && paneSize.y != -1) { + PProperty psize = obj->GetProperty(wxT("pane_size")); + + if (psize->GetValue() != TypeConv::SizeToString(paneSize)) { + psize->SetValue(TypeConv::SizeToString(paneSize)); + obj->GetProperty(wxT("resize"))->SetValue(wxT("Resizable")); + + updateNeeded = true; + } + } + + dock = wxT("Float"); + } + PProperty pfloat = obj->GetProperty(wxT("dock")); + if (pfloat->GetValue() != dock) { + pfloat->SetValue(dock); + updateNeeded = true; + } + // scan "best size" + /*wxSize bestSize = inf.best_size; + if ( bestSize.x != -1 && bestSize.y != -1 ) + { + PProperty psize = obj->GetProperty( wxT("best_size") ); + + if( psize->GetValue() != TypeConv::SizeToString( bestSize ) ) + { + psize->SetValue( TypeConv::SizeToString( bestSize ) ); + obj->GetProperty( wxT("resize") )->SetValue( wxT("Resizable") ); + + updateNeeded = true; + } + }*/ + + // scan "row" and "layer" + PProperty prop = obj->GetProperty(wxT("aui_row")); + if (obj->GetPropertyAsInteger(wxT("aui_row")) != inf.dock_row) { + prop->SetValue(inf.dock_row); + updateNeeded = true; + } + prop = obj->GetProperty(wxT("aui_layer")); + if (obj->GetPropertyAsInteger(wxT("aui_layer")) != inf.dock_layer) { + prop->SetValue(inf.dock_layer); + updateNeeded = true; + } + } + + // scan "show" property + PProperty pshow = obj->GetProperty(wxT("show")); + if (obj->GetPropertyAsInteger(wxT("show")) != (int)inf.IsShown()) { + pshow->SetValue(inf.IsShown() ? 1 : 0); + updateNeeded = true; + } + + if (updateNeeded) + AppData()->SelectObject(obj, true, true); + } + } + } + } } void VisualEditor::ClearAui() { - if ( m_auimgr ) - { - m_auimgr->UnInit(); - - delete m_auimgr; - m_auimgr = NULL; - m_auipanel = NULL; - } + if (m_auimgr) { + m_auimgr->UnInit(); + + delete m_auimgr; + m_auimgr = NULL; + m_auipanel = NULL; + } } void VisualEditor::ClearWizard() { - if ( m_wizard ) - { - m_wizard->Disconnect( wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler( VisualEditor::OnWizardPageChanged ) ); + if (m_wizard) { + m_wizard->Disconnect( + wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler(VisualEditor::OnWizardPageChanged)); m_wizard->Destroy(); - m_wizard = NULL; - } + m_wizard = NULL; + } } -void VisualEditor::ClearComponents( wxWindow* parent ) +void VisualEditor::ClearComponents(wxWindow* parent) { - // Individual wxWindow's of composite components made of wxWindow's will be found here as well and won't have an associated ObjectBase, - // prevent the error log messages + // Individual wxWindow's of composite components made of wxWindow's will be found here as well and won't have an + // associated ObjectBase, prevent the error log messages wxLogNull stopTheLogging; const wxWindowList& children = parent->GetChildren(); - for ( wxWindowList::const_reverse_iterator child = children.rbegin(); child != children.rend(); ++child ) - { - ClearComponents( *child ); + for (wxWindowList::const_reverse_iterator child = children.rbegin(); child != children.rend(); ++child) { + ClearComponents(*child); - PObjectBase obj = GetObjectBase( *child ); - if ( obj ) - { - PObjectInfo obj_info = obj->GetObjectInfo(); + PObjectBase obj = GetObjectBase(*child); + if (obj) { + PObjectInfo obj_info = obj->GetObjectInfo(); IComponent* comp = obj_info->GetComponent(); - if ( comp ) - { - comp->Cleanup( *child ); + if (comp) { + comp->Cleanup(*child); } } } } /** -* Crea la vista preliminar borrando la previa. -*/ + * Crea la vista preliminar borrando la previa. + */ void VisualEditor::Create() { -#if !defined(__WXGTK__ ) - if ( IsShown() ) - { - Freeze(); // Prevent flickering on wx 2.8, - // Causes problems on wx 2.9 in wxGTK (e.g. wxNoteBook objects) - } +#if !defined(__WXGTK__) + if (IsShown()) { + Freeze(); // Prevent flickering on wx 2.8, + // Causes problems on wx 2.9 in wxGTK (e.g. wxNoteBook objects) + } #endif - // Delete objects which had no parent - DeleteAbstractObjects(); + // Delete objects which had no parent + DeleteAbstractObjects(); - // Clear selections, delete objects - m_back->SetSelectedItem(NULL); - m_back->SetSelectedSizer(NULL); - m_back->SetSelectedObject(PObjectBase()); + // Clear selections, delete objects + m_back->SetSelectedItem(NULL); + m_back->SetSelectedSizer(NULL); + m_back->SetSelectedObject(PObjectBase()); - ClearAui(); + ClearAui(); ClearWizard(); - ClearComponents( m_back->GetFrameContentPanel() ); - - m_back->GetFrameContentPanel()->DestroyChildren(); - m_back->GetFrameContentPanel()->SetSizer( NULL ); // *!* - - // Clear all associations between ObjectBase and wxObjects - m_wxobjects.clear(); - m_baseobjects.clear(); - - if( IsShown() ) - { - m_form = AppData()->GetSelectedForm(); - if ( m_form ) - { - m_back->Show(true); - - // --- [1] Configure the size of the form --------------------------- - - // Get size properties - wxSize minSize( m_form->GetPropertyAsSize( wxT("minimum_size") ) ); - m_back->SetMinSize( minSize ); - - wxSize maxSize( m_form->GetPropertyAsSize( wxT("maximum_size") ) ); - m_back->SetMaxSize( maxSize ); - - wxSize size( m_form->GetPropertyAsSize( wxT("size") ) ); - - // Determine necessary size for back panel - wxSize backSize = size; - if ( backSize.GetWidth() < minSize.GetWidth() && backSize.GetWidth() != wxDefaultCoord ) - { - backSize.SetWidth( minSize.GetWidth() ); - } - if ( backSize.GetHeight() < minSize.GetHeight() && backSize.GetHeight() != wxDefaultCoord ) - { - backSize.SetHeight( minSize.GetHeight() ); - } - if ( backSize.GetWidth() > maxSize.GetWidth() && maxSize.GetWidth() != wxDefaultCoord ) - { - backSize.SetWidth( maxSize.GetWidth() ); - } - if ( backSize.GetHeight() > maxSize.GetHeight() && maxSize.GetHeight() != wxDefaultCoord ) - { - backSize.SetHeight( maxSize.GetHeight() ); - } - - if ( size != backSize ) - { - // Since we could be called by VisualEditor::OnPropertyModified we mustn't trigger a - // modify event again. Creating a delayed event won't work either, as this would - // mess up the undo/redo stack. Therefore we just log about the invalid size: - LogDebug("size is NOT between of minimum_size and maximum_size"); - } - - // --- [2] Set the color of the form ------------------------------- - PProperty background( m_form->GetProperty( wxT("bg") ) ); - if ( background && !background->GetValue().empty() ) - { - m_back->GetFrameContentPanel()->SetBackgroundColour( TypeConv::StringToColour( background->GetValue() ) ); - } - else - { - if ( m_form->GetClassName() == wxT("Frame") ) - { - m_back->GetFrameContentPanel()->SetOwnBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_APPWORKSPACE ) ); - } - else - { - #ifdef __WXGTK__ - wxVisualAttributes attribs = wxToolBar::GetClassDefaultAttributes(); - m_back->GetFrameContentPanel()->SetOwnBackgroundColour( attribs.colBg ); - #else - m_back->GetFrameContentPanel()->SetOwnBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) ); - #endif - } - } - - // --- [3] Title bar Setup - if ( m_form->GetClassName() == wxT("Frame") || - m_form->GetClassName() == wxT("Dialog") || - m_form->GetClassName() == wxT("Wizard") ) - { - m_back->SetTitle( m_form->GetPropertyAsString( wxT("title") ) ); - long style = m_form->GetPropertyAsInteger( wxT("style") ); - m_back->SetTitleStyle( style ); - m_back->ShowTitleBar( (style & wxCAPTION) != 0 ); - } - else - m_back->ShowTitleBar(false); - - // --- AUI - if( m_form->GetObjectTypeName() == wxT("form") ) - { - if( m_form->GetPropertyAsInteger( wxT("aui_managed") ) == 1) - { - m_auipanel = new wxPanel( m_back->GetFrameContentPanel() ); - m_auimgr = new wxAuiManager( m_auipanel, m_form->GetPropertyAsInteger( wxT("aui_manager_style") ) ); - } - } + ClearComponents(m_back->GetFrameContentPanel()); + + m_back->GetFrameContentPanel()->DestroyChildren(); + m_back->GetFrameContentPanel()->SetSizer(NULL); // *!* + + // Clear all associations between ObjectBase and wxObjects + m_wxobjects.clear(); + m_baseobjects.clear(); + + if (IsShown()) { + m_form = AppData()->GetSelectedForm(); + if (m_form) { + m_back->Show(true); + + // --- [1] Configure the size of the form --------------------------- + + // Get size properties + wxSize minSize(m_form->GetPropertyAsSize(wxT("minimum_size"))); + m_back->SetMinSize(minSize); + + wxSize maxSize(m_form->GetPropertyAsSize(wxT("maximum_size"))); + m_back->SetMaxSize(maxSize); + + wxSize size(m_form->GetPropertyAsSize(wxT("size"))); + + // Determine necessary size for back panel + wxSize backSize = size; + if (backSize.GetWidth() < minSize.GetWidth() && backSize.GetWidth() != wxDefaultCoord) { + backSize.SetWidth(minSize.GetWidth()); + } + if (backSize.GetHeight() < minSize.GetHeight() && backSize.GetHeight() != wxDefaultCoord) { + backSize.SetHeight(minSize.GetHeight()); + } + if (backSize.GetWidth() > maxSize.GetWidth() && maxSize.GetWidth() != wxDefaultCoord) { + backSize.SetWidth(maxSize.GetWidth()); + } + if (backSize.GetHeight() > maxSize.GetHeight() && maxSize.GetHeight() != wxDefaultCoord) { + backSize.SetHeight(maxSize.GetHeight()); + } + + if (size != backSize) { + // Since we could be called by VisualEditor::OnPropertyModified we mustn't trigger a + // modify event again. Creating a delayed event won't work either, as this would + // mess up the undo/redo stack. Therefore we just log about the invalid size: + LogDebug("size is NOT between of minimum_size and maximum_size"); + } + + // --- [2] Set the color of the form ------------------------------- + PProperty background(m_form->GetProperty(wxT("bg"))); + if (background && !background->GetValue().empty()) { + m_back->GetFrameContentPanel()->SetBackgroundColour(TypeConv::StringToColour(background->GetValue())); + } else { + if (m_form->GetClassName() == wxT("Frame")) { + m_back->GetFrameContentPanel()->SetOwnBackgroundColour( + wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE)); + } else { +#ifdef __WXGTK__ + wxVisualAttributes attribs = wxToolBar::GetClassDefaultAttributes(); + m_back->GetFrameContentPanel()->SetOwnBackgroundColour(attribs.colBg); +#else + m_back->GetFrameContentPanel()->SetOwnBackgroundColour( + wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE)); +#endif + } + } + + // --- [3] Title bar Setup + if ( + m_form->GetClassName() == wxT("Frame") || m_form->GetClassName() == wxT("Dialog") || + m_form->GetClassName() == wxT("Wizard")) { + m_back->SetTitle(m_form->GetPropertyAsString(wxT("title"))); + long style = m_form->GetPropertyAsInteger(wxT("style")); + m_back->SetTitleStyle(style); + m_back->ShowTitleBar((style & wxCAPTION) != 0); + } else + m_back->ShowTitleBar(false); + + // --- AUI + if (m_form->GetObjectTypeName() == wxT("form")) { + if (m_form->GetPropertyAsInteger(wxT("aui_managed")) == 1) { + m_auipanel = new wxPanel(m_back->GetFrameContentPanel()); + m_auimgr = new wxAuiManager(m_auipanel, m_form->GetPropertyAsInteger(wxT("aui_manager_style"))); + } + } // --- Wizard - if ( m_form->GetClassName() == wxT("Wizard") ) - { - m_wizard = new Wizard( m_back->GetFrameContentPanel() ); + if (m_form->GetClassName() == wxT("Wizard")) { + m_wizard = new Wizard(m_back->GetFrameContentPanel()); bool showbutton = false; - PProperty pextra_style = m_form->GetProperty( wxT("extra_style") ); - if ( pextra_style ) - { - showbutton = pextra_style->GetValue().Contains( wxT("wxWIZARD_EX_HELPBUTTON") ); + PProperty pextra_style = m_form->GetProperty(wxT("extra_style")); + if (pextra_style) { + showbutton = pextra_style->GetValue().Contains(wxT("wxWIZARD_EX_HELPBUTTON")); } - m_wizard->ShowHelpButton( showbutton ); + m_wizard->ShowHelpButton(showbutton); - if ( !m_form->GetProperty( wxT("bitmap") )->IsNull() ) - { - wxBitmap bmp = m_form->GetPropertyAsBitmap( wxT("bitmap") ); - if ( bmp.IsOk() ) - { - m_wizard->SetBitmap( bmp ); + if (!m_form->GetProperty(wxT("bitmap"))->IsNull()) { + wxBitmap bmp = m_form->GetPropertyAsBitmap(wxT("bitmap")); + if (bmp.IsOk()) { + m_wizard->SetBitmap(bmp); } } } - // --- [4] Create the components of the form ------------------------- - - // Used to save frame objects for later display - PObjectBase menubar; - wxWindow* statusbar = NULL; - wxWindow* toolbar = NULL; - - for ( unsigned int i = 0; i < m_form->GetChildCount(); i++ ) - { - PObjectBase child = m_form->GetChild( i ); - - if( !menubar && (m_form->GetObjectTypeName() == wxT("menubar_form")) ) - { - // main form acts as a menubar - menubar = m_form; - } - else if (child->GetObjectTypeName() == wxT("menubar") ) - { - // Create the menubar later - menubar = child; - } else if (toolbar == nullptr && - m_form->GetObjectTypeName() == wxT("toolbar_form")) { - Generate( m_form, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel() ); - - ObjectBaseMap::iterator it = m_baseobjects.find( m_form.get() ); - toolbar = wxDynamicCast( it->second, wxToolBar ); - - break; - } - else - { - // Recursively generate the ObjectTree - try - { - // we have to put the content frame panel as parentObject in order - // to SetSizeHints be called. - if( m_auipanel ) - { - Generate( child, m_auipanel, m_auipanel ); - } - else if( m_wizard ) - { - Generate( child, m_wizard, m_wizard ); - } - else - Generate( child, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel() ); - - } - catch ( wxFBException& ex ) - { - wxLogError ( ex.what() ); - } - } - - // Attach the toolbar (if any) to the frame - if (child->GetClassName() == wxT("wxToolBar") ) - { - ObjectBaseMap::iterator it = m_baseobjects.find( child.get() ); - toolbar = wxDynamicCast( it->second, wxToolBar ); - } - else if (child->GetClassName() == wxT("wxAuiToolBar") ) - { - ObjectBaseMap::iterator it = m_baseobjects.find( child.get() ); - toolbar = wxDynamicCast( it->second, wxAuiToolBar ); - } - - // Attach the status bar (if any) to the frame - if ( child->GetObjectInfo()->IsSubclassOf( wxT("wxStatusBar") ) ) - { - ObjectBaseMap::iterator it = m_baseobjects.find( child.get() ); - statusbar = wxDynamicCast( it->second, wxStatusBar ); - } - - // Add toolbar(s) to AuiManager and update content - if( m_auimgr && toolbar ) - { - SetupAui( GetObjectBase( toolbar ), toolbar ); - toolbar = NULL; - } - } - - if ( menubar || statusbar || toolbar || m_auipanel || m_wizard ) - { - if( m_auimgr ) - { - m_back->SetFrameWidgets( menubar, NULL, statusbar, m_auipanel ); - } - else if( m_wizard ) - { - m_back->SetFrameWidgets( menubar, NULL, NULL, m_wizard ); + // --- [4] Create the components of the form ------------------------- + + // Used to save frame objects for later display + PObjectBase menubar; + wxWindow* statusbar = NULL; + wxWindow* toolbar = NULL; + + for (unsigned int i = 0; i < m_form->GetChildCount(); i++) { + PObjectBase child = m_form->GetChild(i); + + if (!menubar && (m_form->GetObjectTypeName() == wxT("menubar_form"))) { + // main form acts as a menubar + menubar = m_form; + } else if (child->GetObjectTypeName() == wxT("menubar")) { + // Create the menubar later + menubar = child; + } else if (toolbar == nullptr && m_form->GetObjectTypeName() == wxT("toolbar_form")) { + Generate(m_form, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel()); + + ObjectBaseMap::iterator it = m_baseobjects.find(m_form.get()); + toolbar = wxDynamicCast(it->second, wxToolBar); + + break; + } else { + // Recursively generate the ObjectTree + try { + // we have to put the content frame panel as parentObject in order + // to SetSizeHints be called. + if (m_auipanel) { + Generate(child, m_auipanel, m_auipanel); + } else if (m_wizard) { + Generate(child, m_wizard, m_wizard); + } else + Generate(child, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel()); + + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } + + // Attach the toolbar (if any) to the frame + if (child->GetClassName() == wxT("wxToolBar")) { + ObjectBaseMap::iterator it = m_baseobjects.find(child.get()); + toolbar = wxDynamicCast(it->second, wxToolBar); + } else if (child->GetClassName() == wxT("wxAuiToolBar")) { + ObjectBaseMap::iterator it = m_baseobjects.find(child.get()); + toolbar = wxDynamicCast(it->second, wxAuiToolBar); } - else - m_back->SetFrameWidgets( menubar, toolbar, statusbar, m_auipanel ); - } - - m_back->Layout(); - - if ( backSize.GetHeight() == wxDefaultCoord || backSize.GetWidth() == wxDefaultCoord ) - { - m_back->GetSizer()->Fit( m_back ); - m_back->SetClientSize( m_back->GetBestSize() ); - } - - // Set size after fitting so if only one dimesion is -1, it still fits that dimension - m_back->SetSize( backSize ); - - PProperty enabled( m_form->GetProperty( wxT("enabled") ) ); - if ( enabled ) - { - m_back->Enable( TypeConv::StringToInt( enabled->GetValue() ) != 0 ); - } - - PProperty hidden( m_form->GetProperty( wxT("hidden") ) ); - if ( hidden ) - { - m_back->Show( TypeConv::StringToInt( hidden->GetValue() ) == 0 ); - } - - if( m_auimgr ) m_auimgr->Update(); - else - m_back->Refresh(); - - Refresh(); - } - else - { - // There is no form to display - m_back->Show(false); - Refresh(); - } + + // Attach the status bar (if any) to the frame + if (child->GetObjectInfo()->IsSubclassOf(wxT("wxStatusBar"))) { + ObjectBaseMap::iterator it = m_baseobjects.find(child.get()); + statusbar = wxDynamicCast(it->second, wxStatusBar); + } + + // Add toolbar(s) to AuiManager and update content + if (m_auimgr && toolbar) { + SetupAui(GetObjectBase(toolbar), toolbar); + toolbar = NULL; + } + } + + if (menubar || statusbar || toolbar || m_auipanel || m_wizard) { + if (m_auimgr) { + m_back->SetFrameWidgets(menubar, NULL, statusbar, m_auipanel); + } else if (m_wizard) { + m_back->SetFrameWidgets(menubar, NULL, NULL, m_wizard); + } else + m_back->SetFrameWidgets(menubar, toolbar, statusbar, m_auipanel); + } + + m_back->Layout(); + + if (backSize.GetHeight() == wxDefaultCoord || backSize.GetWidth() == wxDefaultCoord) { + m_back->GetSizer()->Fit(m_back); + m_back->SetClientSize(m_back->GetBestSize()); + } + + // Set size after fitting so if only one dimesion is -1, it still fits that dimension + m_back->SetSize(backSize); + + PProperty enabled(m_form->GetProperty(wxT("enabled"))); + if (enabled) { + m_back->Enable(TypeConv::StringToInt(enabled->GetValue()) != 0); + } + + PProperty hidden(m_form->GetProperty(wxT("hidden"))); + if (hidden) { + m_back->Show(TypeConv::StringToInt(hidden->GetValue()) == 0); + } + + if (m_auimgr) + m_auimgr->Update(); + else + m_back->Refresh(); + + Refresh(); + } else { + // There is no form to display + m_back->Show(false); + Refresh(); + } #if !defined(__WXGTK__) - Thaw(); + Thaw(); #endif - } + } - UpdateVirtualSize(); + UpdateVirtualSize(); } /** -* Generates wxObjects from ObjectBase -* -* @param obj ObjectBase to generate. -* @param parent wxWindow parent, necessary to instantiate a widget. -* @param parentObject ObjectBase parent - not always the same as the wxparent (e.g. an abstract component). -*/ -void VisualEditor::Generate( PObjectBase obj, wxWindow* wxparent, wxObject* parentObject ) + * Generates wxObjects from ObjectBase + * + * @param obj ObjectBase to generate. + * @param parent wxWindow parent, necessary to instantiate a widget. + * @param parentObject ObjectBase parent - not always the same as the wxparent (e.g. an abstract component). + */ +void VisualEditor::Generate(PObjectBase obj, wxWindow* wxparent, wxObject* parentObject) { - // Get Component - PObjectInfo obj_info = obj->GetObjectInfo(); - IComponent* comp = obj_info->GetComponent(); - - if ( NULL == comp ) - { - THROW_WXFBEX( wxString::Format( wxT("Component for %s not found!"), obj->GetClassName() ) ); - } - - // Create Object - wxObject* createdObject = comp->Create( obj.get(), wxparent ); - wxWindow* createdWindow = NULL; - wxSizer* createdSizer = NULL; - wxWindow* vobjWindow = nullptr; - wxEvtHandler* vobjHandler = nullptr; - - switch ( comp->GetComponentType() ) - { - case COMPONENT_TYPE_WINDOW: - createdWindow = wxDynamicCast( createdObject, wxWindow ); - if ( NULL == createdWindow ) - { - THROW_WXFBEX( wxString::Format( wxT("Component for %s was registered as a window component, but this is not a wxWindow!"), obj->GetClassName() ) ); - } - SetupWindow( obj, createdWindow ); - - // The event handler must be pushed after OnCreated() because that might push its own event handlers, so record it here only - // Because wxCollapsiblePane replaces createdWindow the target for the event handler must be recorded as well - vobjWindow = createdWindow; - vobjHandler = new VObjEvtHandler(createdWindow, obj); - break; - - case COMPONENT_TYPE_SIZER: - { - wxStaticBoxSizer* staticBoxSizer = wxDynamicCast( createdObject, wxStaticBoxSizer ); - if ( staticBoxSizer ) - { - createdWindow = staticBoxSizer->GetStaticBox(); - createdSizer = staticBoxSizer; - } - else - { - createdSizer = wxDynamicCast( createdObject, wxSizer ); - } - if ( NULL == createdSizer ) - { - THROW_WXFBEX( wxString::Format( wxT("Component for %s was registered as a sizer component, but this is not a wxSizer!"), obj->GetClassName() ) ); - } - SetupSizer( obj, createdSizer ); - - if (createdWindow) - { - // The event handler must be pushed after OnCreated() because that might push its own event handlers, so record it here only - // Because wxCollapsiblePane replaces createdWindow the target for the event handler must be recorded as well - vobjWindow = createdWindow; - vobjHandler = new VObjEvtHandler(createdWindow, obj); - } - break; - } - default: - break; - } - - // Associate the wxObject* with the PObjectBase - m_wxobjects.insert( wxObjectMap::value_type( createdObject, obj ) ); - m_baseobjects.insert( ObjectBaseMap::value_type( obj.get(), createdObject ) ); - - // Access to collapsible pane - wxCollapsiblePane* collpane = wxDynamicCast( createdObject, wxCollapsiblePane ); - if ( collpane != NULL ) { - createdWindow = collpane->GetPane(); - createdObject = createdWindow; - } - - // New wxparent for the window's children - wxWindow* new_wxparent = ( createdWindow ? createdWindow : wxparent ); - - // Recursively generate the children - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - Generate( obj->GetChild( i ), new_wxparent, createdObject ); - } - - comp->OnCreated( createdObject, wxparent ); - - // Now push the event handler so that it will be the last one in the chain - if (vobjWindow && vobjHandler) - { - vobjWindow->PushEventHandler(vobjHandler); - } - - // If the created object is a sizer and the parent object is a window, set the sizer to the window - if ( - ( createdSizer != NULL && NULL != wxDynamicCast( parentObject, wxWindow ) ) - || - ( NULL == parentObject && createdSizer != NULL ) - ) - { - wxparent->SetSizer( createdSizer ); - if ( parentObject ) - createdSizer->SetSizeHints( wxparent ); - - wxparent->SetAutoLayout(true); - wxparent->Layout(); - } + // Get Component + PObjectInfo obj_info = obj->GetObjectInfo(); + IComponent* comp = obj_info->GetComponent(); + + if (NULL == comp) { + THROW_WXFBEX(wxString::Format(wxT("Component for %s not found!"), obj->GetClassName())); + } + + // Create Object + wxObject* createdObject = comp->Create(obj.get(), wxparent); + wxWindow* createdWindow = NULL; + wxSizer* createdSizer = NULL; + wxWindow* vobjWindow = nullptr; + wxEvtHandler* vobjHandler = nullptr; + + switch (comp->GetComponentType()) { + case COMPONENT_TYPE_WINDOW: + createdWindow = wxDynamicCast(createdObject, wxWindow); + if (NULL == createdWindow) { + THROW_WXFBEX(wxString::Format( + wxT("Component for %s was registered as a window component, but this is not a wxWindow!"), + obj->GetClassName())); + } + SetupWindow(obj, createdWindow); + + // The event handler must be pushed after OnCreated() because that might push its own event handlers, so + // record it here only Because wxCollapsiblePane replaces createdWindow the target for the event handler + // must be recorded as well + vobjWindow = createdWindow; + vobjHandler = new VObjEvtHandler(createdWindow, obj); + break; + + case COMPONENT_TYPE_SIZER: { + wxStaticBoxSizer* staticBoxSizer = wxDynamicCast(createdObject, wxStaticBoxSizer); + if (staticBoxSizer) { + createdWindow = staticBoxSizer->GetStaticBox(); + createdSizer = staticBoxSizer; + } else { + createdSizer = wxDynamicCast(createdObject, wxSizer); + } + if (NULL == createdSizer) { + THROW_WXFBEX(wxString::Format( + wxT("Component for %s was registered as a sizer component, but this is not a wxSizer!"), + obj->GetClassName())); + } + SetupSizer(obj, createdSizer); + + if (createdWindow) { + // The event handler must be pushed after OnCreated() because that might push its own event handlers, so + // record it here only Because wxCollapsiblePane replaces createdWindow the target for the event handler + // must be recorded as well + vobjWindow = createdWindow; + vobjHandler = new VObjEvtHandler(createdWindow, obj); + } + break; + } + default: + break; + } + + // Associate the wxObject* with the PObjectBase + m_wxobjects.insert(wxObjectMap::value_type(createdObject, obj)); + m_baseobjects.insert(ObjectBaseMap::value_type(obj.get(), createdObject)); + + // Access to collapsible pane + wxCollapsiblePane* collpane = wxDynamicCast(createdObject, wxCollapsiblePane); + if (collpane != NULL) { + createdWindow = collpane->GetPane(); + createdObject = createdWindow; + } + + // New wxparent for the window's children + wxWindow* new_wxparent = (createdWindow ? createdWindow : wxparent); + + // Recursively generate the children + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { Generate(obj->GetChild(i), new_wxparent, createdObject); } + + comp->OnCreated(createdObject, wxparent); + + // Now push the event handler so that it will be the last one in the chain + if (vobjWindow && vobjHandler) { + vobjWindow->PushEventHandler(vobjHandler); + } + + // If the created object is a sizer and the parent object is a window, set the sizer to the window + if ( + (createdSizer != NULL && NULL != wxDynamicCast(parentObject, wxWindow)) || + (NULL == parentObject && createdSizer != NULL)) { + wxparent->SetSizer(createdSizer); + if (parentObject) + createdSizer->SetSizeHints(wxparent); + + wxparent->SetAutoLayout(true); + wxparent->Layout(); + } } -void VisualEditor::SetupSizer( PObjectBase obj, wxSizer* sizer ) +void VisualEditor::SetupSizer(PObjectBase obj, wxSizer* sizer) { - wxSize minsize = obj->GetPropertyAsSize( wxT("minimum_size") ); - if ( minsize != wxDefaultSize ) - { - sizer->SetMinSize( minsize ); - sizer->Layout(); - } + wxSize minsize = obj->GetPropertyAsSize(wxT("minimum_size")); + if (minsize != wxDefaultSize) { + sizer->SetMinSize(minsize); + sizer->Layout(); + } } -void VisualEditor::SetupWindow( PObjectBase obj, wxWindow* window ) +void VisualEditor::SetupWindow(PObjectBase obj, wxWindow* window) { - // All of the properties of the wxWindow object are applied in this function - - // Position - /* Position does nothing in wxFB - this is pointless - wxPoint pos; - PProperty ppos = obj->GetProperty( wxT("pos") ); - if ( ppos ) - { - pos = TypeConv::StringToPoint( ppos->GetValue() ); - } - */ - - // Size - wxSize size = obj->GetPropertyAsSize( wxT("size") ); - if ( size != wxDefaultSize ) - { - window->SetSize( size ); - } - - // Minimum size - wxSize minsize = obj->GetPropertyAsSize( wxT("minimum_size") ); - if ( minsize != wxDefaultSize ) - { - window->SetMinSize( minsize ); - } - - // Maximum size - wxSize maxsize = obj->GetPropertyAsSize( wxT("maximum_size") ); - if ( maxsize != wxDefaultSize ) - { - window->SetMaxSize( maxsize ); - } - - // Font - PProperty pfont = obj->GetProperty( wxT("font") ); - if ( pfont && !pfont->GetValue().empty() ) - { - window->SetFont( TypeConv::StringToFont( pfont->GetValue() ) ); - } - - // Foreground - PProperty pfg_colour = obj->GetProperty( wxT("fg") ); - if ( pfg_colour && !pfg_colour->GetValue().empty() ) - { - window->SetForegroundColour( TypeConv::StringToColour( pfg_colour->GetValue() ) ); - } - - // Background - PProperty pbg_colour = obj->GetProperty( wxT("bg") ); - if ( pbg_colour && !pbg_colour->GetValue().empty() ) - { - window->SetBackgroundColour( TypeConv::StringToColour( pbg_colour->GetValue() ) ); - } - - // Extra Style - PProperty pextra_style = obj->GetProperty( wxT("window_extra_style") ); - if ( pextra_style ) - { - window->SetExtraStyle( TypeConv::StringToInt( pextra_style->GetValue() ) ); - } - - // Enabled - PProperty penabled = obj->GetProperty( wxT("enabled") ); - if ( penabled ) - { - window->Enable( ( penabled->GetValueAsInteger() !=0 ) ); - } - - // Hidden - PProperty phidden = obj->GetProperty( wxT("hidden") ); - if ( phidden ) - { - window->Show(phidden->GetValueAsInteger() == 0); - } - - // Tooltip - PProperty ptooltip = obj->GetProperty( wxT("tooltip") ); - if ( ptooltip ) - { - window->SetToolTip( ptooltip->GetValueAsString() ); - } - - //AUI - wxString tname = obj->GetObjectInfo()->GetObjectType()->GetName(); - if( m_auimgr && ( tname == wxT("widget") || - tname == wxT("expanded_widget") || - tname == wxT("container") || - tname == wxT("notebook") || - tname == wxT("auinotebook") || - tname == wxT("flatnotebook") || - tname == wxT("listbook") || - tname == wxT("simplebook") || - tname == wxT("choicebook") || - tname == wxT("treelistctrl") || - tname == wxT("ribbonbar") || - tname == wxT("dataviewctrl") || - tname == wxT("dataviewtreectrl") || - tname == wxT("dataviewlistctrl") || - tname == wxT("propgrid") || - tname == wxT("propgridman") || - tname == wxT("splitter") ) ) - { - if( obj->GetParent()->GetObjectTypeName() == wxT("form") ) - { - SetupAui(obj, window); - } - } - // Wizard - else if ( obj->GetParent()->GetObjectTypeName() == wxT("wizard") ) + // All of the properties of the wxWindow object are applied in this function + + // Position + /* Position does nothing in wxFB - this is pointless + wxPoint pos; + PProperty ppos = obj->GetProperty( wxT("pos") ); + if ( ppos ) { - SetupWizard( obj, window, true ); + pos = TypeConv::StringToPoint( ppos->GetValue() ); } -} + */ -void VisualEditor::SetupAui( PObjectBase obj, wxWindow* window ) -{ - wxAuiPaneInfo info; - - // check whether the object contains AUI info... - if( !obj->GetProperty( wxT("aui_name") ) ) return; - - wxString name = obj->GetPropertyAsString( wxT("aui_name") ); - if( name != wxT("") ) info.Name( name ); - - if (obj->GetPropertyAsInteger(wxT("center_pane")) != 0) { - info.CenterPane(); - } - if (obj->GetPropertyAsInteger(wxT("default_pane")) != 0) { - info.DefaultPane(); - } - - if( !obj->IsNull(wxT("caption"))) info.Caption(obj->GetPropertyAsString(wxT("caption"))); - info.CaptionVisible(obj->GetPropertyAsInteger(wxT("caption_visible")) != 0); - info.CloseButton(obj->GetPropertyAsInteger(wxT("close_button")) != 0); - info.MaximizeButton(obj->GetPropertyAsInteger(wxT("maximize_button")) != 0); - info.MinimizeButton(obj->GetPropertyAsInteger(wxT("minimize_button")) != 0); - info.PinButton(obj->GetPropertyAsInteger(wxT("pin_button")) != 0); - info.PaneBorder(obj->GetPropertyAsInteger(wxT("pane_border")) != 0); - info.Gripper(obj->GetPropertyAsInteger(wxT("gripper")) != 0); - - info.BottomDockable(obj->GetPropertyAsInteger(wxT("BottomDockable")) != 0); - info.TopDockable(obj->GetPropertyAsInteger(wxT("TopDockable")) != 0); - info.LeftDockable(obj->GetPropertyAsInteger(wxT("LeftDockable")) != 0); - info.RightDockable(obj->GetPropertyAsInteger(wxT("RightDockable")) != 0); - - if( !obj->IsNull(wxT("dock")) ) - { - if( obj->GetPropertyAsString( wxT("dock") ) == wxT("Dock")) - { - info.Dock(); - if( !obj->IsNull(wxT("docking")) ) - { - if( obj->GetPropertyAsString(wxT("docking")) == wxT("Bottom") ) info.Bottom(); - else if( obj->GetPropertyAsString(wxT("docking")) == wxT("Top") ) info.Top(); - else if( obj->GetPropertyAsString(wxT("docking")) == wxT("Center") ) info.Center(); - else if( obj->GetPropertyAsString(wxT("docking")) == wxT("Right") ) info.Right(); - } - } - else - { - info.Float(); - info.FloatingPosition( obj->GetPropertyAsPoint( wxT("pane_position") ) ); - } - } - - if( !obj->IsNull(wxT("resize")) ) - { - if( obj->GetPropertyAsString( wxT("resize") ) == wxT("Resizable")) info.Resizable(); - else info.Fixed(); - } - - info.DockFixed(obj->GetPropertyAsInteger(wxT("dock_fixed")) != 0); - info.Movable(obj->GetPropertyAsInteger(wxT("moveable")) != 0); - info.Floatable(obj->GetPropertyAsInteger(wxT("floatable")) != 0); - - if( !obj->GetProperty( wxT("pane_size" ) )->IsNull() ) info.FloatingSize( obj->GetPropertyAsSize( wxT("pane_size") )); - if( !obj->GetProperty( wxT("best_size" ) )->IsNull() ) info.BestSize( obj->GetPropertyAsSize( wxT("best_size") ) ); - if( !obj->GetProperty( wxT("min_size" ) )->IsNull() ) info.MinSize( obj->GetPropertyAsSize( wxT("min_size") ) ); - if( !obj->GetProperty( wxT("max_size" ) )->IsNull() ) info.MaxSize( obj->GetPropertyAsSize( wxT("max_size") ) ); - - if (obj->GetPropertyAsInteger(wxT("toolbar_pane")) != 0) { - info.ToolbarPane(); - } - if( !obj->IsNull( wxT("aui_position") ) ) info.Position( obj->GetPropertyAsInteger( wxT("aui_position") )); - if( !obj->IsNull( wxT("aui_row") ) ) info.Row( obj->GetPropertyAsInteger( wxT("aui_row") )); - if( !obj->IsNull( wxT("aui_layer") ) ) info.Layer( obj->GetPropertyAsInteger( wxT("aui_layer") )); - if (obj->GetPropertyAsInteger(wxT("show")) == 0) { - info.Hide(); - } - - m_auimgr->AddPane( window, info ); + // Size + wxSize size = obj->GetPropertyAsSize(wxT("size")); + if (size != wxDefaultSize) { + window->SetSize(size); + } + + // Minimum size + wxSize minsize = obj->GetPropertyAsSize(wxT("minimum_size")); + if (minsize != wxDefaultSize) { + window->SetMinSize(minsize); + } + + // Maximum size + wxSize maxsize = obj->GetPropertyAsSize(wxT("maximum_size")); + if (maxsize != wxDefaultSize) { + window->SetMaxSize(maxsize); + } + + // Font + PProperty pfont = obj->GetProperty(wxT("font")); + if (pfont && !pfont->GetValue().empty()) { + window->SetFont(TypeConv::StringToFont(pfont->GetValue())); + } + + // Foreground + PProperty pfg_colour = obj->GetProperty(wxT("fg")); + if (pfg_colour && !pfg_colour->GetValue().empty()) { + window->SetForegroundColour(TypeConv::StringToColour(pfg_colour->GetValue())); + } + + // Background + PProperty pbg_colour = obj->GetProperty(wxT("bg")); + if (pbg_colour && !pbg_colour->GetValue().empty()) { + window->SetBackgroundColour(TypeConv::StringToColour(pbg_colour->GetValue())); + } + + // Extra Style + PProperty pextra_style = obj->GetProperty(wxT("window_extra_style")); + if (pextra_style) { + window->SetExtraStyle(TypeConv::StringToInt(pextra_style->GetValue())); + } + + // Enabled + PProperty penabled = obj->GetProperty(wxT("enabled")); + if (penabled) { + window->Enable((penabled->GetValueAsInteger() != 0)); + } + + // Hidden + PProperty phidden = obj->GetProperty(wxT("hidden")); + if (phidden) { + window->Show(phidden->GetValueAsInteger() == 0); + } + + // Tooltip + PProperty ptooltip = obj->GetProperty(wxT("tooltip")); + if (ptooltip) { + window->SetToolTip(ptooltip->GetValueAsString()); + } + + // AUI + wxString tname = obj->GetObjectInfo()->GetObjectType()->GetName(); + if ( + m_auimgr && (tname == wxT("widget") || tname == wxT("expanded_widget") || tname == wxT("container") || + tname == wxT("notebook") || tname == wxT("auinotebook") || tname == wxT("flatnotebook") || + tname == wxT("listbook") || tname == wxT("simplebook") || tname == wxT("choicebook") || + tname == wxT("treelistctrl") || tname == wxT("ribbonbar") || tname == wxT("dataviewctrl") || + tname == wxT("dataviewtreectrl") || tname == wxT("dataviewlistctrl") || tname == wxT("propgrid") || + tname == wxT("propgridman") || tname == wxT("splitter"))) { + if (obj->GetParent()->GetObjectTypeName() == wxT("form")) { + SetupAui(obj, window); + } + } + // Wizard + else if (obj->GetParent()->GetObjectTypeName() == wxT("wizard")) { + SetupWizard(obj, window, true); + } } -void VisualEditor::SetupWizard( PObjectBase obj, wxWindow *window, bool pageAdding ) +void VisualEditor::SetupAui(PObjectBase obj, wxWindow* window) { - WizardPageSimple *wizpage = wxDynamicCast( window, WizardPageSimple ); + wxAuiPaneInfo info; - if ( pageAdding ) - { - m_wizard->AddPage( wizpage ); - m_wizard->Connect( wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler( VisualEditor::OnWizardPageChanged ) ); + // check whether the object contains AUI info... + if (!obj->GetProperty(wxT("aui_name"))) + return; + + wxString name = obj->GetPropertyAsString(wxT("aui_name")); + if (name != wxT("")) + info.Name(name); + + if (obj->GetPropertyAsInteger(wxT("center_pane")) != 0) { + info.CenterPane(); } - else - { - WizardEvent eventChanged( wxFB_EVT_WIZARD_PAGE_CHANGED, m_wizard->GetId(), false, wizpage ); - eventChanged.SetInt( 1 ); - wizpage->GetEventHandler()->ProcessEvent( eventChanged ); - - bool wizBmpOk = !obj->GetParent()->GetProperty( wxT("bitmap") )->IsNull(); - bool pgeBmpOk = !obj->GetProperty( wxT("bitmap") )->IsNull(); - wxBitmap wizBmp = obj->GetParent()->GetPropertyAsBitmap( wxT("bitmap") ); - wxBitmap pgeBmp = obj->GetPropertyAsBitmap( wxT("bitmap") ); - - if ( pgeBmpOk && pgeBmp.IsOk() ) - { - m_wizard->SetBitmap( pgeBmp ); + if (obj->GetPropertyAsInteger(wxT("default_pane")) != 0) { + info.DefaultPane(); + } + + if (!obj->IsNull(wxT("caption"))) + info.Caption(obj->GetPropertyAsString(wxT("caption"))); + info.CaptionVisible(obj->GetPropertyAsInteger(wxT("caption_visible")) != 0); + info.CloseButton(obj->GetPropertyAsInteger(wxT("close_button")) != 0); + info.MaximizeButton(obj->GetPropertyAsInteger(wxT("maximize_button")) != 0); + info.MinimizeButton(obj->GetPropertyAsInteger(wxT("minimize_button")) != 0); + info.PinButton(obj->GetPropertyAsInteger(wxT("pin_button")) != 0); + info.PaneBorder(obj->GetPropertyAsInteger(wxT("pane_border")) != 0); + info.Gripper(obj->GetPropertyAsInteger(wxT("gripper")) != 0); + + info.BottomDockable(obj->GetPropertyAsInteger(wxT("BottomDockable")) != 0); + info.TopDockable(obj->GetPropertyAsInteger(wxT("TopDockable")) != 0); + info.LeftDockable(obj->GetPropertyAsInteger(wxT("LeftDockable")) != 0); + info.RightDockable(obj->GetPropertyAsInteger(wxT("RightDockable")) != 0); + + if (!obj->IsNull(wxT("dock"))) { + if (obj->GetPropertyAsString(wxT("dock")) == wxT("Dock")) { + info.Dock(); + if (!obj->IsNull(wxT("docking"))) { + if (obj->GetPropertyAsString(wxT("docking")) == wxT("Bottom")) + info.Bottom(); + else if (obj->GetPropertyAsString(wxT("docking")) == wxT("Top")) + info.Top(); + else if (obj->GetPropertyAsString(wxT("docking")) == wxT("Center")) + info.Center(); + else if (obj->GetPropertyAsString(wxT("docking")) == wxT("Right")) + info.Right(); + } + } else { + info.Float(); + info.FloatingPosition(obj->GetPropertyAsPoint(wxT("pane_position"))); } - else if ( wizBmpOk && wizBmp.IsOk() ) - { - m_wizard->SetBitmap( wizBmp ); + } + + if (!obj->IsNull(wxT("resize"))) { + if (obj->GetPropertyAsString(wxT("resize")) == wxT("Resizable")) + info.Resizable(); + else + info.Fixed(); + } + + info.DockFixed(obj->GetPropertyAsInteger(wxT("dock_fixed")) != 0); + info.Movable(obj->GetPropertyAsInteger(wxT("moveable")) != 0); + info.Floatable(obj->GetPropertyAsInteger(wxT("floatable")) != 0); + + if (!obj->GetProperty(wxT("pane_size"))->IsNull()) + info.FloatingSize(obj->GetPropertyAsSize(wxT("pane_size"))); + if (!obj->GetProperty(wxT("best_size"))->IsNull()) + info.BestSize(obj->GetPropertyAsSize(wxT("best_size"))); + if (!obj->GetProperty(wxT("min_size"))->IsNull()) + info.MinSize(obj->GetPropertyAsSize(wxT("min_size"))); + if (!obj->GetProperty(wxT("max_size"))->IsNull()) + info.MaxSize(obj->GetPropertyAsSize(wxT("max_size"))); + + if (obj->GetPropertyAsInteger(wxT("toolbar_pane")) != 0) { + info.ToolbarPane(); + } + if (!obj->IsNull(wxT("aui_position"))) + info.Position(obj->GetPropertyAsInteger(wxT("aui_position"))); + if (!obj->IsNull(wxT("aui_row"))) + info.Row(obj->GetPropertyAsInteger(wxT("aui_row"))); + if (!obj->IsNull(wxT("aui_layer"))) + info.Layer(obj->GetPropertyAsInteger(wxT("aui_layer"))); + if (obj->GetPropertyAsInteger(wxT("show")) == 0) { + info.Hide(); + } + + m_auimgr->AddPane(window, info); +} + +void VisualEditor::SetupWizard(PObjectBase obj, wxWindow* window, bool pageAdding) +{ + WizardPageSimple* wizpage = wxDynamicCast(window, WizardPageSimple); + + if (pageAdding) { + m_wizard->AddPage(wizpage); + m_wizard->Connect( + wxID_ANY, wxFB_EVT_WIZARD_PAGE_CHANGED, WizardEventHandler(VisualEditor::OnWizardPageChanged)); + } else { + WizardEvent eventChanged(wxFB_EVT_WIZARD_PAGE_CHANGED, m_wizard->GetId(), false, wizpage); + eventChanged.SetInt(1); + wizpage->GetEventHandler()->ProcessEvent(eventChanged); + + bool wizBmpOk = !obj->GetParent()->GetProperty(wxT("bitmap"))->IsNull(); + bool pgeBmpOk = !obj->GetProperty(wxT("bitmap"))->IsNull(); + wxBitmap wizBmp = obj->GetParent()->GetPropertyAsBitmap(wxT("bitmap")); + wxBitmap pgeBmp = obj->GetPropertyAsBitmap(wxT("bitmap")); + + if (pgeBmpOk && pgeBmp.IsOk()) { + m_wizard->SetBitmap(pgeBmp); + } else if (wizBmpOk && wizBmp.IsOk()) { + m_wizard->SetBitmap(wizBmp); } - size_t selection = m_wizard->GetPageIndex( wizpage ); - m_wizard->SetSelection( selection ); + size_t selection = m_wizard->GetPageIndex(wizpage); + m_wizard->SetSelection(selection); } } ///////////////////////////////////////////////////////////////////////////// -void VisualEditor::PreventOnSelected( bool prevent ) +void VisualEditor::PreventOnSelected(bool prevent) { - m_stopSelectedEvent = prevent; + m_stopSelectedEvent = prevent; } -void VisualEditor::PreventOnModified( bool prevent ) +void VisualEditor::PreventOnModified(bool prevent) { - m_stopModifiedEvent = prevent; + m_stopModifiedEvent = prevent; } -void VisualEditor::OnProjectLoaded ( wxFBEvent &) +void VisualEditor::OnProjectLoaded(wxFBEvent&) { - Create(); + Create(); } -void VisualEditor::OnProjectSaved ( wxFBEvent & ) +void VisualEditor::OnProjectSaved(wxFBEvent&) { - //Create(); + // Create(); } -void VisualEditor::OnObjectSelected( wxFBObjectEvent &event ) +void VisualEditor::OnObjectSelected(wxFBObjectEvent& event) { - // It is only necessary to Create() if the selected object is on a different form - if ( AppData()->GetSelectedForm() != m_form ) - { - Create(); - } - - // Get the ObjectBase from the event - PObjectBase obj = event.GetFBObject(); - if ( !obj ) - { - // Strange... - LogDebug( wxT("The event object is NULL - why?") ); - return; - } - - // highlight parent toolbar instead of its children - PObjectBase toolbar = obj->FindNearAncestor( wxT("toolbar") ); - if( !toolbar ) toolbar = obj->FindNearAncestor( wxT("toolbar_form") ); - if( toolbar ) obj = toolbar; - - // Make sure this is a visible object - ObjectBaseMap::iterator it = m_baseobjects.find( obj.get() ); - if ( m_baseobjects.end() == it ) - { - m_back->SetSelectedSizer( NULL ); - m_back->SetSelectedItem( NULL ); - m_back->SetSelectedObject( PObjectBase() ); - m_back->SetSelectedPanel( NULL ); - m_back->Refresh(); - return; - } - - // Save wxobject - wxObject* item = it->second; - - int componentType = COMPONENT_TYPE_ABSTRACT; - IComponent *comp = obj->GetObjectInfo()->GetComponent(); - if ( comp ) - { - componentType = comp->GetComponentType(); - - // Fire selection event in plugin - if ( !m_stopSelectedEvent ) - { - comp->OnSelected( item ); - } - } - - if ( obj->GetObjectInfo()->GetObjectTypeName() == wxT("wizardpagesimple") ) - { - ObjectBaseMap::iterator pageIt = m_baseobjects.find( obj.get() ); - WizardPageSimple* wizpage = wxDynamicCast( pageIt->second, WizardPageSimple ); - - SetupWizard( obj, wizpage ); - } - - if ( componentType != COMPONENT_TYPE_WINDOW && componentType != COMPONENT_TYPE_SIZER ) - { - item = NULL; - } - - // Fire selection event in plugin for all parents - if ( !m_stopSelectedEvent ) - { - PObjectBase parent = obj->GetParent(); - while ( parent ) - { - IComponent* parentComp = parent->GetObjectInfo()->GetComponent(); - if ( parentComp ) - { - ObjectBaseMap::iterator parentIt = m_baseobjects.find( parent.get() ); - if ( parentIt != m_baseobjects.end() ) - { - if ( parent->GetObjectInfo()->GetObjectTypeName() == wxT("wizardpagesimple") ) - { - WizardPageSimple* wizpage = wxDynamicCast( parentIt->second, WizardPageSimple ); - - SetupWizard( parent, wizpage ); + // It is only necessary to Create() if the selected object is on a different form + if (AppData()->GetSelectedForm() != m_form) { + Create(); + } + + // Get the ObjectBase from the event + PObjectBase obj = event.GetFBObject(); + if (!obj) { + // Strange... + LogDebug(wxT("The event object is NULL - why?")); + return; + } + + // highlight parent toolbar instead of its children + PObjectBase toolbar = obj->FindNearAncestor(wxT("toolbar")); + if (!toolbar) + toolbar = obj->FindNearAncestor(wxT("toolbar_form")); + if (toolbar) + obj = toolbar; + + // Make sure this is a visible object + ObjectBaseMap::iterator it = m_baseobjects.find(obj.get()); + if (m_baseobjects.end() == it) { + m_back->SetSelectedSizer(NULL); + m_back->SetSelectedItem(NULL); + m_back->SetSelectedObject(PObjectBase()); + m_back->SetSelectedPanel(NULL); + m_back->Refresh(); + return; + } + + // Save wxobject + wxObject* item = it->second; + + int componentType = COMPONENT_TYPE_ABSTRACT; + IComponent* comp = obj->GetObjectInfo()->GetComponent(); + if (comp) { + componentType = comp->GetComponentType(); + + // Fire selection event in plugin + if (!m_stopSelectedEvent) { + comp->OnSelected(item); + } + } + + if (obj->GetObjectInfo()->GetObjectTypeName() == wxT("wizardpagesimple")) { + ObjectBaseMap::iterator pageIt = m_baseobjects.find(obj.get()); + WizardPageSimple* wizpage = wxDynamicCast(pageIt->second, WizardPageSimple); + + SetupWizard(obj, wizpage); + } + + if (componentType != COMPONENT_TYPE_WINDOW && componentType != COMPONENT_TYPE_SIZER) { + item = NULL; + } + + // Fire selection event in plugin for all parents + if (!m_stopSelectedEvent) { + PObjectBase parent = obj->GetParent(); + while (parent) { + IComponent* parentComp = parent->GetObjectInfo()->GetComponent(); + if (parentComp) { + ObjectBaseMap::iterator parentIt = m_baseobjects.find(parent.get()); + if (parentIt != m_baseobjects.end()) { + if (parent->GetObjectInfo()->GetObjectTypeName() == wxT("wizardpagesimple")) { + WizardPageSimple* wizpage = wxDynamicCast(parentIt->second, WizardPageSimple); + + SetupWizard(parent, wizpage); } - parentComp->OnSelected( parentIt->second ); - } - } - parent = parent->GetParent(); - } - } - - // Look for the active panel - this is where the boxes will be drawn during OnPaint - // This is the closest parent of type COMPONENT_TYPE_WINDOW - PObjectBase nextParent = obj->GetParent(); - while ( nextParent ) - { - IComponent* parentComp = nextParent->GetObjectInfo()->GetComponent(); - if ( !parentComp ) - { - nextParent.reset(); - break; - } - - if ( parentComp->GetComponentType() == COMPONENT_TYPE_WINDOW ) - { - break; - } - - it = m_baseobjects.find(nextParent.get()); - if (m_baseobjects.end() != it) - { - if (wxDynamicCast(it->second, wxStaticBoxSizer)) - { - break; - } - } - - nextParent = nextParent->GetParent(); - } - - // Get the panel to draw on - wxWindow* selPanel = NULL; - if ( nextParent ) - { - it = m_baseobjects.find( nextParent.get() ); - if ( m_baseobjects.end() == it ) - { - selPanel = m_back->GetFrameContentPanel(); - } - else - { - if (auto* sizer = wxDynamicCast(it->second, wxStaticBoxSizer)) - { - selPanel = sizer->GetStaticBox(); - } - else - { - selPanel = wxDynamicCast(it->second, wxWindow); - } - } - } - else - { - selPanel = m_back->GetFrameContentPanel(); - } - - // Find the first COMPONENT_TYPE_WINDOW or COMPONENT_TYPE_SIZER - // If it is a sizer, save it - wxSizer* sizer = NULL; - PObjectBase nextObj = obj->GetParent(); - while ( nextObj ) - { - IComponent* nextComp = nextObj->GetObjectInfo()->GetComponent(); - if ( !nextComp ) - { - break; - } - - if ( nextComp->GetComponentType() == COMPONENT_TYPE_SIZER ) - { - it = m_baseobjects.find( nextObj.get() ); - if ( it != m_baseobjects.end() ) - { - sizer = wxDynamicCast( it->second, wxSizer ); - } - break; - } - else if ( nextComp->GetComponentType() == COMPONENT_TYPE_WINDOW ) - { - break; - } - - nextObj = nextObj->GetParent(); - } - - m_back->SetSelectedSizer( sizer ); - m_back->SetSelectedItem( item ); - m_back->SetSelectedObject( obj ); - m_back->SetSelectedPanel( selPanel ); - m_back->Refresh(); + parentComp->OnSelected(parentIt->second); + } + } + parent = parent->GetParent(); + } + } + + // Look for the active panel - this is where the boxes will be drawn during OnPaint + // This is the closest parent of type COMPONENT_TYPE_WINDOW + PObjectBase nextParent = obj->GetParent(); + while (nextParent) { + IComponent* parentComp = nextParent->GetObjectInfo()->GetComponent(); + if (!parentComp) { + nextParent.reset(); + break; + } + + if (parentComp->GetComponentType() == COMPONENT_TYPE_WINDOW) { + break; + } + + it = m_baseobjects.find(nextParent.get()); + if (m_baseobjects.end() != it) { + if (wxDynamicCast(it->second, wxStaticBoxSizer)) { + break; + } + } + + nextParent = nextParent->GetParent(); + } + + // Get the panel to draw on + wxWindow* selPanel = NULL; + if (nextParent) { + it = m_baseobjects.find(nextParent.get()); + if (m_baseobjects.end() == it) { + selPanel = m_back->GetFrameContentPanel(); + } else { + if (auto* sizer = wxDynamicCast(it->second, wxStaticBoxSizer)) { + selPanel = sizer->GetStaticBox(); + } else { + selPanel = wxDynamicCast(it->second, wxWindow); + } + } + } else { + selPanel = m_back->GetFrameContentPanel(); + } + + // Find the first COMPONENT_TYPE_WINDOW or COMPONENT_TYPE_SIZER + // If it is a sizer, save it + wxSizer* sizer = NULL; + PObjectBase nextObj = obj->GetParent(); + while (nextObj) { + IComponent* nextComp = nextObj->GetObjectInfo()->GetComponent(); + if (!nextComp) { + break; + } + + if (nextComp->GetComponentType() == COMPONENT_TYPE_SIZER) { + it = m_baseobjects.find(nextObj.get()); + if (it != m_baseobjects.end()) { + sizer = wxDynamicCast(it->second, wxSizer); + } + break; + } else if (nextComp->GetComponentType() == COMPONENT_TYPE_WINDOW) { + break; + } + + nextObj = nextObj->GetParent(); + } + + m_back->SetSelectedSizer(sizer); + m_back->SetSelectedItem(item); + m_back->SetSelectedObject(obj); + m_back->SetSelectedPanel(selPanel); + m_back->Refresh(); } -void VisualEditor::OnObjectCreated( wxFBObjectEvent &) +void VisualEditor::OnObjectCreated(wxFBObjectEvent&) { - Create(); + Create(); } -void VisualEditor::OnObjectRemoved( wxFBObjectEvent & ) +void VisualEditor::OnObjectRemoved(wxFBObjectEvent&) { - Create(); + Create(); } -void VisualEditor::OnPropertyModified( wxFBPropertyEvent &) +void VisualEditor::OnPropertyModified(wxFBPropertyEvent&) { - if ( !m_stopModifiedEvent ) - { - PObjectBase aux = m_back->GetSelectedObject(); - Create(); - if ( aux ) - { - wxFBObjectEvent objEvent( wxEVT_FB_OBJECT_SELECTED, aux ); - this->ProcessEvent( objEvent ); - } - UpdateVirtualSize(); - } + if (!m_stopModifiedEvent) { + PObjectBase aux = m_back->GetSelectedObject(); + Create(); + if (aux) { + wxFBObjectEvent objEvent(wxEVT_FB_OBJECT_SELECTED, aux); + this->ProcessEvent(objEvent); + } + UpdateVirtualSize(); + } } -void VisualEditor::OnProjectRefresh( wxFBEvent &) +void VisualEditor::OnProjectRefresh(wxFBEvent&) { - Create(); + Create(); } -void VisualEditor::OnAuiScaner(wxTimerEvent&) { - if( m_auimgr ) - { - ScanPanes( m_back->GetFrameContentPanel() ); - } +void VisualEditor::OnAuiScaner(wxTimerEvent&) +{ + if (m_auimgr) { + ScanPanes(m_back->GetFrameContentPanel()); + } } -IMPLEMENT_CLASS( DesignerWindow, wxInnerFrame) +IMPLEMENT_CLASS(DesignerWindow, wxInnerFrame) -BEGIN_EVENT_TABLE(DesignerWindow,wxInnerFrame) - EVT_PAINT(DesignerWindow::OnPaint) +BEGIN_EVENT_TABLE(DesignerWindow, wxInnerFrame) +EVT_PAINT(DesignerWindow::OnPaint) END_EVENT_TABLE() -DesignerWindow::DesignerWindow( wxWindow *parent, int id, const wxPoint& pos, const wxSize &size, long style, const wxString & /*name*/ ) -: -wxInnerFrame(parent, id, pos, size, style) +DesignerWindow::DesignerWindow( + wxWindow* parent, int id, const wxPoint& pos, const wxSize& size, long style, const wxString& /*name*/) : + wxInnerFrame(parent, id, pos, size, style) { - ShowTitleBar(false); - SetGrid( 10, 10 ); - m_selSizer = NULL; - m_selItem = NULL; - m_actPanel = NULL; - SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) ); - - GetFrameContentPanel()->PushEventHandler(new HighlightPaintHandler(GetFrameContentPanel())); + ShowTitleBar(false); + SetGrid(10, 10); + m_selSizer = NULL; + m_selItem = NULL; + m_actPanel = NULL; + SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE)); + + GetFrameContentPanel()->PushEventHandler(new HighlightPaintHandler(GetFrameContentPanel())); } DesignerWindow::~DesignerWindow() { - GetFrameContentPanel()->PopEventHandler( true ); + GetFrameContentPanel()->PopEventHandler(true); } -void DesignerWindow::SetGrid( int x, int y ) +void DesignerWindow::SetGrid(int x, int y) { - m_x = x; - m_y = y; + m_x = x; + m_y = y; } -void DesignerWindow::OnPaint(wxPaintEvent &event) +void DesignerWindow::OnPaint(wxPaintEvent& event) { - // This paint event helps draw the selection boxes - // when they extend beyond the edges of the content panel - wxPaintDC dc(this); - - if ( m_actPanel == GetFrameContentPanel() ) - { - wxPoint origin = GetFrameContentPanel()->GetPosition(); - dc.SetDeviceOrigin( origin.x, origin.y ); - HighlightSelection( dc ); - } - - event.Skip(); + // This paint event helps draw the selection boxes + // when they extend beyond the edges of the content panel + wxPaintDC dc(this); + + if (m_actPanel == GetFrameContentPanel()) { + wxPoint origin = GetFrameContentPanel()->GetPosition(); + dc.SetDeviceOrigin(origin.x, origin.y); + HighlightSelection(dc); + } + + event.Skip(); } -void DesignerWindow::DrawRectangle( wxDC& dc, const wxPoint& point, const wxSize& size, PObjectBase object ) +void DesignerWindow::DrawRectangle(wxDC& dc, const wxPoint& point, const wxSize& size, PObjectBase object) { - bool isSizer = ( object->GetObjectInfo()->IsSubclassOf( wxT("sizer") ) || object->GetObjectInfo()->IsSubclassOf( wxT("gbsizer") ) ); - int min = ( isSizer ? 0 : 1 ); - - int border = object->GetParent()->GetPropertyAsInteger( wxT("border") ); - if ( border == 0 ) - { - border = min; - } - - int flag = object->GetParent()->GetPropertyAsInteger( wxT("flag") ); - int topBorder = ( flag & wxTOP ) == 0 ? min : border; - int bottomBorder = ( flag & wxBOTTOM ) == 0 ? min : border; - int rightBorder = ( flag & wxRIGHT ) == 0 ? min : border; - int leftBorder = ( flag & wxLEFT ) == 0 ? min : border; - - dc.DrawRectangle( point.x - leftBorder, - point.y - topBorder, - size.x + leftBorder + rightBorder, - size.y + topBorder + bottomBorder ); + bool isSizer = + (object->GetObjectInfo()->IsSubclassOf(wxT("sizer")) || object->GetObjectInfo()->IsSubclassOf(wxT("gbsizer"))); + int min = (isSizer ? 0 : 1); + + int border = object->GetParent()->GetPropertyAsInteger(wxT("border")); + if (border == 0) { + border = min; + } + + int flag = object->GetParent()->GetPropertyAsInteger(wxT("flag")); + int topBorder = (flag & wxTOP) == 0 ? min : border; + int bottomBorder = (flag & wxBOTTOM) == 0 ? min : border; + int rightBorder = (flag & wxRIGHT) == 0 ? min : border; + int leftBorder = (flag & wxLEFT) == 0 ? min : border; + + dc.DrawRectangle( + point.x - leftBorder, point.y - topBorder, size.x + leftBorder + rightBorder, size.y + topBorder + bottomBorder); } -void DesignerWindow::HighlightSelection( wxDC& dc ) +void DesignerWindow::HighlightSelection(wxDC& dc) { - // do not highlight if AUI is used in floating mode - VisualEditor *editor = wxDynamicCast( GetParent(), VisualEditor ); - if( editor && editor->m_auimgr ) - { - wxWindow *windowItem = wxDynamicCast( m_selItem, wxWindow ); - while( windowItem ) - { - wxAuiPaneInfo info = editor->m_auimgr->GetPane( windowItem ); - if( info.IsOk() ) - { - if( info.IsFloating() ) return; - else break; - } - windowItem = windowItem->GetParent(); - } - } - - wxSize size; - PObjectBase object = m_selObj.lock(); - if ( m_selSizer ) - { - wxScrolledWindow* scrolwin = wxDynamicCast(m_selSizer->GetContainingWindow (), wxScrolledWindow); - if(scrolwin) - { - scrolwin->FitInside(); - } - wxPoint point = m_selSizer->GetPosition(); - if (auto* sbSizer = wxDynamicCast(m_selSizer, wxStaticBoxSizer)) - { - // In case of wxStaticBoxSizer, m_actPanel is not a parent window - // of the sizer (m_actPanel==sbSizer->GetStaticBox()). - // Thus we need to convert the sizer's position into coordinates - // of m_actPanel. - // We could do this via parent window of the sizer, but it's hard to - // obtain this window. The m_selSizer->GetContainingWindow() doesn't - // always return the parent window of the sizer, namely in the case - // the m_selSizer is inside another wxStaticBoxSizer - // (at least in MSW build, wxWidgets 3.0.1). - // We convert its StaticBox origin (StaticBox is a window) since origins - // of wxStaticBoxSizer and its StaticBox are the same point. - point = m_actPanel->ScreenToClient(sbSizer->GetStaticBox()->GetScreenPosition()); - } - size = m_selSizer->GetSize(); - - wxPen bluePen(*wxBLUE, 1, wxPENSTYLE_SOLID); - dc.SetPen( bluePen ); - dc.SetBrush( *wxTRANSPARENT_BRUSH ); - PObjectBase sizerParent = object->FindNearAncestorByBaseClass( wxT("sizer") ); - if( !sizerParent ) sizerParent = object->FindNearAncestorByBaseClass( wxT("gbsizer") ); - if ( sizerParent && sizerParent->GetParent() ) - { - DrawRectangle( dc, point, size, sizerParent ); - } - } - - if ( m_selItem ) - { - wxPoint point; - bool shown; - - wxWindow* windowItem = wxDynamicCast( m_selItem, wxWindow ); - wxSizer* sizerItem = wxDynamicCast( m_selItem, wxSizer ); - if ( NULL != windowItem ) - { - // In case the windowItem is inside a wxStaticBoxSizer its position is relative to - // the wxStaticBox which is NOT m_actPanel in on which the highlight is painted, - // so get the screen coordinates of the item and convert them into client coordinates - // of the panel to get the correct relative coordinates. This doesn't do any harm if - // the item is not inside a wxStaticBoxSizer, if this conversion results in a big - // performance penalty maybe check if the parent is a wxStaticBox and only then do - // this conversion. - point = m_actPanel->ScreenToClient(windowItem->GetScreenPosition()); - size = windowItem->GetSize(); - shown = windowItem->IsShown(); - } - else if ( NULL != sizerItem ) - { - point = sizerItem->GetPosition(); - size = sizerItem->GetSize(); - shown = true; - } - else - { - return; - } - - if ( shown ) - { - wxPen redPen(*wxRED, 1, wxPENSTYLE_SOLID); - dc.SetPen( redPen ); - dc.SetBrush( *wxTRANSPARENT_BRUSH ); - DrawRectangle( dc, point, size, object ); - } - } + // do not highlight if AUI is used in floating mode + VisualEditor* editor = wxDynamicCast(GetParent(), VisualEditor); + if (editor && editor->m_auimgr) { + wxWindow* windowItem = wxDynamicCast(m_selItem, wxWindow); + while (windowItem) { + wxAuiPaneInfo info = editor->m_auimgr->GetPane(windowItem); + if (info.IsOk()) { + if (info.IsFloating()) + return; + else + break; + } + windowItem = windowItem->GetParent(); + } + } + + wxSize size; + PObjectBase object = m_selObj.lock(); + if (m_selSizer) { + wxScrolledWindow* scrolwin = wxDynamicCast(m_selSizer->GetContainingWindow(), wxScrolledWindow); + if (scrolwin) { + scrolwin->FitInside(); + } + wxPoint point = m_selSizer->GetPosition(); + if (auto* sbSizer = wxDynamicCast(m_selSizer, wxStaticBoxSizer)) { + // In case of wxStaticBoxSizer, m_actPanel is not a parent window + // of the sizer (m_actPanel==sbSizer->GetStaticBox()). + // Thus we need to convert the sizer's position into coordinates + // of m_actPanel. + // We could do this via parent window of the sizer, but it's hard to + // obtain this window. The m_selSizer->GetContainingWindow() doesn't + // always return the parent window of the sizer, namely in the case + // the m_selSizer is inside another wxStaticBoxSizer + // (at least in MSW build, wxWidgets 3.0.1). + // We convert its StaticBox origin (StaticBox is a window) since origins + // of wxStaticBoxSizer and its StaticBox are the same point. + point = m_actPanel->ScreenToClient(sbSizer->GetStaticBox()->GetScreenPosition()); + } + size = m_selSizer->GetSize(); + + wxPen bluePen(*wxBLUE, 1, wxPENSTYLE_SOLID); + dc.SetPen(bluePen); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + PObjectBase sizerParent = object->FindNearAncestorByBaseClass(wxT("sizer")); + if (!sizerParent) + sizerParent = object->FindNearAncestorByBaseClass(wxT("gbsizer")); + if (sizerParent && sizerParent->GetParent()) { + DrawRectangle(dc, point, size, sizerParent); + } + } + + if (m_selItem) { + wxPoint point; + bool shown; + + wxWindow* windowItem = wxDynamicCast(m_selItem, wxWindow); + wxSizer* sizerItem = wxDynamicCast(m_selItem, wxSizer); + if (NULL != windowItem) { + // In case the windowItem is inside a wxStaticBoxSizer its position is relative to + // the wxStaticBox which is NOT m_actPanel in on which the highlight is painted, + // so get the screen coordinates of the item and convert them into client coordinates + // of the panel to get the correct relative coordinates. This doesn't do any harm if + // the item is not inside a wxStaticBoxSizer, if this conversion results in a big + // performance penalty maybe check if the parent is a wxStaticBox and only then do + // this conversion. + point = m_actPanel->ScreenToClient(windowItem->GetScreenPosition()); + size = windowItem->GetSize(); + shown = windowItem->IsShown(); + } else if (NULL != sizerItem) { + point = sizerItem->GetPosition(); + size = sizerItem->GetSize(); + shown = true; + } else { + return; + } + + if (shown) { + wxPen redPen(*wxRED, 1, wxPENSTYLE_SOLID); + dc.SetPen(redPen); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + DrawRectangle(dc, point, size, object); + } + } } wxMenu* DesignerWindow::GetMenuFromObject(PObjectBase menu) { - int lastMenuId = wxID_HIGHEST + 1; - wxMenu* menuWidget = new wxMenu(); - for ( unsigned int j = 0; j < menu->GetChildCount(); j++ ) - { - PObjectBase menuItem = menu->GetChild( j ); - if ( menuItem->GetObjectTypeName() == wxT("submenu") ) - { - wxMenuItem *item = new wxMenuItem( menuWidget, - lastMenuId++, - menuItem->GetPropertyAsString( wxT("label") ), - menuItem->GetPropertyAsString( wxT("help") ), - wxITEM_NORMAL, - GetMenuFromObject( menuItem ) - ); - item->SetBitmap( menuItem->GetPropertyAsBitmap( wxT("bitmap") ) ); - menuWidget->Append( item ); - } - else if ( menuItem->GetClassName() == wxT("separator") ) - { - menuWidget->AppendSeparator(); - } - else - { - wxString label = menuItem->GetPropertyAsString( wxT("label") ); - wxString shortcut = menuItem->GetPropertyAsString( wxT("shortcut") ); - if ( !shortcut.IsEmpty() ) - { - label = label + wxChar('\t') + shortcut; - } - - wxMenuItem *item = new wxMenuItem( menuWidget, - lastMenuId++, - label, - menuItem->GetPropertyAsString( wxT("help") ), - ( wxItemKind ) menuItem->GetPropertyAsInteger( wxT("kind") ) - ); - - if ( !menuItem->GetProperty( wxT("bitmap") )->IsNull() ) - { - wxBitmap unchecked = wxNullBitmap; - if ( !menuItem->GetProperty( wxT("unchecked_bitmap") )->IsNull() ) - { - unchecked = menuItem->GetPropertyAsBitmap( wxT("unchecked_bitmap") ); - } - #ifdef __WXMSW__ - item->SetBitmaps( menuItem->GetPropertyAsBitmap( wxT("bitmap") ), unchecked ); - #elif defined( __WXGTK__ ) - item->SetBitmap( menuItem->GetPropertyAsBitmap( wxT("bitmap") ) ); - #endif - } - else - { - if ( !menuItem->GetProperty( wxT("unchecked_bitmap") )->IsNull() ) - { - #ifdef __WXMSW__ - item->SetBitmaps( wxNullBitmap, menuItem->GetPropertyAsBitmap( wxT("unchecked_bitmap") ) ); - #endif - } - } - - menuWidget->Append( item ); - - if (item->GetKind() == wxITEM_CHECK && - menuItem->GetPropertyAsInteger(wxT("checked")) != 0) { - item->Check( true ); - } - - item->Enable( ( menuItem->GetPropertyAsInteger( wxT("enabled") ) != 0 ) ); - } - } - - return menuWidget; + int lastMenuId = wxID_HIGHEST + 1; + wxMenu* menuWidget = new wxMenu(); + for (unsigned int j = 0; j < menu->GetChildCount(); j++) { + PObjectBase menuItem = menu->GetChild(j); + if (menuItem->GetObjectTypeName() == wxT("submenu")) { + wxMenuItem* item = new wxMenuItem( + menuWidget, lastMenuId++, menuItem->GetPropertyAsString(wxT("label")), + menuItem->GetPropertyAsString(wxT("help")), wxITEM_NORMAL, GetMenuFromObject(menuItem)); + item->SetBitmap(menuItem->GetPropertyAsBitmap(wxT("bitmap"))); + menuWidget->Append(item); + } else if (menuItem->GetClassName() == wxT("separator")) { + menuWidget->AppendSeparator(); + } else { + wxString label = menuItem->GetPropertyAsString(wxT("label")); + wxString shortcut = menuItem->GetPropertyAsString(wxT("shortcut")); + if (!shortcut.IsEmpty()) { + label = label + wxChar('\t') + shortcut; + } + + wxMenuItem* item = new wxMenuItem( + menuWidget, lastMenuId++, label, menuItem->GetPropertyAsString(wxT("help")), + (wxItemKind)menuItem->GetPropertyAsInteger(wxT("kind"))); + + if (!menuItem->GetProperty(wxT("bitmap"))->IsNull()) { + wxBitmap unchecked = wxNullBitmap; + if (!menuItem->GetProperty(wxT("unchecked_bitmap"))->IsNull()) { + unchecked = menuItem->GetPropertyAsBitmap(wxT("unchecked_bitmap")); + } +#ifdef __WXMSW__ + item->SetBitmaps(menuItem->GetPropertyAsBitmap(wxT("bitmap")), unchecked); +#elif defined(__WXGTK__) + item->SetBitmap(menuItem->GetPropertyAsBitmap(wxT("bitmap"))); +#endif + } else { + if (!menuItem->GetProperty(wxT("unchecked_bitmap"))->IsNull()) { +#ifdef __WXMSW__ + item->SetBitmaps(wxNullBitmap, menuItem->GetPropertyAsBitmap(wxT("unchecked_bitmap"))); +#endif + } + } + + menuWidget->Append(item); + + if (item->GetKind() == wxITEM_CHECK && menuItem->GetPropertyAsInteger(wxT("checked")) != 0) { + item->Check(true); + } + + item->Enable((menuItem->GetPropertyAsInteger(wxT("enabled")) != 0)); + } + } + + return menuWidget; } -void DesignerWindow::SetFrameWidgets(PObjectBase menubar, wxWindow *toolbar, wxWindow *statusbar, wxWindow *auipanel) +void DesignerWindow::SetFrameWidgets(PObjectBase menubar, wxWindow* toolbar, wxWindow* statusbar, wxWindow* auipanel) { - wxWindow *contentPanel = GetFrameContentPanel(); - Menubar *mbWidget = NULL; - - if ( menubar ) - { - mbWidget = new Menubar(contentPanel, wxID_ANY); - for ( unsigned int i = 0; i < menubar->GetChildCount(); i++ ) - { - PObjectBase menu = menubar->GetChild( i ); - wxMenu *menuWidget = GetMenuFromObject( menu ); - mbWidget->AppendMenu( menu->GetPropertyAsString( wxT("label") ), menuWidget ); - } - } - - wxSizer *mainSizer = contentPanel->GetSizer(); - - contentPanel->SetSizer( NULL, false ); - - wxSizer *dummySizer = new wxBoxSizer( wxVERTICAL ); - - if ( mbWidget ) - { - dummySizer->Add(mbWidget, 0, wxEXPAND | wxTOP | wxBOTTOM, 0); - dummySizer->Add(new wxStaticLine(contentPanel, wxID_ANY), 0, wxEXPAND | wxALL, 0); - } - - wxSizer* contentSizer = dummySizer; - if (toolbar) - { - if ( (toolbar->GetWindowStyle() & wxTB_VERTICAL) != 0 ) - { - wxSizer* horiz = new wxBoxSizer( wxHORIZONTAL ); - horiz->Add(toolbar, 0, wxEXPAND | wxALL, 0); - - wxSizer* vert = new wxBoxSizer( wxVERTICAL ); - horiz->Add( vert, 1, wxEXPAND, 0 ); - - dummySizer->Add( horiz, 1, wxEXPAND, 0); - - contentSizer = vert; - } - else - { - dummySizer->Add(toolbar, 0, wxEXPAND | wxALL, 0); - } - } - - if (auipanel) - { - contentSizer->Add(auipanel, 1, wxEXPAND | wxALL, 0); - } - else if (mainSizer) - { - contentSizer->Add(mainSizer, 1, wxEXPAND | wxALL, 0); - if ( mainSizer->GetChildren().IsEmpty() ) - { - // Sizers do not expand if they are empty - mainSizer->AddStretchSpacer(1); - } - } - else - contentSizer->AddStretchSpacer(1); - - if (statusbar) - { - if( auipanel ) statusbar->Reparent( contentPanel ); - contentSizer->Add(statusbar, 0, wxEXPAND | wxALL, 0); - } - - contentPanel->SetSizer(dummySizer, false); - contentPanel->Layout(); + wxWindow* contentPanel = GetFrameContentPanel(); + Menubar* mbWidget = NULL; + + if (menubar) { + mbWidget = new Menubar(contentPanel, wxID_ANY); + for (unsigned int i = 0; i < menubar->GetChildCount(); i++) { + PObjectBase menu = menubar->GetChild(i); + wxMenu* menuWidget = GetMenuFromObject(menu); + mbWidget->AppendMenu(menu->GetPropertyAsString(wxT("label")), menuWidget); + } + } + + wxSizer* mainSizer = contentPanel->GetSizer(); + + contentPanel->SetSizer(NULL, false); + + wxSizer* dummySizer = new wxBoxSizer(wxVERTICAL); + + if (mbWidget) { + dummySizer->Add(mbWidget, 0, wxEXPAND | wxTOP | wxBOTTOM, 0); + dummySizer->Add(new wxStaticLine(contentPanel, wxID_ANY), 0, wxEXPAND | wxALL, 0); + } + + wxSizer* contentSizer = dummySizer; + if (toolbar) { + if ((toolbar->GetWindowStyle() & wxTB_VERTICAL) != 0) { + wxSizer* horiz = new wxBoxSizer(wxHORIZONTAL); + horiz->Add(toolbar, 0, wxEXPAND | wxALL, 0); + + wxSizer* vert = new wxBoxSizer(wxVERTICAL); + horiz->Add(vert, 1, wxEXPAND, 0); + + dummySizer->Add(horiz, 1, wxEXPAND, 0); + + contentSizer = vert; + } else { + dummySizer->Add(toolbar, 0, wxEXPAND | wxALL, 0); + } + } + + if (auipanel) { + contentSizer->Add(auipanel, 1, wxEXPAND | wxALL, 0); + } else if (mainSizer) { + contentSizer->Add(mainSizer, 1, wxEXPAND | wxALL, 0); + if (mainSizer->GetChildren().IsEmpty()) { + // Sizers do not expand if they are empty + mainSizer->AddStretchSpacer(1); + } + } else + contentSizer->AddStretchSpacer(1); + + if (statusbar) { + if (auipanel) + statusbar->Reparent(contentPanel); + contentSizer->Add(statusbar, 0, wxEXPAND | wxALL, 0); + } + + contentPanel->SetSizer(dummySizer, false); + contentPanel->Layout(); } -BEGIN_EVENT_TABLE(DesignerWindow::HighlightPaintHandler,wxEvtHandler) - EVT_PAINT(DesignerWindow::HighlightPaintHandler::OnPaint) +BEGIN_EVENT_TABLE(DesignerWindow::HighlightPaintHandler, wxEvtHandler) +EVT_PAINT(DesignerWindow::HighlightPaintHandler::OnPaint) END_EVENT_TABLE() -DesignerWindow::HighlightPaintHandler::HighlightPaintHandler(wxWindow *win) +DesignerWindow::HighlightPaintHandler::HighlightPaintHandler(wxWindow* win) { - m_window = win; + m_window = win; } -void DesignerWindow::HighlightPaintHandler::OnPaint(wxPaintEvent &event) +void DesignerWindow::HighlightPaintHandler::OnPaint(wxPaintEvent& event) { - wxWindow *aux = m_window; - while (!aux->IsKindOf(CLASSINFO(DesignerWindow))) aux = aux->GetParent(); - DesignerWindow *dsgnWin = (DesignerWindow*) aux; - if (dsgnWin->GetActivePanel() == m_window) - { - wxPaintDC dc(m_window); - dsgnWin->HighlightSelection(dc); - } - - event.Skip(); + wxWindow* aux = m_window; + while (!aux->IsKindOf(CLASSINFO(DesignerWindow))) aux = aux->GetParent(); + DesignerWindow* dsgnWin = (DesignerWindow*)aux; + if (dsgnWin->GetActivePanel() == m_window) { + wxPaintDC dc(m_window); + dsgnWin->HighlightSelection(dc); + } + + event.Skip(); } diff --git a/src/rad/designer/visualeditor.h b/src/rad/designer/visualeditor.h index 237aeb657..61558a6ee 100644 --- a/src/rad/designer/visualeditor.h +++ b/src/rad/designer/visualeditor.h @@ -26,61 +26,63 @@ #ifndef RAD_DESIGNER_VISUALEDITOR_H #define RAD_DESIGNER_VISUALEDITOR_H +#include + #include "rad/designer/innerframe.h" #include "rad/designer/visualobj.h" -#include + /** * Extends the wxInnerFrame to show the object highlight */ class DesignerWindow : public wxInnerFrame { - private: - int m_x; - int m_y; - wxSizer *m_selSizer; - wxObject *m_selItem; - WPObjectBase m_selObj; - wxWindow *m_actPanel; - - void DrawRectangle(wxDC& dc, const wxPoint& point, const wxSize& size, PObjectBase object); - - DECLARE_CLASS(DesignerWindow) - - // Augh!, this class is needed to paint the highlight in the - // frame content panel. - class HighlightPaintHandler : public wxEvtHandler - { - DECLARE_EVENT_TABLE() - - wxWindow *m_window; - - public: - HighlightPaintHandler(wxWindow *win); - void OnPaint(wxPaintEvent &event); - }; - - protected: - - DECLARE_EVENT_TABLE() - - public: - DesignerWindow(wxWindow *parent, int id, const wxPoint& pos, const wxSize &size = wxDefaultSize, - long style = 0, const wxString &name = wxT("designer_win")); - ~DesignerWindow() override; - void SetGrid(int x, int y); - void SetSelectedSizer(wxSizer *sizer) { m_selSizer = sizer; } - void SetSelectedItem(wxObject *item) { m_selItem = item; } - void SetSelectedObject(PObjectBase object) { m_selObj = object; } - void SetSelectedPanel(wxWindow *actPanel) { m_actPanel = actPanel; } - wxSizer *GetSelectedSizer() { return m_selSizer; } - wxObject* GetSelectedItem() { return m_selItem; } - PObjectBase GetSelectedObject() { return m_selObj.lock(); } - wxWindow* GetActivePanel() { return m_actPanel; } - static wxMenu* GetMenuFromObject(PObjectBase menu); - void SetFrameWidgets(PObjectBase menubar, wxWindow *toolbar, wxWindow* statusbar, wxWindow *auipanel); - void HighlightSelection(wxDC& dc); - void OnPaint(wxPaintEvent &event); +private: + int m_x; + int m_y; + wxSizer* m_selSizer; + wxObject* m_selItem; + WPObjectBase m_selObj; + wxWindow* m_actPanel; + + void DrawRectangle(wxDC& dc, const wxPoint& point, const wxSize& size, PObjectBase object); + + DECLARE_CLASS(DesignerWindow) + + // Augh!, this class is needed to paint the highlight in the + // frame content panel. + class HighlightPaintHandler : public wxEvtHandler + { + DECLARE_EVENT_TABLE() + + wxWindow* m_window; + + public: + HighlightPaintHandler(wxWindow* win); + void OnPaint(wxPaintEvent& event); + }; + +protected: + DECLARE_EVENT_TABLE() + +public: + DesignerWindow( + wxWindow* parent, int id, const wxPoint& pos, const wxSize& size = wxDefaultSize, long style = 0, + const wxString& name = wxT("designer_win")); + ~DesignerWindow() override; + void SetGrid(int x, int y); + void SetSelectedSizer(wxSizer* sizer) { m_selSizer = sizer; } + void SetSelectedItem(wxObject* item) { m_selItem = item; } + void SetSelectedObject(PObjectBase object) { m_selObj = object; } + void SetSelectedPanel(wxWindow* actPanel) { m_actPanel = actPanel; } + wxSizer* GetSelectedSizer() { return m_selSizer; } + wxObject* GetSelectedItem() { return m_selItem; } + PObjectBase GetSelectedObject() { return m_selObj.lock(); } + wxWindow* GetActivePanel() { return m_actPanel; } + static wxMenu* GetMenuFromObject(PObjectBase menu); + void SetFrameWidgets(PObjectBase menubar, wxWindow* toolbar, wxWindow* statusbar, wxWindow* auipanel); + void HighlightSelection(wxDC& dc); + void OnPaint(wxPaintEvent& event); }; class wxFBEvent; @@ -89,76 +91,76 @@ class wxFBObjectEvent; class VisualEditor : public wxScrolledWindow { - private: - typedef std::map< wxObject*, PObjectBase > wxObjectMap; - wxObjectMap m_wxobjects; +private: + typedef std::map wxObjectMap; + wxObjectMap m_wxobjects; - typedef std::map< ObjectBase*, wxObject* > ObjectBaseMap; - ObjectBaseMap m_baseobjects; + typedef std::map ObjectBaseMap; + ObjectBaseMap m_baseobjects; - DesignerWindow *m_back; - wxPanel *m_auipanel; + DesignerWindow* m_back; + wxPanel* m_auipanel; - PObjectBase m_form; // Pointer to last form created + PObjectBase m_form; // Pointer to last form created - // Prevent OnSelected in components - bool m_stopSelectedEvent; + // Prevent OnSelected in components + bool m_stopSelectedEvent; - // Prevent OnModified in components - bool m_stopModifiedEvent; + // Prevent OnModified in components + bool m_stopModifiedEvent; - // aui scan timer - wxTimer m_AuiScaner; + // aui scan timer + wxTimer m_AuiScaner; - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() - protected: - void Generate( PObjectBase obj, wxWindow* parent, wxObject* parentObject ); - void SetupWindow( PObjectBase obj, wxWindow* window ); - void SetupSizer( PObjectBase obj, wxSizer* sizer ); - void Create(); - void DeleteAbstractObjects(); +protected: + void Generate(PObjectBase obj, wxWindow* parent, wxObject* parentObject); + void SetupWindow(PObjectBase obj, wxWindow* window); + void SetupSizer(PObjectBase obj, wxSizer* sizer); + void Create(); + void DeleteAbstractObjects(); - void ClearAui(); - void SetupAui( PObjectBase obj, wxWindow* window ); - void ScanPanes( wxWindow* parent ); + void ClearAui(); + void SetupAui(PObjectBase obj, wxWindow* window); + void ScanPanes(wxWindow* parent); - void OnAuiScaner(wxTimerEvent& event); + void OnAuiScaner(wxTimerEvent& event); void ClearWizard(); - void SetupWizard( PObjectBase obj, wxWindow* window, bool pageAdding = false ); - void OnWizardPageChanged( WizardEvent &event ); - - public: - VisualEditor(wxWindow *parent); - ~VisualEditor() override; - void OnResizeBackPanel (wxCommandEvent &event); - void OnClickBackPanel( wxMouseEvent& event ); - void PreventOnSelected( bool prevent = true ); - void PreventOnModified( bool prevent = true ); - - void UpdateVirtualSize(); - - PObjectBase GetObjectBase( wxObject* wxobject ); - wxObject* GetWxObject( PObjectBase baseobject ); - - //AUI - wxAuiManager *m_auimgr; - - //Wizard - Wizard *m_wizard; - - // Give components an opportunity to cleanup - void ClearComponents( wxWindow* parent ); - - // Events - void OnProjectLoaded ( wxFBEvent &event ); - void OnProjectSaved ( wxFBEvent &event ); - void OnObjectSelected( wxFBObjectEvent &event ); - void OnObjectCreated ( wxFBObjectEvent &event ); - void OnObjectRemoved ( wxFBObjectEvent &event ); - void OnPropertyModified ( wxFBPropertyEvent &event ); - void OnProjectRefresh ( wxFBEvent &event); + void SetupWizard(PObjectBase obj, wxWindow* window, bool pageAdding = false); + void OnWizardPageChanged(WizardEvent& event); + +public: + VisualEditor(wxWindow* parent); + ~VisualEditor() override; + void OnResizeBackPanel(wxCommandEvent& event); + void OnClickBackPanel(wxMouseEvent& event); + void PreventOnSelected(bool prevent = true); + void PreventOnModified(bool prevent = true); + + void UpdateVirtualSize(); + + PObjectBase GetObjectBase(wxObject* wxobject); + wxObject* GetWxObject(PObjectBase baseobject); + + // AUI + wxAuiManager* m_auimgr; + + // Wizard + Wizard* m_wizard; + + // Give components an opportunity to cleanup + void ClearComponents(wxWindow* parent); + + // Events + void OnProjectLoaded(wxFBEvent& event); + void OnProjectSaved(wxFBEvent& event); + void OnObjectSelected(wxFBObjectEvent& event); + void OnObjectCreated(wxFBObjectEvent& event); + void OnObjectRemoved(wxFBObjectEvent& event); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); }; -#endif // RAD_DESIGNER_VISUALEDITOR_H +#endif // RAD_DESIGNER_VISUALEDITOR_H diff --git a/src/rad/designer/visualobj.cpp b/src/rad/designer/visualobj.cpp index 70faab1ec..5bc735974 100644 --- a/src/rad/designer/visualobj.cpp +++ b/src/rad/designer/visualobj.cpp @@ -23,121 +23,111 @@ // /////////////////////////////////////////////////////////////////////////////// -#include "visualeditor.h" - #include "model/objectbase.h" -#include "utils/typeconv.h" #include "rad/appdata.h" +#include "utils/typeconv.h" +#include "visualeditor.h" -using namespace TypeConv; -/////////////////////////////////////////////////////////////////////////////// +using namespace TypeConv; -BEGIN_EVENT_TABLE( VObjEvtHandler, wxEvtHandler ) - EVT_LEFT_DOWN( VObjEvtHandler::OnLeftClick ) - EVT_RIGHT_DOWN( VObjEvtHandler::OnRightClick ) - EVT_PAINT( VObjEvtHandler::OnPaint ) - EVT_SET_CURSOR( VObjEvtHandler::OnSetCursor ) +BEGIN_EVENT_TABLE(VObjEvtHandler, wxEvtHandler) +EVT_LEFT_DOWN(VObjEvtHandler::OnLeftClick) +EVT_RIGHT_DOWN(VObjEvtHandler::OnRightClick) +EVT_PAINT(VObjEvtHandler::OnPaint) +EVT_SET_CURSOR(VObjEvtHandler::OnSetCursor) END_EVENT_TABLE() -VObjEvtHandler::VObjEvtHandler(wxWindow *win, PObjectBase obj) + +VObjEvtHandler::VObjEvtHandler(wxWindow* win, PObjectBase obj) { - m_window = win; - m_object = obj; + m_window = win; + m_object = obj; } -void VObjEvtHandler::OnLeftClick(wxMouseEvent &event) +void VObjEvtHandler::OnLeftClick(wxMouseEvent& event) { - PObjectBase obj = m_object.lock(); - - if (obj) - { - if( obj->GetObjectTypeName() == wxT("ribbonbar") ) - { - if (AppData()->GetSelectedObject() != obj) - AppData()->SelectObject(obj); - - event.Skip(); - return; - } - - if (AppData()->GetSelectedObject() != obj) - { - AppData()->SelectObject(obj); - - // this event is always redirected to parent (aui)toolbar even if its tool was clicked - // so it is important to skip the event to select clicked tool later in "common" - // plugin. - if( obj->GetObjectTypeName() == wxT("toolbar") || - obj->GetObjectTypeName() == wxT("toolbar_form") ) event.Skip(); - } - else - { - // *!* Event should be skipped only in the case of the object selected - // is the same that the object clicked. You will experiment rare things - // in other case. - event.Skip(); - } - } - - m_window->ClientToScreen(&event.m_x, &event.m_y); - m_window->GetParent()->ScreenToClient(&event.m_x, &event.m_y); - ::wxPostEvent(m_window->GetParent(), event); + PObjectBase obj = m_object.lock(); + + if (obj) { + if (obj->GetObjectTypeName() == wxT("ribbonbar")) { + if (AppData()->GetSelectedObject() != obj) + AppData()->SelectObject(obj); + + event.Skip(); + return; + } + + if (AppData()->GetSelectedObject() != obj) { + AppData()->SelectObject(obj); + + // this event is always redirected to parent (aui)toolbar even if its tool was clicked + // so it is important to skip the event to select clicked tool later in "common" + // plugin. + if (obj->GetObjectTypeName() == wxT("toolbar") || obj->GetObjectTypeName() == wxT("toolbar_form")) + event.Skip(); + } else { + // *!* Event should be skipped only in the case of the object selected + // is the same that the object clicked. You will experiment rare things + // in other case. + event.Skip(); + } + } + + m_window->ClientToScreen(&event.m_x, &event.m_y); + m_window->GetParent()->ScreenToClient(&event.m_x, &event.m_y); + ::wxPostEvent(m_window->GetParent(), event); } -void VObjEvtHandler::OnRightClick(wxMouseEvent &event) +void VObjEvtHandler::OnRightClick(wxMouseEvent& event) { - // show context menu associated with the widget if any - - PObjectBase obj = m_object.lock(); - - if (obj) - { - if (obj->GetPropertyAsInteger(wxT("context_menu")) != 0) { - PObjectBase menu; - - for( size_t i = 0; i < obj->GetChildCount(); i++ ) - { - if( obj->GetChild( i )->GetObjectTypeName() == wxT("menu") ) - { - menu = obj->GetChild( i ); - break; - } - } - - if( menu ) m_window->PopupMenu( DesignerWindow::GetMenuFromObject( menu ), event.GetPosition() ); - } - else - event.Skip(); - } - - m_window->ClientToScreen(&event.m_x, &event.m_y); - m_window->GetParent()->ScreenToClient(&event.m_x, &event.m_y); - ::wxPostEvent(m_window->GetParent(), event); + // show context menu associated with the widget if any + + PObjectBase obj = m_object.lock(); + + if (obj) { + if (obj->GetPropertyAsInteger(wxT("context_menu")) != 0) { + PObjectBase menu; + + for (size_t i = 0; i < obj->GetChildCount(); i++) { + if (obj->GetChild(i)->GetObjectTypeName() == wxT("menu")) { + menu = obj->GetChild(i); + break; + } + } + + if (menu) + m_window->PopupMenu(DesignerWindow::GetMenuFromObject(menu), event.GetPosition()); + } else + event.Skip(); + } + + m_window->ClientToScreen(&event.m_x, &event.m_y); + m_window->GetParent()->ScreenToClient(&event.m_x, &event.m_y); + ::wxPostEvent(m_window->GetParent(), event); } -void VObjEvtHandler::OnPaint(wxPaintEvent &event) +void VObjEvtHandler::OnPaint(wxPaintEvent& event) { -/* PObjectBase wo = boost::shared_dynamic_cast(m_object.lock()); - if (wo->IsContainer()) - { TODO: what this check is for? */ - wxWindow *aux = m_window; - while (!aux->IsKindOf(CLASSINFO(DesignerWindow))) aux = aux->GetParent(); - DesignerWindow *dsgnWin = (DesignerWindow*) aux; - if (dsgnWin->GetActivePanel() == m_window) - { - wxPaintDC dc(m_window); - dsgnWin->HighlightSelection(dc); - } -/* }*/ - event.Skip(); + /* PObjectBase wo = boost::shared_dynamic_cast(m_object.lock()); + if (wo->IsContainer()) + { TODO: what this check is for? */ + wxWindow* aux = m_window; + while (!aux->IsKindOf(CLASSINFO(DesignerWindow))) aux = aux->GetParent(); + DesignerWindow* dsgnWin = (DesignerWindow*)aux; + if (dsgnWin->GetActivePanel() == m_window) { + wxPaintDC dc(m_window); + dsgnWin->HighlightSelection(dc); + } + /* }*/ + event.Skip(); } -void VObjEvtHandler::OnSetCursor(wxSetCursorEvent &event) +void VObjEvtHandler::OnSetCursor(wxSetCursorEvent& event) { - wxCoord x = event.GetX(), y = event.GetY(); - m_window->ClientToScreen(&x, &y); - m_window->GetParent()->ScreenToClient(&x, &y); - wxSetCursorEvent sce(x, y); - ::wxPostEvent(m_window->GetParent(), sce); + wxCoord x = event.GetX(), y = event.GetY(); + m_window->ClientToScreen(&x, &y); + m_window->GetParent()->ScreenToClient(&x, &y); + wxSetCursorEvent sce(x, y); + ::wxPostEvent(m_window->GetParent(), sce); } diff --git a/src/rad/designer/visualobj.h b/src/rad/designer/visualobj.h index a8a61a122..759753186 100644 --- a/src/rad/designer/visualobj.h +++ b/src/rad/designer/visualobj.h @@ -26,34 +26,31 @@ #ifndef RAD_DESIGNER_VISUALOBJ_H #define RAD_DESIGNER_VISUALOBJ_H +#include + #include "utils/wxfbdefs.h" -#include /** * Processes events from visual objects. */ class VObjEvtHandler : public wxEvtHandler { - private: - WPObjectBase m_object; - wxWindow *m_window; +private: + WPObjectBase m_object; + wxWindow* m_window; - VObjEvtHandler() = default; + VObjEvtHandler() = default; - protected: - DECLARE_EVENT_TABLE() +protected: + DECLARE_EVENT_TABLE() - public: - VObjEvtHandler(wxWindow *win, PObjectBase obj); - void OnLeftClick(wxMouseEvent &event); - void OnRightClick(wxMouseEvent &event); - void OnPaint(wxPaintEvent &event); - void OnSetCursor(wxSetCursorEvent &event); +public: + VObjEvtHandler(wxWindow* win, PObjectBase obj); + void OnLeftClick(wxMouseEvent& event); + void OnRightClick(wxMouseEvent& event); + void OnPaint(wxPaintEvent& event); + void OnSetCursor(wxSetCursorEvent& event); }; - -/////////////////////////////////////////////////////////////////////////////// - - -#endif // RAD_DESIGNER_VISUALOBJ_H +#endif // RAD_DESIGNER_VISUALOBJ_H diff --git a/src/rad/designer/window_buttons.h b/src/rad/designer/window_buttons.h index c55ffc07d..a3b89ec7f 100644 --- a/src/rad/designer/window_buttons.h +++ b/src/rad/designer/window_buttons.h @@ -22,9 +22,11 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_DESIGNER_WINDOW_BUTTONS_H #define RAD_DESIGNER_WINDOW_BUTTONS_H +// clang-format off /* XPM */ static const char * minimize_xpm[] = { "17 15 6 1", @@ -169,5 +171,6 @@ static const char * close_disabled_xpm[] = { " .@@@@@@@@@@@@@@#+", " .###############+", " +++++++++++++++++"}; +// clang-format on -#endif // RAD_DESIGNER_WINDOW_BUTTONS_H +#endif // RAD_DESIGNER_WINDOW_BUTTONS_H diff --git a/src/rad/dialogfindcomponent.cpp b/src/rad/dialogfindcomponent.cpp index a10bbabbe..09f2f6b17 100644 --- a/src/rad/dialogfindcomponent.cpp +++ b/src/rad/dialogfindcomponent.cpp @@ -29,26 +29,24 @@ #include -#include "rad/appdata.h" #include "model/objectbase.h" +#include "rad/appdata.h" #include "utils/wxfbdefs.h" -DialogFindComponent::DialogFindComponent(wxWindow* parent, - wxWindowID id, const wxString& title, const wxPoint& pos, - const wxSize& size, long style) - : wxDialog(parent, id, title, pos, size, style) +DialogFindComponent::DialogFindComponent( + wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : + wxDialog(parent, id, title, pos, size, style) { - this->SetSizeHints(wxSize(250,400), wxDefaultSize); + this->SetSizeHints(wxSize(250, 400), wxDefaultSize); wxBoxSizer* bSizerMain = new wxBoxSizer(wxVERTICAL); m_textCtrlComponent = new wxTextCtrl(this, wxID_ANY); - bSizerMain->Add(m_textCtrlComponent, 0, wxALL|wxEXPAND, 5); + bSizerMain->Add(m_textCtrlComponent, 0, wxALL | wxEXPAND, 5); - m_listBoxComponents = new wxListBox(this, wxID_ANY, wxDefaultPosition, - wxDefaultSize, 0, nullptr, wxLB_SINGLE); - bSizerMain->Add(m_listBoxComponents, 1, wxALL|wxEXPAND, 5); + m_listBoxComponents = new wxListBox(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxLB_SINGLE); + bSizerMain->Add(m_listBoxComponents, 1, wxALL | wxEXPAND, 5); m_staticline = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL); bSizerMain->Add(m_staticline, 0, wxEXPAND | wxALL, 5); @@ -58,37 +56,35 @@ DialogFindComponent::DialogFindComponent(wxWindow* parent, m_buttonInsert = new wxButton(this, wxID_OK, _("Insert")); m_buttonInsert->SetDefault(); - bSizerButton->Add( m_buttonInsert, 0, wxALL, 5 ); + bSizerButton->Add(m_buttonInsert, 0, wxALL, 5); m_buttonCancel = new wxButton(this, wxID_CANCEL); - bSizerButton->Add( m_buttonCancel, 0, wxALL, 5 ); - - bSizerMain->Add( bSizerButton, 0, wxEXPAND, 5 ); + bSizerButton->Add(m_buttonCancel, 0, wxALL, 5); + + bSizerMain->Add(bSizerButton, 0, wxEXPAND, 5); m_textCtrlComponent->Bind(wxEVT_TEXT, &DialogFindComponent::OnTextCtrlComponent, this); - m_listBoxComponents->Bind(wxEVT_LISTBOX_DCLICK, &DialogFindComponent::OnListBoxComponentsDClick, - this); - m_listBoxComponents->Bind(wxEVT_LISTBOX, &DialogFindComponent::OnListBoxComponents,this); + m_listBoxComponents->Bind(wxEVT_LISTBOX_DCLICK, &DialogFindComponent::OnListBoxComponentsDClick, this); + m_listBoxComponents->Bind(wxEVT_LISTBOX, &DialogFindComponent::OnListBoxComponents, this); SetAffirmativeId(m_buttonInsert->GetId()); - this->SetSizer( bSizerMain ); + this->SetSizer(bSizerMain); this->Layout(); - this->Centre( wxBOTH ); + this->Centre(wxBOTH); } -bool DialogFindComponent::TransferDataToWindow() { +bool DialogFindComponent::TransferDataToWindow() +{ m_allComponents.clear(); - for ( unsigned i = 0; i < AppData()->GetPackageCount(); ++i ) - { - auto pkg = AppData()->GetPackage( i ); - m_allComponents.reserve(m_allComponents.size() + pkg->GetObjectCount()); + for (unsigned i = 0; i < AppData()->GetPackageCount(); ++i) { + auto pkg = AppData()->GetPackage(i); + m_allComponents.reserve(m_allComponents.size() + pkg->GetObjectCount()); - for ( unsigned j = 0; j < pkg->GetObjectCount(); ++j) - { - PObjectInfo info = pkg->GetObjectInfo( j ); + for (unsigned j = 0; j < pkg->GetObjectCount(); ++j) { + PObjectInfo info = pkg->GetObjectInfo(j); m_allComponents.emplace_back(info->GetClassName()); } @@ -106,19 +102,21 @@ bool DialogFindComponent::TransferDataToWindow() { } // Clear() emits a text change event m_textCtrlComponent->ChangeValue(wxEmptyString); - + updateEnabledState(); return wxDialog::TransferDataToWindow(); } -bool DialogFindComponent::TransferDataFromWindow() { +bool DialogFindComponent::TransferDataFromWindow() +{ m_chosenComponent = m_listBoxComponents->GetString(m_listBoxComponents->GetSelection()); return wxDialog::TransferDataFromWindow(); } -bool DialogFindComponent::Validate() { +bool DialogFindComponent::Validate() +{ if (m_listBoxComponents->GetSelection() == wxNOT_FOUND) { return false; } @@ -127,7 +125,8 @@ bool DialogFindComponent::Validate() { } -void DialogFindComponent::updateEnabledState() { +void DialogFindComponent::updateEnabledState() +{ const auto enableInsert = (m_listBoxComponents->GetSelection() != wxNOT_FOUND); if (m_buttonInsert->IsThisEnabled() != enableInsert) { m_buttonInsert->Enable(enableInsert); @@ -139,7 +138,8 @@ void DialogFindComponent::OnTextCtrlComponent(wxCommandEvent& WXUNUSED(event)) { auto nextSearch = m_textCtrlComponent->GetValue(); nextSearch.MakeLower(); - const auto& searchComponents = (!m_prevSearch.empty() && nextSearch.Find(m_prevSearch) != wxNOT_FOUND ? m_prevComponents : m_allComponents); + const auto& searchComponents = + (!m_prevSearch.empty() && nextSearch.Find(m_prevSearch) != wxNOT_FOUND ? m_prevComponents : m_allComponents); std::vector nextComponents; nextComponents.reserve(searchComponents.size()); diff --git a/src/rad/dialogfindcomponent.h b/src/rad/dialogfindcomponent.h index 360bd0959..6d43416fc 100644 --- a/src/rad/dialogfindcomponent.h +++ b/src/rad/dialogfindcomponent.h @@ -34,20 +34,20 @@ #include +#include #include -#include #include #include -#include +#include class DialogFindComponent : public wxDialog { public: - DialogFindComponent(wxWindow* parent, - wxWindowID id = wxID_ANY, const wxString& title = _("Find Component"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxSize( 250,400 ), long style = wxDEFAULT_DIALOG_STYLE); + DialogFindComponent( + wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Find Component"), + const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(250, 400), + long style = wxDEFAULT_DIALOG_STYLE); const wxString& GetSelected() const { return m_chosenComponent; } @@ -64,11 +64,11 @@ class DialogFindComponent : public wxDialog void OnListBoxComponents(wxCommandEvent& event); private: - wxTextCtrl *m_textCtrlComponent; - wxListBox *m_listBoxComponents; - wxStaticLine *m_staticline; - wxButton *m_buttonCancel; - wxButton *m_buttonInsert; + wxTextCtrl* m_textCtrlComponent; + wxListBox* m_listBoxComponents; + wxStaticLine* m_staticline; + wxButton* m_buttonCancel; + wxButton* m_buttonInsert; std::vector m_allComponents; std::vector m_prevComponents; @@ -76,4 +76,4 @@ class DialogFindComponent : public wxDialog wxString m_chosenComponent; }; -#endif // RAD_DIALOGFINDCOMPONENT_H +#endif // RAD_DIALOGFINDCOMPONENT_H diff --git a/src/rad/genericpanel.cpp b/src/rad/genericpanel.cpp index 08b870e23..9b812d720 100644 --- a/src/rad/genericpanel.cpp +++ b/src/rad/genericpanel.cpp @@ -25,22 +25,22 @@ #include "genericpanel.h" -BEGIN_EVENT_TABLE(GenericWindow,wxPanel) - EVT_PAINT(GenericWindow::OnPaint) + +BEGIN_EVENT_TABLE(GenericWindow, wxPanel) +EVT_PAINT(GenericWindow::OnPaint) END_EVENT_TABLE() -GenericWindow::GenericWindow(wxWindow *parent) - : wxPanel (parent, wxID_ANY,wxDefaultPosition,wxSize(30,30)) + +GenericWindow::GenericWindow(wxWindow* parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(30, 30)) { } -void GenericWindow::OnPaint(wxPaintEvent &) -{ - wxPaintDC dc(this); - wxSize size = GetSize(); - dc.SetPen(*wxBLACK_PEN); - for (int i=0;i + class GenericWindow : public wxPanel { - private: - DECLARE_EVENT_TABLE() - public: - GenericWindow(wxWindow *parent); - void OnPaint(wxPaintEvent &event); +private: + DECLARE_EVENT_TABLE() +public: + GenericWindow(wxWindow* parent); + void OnPaint(wxPaintEvent& event); }; - -#endif // RAD_GENERICPANEL_H +#endif // RAD_GENERICPANEL_H diff --git a/src/rad/geninheritclass/geninhertclass.cpp b/src/rad/geninheritclass/geninhertclass.cpp index a29586f24..34b31cd39 100644 --- a/src/rad/geninheritclass/geninhertclass.cpp +++ b/src/rad/geninheritclass/geninhertclass.cpp @@ -22,79 +22,75 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "geninhertclass.h" #include "model/objectbase.h" -GenInheritedClassDlg::GenInheritedClassDlg( wxWindow* parent, PObjectBase project ) -: -GenInheritedClassDlgBase( parent ) + +GenInheritedClassDlg::GenInheritedClassDlg(wxWindow* parent, PObjectBase project) : GenInheritedClassDlgBase(parent) { - const wxString& projectName = project->GetPropertyAsString( _("name") ); + const wxString& projectName = project->GetPropertyAsString(_("name")); - // Setup the initial values for the maps of class names and file names. - for ( unsigned int i = 0; i < project->GetChildCount(); ++i ) - { - PObjectBase child = project->GetChild( i ); - const wxString& formName = child->GetPropertyAsString( _("name") ); - const wxString& name = projectName + formName; - m_classDetails.push_back( GenClassDetails( child, name, name ) ); + // Setup the initial values for the maps of class names and file names. + for (unsigned int i = 0; i < project->GetChildCount(); ++i) { + PObjectBase child = project->GetChild(i); + const wxString& formName = child->GetPropertyAsString(_("name")); + const wxString& name = projectName + formName; + m_classDetails.push_back(GenClassDetails(child, name, name)); - // Add the forms to the listctrl. - m_formsCheckList->AppendString( formName ); - } + // Add the forms to the listctrl. + m_formsCheckList->AppendString(formName); + } - // Disable the controls till the check listbox is selected. - m_classNameTextCtrl->Disable(); - m_fileNameTextCtrl->Disable(); + // Disable the controls till the check listbox is selected. + m_classNameTextCtrl->Disable(); + m_fileNameTextCtrl->Disable(); } -void GenInheritedClassDlg::GetFormsSelected( std::vector< GenClassDetails >* forms ) +void GenInheritedClassDlg::GetFormsSelected(std::vector* forms) { - // Clear the selected forms array. - forms->clear(); + // Clear the selected forms array. + forms->clear(); - for ( size_t i = 0; i < m_classDetails.size(); ++i ) - { - if ( m_classDetails[i].m_isSelected ) - { - forms->push_back( m_classDetails[i] ); - } - } + for (size_t i = 0; i < m_classDetails.size(); ++i) { + if (m_classDetails[i].m_isSelected) { + forms->push_back(m_classDetails[i]); + } + } } -void GenInheritedClassDlg::OnFormsSelected( wxCommandEvent& ) +void GenInheritedClassDlg::OnFormsSelected(wxCommandEvent&) { - // Enable controls because an item is selected. - int selection = m_formsCheckList->GetSelection(); - if ( wxNOT_FOUND == selection ) - { - m_classNameTextCtrl->Disable(); - m_fileNameTextCtrl->Disable(); - return; - } + // Enable controls because an item is selected. + int selection = m_formsCheckList->GetSelection(); + if (wxNOT_FOUND == selection) { + m_classNameTextCtrl->Disable(); + m_fileNameTextCtrl->Disable(); + return; + } - m_classNameTextCtrl->Enable(); - m_fileNameTextCtrl->Enable(); + m_classNameTextCtrl->Enable(); + m_fileNameTextCtrl->Enable(); - // Set the values of the controls - GenClassDetails& details = m_classDetails[ selection ]; - m_classNameTextCtrl->SetValue( details.m_className ); - m_fileNameTextCtrl->SetValue( details.m_fileName ); + // Set the values of the controls + GenClassDetails& details = m_classDetails[selection]; + m_classNameTextCtrl->SetValue(details.m_className); + m_fileNameTextCtrl->SetValue(details.m_fileName); } -void GenInheritedClassDlg::OnFormsToggle( wxCommandEvent& event ) +void GenInheritedClassDlg::OnFormsToggle(wxCommandEvent& event) { - int selection = event.GetSelection(); - m_classDetails[ selection ].m_isSelected = m_formsCheckList->IsChecked( selection ); + int selection = event.GetSelection(); + m_classDetails[selection].m_isSelected = m_formsCheckList->IsChecked(selection); } -void GenInheritedClassDlg::OnClassNameChange( wxCommandEvent& ) +void GenInheritedClassDlg::OnClassNameChange(wxCommandEvent&) { - m_classDetails[ m_formsCheckList->GetSelection() ].m_className = m_classNameTextCtrl->GetValue(); + m_classDetails[m_formsCheckList->GetSelection()].m_className = m_classNameTextCtrl->GetValue(); } -void GenInheritedClassDlg::OnFileNameChange( wxCommandEvent& ) +void GenInheritedClassDlg::OnFileNameChange(wxCommandEvent&) { - m_classDetails[ m_formsCheckList->GetSelection() ].m_fileName = m_fileNameTextCtrl->GetValue(); + m_classDetails[m_formsCheckList->GetSelection()].m_fileName = m_fileNameTextCtrl->GetValue(); } diff --git a/src/rad/geninheritclass/geninhertclass.h b/src/rad/geninheritclass/geninhertclass.h index dc60f84bc..e20a68d95 100644 --- a/src/rad/geninheritclass/geninhertclass.h +++ b/src/rad/geninheritclass/geninhertclass.h @@ -22,6 +22,7 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_GENINHERITCLASS_GENINHERTCLASS_H #define RAD_GENINHERITCLASS_GENINHERTCLASS_H @@ -33,53 +34,49 @@ the wxFormBuilder GUI code. @date 01/14/2007 */ -#include "utils/wxfbdefs.h" #include "rad/geninheritclass/geninhertclass_gui.h" +#include "utils/wxfbdefs.h" + /** Holds the details of the class to generate. */ class GenClassDetails { public: + /** Default Constructor. */ + GenClassDetails() {} - /** Default Constructor. */ - GenClassDetails() {} - - /** - Constructor. - @param form Form object. - @param className Name of the class to generate. - @param fileName File name of the output files the at generated class will be in. - @param isSelected If true then the class is selected, else it is not. - */ - GenClassDetails( PObjectBase form, const wxString& className, const wxString& fileName, bool isSelected = false ) - : - m_form( form ), - m_className( className ), - m_fileName( fileName ), - m_isSelected( isSelected ) - { - } + /** + Constructor. + @param form Form object. + @param className Name of the class to generate. + @param fileName File name of the output files the at generated class will be in. + @param isSelected If true then the class is selected, else it is not. + */ + GenClassDetails(PObjectBase form, const wxString& className, const wxString& fileName, bool isSelected = false) : + m_form(form), m_className(className), m_fileName(fileName), m_isSelected(isSelected) + { + } - PObjectBase m_form; /**< Form object. */ - wxString m_className; /**< Name of the class to generate. */ - wxString m_fileName; /**< File name to generate the class in. */ - bool m_isSelected; /**< Holds if the checkbox is selected for the form. */ + PObjectBase m_form; /**< Form object. */ + wxString m_className; /**< Name of the class to generate. */ + wxString m_fileName; /**< File name to generate the class in. */ + bool m_isSelected; /**< Holds if the checkbox is selected for the form. */ }; /** */ class GenInheritedClassDlg : public GenInheritedClassDlgBase { public: - GenInheritedClassDlg( wxWindow* parent, PObjectBase project ); - void GetFormsSelected( std::vector< GenClassDetails >* forms ); + GenInheritedClassDlg(wxWindow* parent, PObjectBase project); + void GetFormsSelected(std::vector* forms); private: - std::vector< GenClassDetails > m_classDetails; + std::vector m_classDetails; - void OnFormsSelected(wxCommandEvent& event) override; - void OnFormsToggle(wxCommandEvent& event) override; - void OnClassNameChange(wxCommandEvent& event) override; - void OnFileNameChange(wxCommandEvent& event) override; + void OnFormsSelected(wxCommandEvent& event) override; + void OnFormsToggle(wxCommandEvent& event) override; + void OnClassNameChange(wxCommandEvent& event) override; + void OnFileNameChange(wxCommandEvent& event) override; }; -#endif // RAD_GENINHERITCLASS_GENINHERTCLASS_H +#endif // RAD_GENINHERITCLASS_GENINHERTCLASS_H diff --git a/src/rad/inspector/objinspect.cpp b/src/rad/inspector/objinspect.cpp index 52685e661..93eb4b1a3 100644 --- a/src/rad/inspector/objinspect.cpp +++ b/src/rad/inspector/objinspect.cpp @@ -28,1248 +28,1063 @@ #include "objinspect.h" -#include "rad/inspector/wxfbadvprops.h" - -#include "utils/debug.h" -#include "utils/typeconv.h" -#include "utils/wxfbexception.h" +#include +#include #include "rad/appdata.h" #include "rad/auitabart.h" #include "rad/bitmaps.h" +#include "rad/inspector/wxfbadvprops.h" #include "rad/wxfbevent.h" +#include "utils/debug.h" +#include "utils/typeconv.h" +#include "utils/wxfbexception.h" -#include -#include static int wxEVT_FB_PROP_BITMAP_CHANGED = wxNewEventType(); enum { - WXFB_PROPERTY_GRID = wxID_HIGHEST + 1000, - WXFB_EVENT_GRID, + WXFB_PROPERTY_GRID = wxID_HIGHEST + 1000, + WXFB_EVENT_GRID, }; // ----------------------------------------------------------------------- // ObjectInspector // ----------------------------------------------------------------------- BEGIN_EVENT_TABLE(ObjectInspector, wxPanel) - EVT_PG_CHANGING(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridChanging) - EVT_PG_CHANGED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridChanged) - EVT_PG_CHANGED(WXFB_EVENT_GRID, ObjectInspector::OnEventGridChanged) - EVT_PG_DOUBLE_CLICK(WXFB_EVENT_GRID, ObjectInspector::OnEventGridDblClick) - EVT_PG_DOUBLE_CLICK(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridDblClick) - EVT_PG_ITEM_COLLAPSED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridExpand) - EVT_PG_ITEM_EXPANDED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridExpand) - EVT_PG_ITEM_COLLAPSED(WXFB_EVENT_GRID, ObjectInspector::OnEventGridExpand) - EVT_PG_ITEM_EXPANDED(WXFB_EVENT_GRID, ObjectInspector::OnEventGridExpand) - EVT_PG_SELECTED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridItemSelected) - EVT_PG_SELECTED(WXFB_EVENT_GRID, ObjectInspector::OnPropertyGridItemSelected) - - EVT_FB_OBJECT_SELECTED( ObjectInspector::OnObjectSelected ) - EVT_FB_PROJECT_REFRESH( ObjectInspector::OnProjectRefresh ) - EVT_FB_PROPERTY_MODIFIED( ObjectInspector::OnPropertyModified ) - EVT_FB_EVENT_HANDLER_MODIFIED( ObjectInspector::OnEventHandlerModified ) - EVT_CHILD_FOCUS( ObjectInspector::OnChildFocus ) +EVT_PG_CHANGING(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridChanging) +EVT_PG_CHANGED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridChanged) +EVT_PG_CHANGED(WXFB_EVENT_GRID, ObjectInspector::OnEventGridChanged) +EVT_PG_DOUBLE_CLICK(WXFB_EVENT_GRID, ObjectInspector::OnEventGridDblClick) +EVT_PG_DOUBLE_CLICK(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridDblClick) +EVT_PG_ITEM_COLLAPSED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridExpand) +EVT_PG_ITEM_EXPANDED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridExpand) +EVT_PG_ITEM_COLLAPSED(WXFB_EVENT_GRID, ObjectInspector::OnEventGridExpand) +EVT_PG_ITEM_EXPANDED(WXFB_EVENT_GRID, ObjectInspector::OnEventGridExpand) +EVT_PG_SELECTED(WXFB_PROPERTY_GRID, ObjectInspector::OnPropertyGridItemSelected) +EVT_PG_SELECTED(WXFB_EVENT_GRID, ObjectInspector::OnPropertyGridItemSelected) + +EVT_FB_OBJECT_SELECTED(ObjectInspector::OnObjectSelected) +EVT_FB_PROJECT_REFRESH(ObjectInspector::OnProjectRefresh) +EVT_FB_PROPERTY_MODIFIED(ObjectInspector::OnPropertyModified) +EVT_FB_EVENT_HANDLER_MODIFIED(ObjectInspector::OnEventHandlerModified) +EVT_CHILD_FOCUS(ObjectInspector::OnChildFocus) END_EVENT_TABLE() -ObjectInspector::ObjectInspector( wxWindow* parent, int id, int style ) -: wxPanel(parent,id), m_style(style) + +ObjectInspector::ObjectInspector(wxWindow* parent, int id, int style) : wxPanel(parent, id), m_style(style) { - AppData()->AddHandler( this->GetEventHandler() ); - m_currentSel = PObjectBase(); + AppData()->AddHandler(this->GetEventHandler()); + m_currentSel = PObjectBase(); - m_nb = new wxAuiNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP ); - m_nb->SetArtProvider( new AuiTabArt() ); + m_nb = new wxAuiNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP); + m_nb->SetArtProvider(new AuiTabArt()); - // The colour of property grid description looks ugly if we don't set this colour - m_nb->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE)); + // The colour of property grid description looks ugly if we don't set this colour + m_nb->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE)); - // Register the slider editor + // Register the slider editor #if wxUSE_SLIDER - // TODO + // TODO #endif - m_pg = CreatePropertyGridManager(m_nb, WXFB_PROPERTY_GRID); - m_eg = CreatePropertyGridManager(m_nb, WXFB_EVENT_GRID); + m_pg = CreatePropertyGridManager(m_nb, WXFB_PROPERTY_GRID); + m_eg = CreatePropertyGridManager(m_nb, WXFB_EVENT_GRID); - m_nb->InsertPage( 0, m_pg, _("Properties"), false ); - m_nb->InsertPage( 1, m_eg, _("Events"), false ); + m_nb->InsertPage(0, m_pg, _("Properties"), false); + m_nb->InsertPage(1, m_eg, _("Events"), false); - m_nb->SetPageBitmap( 0, AppBitmaps::GetBitmap( wxT("properties"), 16 ) ); - m_nb->SetPageBitmap( 1, AppBitmaps::GetBitmap( wxT("events"), 16 ) ); + m_nb->SetPageBitmap(0, AppBitmaps::GetBitmap(wxT("properties"), 16)); + m_nb->SetPageBitmap(1, AppBitmaps::GetBitmap(wxT("events"), 16)); - wxBoxSizer* topSizer = new wxBoxSizer( wxVERTICAL ); - topSizer->Add( m_nb, 1, wxALL | wxEXPAND, 0 ); - SetSizer( topSizer ); + wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL); + topSizer->Add(m_nb, 1, wxALL | wxEXPAND, 0); + SetSizer(topSizer); - Connect( wxID_ANY, wxEVT_FB_PROP_BITMAP_CHANGED, wxCommandEventHandler( ObjectInspector::OnBitmapPropertyChanged) ); + Connect(wxID_ANY, wxEVT_FB_PROP_BITMAP_CHANGED, wxCommandEventHandler(ObjectInspector::OnBitmapPropertyChanged)); } ObjectInspector::~ObjectInspector() { - Disconnect( wxID_ANY, wxEVT_FB_PROP_BITMAP_CHANGED, wxCommandEventHandler( ObjectInspector::OnBitmapPropertyChanged) ); + Disconnect(wxID_ANY, wxEVT_FB_PROP_BITMAP_CHANGED, wxCommandEventHandler(ObjectInspector::OnBitmapPropertyChanged)); - AppData()->RemoveHandler( this->GetEventHandler() ); + AppData()->RemoveHandler(this->GetEventHandler()); } void ObjectInspector::SavePosition() { - // Save Layout - wxConfigBase* config = wxConfigBase::Get(); - config->Write( wxT("/mainframe/objectInspector/DescBoxHeight" ), m_pg->GetDescBoxHeight() ); + // Save Layout + wxConfigBase* config = wxConfigBase::Get(); + config->Write(wxT("/mainframe/objectInspector/DescBoxHeight"), m_pg->GetDescBoxHeight()); } -void ObjectInspector::Create( bool force ) +void ObjectInspector::Create(bool force) { - PObjectBase sel_obj = AppData()->GetSelectedObject(); - if ( sel_obj && ( sel_obj != m_currentSel || force ) ) - { - Freeze(); - - m_currentSel = sel_obj; - - int pageNumber = m_pg->GetSelectedPage(); - wxString pageName; - if ( pageNumber != wxNOT_FOUND ) - { - pageName = m_pg->GetPageName( pageNumber ); - } - - // Clear Property Grid Manager - m_pg->Clear(); - - // Now we do the same thing for event grid... - m_eg->Clear(); - - m_propMap.clear(); - m_eventMap.clear(); - - PObjectInfo obj_desc = sel_obj->GetObjectInfo(); - if (obj_desc) - { - PropertyMap propMap, dummyPropMap; - EventMap eventMap, dummyEventMap; - - // We create the categories with the properties of the object organized by "classes" - CreateCategory( obj_desc->GetClassName(), sel_obj, obj_desc, propMap, false ); - CreateCategory( obj_desc->GetClassName(), sel_obj, obj_desc, eventMap, true ); - - for (unsigned int i=0; iGetBaseClassCount() ; i++) - { - PObjectInfo info_base = obj_desc->GetBaseClass(i); - CreateCategory( info_base->GetClassName(), sel_obj, info_base, propMap, false ); - CreateCategory( info_base->GetClassName(), sel_obj, info_base, eventMap, true ); - } - - PObjectBase parent = sel_obj->GetParent(); - if ( parent ) - { - PObjectInfo parent_desc = parent->GetObjectInfo(); - if ( parent_desc->GetObjectType()->IsItem()) - { - CreateCategory( parent_desc->GetClassName(), parent, parent_desc, dummyPropMap, false ); - CreateCategory( parent_desc->GetClassName(), parent, parent_desc, dummyEventMap, true ); - - for (unsigned int i=0; iGetBaseClassCount() ; i++) - { - PObjectInfo info_base = parent_desc->GetBaseClass(i); - CreateCategory( info_base->GetClassName(), parent, info_base, dummyPropMap, false ); - CreateCategory( info_base->GetClassName(), parent, info_base, dummyEventMap, true ); - } - } - } - - // Select previously selected page, or first page - if ( m_pg->GetPageCount() > 0 ) - { - int pageIndex = m_pg->GetPageByName( pageName ); - if ( wxNOT_FOUND != pageIndex ) - { - m_pg->SelectPage( pageIndex ); - } - else - { - m_pg->SelectPage( 0 ); - } - } - } - - m_pg->Refresh(); - m_pg->Update(); - m_eg->Refresh(); - m_eg->Update(); - Thaw(); - - RestoreLastSelectedPropItem(); - } + PObjectBase sel_obj = AppData()->GetSelectedObject(); + if (sel_obj && (sel_obj != m_currentSel || force)) { + Freeze(); + + m_currentSel = sel_obj; + + int pageNumber = m_pg->GetSelectedPage(); + wxString pageName; + if (pageNumber != wxNOT_FOUND) { + pageName = m_pg->GetPageName(pageNumber); + } + + // Clear Property Grid Manager + m_pg->Clear(); + + // Now we do the same thing for event grid... + m_eg->Clear(); + + m_propMap.clear(); + m_eventMap.clear(); + + PObjectInfo obj_desc = sel_obj->GetObjectInfo(); + if (obj_desc) { + PropertyMap propMap, dummyPropMap; + EventMap eventMap, dummyEventMap; + + // We create the categories with the properties of the object organized by "classes" + CreateCategory(obj_desc->GetClassName(), sel_obj, obj_desc, propMap, false); + CreateCategory(obj_desc->GetClassName(), sel_obj, obj_desc, eventMap, true); + + for (unsigned int i = 0; i < obj_desc->GetBaseClassCount(); i++) { + PObjectInfo info_base = obj_desc->GetBaseClass(i); + CreateCategory(info_base->GetClassName(), sel_obj, info_base, propMap, false); + CreateCategory(info_base->GetClassName(), sel_obj, info_base, eventMap, true); + } + + PObjectBase parent = sel_obj->GetParent(); + if (parent) { + PObjectInfo parent_desc = parent->GetObjectInfo(); + if (parent_desc->GetObjectType()->IsItem()) { + CreateCategory(parent_desc->GetClassName(), parent, parent_desc, dummyPropMap, false); + CreateCategory(parent_desc->GetClassName(), parent, parent_desc, dummyEventMap, true); + + for (unsigned int i = 0; i < parent_desc->GetBaseClassCount(); i++) { + PObjectInfo info_base = parent_desc->GetBaseClass(i); + CreateCategory(info_base->GetClassName(), parent, info_base, dummyPropMap, false); + CreateCategory(info_base->GetClassName(), parent, info_base, dummyEventMap, true); + } + } + } + + // Select previously selected page, or first page + if (m_pg->GetPageCount() > 0) { + int pageIndex = m_pg->GetPageByName(pageName); + if (wxNOT_FOUND != pageIndex) { + m_pg->SelectPage(pageIndex); + } else { + m_pg->SelectPage(0); + } + } + } + + m_pg->Refresh(); + m_pg->Update(); + m_eg->Refresh(); + m_eg->Update(); + Thaw(); + + RestoreLastSelectedPropItem(); + } } int ObjectInspector::StringToBits(const wxString& strVal, wxPGChoices& constants) { - wxStringTokenizer strTok(strVal, wxT(" |")); - int val = 0; - while (strTok.HasMoreTokens()) - { - wxString token = strTok.GetNextToken(); - unsigned int i = 0; - bool done = false; - while (i < constants.GetCount() && !done) - { - if (constants.GetLabel(i) == token) - { - val |= constants.GetValue(i); - done = true; - } - i++; - } - } - return val; + wxStringTokenizer strTok(strVal, wxT(" |")); + int val = 0; + while (strTok.HasMoreTokens()) { + wxString token = strTok.GetNextToken(); + unsigned int i = 0; + bool done = false; + while (i < constants.GetCount() && !done) { + if (constants.GetLabel(i) == token) { + val |= constants.GetValue(i); + done = true; + } + i++; + } + } + return val; } -wxPGProperty* ObjectInspector::GetProperty( PProperty prop ) +wxPGProperty* ObjectInspector::GetProperty(PProperty prop) { - wxPGProperty *result = NULL; - PropertyType type = prop->GetType(); - wxString name = prop->GetName(); - wxVariant vTrue = wxVariant( true, wxT("true") ); - - if (type == PT_MACRO) - { - result = new wxStringProperty( name, wxPG_LABEL, prop->GetValueAsString() ); - } - else if (type == PT_INT) - { - result = new wxIntProperty( name, wxPG_LABEL, prop->GetValueAsInteger() ); - } - else if (type == PT_UINT) - { - result = new wxUIntProperty( name, wxPG_LABEL, (unsigned)prop->GetValueAsInteger() ); - } - else if (type == PT_WXSTRING || type == PT_WXSTRING_I18N) - { - result = new wxLongStringProperty( name, wxPG_LABEL, prop->GetValueAsText() ); - } - else if (type == PT_TEXT) - { - result = new wxLongStringProperty( name, wxPG_LABEL, prop->GetValueAsText() ); - } - else if (type == PT_BOOL) - { - result = new wxBoolProperty( name, wxPG_LABEL, prop->GetValue() == wxT("1") ); - } - else if (type == PT_BITLIST) - { - PPropertyInfo prop_desc = prop->GetPropertyInfo(); - POptionList opt_list = prop_desc->GetOptionList(); - - assert(opt_list && opt_list->GetOptionCount() > 0); - - wxPGChoices constants; - const std::map< wxString, wxString > options = opt_list->GetOptions(); - std::map< wxString, wxString >::const_iterator it; - unsigned int index = 0; - for( it = options.begin(); it != options.end(); ++it ) - { - constants.Add(it->first, 1 << index++); - } - - int val = StringToBits(prop->GetValueAsString(), constants); - result = new wxFlagsProperty(name, wxPG_LABEL, constants, val); - - // Workaround to set the help strings for individual members of a wxFlagsProperty - wxFlagsProperty* flagsProp = dynamic_cast< wxFlagsProperty* >( result ); - if ( NULL != flagsProp ) - { - for ( size_t i = 0; i < flagsProp->GetItemCount(); i++ ) - { - wxPGProperty* itemProp = flagsProp->Item(i); - std::map::const_iterator option = options.find(itemProp->GetLabel()); - if ( option != options.end() ) - { - m_pg->SetPropertyHelpString(itemProp, option->second); - } - } - } - } - else if (type == PT_INTLIST || type == PT_UINTLIST || type == PT_INTPAIRLIST || type == PT_UINTPAIRLIST) - { - result = new wxStringProperty(name, wxPG_LABEL, IntList(prop->GetValueAsString(), type == PT_UINTLIST, (PT_INTPAIRLIST == type || PT_UINTPAIRLIST == type)).ToString(true)); - } - else if (type == PT_OPTION || type == PT_EDIT_OPTION) - { - PPropertyInfo prop_desc = prop->GetPropertyInfo(); - POptionList opt_list = prop_desc->GetOptionList(); - - assert(opt_list && opt_list->GetOptionCount() > 0); - - wxString value = prop->GetValueAsString(); - wxString help; - - wxPGChoices constants; - const std::map< wxString, wxString > options = opt_list->GetOptions(); - std::map< wxString, wxString >::const_iterator it; - unsigned int i = 0; - for( it = options.begin(); it != options.end(); ++it ) - { - constants.Add( it->first, i++ ); - if ( it->first == value ) - { - // Save help - help = it->second; - } - } - - if ( type == PT_EDIT_OPTION ) - { - result = new wxEditEnumProperty( name, wxPG_LABEL, constants ); - } - else - { - result = new wxEnumProperty( name, wxPG_LABEL, constants ); - } - result->SetValueFromString( value, 0 ); - wxString desc = prop_desc->GetDescription(); - if ( desc.empty() ) - { - desc = value + wxT(":\n") + help; - } - else - { - desc += wxT("\n\n") + value + wxT(":\n") + help; - } - result->SetHelpString( wxGetTranslation( desc ) ); - - } - else if (type == PT_WXPOINT) - { - result = new wxFBPointProperty( name, wxPG_LABEL, prop->GetValueAsPoint() ); - } - else if (type == PT_WXSIZE) - { - result = new wxFBSizeProperty( name, wxPG_LABEL, prop->GetValueAsSize() ); - } - else if (type == PT_WXFONT) - { - result = new wxFBFontProperty( name, wxPG_LABEL, TypeConv::StringToFont( prop->GetValueAsString() ) ); - } - else if (type == PT_WXCOLOUR) - { - wxString value = prop->GetValueAsString(); - if ( value.empty() ) // Default Colour - { - wxColourPropertyValue colProp; - colProp.m_type = wxSYS_COLOUR_WINDOW; - colProp.m_colour = TypeConv::StringToSystemColour( wxT("wxSYS_COLOUR_WINDOW") ); - result = new wxSystemColourProperty( name, wxPG_LABEL, colProp ); - } - else - { - if ( value.find_first_of( wxT("wx") ) == 0 ) - { - wxColourPropertyValue def; // System Colour - def.m_type = TypeConv::StringToSystemColour( value ); - result = new wxSystemColourProperty( name, wxPG_LABEL, def ); - } - else - { - result = new wxSystemColourProperty( name, wxPG_LABEL, prop->GetValueAsColour() ); - } - } - } - else if (type == PT_PATH) - { - result = new wxDirProperty( name, wxPG_LABEL, prop->GetValueAsString() ); - } - else if (type == PT_FILE) - { - result = new wxFileProperty( name, wxPG_LABEL, prop->GetValueAsString() ); - } - else if (type == PT_BITMAP) - { - wxLogDebug( wxT("OI::GetProperty: prop:%s"), prop->GetValueAsString() ); - - result = new wxFBBitmapProperty( name, wxPG_LABEL, prop->GetValueAsString() ); - } - else if (type == PT_STRINGLIST) - { - result = new wxArrayStringProperty( name, wxPG_LABEL,prop->GetValueAsArrayString() ); - wxVariant v("\""); - result->DoSetAttribute(wxPG_ARRAY_DELIMITER, v); - } - else if (type == PT_FLOAT) - { - result = new wxFloatProperty( name, wxPG_LABEL, prop->GetValueAsFloat() ); - } - else if ( type == PT_PARENT ) - { - result = new wxStringProperty( name, wxPG_LABEL ); - result->ChangeFlag(wxPG_PROP_READONLY, true); - - /*wxPGProperty* parent = new wxPGProperty( name, wxPG_LABEL ); - parent->SetValueFromString( prop->GetValueAsString(), wxPG_FULL_VALUE ); - //wxPGProperty* parent = new wxStringProperty( name, wxPG_LABEL, wxT("") ); - //parent->SetValueFromString( prop->GetValueAsString() ); - - PPropertyInfo prop_desc = prop->GetPropertyInfo(); - std::list< PropertyChild >* children = prop_desc->GetChildren(); - std::list< PropertyChild >::iterator it; - for ( it = children->begin(); it != children->end(); ++it ) - { - wxPGProperty* child = new wxStringProperty( it->m_name, wxPG_LABEL, wxEmptyString ); - parent->AppendChild( child ); - m_pg->SetPropertyHelpString( child, it->m_description ); - } - - result = parent;*/ - } - else // Unknown property - { - result = new wxStringProperty( name, wxPG_LABEL, prop->GetValueAsString() ); - result->SetAttribute( wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING, vTrue ); - wxLogError(_("Property type Unknown") ); - } - - return result; + wxPGProperty* result = NULL; + PropertyType type = prop->GetType(); + wxString name = prop->GetName(); + wxVariant vTrue = wxVariant(true, wxT("true")); + + if (type == PT_MACRO) { + result = new wxStringProperty(name, wxPG_LABEL, prop->GetValueAsString()); + } else if (type == PT_INT) { + result = new wxIntProperty(name, wxPG_LABEL, prop->GetValueAsInteger()); + } else if (type == PT_UINT) { + result = new wxUIntProperty(name, wxPG_LABEL, (unsigned)prop->GetValueAsInteger()); + } else if (type == PT_WXSTRING || type == PT_WXSTRING_I18N) { + result = new wxLongStringProperty(name, wxPG_LABEL, prop->GetValueAsText()); + } else if (type == PT_TEXT) { + result = new wxLongStringProperty(name, wxPG_LABEL, prop->GetValueAsText()); + } else if (type == PT_BOOL) { + result = new wxBoolProperty(name, wxPG_LABEL, prop->GetValue() == wxT("1")); + } else if (type == PT_BITLIST) { + PPropertyInfo prop_desc = prop->GetPropertyInfo(); + POptionList opt_list = prop_desc->GetOptionList(); + + assert(opt_list && opt_list->GetOptionCount() > 0); + + wxPGChoices constants; + const std::map options = opt_list->GetOptions(); + std::map::const_iterator it; + unsigned int index = 0; + for (it = options.begin(); it != options.end(); ++it) { constants.Add(it->first, 1 << index++); } + + int val = StringToBits(prop->GetValueAsString(), constants); + result = new wxFlagsProperty(name, wxPG_LABEL, constants, val); + + // Workaround to set the help strings for individual members of a wxFlagsProperty + wxFlagsProperty* flagsProp = dynamic_cast(result); + if (NULL != flagsProp) { + for (size_t i = 0; i < flagsProp->GetItemCount(); i++) { + wxPGProperty* itemProp = flagsProp->Item(i); + std::map::const_iterator option = options.find(itemProp->GetLabel()); + if (option != options.end()) { + m_pg->SetPropertyHelpString(itemProp, option->second); + } + } + } + } else if (type == PT_INTLIST || type == PT_UINTLIST || type == PT_INTPAIRLIST || type == PT_UINTPAIRLIST) { + result = new wxStringProperty( + name, wxPG_LABEL, + IntList(prop->GetValueAsString(), type == PT_UINTLIST, (PT_INTPAIRLIST == type || PT_UINTPAIRLIST == type)) + .ToString(true)); + } else if (type == PT_OPTION || type == PT_EDIT_OPTION) { + PPropertyInfo prop_desc = prop->GetPropertyInfo(); + POptionList opt_list = prop_desc->GetOptionList(); + + assert(opt_list && opt_list->GetOptionCount() > 0); + + wxString value = prop->GetValueAsString(); + wxString help; + + wxPGChoices constants; + const std::map options = opt_list->GetOptions(); + std::map::const_iterator it; + unsigned int i = 0; + for (it = options.begin(); it != options.end(); ++it) { + constants.Add(it->first, i++); + if (it->first == value) { + // Save help + help = it->second; + } + } + + if (type == PT_EDIT_OPTION) { + result = new wxEditEnumProperty(name, wxPG_LABEL, constants); + } else { + result = new wxEnumProperty(name, wxPG_LABEL, constants); + } + result->SetValueFromString(value, 0); + wxString desc = prop_desc->GetDescription(); + if (desc.empty()) { + desc = value + wxT(":\n") + help; + } else { + desc += wxT("\n\n") + value + wxT(":\n") + help; + } + result->SetHelpString(wxGetTranslation(desc)); + + } else if (type == PT_WXPOINT) { + result = new wxFBPointProperty(name, wxPG_LABEL, prop->GetValueAsPoint()); + } else if (type == PT_WXSIZE) { + result = new wxFBSizeProperty(name, wxPG_LABEL, prop->GetValueAsSize()); + } else if (type == PT_WXFONT) { + result = new wxFBFontProperty(name, wxPG_LABEL, TypeConv::StringToFont(prop->GetValueAsString())); + } else if (type == PT_WXCOLOUR) { + wxString value = prop->GetValueAsString(); + if (value.empty()) // Default Colour + { + wxColourPropertyValue colProp; + colProp.m_type = wxSYS_COLOUR_WINDOW; + colProp.m_colour = TypeConv::StringToSystemColour(wxT("wxSYS_COLOUR_WINDOW")); + result = new wxSystemColourProperty(name, wxPG_LABEL, colProp); + } else { + if (value.find_first_of(wxT("wx")) == 0) { + wxColourPropertyValue def; // System Colour + def.m_type = TypeConv::StringToSystemColour(value); + result = new wxSystemColourProperty(name, wxPG_LABEL, def); + } else { + result = new wxSystemColourProperty(name, wxPG_LABEL, prop->GetValueAsColour()); + } + } + } else if (type == PT_PATH) { + result = new wxDirProperty(name, wxPG_LABEL, prop->GetValueAsString()); + } else if (type == PT_FILE) { + result = new wxFileProperty(name, wxPG_LABEL, prop->GetValueAsString()); + } else if (type == PT_BITMAP) { + wxLogDebug(wxT("OI::GetProperty: prop:%s"), prop->GetValueAsString()); + + result = new wxFBBitmapProperty(name, wxPG_LABEL, prop->GetValueAsString()); + } else if (type == PT_STRINGLIST) { + result = new wxArrayStringProperty(name, wxPG_LABEL, prop->GetValueAsArrayString()); + wxVariant v("\""); + result->DoSetAttribute(wxPG_ARRAY_DELIMITER, v); + } else if (type == PT_FLOAT) { + result = new wxFloatProperty(name, wxPG_LABEL, prop->GetValueAsFloat()); + } else if (type == PT_PARENT) { + result = new wxStringProperty(name, wxPG_LABEL); + result->ChangeFlag(wxPG_PROP_READONLY, true); + + /*wxPGProperty* parent = new wxPGProperty( name, wxPG_LABEL ); + parent->SetValueFromString( prop->GetValueAsString(), wxPG_FULL_VALUE ); + //wxPGProperty* parent = new wxStringProperty( name, wxPG_LABEL, wxT("") ); + //parent->SetValueFromString( prop->GetValueAsString() ); + + PPropertyInfo prop_desc = prop->GetPropertyInfo(); + std::list< PropertyChild >* children = prop_desc->GetChildren(); + std::list< PropertyChild >::iterator it; + for ( it = children->begin(); it != children->end(); ++it ) + { + wxPGProperty* child = new wxStringProperty( it->m_name, wxPG_LABEL, wxEmptyString ); + parent->AppendChild( child ); + m_pg->SetPropertyHelpString( child, it->m_description ); + } + + result = parent;*/ + } else // Unknown property + { + result = new wxStringProperty(name, wxPG_LABEL, prop->GetValueAsString()); + result->SetAttribute(wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING, vTrue); + wxLogError(_("Property type Unknown")); + } + + return result; } -void ObjectInspector::AddItems( const wxString& name, PObjectBase obj, - PObjectInfo obj_info, PPropertyCategory category, PropertyMap &properties ) +void ObjectInspector::AddItems( + const wxString& name, PObjectBase obj, PObjectInfo obj_info, PPropertyCategory category, PropertyMap& properties) { - size_t propCount = category->GetPropertyCount(); - for ( size_t i = 0; i < propCount; i++ ) - { - wxString propName = category->GetPropertyName( i ); - PProperty prop = obj->GetProperty( propName ); - - if ( !prop ) - continue; - - PPropertyInfo propInfo = prop->GetPropertyInfo(); - - // we do not want to duplicate inherited properties - if ( properties.find( propName ) == properties.end() ) - { - wxPGProperty* id = m_pg->Append( GetProperty( prop ) ); - int propType = prop->GetType(); - - if ( propType != PT_OPTION ) - { - m_pg->SetPropertyHelpString( id, propInfo->GetDescription() ); - - if ( propType == PT_BITMAP ) - { - wxFBBitmapProperty *bp = wxDynamicCast( id, wxFBBitmapProperty ); - if ( bp ) - { - bp->CreateChildren(); - - // perform delayed child properties update - wxCommandEvent e( wxEVT_FB_PROP_BITMAP_CHANGED ); - e.SetString( bp->GetName() + wxT(":") + prop->GetValue() ); - GetEventHandler()->AddPendingEvent( e ); - - //AppData()->ModifyProperty( prop, bp->GetValueAsString() ); - } - } - else if( propType == PT_PARENT ) - { - PPropertyInfo prop_desc = prop->GetPropertyInfo(); - std::list< PropertyChild >* children = prop_desc->GetChildren(); - std::list< PropertyChild >::iterator it; - wxArrayString values = wxStringTokenize( prop->GetValueAsString(), wxT(";"), wxTOKEN_RET_EMPTY_ALL ); - size_t index = 0; - wxString value; - - for ( it = children->begin(); it != children->end(); ++it ) - { - if (values.GetCount() > index) value = values[index++].Trim().Trim(false); - else value = wxT(""); - - wxPGProperty* child = nullptr; - if( PT_BOOL == it->m_type ) - { - // Because the format of a composed wxPGProperty value is stored this needs to be converted - // true == "" - // false == "Not " - // TODO: The subclass property is currently the only one using this child type, - // because the only instance using this property, the c++ code generator, - // interprets a missing value as true and currently no project file update - // adds this value if it is missing, here a missing value also needs to be - // interpreted as true - child = new wxBoolProperty(it->m_name, wxPG_LABEL, value.empty() || value == it->m_name); - } - else if( PT_WXSTRING == it->m_type ) - { - child = new wxStringProperty( it->m_name, wxPG_LABEL, value ); - } - else - { - THROW_WXFBEX( wxT("Invalid Child Property Type: ") << it->m_type ); - } - - id->AppendChild( child ); - m_pg->SetPropertyHelpString( child, it->m_description ); - } - } - } - - wxString customEditor = propInfo->GetCustomEditor(); - if ( !customEditor.empty() ) - { - wxPGEditor* editor = m_pg->GetEditorByName( customEditor ); - if ( editor ) - { - m_pg->SetPropertyEditor( id, editor ); - } - } - - if (m_style != wxFB_OI_MULTIPAGE_STYLE) - { - // Most common classes will be showed with a slightly different colour. - if (!AppData()->IsDarkMode()) - { - if (name == wxT("wxWindow")) - m_pg->SetPropertyBackgroundColour(id,wxColour(255,255,205)); // yellow - else if (name == wxT("AUI")) - m_pg->SetPropertyBackgroundColour(id,wxColour(240,240,255)); // light blue - else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) - m_pg->SetPropertyBackgroundColour(id,wxColour(220,255,255)); // cyan - } - else - { - if (name == wxT("wxWindow")) - m_pg->SetPropertyBackgroundColour(id,wxColour(127,127,51)); // dark yellow - else if (name == wxT("AUI")) - m_pg->SetPropertyBackgroundColour(id,wxColour(76,76,153)); // dark blue - else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) - m_pg->SetPropertyBackgroundColour(id,wxColour(51,127,127)); // dark cyan - } - } - - ExpandMap::iterator it = m_isExpanded.find( propName ); - if ( it != m_isExpanded.end() ) - { - if ( it->second ) - { - m_pg->Expand( id ); - } - else - { - m_pg->Collapse( id ); - } - } - - properties.insert( PropertyMap::value_type( propName, prop ) ); - m_propMap.insert( ObjInspectorPropertyMap::value_type( id, prop ) ); - } - } - - size_t catCount = category->GetCategoryCount(); - for ( size_t i = 0; i < catCount; i++ ) - { - PPropertyCategory nextCat = category->GetCategory( i ); - if ( 0 == nextCat->GetCategoryCount() && 0 == nextCat->GetPropertyCount() ) - { - continue; - } - wxPGProperty* catId = m_pg->AppendIn( category->GetName() , new wxPropertyCategory( nextCat->GetName() ) ); - - AddItems( name, obj, obj_info, nextCat, properties ); - - ExpandMap::iterator it = m_isExpanded.find( nextCat->GetName() ); - if ( it != m_isExpanded.end() ) - { - if ( it->second ) - { - m_pg->Expand( catId ); - } - else - { - m_pg->Collapse( catId ); - } - } - } + size_t propCount = category->GetPropertyCount(); + for (size_t i = 0; i < propCount; i++) { + wxString propName = category->GetPropertyName(i); + PProperty prop = obj->GetProperty(propName); + + if (!prop) + continue; + + PPropertyInfo propInfo = prop->GetPropertyInfo(); + + // we do not want to duplicate inherited properties + if (properties.find(propName) == properties.end()) { + wxPGProperty* id = m_pg->Append(GetProperty(prop)); + int propType = prop->GetType(); + + if (propType != PT_OPTION) { + m_pg->SetPropertyHelpString(id, propInfo->GetDescription()); + + if (propType == PT_BITMAP) { + wxFBBitmapProperty* bp = wxDynamicCast(id, wxFBBitmapProperty); + if (bp) { + bp->CreateChildren(); + + // perform delayed child properties update + wxCommandEvent e(wxEVT_FB_PROP_BITMAP_CHANGED); + e.SetString(bp->GetName() + wxT(":") + prop->GetValue()); + GetEventHandler()->AddPendingEvent(e); + + // AppData()->ModifyProperty( prop, bp->GetValueAsString() ); + } + } else if (propType == PT_PARENT) { + PPropertyInfo prop_desc = prop->GetPropertyInfo(); + std::list* children = prop_desc->GetChildren(); + std::list::iterator it; + wxArrayString values = wxStringTokenize(prop->GetValueAsString(), wxT(";"), wxTOKEN_RET_EMPTY_ALL); + size_t index = 0; + wxString value; + + for (it = children->begin(); it != children->end(); ++it) { + if (values.GetCount() > index) + value = values[index++].Trim().Trim(false); + else + value = wxT(""); + + wxPGProperty* child = nullptr; + if (PT_BOOL == it->m_type) { + // Because the format of a composed wxPGProperty value is stored this needs to be converted + // true == "" + // false == "Not " + // TODO: The subclass property is currently the only one using this child type, + // because the only instance using this property, the c++ code generator, + // interprets a missing value as true and currently no project file update + // adds this value if it is missing, here a missing value also needs to be + // interpreted as true + child = new wxBoolProperty(it->m_name, wxPG_LABEL, value.empty() || value == it->m_name); + } else if (PT_WXSTRING == it->m_type) { + child = new wxStringProperty(it->m_name, wxPG_LABEL, value); + } else { + THROW_WXFBEX(wxT("Invalid Child Property Type: ") << it->m_type); + } + + id->AppendChild(child); + m_pg->SetPropertyHelpString(child, it->m_description); + } + } + } + + wxString customEditor = propInfo->GetCustomEditor(); + if (!customEditor.empty()) { + wxPGEditor* editor = m_pg->GetEditorByName(customEditor); + if (editor) { + m_pg->SetPropertyEditor(id, editor); + } + } + + if (m_style != wxFB_OI_MULTIPAGE_STYLE) { + // Most common classes will be showed with a slightly different colour. + if (!AppData()->IsDarkMode()) { + if (name == wxT("wxWindow")) + m_pg->SetPropertyBackgroundColour(id, wxColour(255, 255, 205)); // yellow + else if (name == wxT("AUI")) + m_pg->SetPropertyBackgroundColour(id, wxColour(240, 240, 255)); // light blue + else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) + m_pg->SetPropertyBackgroundColour(id, wxColour(220, 255, 255)); // cyan + } else { + if (name == wxT("wxWindow")) + m_pg->SetPropertyBackgroundColour(id, wxColour(127, 127, 51)); // dark yellow + else if (name == wxT("AUI")) + m_pg->SetPropertyBackgroundColour(id, wxColour(76, 76, 153)); // dark blue + else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) + m_pg->SetPropertyBackgroundColour(id, wxColour(51, 127, 127)); // dark cyan + } + } + + ExpandMap::iterator it = m_isExpanded.find(propName); + if (it != m_isExpanded.end()) { + if (it->second) { + m_pg->Expand(id); + } else { + m_pg->Collapse(id); + } + } + + properties.insert(PropertyMap::value_type(propName, prop)); + m_propMap.insert(ObjInspectorPropertyMap::value_type(id, prop)); + } + } + + size_t catCount = category->GetCategoryCount(); + for (size_t i = 0; i < catCount; i++) { + PPropertyCategory nextCat = category->GetCategory(i); + if (0 == nextCat->GetCategoryCount() && 0 == nextCat->GetPropertyCount()) { + continue; + } + wxPGProperty* catId = m_pg->AppendIn(category->GetName(), new wxPropertyCategory(nextCat->GetName())); + + AddItems(name, obj, obj_info, nextCat, properties); + + ExpandMap::iterator it = m_isExpanded.find(nextCat->GetName()); + if (it != m_isExpanded.end()) { + if (it->second) { + m_pg->Expand(catId); + } else { + m_pg->Collapse(catId); + } + } + } } -void ObjectInspector::AddItems( const wxString& name, PObjectBase obj, - PObjectInfo obj_info, PPropertyCategory category, EventMap &events ) +void ObjectInspector::AddItems( + const wxString& name, PObjectBase obj, PObjectInfo obj_info, PPropertyCategory category, EventMap& events) { - size_t eventCount = category->GetEventCount(); - for ( size_t i = 0; i < eventCount; i++ ) - { - wxString eventName = category->GetEventName( i ); - PEvent event = obj->GetEvent( eventName ); - - if ( !event ) - continue; - - PEventInfo eventInfo = event->GetEventInfo(); - - // We do not want to duplicate inherited events - if ( events.find( eventName ) == events.end() ) - { - wxPGProperty* pgProp = new wxStringProperty( eventInfo->GetName(), wxPG_LABEL, event->GetValue() ); - wxPGProperty* id = m_eg->Append( pgProp ); - - m_eg->SetPropertyHelpString( id, wxGetTranslation( eventInfo->GetDescription() ) ); - - if (m_style != wxFB_OI_MULTIPAGE_STYLE) - { - // Most common classes will be showed with a slightly different colour. - if (!AppData()->IsDarkMode()) - { - if (name == wxT("wxWindow")) - m_pg->SetPropertyBackgroundColour(id,wxColour(255,255,205)); // yellow - else if (name == wxT("AUI")) - m_pg->SetPropertyBackgroundColour(id,wxColour(240,240,255)); // light blue - else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) - m_pg->SetPropertyBackgroundColour(id,wxColour(220,255,255)); // cyan - } - else - { - if (name == wxT("wxWindow")) - m_pg->SetPropertyBackgroundColour(id,wxColour(127,127,51)); // dark yellow - else if (name == wxT("AUI")) - m_pg->SetPropertyBackgroundColour(id,wxColour(76,76,153)); // dark blue - else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) - m_pg->SetPropertyBackgroundColour(id,wxColour(51,127,127)); // dark cyan - } - } - - ExpandMap::iterator it = m_isExpanded.find(eventName); - if ( it != m_isExpanded.end() ) - { - if ( it->second ) - { - m_eg->Expand( id ); - } - else - { - m_eg->Collapse( id ); - } - } - - events.insert( EventMap::value_type( eventName, event ) ); - m_eventMap.insert( ObjInspectorEventMap::value_type( id, event ) ); - } - } - - size_t catCount = category->GetCategoryCount(); - for ( size_t i = 0; i < catCount; i++ ) - { - PPropertyCategory nextCat = category->GetCategory( i ); - if ( 0 == nextCat->GetCategoryCount() && 0 == nextCat->GetEventCount() ) - { - continue; - } - wxPGProperty* catId = m_eg->AppendIn( category->GetName(), new wxPropertyCategory( nextCat->GetName() ) ); - - AddItems( name, obj, obj_info, nextCat, events ); - - ExpandMap::iterator it = m_isExpanded.find( nextCat->GetName() ); - if ( it != m_isExpanded.end() ) - { - if ( it->second ) - { - m_eg->Expand( catId ); - } - else - { - m_eg->Collapse( catId ); - } - } - } + size_t eventCount = category->GetEventCount(); + for (size_t i = 0; i < eventCount; i++) { + wxString eventName = category->GetEventName(i); + PEvent event = obj->GetEvent(eventName); + + if (!event) + continue; + + PEventInfo eventInfo = event->GetEventInfo(); + + // We do not want to duplicate inherited events + if (events.find(eventName) == events.end()) { + wxPGProperty* pgProp = new wxStringProperty(eventInfo->GetName(), wxPG_LABEL, event->GetValue()); + wxPGProperty* id = m_eg->Append(pgProp); + + m_eg->SetPropertyHelpString(id, wxGetTranslation(eventInfo->GetDescription())); + + if (m_style != wxFB_OI_MULTIPAGE_STYLE) { + // Most common classes will be showed with a slightly different colour. + if (!AppData()->IsDarkMode()) { + if (name == wxT("wxWindow")) + m_pg->SetPropertyBackgroundColour(id, wxColour(255, 255, 205)); // yellow + else if (name == wxT("AUI")) + m_pg->SetPropertyBackgroundColour(id, wxColour(240, 240, 255)); // light blue + else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) + m_pg->SetPropertyBackgroundColour(id, wxColour(220, 255, 255)); // cyan + } else { + if (name == wxT("wxWindow")) + m_pg->SetPropertyBackgroundColour(id, wxColour(127, 127, 51)); // dark yellow + else if (name == wxT("AUI")) + m_pg->SetPropertyBackgroundColour(id, wxColour(76, 76, 153)); // dark blue + else if (name == wxT("sizeritem") || name == wxT("gbsizeritem") || name == wxT("sizeritembase")) + m_pg->SetPropertyBackgroundColour(id, wxColour(51, 127, 127)); // dark cyan + } + } + + ExpandMap::iterator it = m_isExpanded.find(eventName); + if (it != m_isExpanded.end()) { + if (it->second) { + m_eg->Expand(id); + } else { + m_eg->Collapse(id); + } + } + + events.insert(EventMap::value_type(eventName, event)); + m_eventMap.insert(ObjInspectorEventMap::value_type(id, event)); + } + } + + size_t catCount = category->GetCategoryCount(); + for (size_t i = 0; i < catCount; i++) { + PPropertyCategory nextCat = category->GetCategory(i); + if (0 == nextCat->GetCategoryCount() && 0 == nextCat->GetEventCount()) { + continue; + } + wxPGProperty* catId = m_eg->AppendIn(category->GetName(), new wxPropertyCategory(nextCat->GetName())); + + AddItems(name, obj, obj_info, nextCat, events); + + ExpandMap::iterator it = m_isExpanded.find(nextCat->GetName()); + if (it != m_isExpanded.end()) { + if (it->second) { + m_eg->Expand(catId); + } else { + m_eg->Collapse(catId); + } + } + } } -void ObjectInspector::OnPropertyGridChanging( wxPropertyGridEvent& event ) +void ObjectInspector::OnPropertyGridChanging(wxPropertyGridEvent& event) { - wxImageFileProperty *imgFileProp = wxDynamicCast( event.GetProperty(), wxImageFileProperty ); - - if ( imgFileProp ) - { - // GetValue() returns the pending value, but is only supported by wxEVT_PG_CHANGING. - wxFBBitmapProperty *bmpProp = wxDynamicCast( imgFileProp->GetParent(), wxFBBitmapProperty ); - - if ( bmpProp ) - { - wxString img = bmpProp->SetupImage( event.GetValue().GetString() ); - if ( img == wxEmptyString ) - { - event.Veto(); - return; - } - } - } + wxImageFileProperty* imgFileProp = wxDynamicCast(event.GetProperty(), wxImageFileProperty); + + if (imgFileProp) { + // GetValue() returns the pending value, but is only supported by wxEVT_PG_CHANGING. + wxFBBitmapProperty* bmpProp = wxDynamicCast(imgFileProp->GetParent(), wxFBBitmapProperty); + + if (bmpProp) { + wxString img = bmpProp->SetupImage(event.GetValue().GetString()); + if (img == wxEmptyString) { + event.Veto(); + return; + } + } + } } -void ObjectInspector::OnPropertyGridChanged( wxPropertyGridEvent& event ) +void ObjectInspector::OnPropertyGridChanged(wxPropertyGridEvent& event) { - wxPGProperty* propPtr = event.GetProperty(); - - ObjInspectorPropertyMap::iterator it = m_propMap.find( propPtr ); - - if ( m_propMap.end() == it ) - { - // Could be a child property - propPtr = propPtr->GetParent(); - it = m_propMap.find( propPtr ); - } - if ( it != m_propMap.end() ) - { - PProperty prop = it->second; - switch ( prop->GetType() ) - { - - case PT_FLOAT: - { - // Use typeconv to properly handle locale - double val = m_pg->GetPropertyValueAsDouble( propPtr ); - ModifyProperty( prop, TypeConv::FloatToString( val ) ); - break; - } - case PT_TEXT: - { - // The used wxPropertyGrid component does (undocumented?) escape certain control characters, - // especially \n, which is not desired for this type, its value should be preserved as is. - // TypeConv::TextToString() reverses exactly the same escape sequences. - auto rawValue = TypeConv::TextToString(m_pg->GetPropertyValueAsString(propPtr)); - ModifyProperty(prop, rawValue); - break; - } - case PT_MACRO: - case PT_INT: - case PT_UINT: - { - ModifyProperty( prop, m_pg->GetPropertyValueAsString( propPtr ) ); - break; - } - case PT_OPTION: - case PT_EDIT_OPTION: - { - wxString value = m_pg->GetPropertyValueAsString( propPtr ); - ModifyProperty( prop, value ); - - // Update displayed description for the new selection - PPropertyInfo prop_desc = prop->GetPropertyInfo(); - POptionList opt_list = prop_desc->GetOptionList(); - - wxString helpString = prop_desc->GetDescription(); - if ( opt_list && opt_list->GetOptionCount() > 0 ) - { - const std::map< wxString, wxString > options = opt_list->GetOptions(); - std::map< wxString, wxString >::const_iterator option = options.find( value ); - if ( option != options.end() ) - { - if ( helpString.empty() ) - { - helpString = value + wxT(":\n") + option->second; - } - else - { - helpString += wxT("\n\n") + value + wxT(":\n") + option->second; - } - } - } - wxString localized = wxGetTranslation( helpString ); - m_pg->SetPropertyHelpString( propPtr, localized ); - m_pg->SetDescription( propPtr->GetLabel(), localized ); - break; - } - case PT_PARENT: - { - // GenerateComposedValue() is the only method that does actually return a value, - // although the documentation claims the other methods just call this one, - // they return an empty value - const auto value = propPtr->GenerateComposedValue(); - ModifyProperty(prop, value); - break; - } - case PT_WXSTRING: - case PT_WXSTRING_I18N: - { - // ObjectInspector's text strings are formatted. - wxString value = TypeConv::TextToString( m_pg->GetPropertyValueAsString( propPtr ) ); - ModifyProperty( prop, value ); - break; - } - case PT_BOOL: - { - if( prop->GetName() == wxT("aui_managed") ) - { - PObjectBase propobj = prop->GetObject(); - if( propobj->GetChildCount() ) - { - wxMessageBox(_("You have to remove all child widgets first.")); - m_pg->SetPropertyValue( propPtr, !m_pg->GetPropertyValueAsBool( propPtr ) ); - } - else - ModifyProperty( prop, m_pg->GetPropertyValueAsBool( propPtr ) ? wxT("1") : wxT("0") ); - } - else - ModifyProperty( prop, m_pg->GetPropertyValueAsBool( propPtr ) ? wxT("1") : wxT("0") ); - break; - } - case PT_BITLIST: - { - wxString aux = m_pg->GetPropertyValueAsString( propPtr ); - aux.Replace( wxT(" "), wxT("") ); - aux.Replace( wxT(","), wxT("|") ); - ModifyProperty( prop, aux ); - break; - } - case PT_WXPOINT: - { - wxPoint point = wxPointRefFromVariant( event.GetPropertyValue () ); - ModifyProperty( prop, wxString::Format( wxT("%i,%i"), point.x, point.y ) ); - break; - } - case PT_WXSIZE: - { - wxSize size = wxSizeRefFromVariant( event.GetPropertyValue() ); - ModifyProperty( prop, wxString::Format( wxT("%i,%i"), size.GetWidth(), size.GetHeight() ) ); - break; - } - case PT_WXFONT: - { - ModifyProperty( prop, event.GetPropertyValue().GetString() ); - break; - } - case PT_WXCOLOUR: - { - wxColourPropertyValue colour; - colour << event.GetPropertyValue(); - switch ( colour.m_type ) { - case wxSYS_COLOUR_MAX: - ModifyProperty( prop, wxT("") ); - break; - case wxPG_COLOUR_CUSTOM: - ModifyProperty( prop, TypeConv::ColourToString( colour.m_colour ) ); - break; - default: - wxString sCol = TypeConv::SystemColourToString( colour.m_type ); - ModifyProperty( prop, sCol ); - } - break; - } - case PT_INTLIST: - case PT_UINTLIST: - case PT_INTPAIRLIST: - case PT_UINTPAIRLIST: - { - IntList il(event.GetPropertyValue(), PT_UINTLIST == prop->GetType(), (PT_INTPAIRLIST == prop->GetType() || PT_UINTPAIRLIST == prop->GetType())); - ModifyProperty(prop, il.ToString(true)); - break; - } - case PT_BITMAP: - { - wxVariant childValue = event.GetProperty()->GetValue(); - - // Also, handle the case where property value is unspecified - if ( childValue.IsNull() ) - return; - - // bp->GetValue() have no updated value... - wxString bmpVal = propPtr->GetValueAsString( wxPG_FULL_VALUE ); - - // Handle changes in values, as needed - wxVariant thisValue = WXVARIANT(bmpVal); - - wxVariant newVal = - propPtr->ChildChanged( thisValue, (int)event.GetProperty()->GetIndexInParent(), childValue ); - - ModifyProperty( prop, newVal.GetString() ); - - if( event.GetProperty()->GetIndexInParent() > 0 ) - { - // perform delayed child properties update - wxCommandEvent e( wxEVT_FB_PROP_BITMAP_CHANGED ); - e.SetString( propPtr->GetName() + wxT(":") + bmpVal ); - GetEventHandler()->AddPendingEvent( e ); - } - - break; - } - - default: - //ModifyProperty( prop, event.GetPropertyValue() ); - ModifyProperty( prop, propPtr->GetValueAsString() ); - } - } + wxPGProperty* propPtr = event.GetProperty(); + + ObjInspectorPropertyMap::iterator it = m_propMap.find(propPtr); + + if (m_propMap.end() == it) { + // Could be a child property + propPtr = propPtr->GetParent(); + it = m_propMap.find(propPtr); + } + if (it != m_propMap.end()) { + PProperty prop = it->second; + switch (prop->GetType()) { + + case PT_FLOAT: { + // Use typeconv to properly handle locale + double val = m_pg->GetPropertyValueAsDouble(propPtr); + ModifyProperty(prop, TypeConv::FloatToString(val)); + break; + } + case PT_TEXT: { + // The used wxPropertyGrid component does (undocumented?) escape certain control characters, + // especially \n, which is not desired for this type, its value should be preserved as is. + // TypeConv::TextToString() reverses exactly the same escape sequences. + auto rawValue = TypeConv::TextToString(m_pg->GetPropertyValueAsString(propPtr)); + ModifyProperty(prop, rawValue); + break; + } + case PT_MACRO: + case PT_INT: + case PT_UINT: { + ModifyProperty(prop, m_pg->GetPropertyValueAsString(propPtr)); + break; + } + case PT_OPTION: + case PT_EDIT_OPTION: { + wxString value = m_pg->GetPropertyValueAsString(propPtr); + ModifyProperty(prop, value); + + // Update displayed description for the new selection + PPropertyInfo prop_desc = prop->GetPropertyInfo(); + POptionList opt_list = prop_desc->GetOptionList(); + + wxString helpString = prop_desc->GetDescription(); + if (opt_list && opt_list->GetOptionCount() > 0) { + const std::map options = opt_list->GetOptions(); + std::map::const_iterator option = options.find(value); + if (option != options.end()) { + if (helpString.empty()) { + helpString = value + wxT(":\n") + option->second; + } else { + helpString += wxT("\n\n") + value + wxT(":\n") + option->second; + } + } + } + wxString localized = wxGetTranslation(helpString); + m_pg->SetPropertyHelpString(propPtr, localized); + m_pg->SetDescription(propPtr->GetLabel(), localized); + break; + } + case PT_PARENT: { + // GenerateComposedValue() is the only method that does actually return a value, + // although the documentation claims the other methods just call this one, + // they return an empty value + const auto value = propPtr->GenerateComposedValue(); + ModifyProperty(prop, value); + break; + } + case PT_WXSTRING: + case PT_WXSTRING_I18N: { + // ObjectInspector's text strings are formatted. + wxString value = TypeConv::TextToString(m_pg->GetPropertyValueAsString(propPtr)); + ModifyProperty(prop, value); + break; + } + case PT_BOOL: { + if (prop->GetName() == wxT("aui_managed")) { + PObjectBase propobj = prop->GetObject(); + if (propobj->GetChildCount()) { + wxMessageBox(_("You have to remove all child widgets first.")); + m_pg->SetPropertyValue(propPtr, !m_pg->GetPropertyValueAsBool(propPtr)); + } else + ModifyProperty(prop, m_pg->GetPropertyValueAsBool(propPtr) ? wxT("1") : wxT("0")); + } else + ModifyProperty(prop, m_pg->GetPropertyValueAsBool(propPtr) ? wxT("1") : wxT("0")); + break; + } + case PT_BITLIST: { + wxString aux = m_pg->GetPropertyValueAsString(propPtr); + aux.Replace(wxT(" "), wxT("")); + aux.Replace(wxT(","), wxT("|")); + ModifyProperty(prop, aux); + break; + } + case PT_WXPOINT: { + wxPoint point = wxPointRefFromVariant(event.GetPropertyValue()); + ModifyProperty(prop, wxString::Format(wxT("%i,%i"), point.x, point.y)); + break; + } + case PT_WXSIZE: { + wxSize size = wxSizeRefFromVariant(event.GetPropertyValue()); + ModifyProperty(prop, wxString::Format(wxT("%i,%i"), size.GetWidth(), size.GetHeight())); + break; + } + case PT_WXFONT: { + ModifyProperty(prop, event.GetPropertyValue().GetString()); + break; + } + case PT_WXCOLOUR: { + wxColourPropertyValue colour; + colour << event.GetPropertyValue(); + switch (colour.m_type) { + case wxSYS_COLOUR_MAX: + ModifyProperty(prop, wxT("")); + break; + case wxPG_COLOUR_CUSTOM: + ModifyProperty(prop, TypeConv::ColourToString(colour.m_colour)); + break; + default: + wxString sCol = TypeConv::SystemColourToString(colour.m_type); + ModifyProperty(prop, sCol); + } + break; + } + case PT_INTLIST: + case PT_UINTLIST: + case PT_INTPAIRLIST: + case PT_UINTPAIRLIST: { + IntList il( + event.GetPropertyValue(), PT_UINTLIST == prop->GetType(), + (PT_INTPAIRLIST == prop->GetType() || PT_UINTPAIRLIST == prop->GetType())); + ModifyProperty(prop, il.ToString(true)); + break; + } + case PT_BITMAP: { + wxVariant childValue = event.GetProperty()->GetValue(); + + // Also, handle the case where property value is unspecified + if (childValue.IsNull()) + return; + + // bp->GetValue() have no updated value... + wxString bmpVal = propPtr->GetValueAsString(wxPG_FULL_VALUE); + + // Handle changes in values, as needed + wxVariant thisValue = WXVARIANT(bmpVal); + + wxVariant newVal = + propPtr->ChildChanged(thisValue, (int)event.GetProperty()->GetIndexInParent(), childValue); + + ModifyProperty(prop, newVal.GetString()); + + if (event.GetProperty()->GetIndexInParent() > 0) { + // perform delayed child properties update + wxCommandEvent e(wxEVT_FB_PROP_BITMAP_CHANGED); + e.SetString(propPtr->GetName() + wxT(":") + bmpVal); + GetEventHandler()->AddPendingEvent(e); + } + + break; + } + + default: + // ModifyProperty( prop, event.GetPropertyValue() ); + ModifyProperty(prop, propPtr->GetValueAsString()); + } + } } -void ObjectInspector::OnEventGridChanged( wxPropertyGridEvent& event ) +void ObjectInspector::OnEventGridChanged(wxPropertyGridEvent& event) { - ObjInspectorEventMap::iterator it = m_eventMap.find( event.GetProperty() ); - - if ( it != m_eventMap.end() ) - { - PEvent evt = it->second; - wxString handler = event.GetPropertyValue(); - handler.Trim(); - handler.Trim( false ); - AppData()->ModifyEventHandler( evt, handler ); - } + ObjInspectorEventMap::iterator it = m_eventMap.find(event.GetProperty()); + + if (it != m_eventMap.end()) { + PEvent evt = it->second; + wxString handler = event.GetPropertyValue(); + handler.Trim(); + handler.Trim(false); + AppData()->ModifyEventHandler(evt, handler); + } } -void ObjectInspector::OnPropertyGridExpand( wxPropertyGridEvent& event ) +void ObjectInspector::OnPropertyGridExpand(wxPropertyGridEvent& event) { - m_isExpanded[event.GetPropertyName()] = event.GetProperty()->IsExpanded(); - - wxPGProperty* egProp = m_eg->GetProperty( event.GetProperty()->GetName() ); - if ( egProp ) - { - if ( event.GetProperty()->IsExpanded() ) - { - m_eg->Expand( egProp ); - } - else - { - m_eg->Collapse( egProp ); - } - } + m_isExpanded[event.GetPropertyName()] = event.GetProperty()->IsExpanded(); + + wxPGProperty* egProp = m_eg->GetProperty(event.GetProperty()->GetName()); + if (egProp) { + if (event.GetProperty()->IsExpanded()) { + m_eg->Expand(egProp); + } else { + m_eg->Collapse(egProp); + } + } } -void ObjectInspector::OnEventGridExpand( wxPropertyGridEvent& event ) +void ObjectInspector::OnEventGridExpand(wxPropertyGridEvent& event) { - m_isExpanded[event.GetPropertyName()] = event.GetProperty()->IsExpanded(); - - wxPGProperty* pgProp = m_pg->GetProperty( event.GetProperty()->GetName() ); - if ( pgProp ) - { - if ( event.GetProperty()->IsExpanded() ) - { - m_pg->Expand( pgProp ); - } - else - { - m_pg->Collapse( pgProp ); - } - } + m_isExpanded[event.GetPropertyName()] = event.GetProperty()->IsExpanded(); + + wxPGProperty* pgProp = m_pg->GetProperty(event.GetProperty()->GetName()); + if (pgProp) { + if (event.GetProperty()->IsExpanded()) { + m_pg->Expand(pgProp); + } else { + m_pg->Collapse(pgProp); + } + } } /////////////////////////////////////////////////////////////////////////////// -void ObjectInspector::OnObjectSelected( wxFBObjectEvent& event) +void ObjectInspector::OnObjectSelected(wxFBObjectEvent& event) { - bool isForced = ( event.GetString() == wxT("force") ); + bool isForced = (event.GetString() == wxT("force")); - Create( isForced ); + Create(isForced); } -void ObjectInspector::OnProjectRefresh( wxFBEvent& ) +void ObjectInspector::OnProjectRefresh(wxFBEvent&) { - Create( true ); + Create(true); } -void ObjectInspector::OnEventHandlerModified( wxFBEventHandlerEvent& event ) +void ObjectInspector::OnEventHandlerModified(wxFBEventHandlerEvent& event) { - PEvent e = event.GetFBEventHandler(); - m_eg->SetPropertyValue( e->GetName(), e->GetValue() ); - m_eg->Refresh(); + PEvent e = event.GetFBEventHandler(); + m_eg->SetPropertyValue(e->GetName(), e->GetValue()); + m_eg->Refresh(); } -void ObjectInspector::OnPropertyModified( wxFBPropertyEvent& event ) +void ObjectInspector::OnPropertyModified(wxFBPropertyEvent& event) { - LogDebug(""); - PProperty prop = event.GetFBProperty(); - - PObjectBase propobj = prop->GetObject(); - PObjectBase appobj = AppData()->GetSelectedObject(); - - bool shouldContinue = ( prop->GetObject() == AppData()->GetSelectedObject() ); - if ( !shouldContinue ) - { - // Item objects cannot be selected - their children are selected instead - if ( propobj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - if ( propobj->GetChildCount() > 0 ) - { - shouldContinue = ( appobj == propobj->GetChild( 0 ) ); - } - } - } - if ( !shouldContinue ) - { - return; - } - - wxPGProperty* pgProp = m_pg->GetPropertyByLabel(prop->GetName() ); - if ( pgProp == NULL ) return; // Maybe now isn't showing this page - - - switch (prop->GetType()) - { - case PT_FLOAT: - { - // Use float instead of string -> typeconv handles locale - pgProp->SetValue( WXVARIANT( prop->GetValueAsFloat() ) ); - break; - } - case PT_INT: - case PT_UINT: - { - pgProp->SetValueFromString(prop->GetValueAsString(), 0); - break; - } - case PT_TEXT: - pgProp->SetValueFromString(prop->GetValueAsText(), 0); - break; - case PT_MACRO: - case PT_OPTION: - case PT_EDIT_OPTION: - case PT_PARENT: - case PT_WXSTRING: - pgProp->SetValueFromString(prop->GetValueAsText(), 0); - break; - case PT_WXSTRING_I18N: - pgProp->SetValueFromString(prop->GetValueAsText(), 0); - break; - case PT_BOOL: - pgProp->SetValueFromInt(prop->GetValueAsString() == wxT("0") ? 0 : 1, 0); - break; - case PT_BITLIST: - { - wxString aux = prop->GetValueAsString(); - aux.Replace(wxT("|"), wxT(", ")); - if (aux == wxT("0")) aux = wxT(""); - pgProp->SetValueFromString(aux, 0); - } - break; - case PT_WXPOINT: - { - //m_pg->SetPropertyValue( pgProp, prop->GetValue() ); - wxString aux = prop->GetValueAsString(); - aux.Replace(wxT(","), wxT(";")); - pgProp->SetValueFromString(aux, 0); - } - break; - case PT_WXSIZE: - { - //m_pg->SetPropertyValue( pgProp, prop->GetValue() ); - wxString aux = prop->GetValueAsString(); - aux.Replace(wxT(","), wxT(";")); - pgProp->SetValueFromString(aux, 0); - } - break; - case PT_WXFONT: - pgProp->SetValue( WXVARIANT( prop->GetValueAsString() ) ); - break; - case PT_WXCOLOUR: - { - wxString value = prop->GetValueAsString(); - if ( value.empty() ) // Default Colour - { - wxColourPropertyValue def; - def.m_type = wxSYS_COLOUR_WINDOW; - def.m_colour = TypeConv::StringToSystemColour( wxT("wxSYS_COLOUR_WINDOW") ); - m_pg->SetPropertyValue( pgProp, def ); - } - else - { - if ( value.find_first_of( wxT("wx") ) == 0 ) - { - // System Colour - wxColourPropertyValue def; - def.m_type = TypeConv::StringToSystemColour( value ); - def.m_colour = prop->GetValueAsColour(); - m_pg->SetPropertyValue( pgProp, WXVARIANT( def ) ); - } - else - { - wxColourPropertyValue def( wxPG_COLOUR_CUSTOM, prop->GetValueAsColour() ); - m_pg->SetPropertyValue( pgProp, WXVARIANT( def ) ); - } - } - } - break; - case PT_BITMAP: -// pgProp->SetValue( WXVARIANT( prop->GetValueAsString() ) ); - wxLogDebug( wxT("OI::OnPropertyModified: prop:%s"), prop->GetValueAsString() ); - break; - default: - pgProp->SetValueFromString(prop->GetValueAsString(), wxPG_FULL_VALUE); - } - AutoGenerateId(AppData()->GetSelectedObject(), event.GetFBProperty(), wxT("PropChange")); - m_pg->Refresh(); + LogDebug(""); + PProperty prop = event.GetFBProperty(); + + PObjectBase propobj = prop->GetObject(); + PObjectBase appobj = AppData()->GetSelectedObject(); + + bool shouldContinue = (prop->GetObject() == AppData()->GetSelectedObject()); + if (!shouldContinue) { + // Item objects cannot be selected - their children are selected instead + if (propobj->GetObjectInfo()->GetObjectType()->IsItem()) { + if (propobj->GetChildCount() > 0) { + shouldContinue = (appobj == propobj->GetChild(0)); + } + } + } + if (!shouldContinue) { + return; + } + + wxPGProperty* pgProp = m_pg->GetPropertyByLabel(prop->GetName()); + if (pgProp == NULL) + return; // Maybe now isn't showing this page + + + switch (prop->GetType()) { + case PT_FLOAT: { + // Use float instead of string -> typeconv handles locale + pgProp->SetValue(WXVARIANT(prop->GetValueAsFloat())); + break; + } + case PT_INT: + case PT_UINT: { + pgProp->SetValueFromString(prop->GetValueAsString(), 0); + break; + } + case PT_TEXT: + pgProp->SetValueFromString(prop->GetValueAsText(), 0); + break; + case PT_MACRO: + case PT_OPTION: + case PT_EDIT_OPTION: + case PT_PARENT: + case PT_WXSTRING: + pgProp->SetValueFromString(prop->GetValueAsText(), 0); + break; + case PT_WXSTRING_I18N: + pgProp->SetValueFromString(prop->GetValueAsText(), 0); + break; + case PT_BOOL: + pgProp->SetValueFromInt(prop->GetValueAsString() == wxT("0") ? 0 : 1, 0); + break; + case PT_BITLIST: { + wxString aux = prop->GetValueAsString(); + aux.Replace(wxT("|"), wxT(", ")); + if (aux == wxT("0")) + aux = wxT(""); + pgProp->SetValueFromString(aux, 0); + } break; + case PT_WXPOINT: { + // m_pg->SetPropertyValue( pgProp, prop->GetValue() ); + wxString aux = prop->GetValueAsString(); + aux.Replace(wxT(","), wxT(";")); + pgProp->SetValueFromString(aux, 0); + } break; + case PT_WXSIZE: { + // m_pg->SetPropertyValue( pgProp, prop->GetValue() ); + wxString aux = prop->GetValueAsString(); + aux.Replace(wxT(","), wxT(";")); + pgProp->SetValueFromString(aux, 0); + } break; + case PT_WXFONT: + pgProp->SetValue(WXVARIANT(prop->GetValueAsString())); + break; + case PT_WXCOLOUR: { + wxString value = prop->GetValueAsString(); + if (value.empty()) // Default Colour + { + wxColourPropertyValue def; + def.m_type = wxSYS_COLOUR_WINDOW; + def.m_colour = TypeConv::StringToSystemColour(wxT("wxSYS_COLOUR_WINDOW")); + m_pg->SetPropertyValue(pgProp, def); + } else { + if (value.find_first_of(wxT("wx")) == 0) { + // System Colour + wxColourPropertyValue def; + def.m_type = TypeConv::StringToSystemColour(value); + def.m_colour = prop->GetValueAsColour(); + m_pg->SetPropertyValue(pgProp, WXVARIANT(def)); + } else { + wxColourPropertyValue def(wxPG_COLOUR_CUSTOM, prop->GetValueAsColour()); + m_pg->SetPropertyValue(pgProp, WXVARIANT(def)); + } + } + } break; + case PT_BITMAP: + // pgProp->SetValue( WXVARIANT( prop->GetValueAsString() ) ); + wxLogDebug(wxT("OI::OnPropertyModified: prop:%s"), prop->GetValueAsString()); + break; + default: + pgProp->SetValueFromString(prop->GetValueAsString(), wxPG_FULL_VALUE); + } + AutoGenerateId(AppData()->GetSelectedObject(), event.GetFBProperty(), wxT("PropChange")); + m_pg->Refresh(); } -wxPropertyGridManager* ObjectInspector::CreatePropertyGridManager(wxWindow *parent, wxWindowID id) +wxPropertyGridManager* ObjectInspector::CreatePropertyGridManager(wxWindow* parent, wxWindowID id) { - int pgStyle; - int defaultDescBoxHeight; - - switch (m_style) - { - case wxFB_OI_MULTIPAGE_STYLE: - pgStyle = wxPG_BOLD_MODIFIED | wxPG_SPLITTER_AUTO_CENTER | wxPG_TOOLBAR | wxPG_DESCRIPTION | wxPGMAN_DEFAULT_STYLE; - defaultDescBoxHeight = 50; - break; - - case wxFB_OI_DEFAULT_STYLE: - case wxFB_OI_SINGLE_PAGE_STYLE: - default: - pgStyle = wxPG_BOLD_MODIFIED | wxPG_SPLITTER_AUTO_CENTER | wxPG_DESCRIPTION | wxPGMAN_DEFAULT_STYLE; - defaultDescBoxHeight = 150; - break; - } - - int descBoxHeight; - wxConfigBase* config = wxConfigBase::Get(); - config->Read( wxT( "/mainframe/objectInspector/DescBoxHeight" ), &descBoxHeight, defaultDescBoxHeight ); - if ( -1 == descBoxHeight ) - { - descBoxHeight = defaultDescBoxHeight; - } - - wxPropertyGridManager* pg; - pg = new wxPropertyGridManager( parent, id, wxDefaultPosition, wxDefaultSize, pgStyle ); - pg->SendSizeEvent(); - pg->SetDescBoxHeight( descBoxHeight ); -// pg->SetExtraStyle( wxPG_EX_NATIVE_DOUBLE_BUFFERING ); Both seems to no more needed. -// pg->SetExtraStyle( wxPG_EX_PROCESS_EVENTS_IMMEDIATELY ); - - return pg; + int pgStyle; + int defaultDescBoxHeight; + + switch (m_style) { + case wxFB_OI_MULTIPAGE_STYLE: + pgStyle = + wxPG_BOLD_MODIFIED | wxPG_SPLITTER_AUTO_CENTER | wxPG_TOOLBAR | wxPG_DESCRIPTION | wxPGMAN_DEFAULT_STYLE; + defaultDescBoxHeight = 50; + break; + + case wxFB_OI_DEFAULT_STYLE: + case wxFB_OI_SINGLE_PAGE_STYLE: + default: + pgStyle = wxPG_BOLD_MODIFIED | wxPG_SPLITTER_AUTO_CENTER | wxPG_DESCRIPTION | wxPGMAN_DEFAULT_STYLE; + defaultDescBoxHeight = 150; + break; + } + + int descBoxHeight; + wxConfigBase* config = wxConfigBase::Get(); + config->Read(wxT("/mainframe/objectInspector/DescBoxHeight"), &descBoxHeight, defaultDescBoxHeight); + if (-1 == descBoxHeight) { + descBoxHeight = defaultDescBoxHeight; + } + + wxPropertyGridManager* pg; + pg = new wxPropertyGridManager(parent, id, wxDefaultPosition, wxDefaultSize, pgStyle); + pg->SendSizeEvent(); + pg->SetDescBoxHeight(descBoxHeight); + // pg->SetExtraStyle( wxPG_EX_NATIVE_DOUBLE_BUFFERING ); Both seems to no more needed. + // pg->SetExtraStyle( wxPG_EX_PROCESS_EVENTS_IMMEDIATELY ); + + return pg; } void ObjectInspector::OnPropertyGridDblClick(wxPropertyGridEvent& event) { - PObjectBase obj = AppData()->GetSelectedObject(); - if( obj ) - { - wxString propName = event.GetProperty()->GetLabel(); - AutoGenerateId(obj, obj->GetProperty(propName), wxT("DblClk")); - m_pg->Refresh(); - } + PObjectBase obj = AppData()->GetSelectedObject(); + if (obj) { + wxString propName = event.GetProperty()->GetLabel(); + AutoGenerateId(obj, obj->GetProperty(propName), wxT("DblClk")); + m_pg->Refresh(); + } } void ObjectInspector::OnEventGridDblClick(wxPropertyGridEvent& event) { - wxPGProperty *pgProp = m_pg->GetPropertyByLabel( wxT("name") ); - if ( !pgProp ) return; - - wxPGProperty *p = event.GetProperty(); - p->SetValueFromString( pgProp->GetDisplayedString() + event.GetProperty()->GetLabel() ); - ObjInspectorEventMap::iterator it = m_eventMap.find( p ); - if ( it != m_eventMap.end() ) - { - PEvent evt = it->second; - wxString handler = p->GetValueAsString(); - handler.Trim(); - handler.Trim( false ); - AppData()->ModifyEventHandler( evt, handler ); - }; + wxPGProperty* pgProp = m_pg->GetPropertyByLabel(wxT("name")); + if (!pgProp) + return; + + wxPGProperty* p = event.GetProperty(); + p->SetValueFromString(pgProp->GetDisplayedString() + event.GetProperty()->GetLabel()); + ObjInspectorEventMap::iterator it = m_eventMap.find(p); + if (it != m_eventMap.end()) { + PEvent evt = it->second; + wxString handler = p->GetValueAsString(); + handler.Trim(); + handler.Trim(false); + AppData()->ModifyEventHandler(evt, handler); + }; } void ObjectInspector::AutoGenerateId(PObjectBase objectChanged, PProperty propChanged, wxString reason) { - if(objectChanged && propChanged) - { - PProperty prop; - if((propChanged->GetName() == wxT("name") && reason == wxT("PropChange")) || - (propChanged->GetName() == wxT("id") && reason == wxT("DblClk"))) - { - //wxPGId pgid = m_pg->GetPropertyByLabel(wxT("")); - prop = AppData()->GetProjectData()->GetProperty( wxT("event_generation") ); - if ( prop ) - { - if(prop->GetValueAsString() == wxT("table")) - { - prop = objectChanged->GetProperty(wxT("id")); - if ( prop ) - { - if(prop->GetValueAsString() == wxT("wxID_ANY") || reason == wxT("DblClk")) - { - PProperty name(objectChanged->GetProperty(wxT("name"))); - wxString idString; - idString << wxT("ID_"); - idString << name->GetValueAsString().Upper(); - ModifyProperty( prop, idString); - - wxPGProperty *pgid = m_pg->GetPropertyByLabel(wxT("id")); - if ( !pgid ) return; - m_pg->SetPropertyValue( pgid, idString ); - } - } - } - else - { - prop = objectChanged->GetProperty(wxT("id")); - if ( prop ) - { - ModifyProperty( prop, wxT("wxID_ANY")); - wxPGProperty *pgid = m_pg->GetPropertyByLabel(wxT("id")); - if ( !pgid ) return; - m_pg->SetPropertyValue( pgid, wxT("wxID_ANY") ); - } - } - } - } - } - m_pg->Update(); + if (objectChanged && propChanged) { + PProperty prop; + if ( + (propChanged->GetName() == wxT("name") && reason == wxT("PropChange")) || + (propChanged->GetName() == wxT("id") && reason == wxT("DblClk"))) { + // wxPGId pgid = m_pg->GetPropertyByLabel(wxT("")); + prop = AppData()->GetProjectData()->GetProperty(wxT("event_generation")); + if (prop) { + if (prop->GetValueAsString() == wxT("table")) { + prop = objectChanged->GetProperty(wxT("id")); + if (prop) { + if (prop->GetValueAsString() == wxT("wxID_ANY") || reason == wxT("DblClk")) { + PProperty name(objectChanged->GetProperty(wxT("name"))); + wxString idString; + idString << wxT("ID_"); + idString << name->GetValueAsString().Upper(); + ModifyProperty(prop, idString); + + wxPGProperty* pgid = m_pg->GetPropertyByLabel(wxT("id")); + if (!pgid) + return; + m_pg->SetPropertyValue(pgid, idString); + } + } + } else { + prop = objectChanged->GetProperty(wxT("id")); + if (prop) { + ModifyProperty(prop, wxT("wxID_ANY")); + wxPGProperty* pgid = m_pg->GetPropertyByLabel(wxT("id")); + if (!pgid) + return; + m_pg->SetPropertyValue(pgid, wxT("wxID_ANY")); + } + } + } + } + } + m_pg->Update(); } -void ObjectInspector::OnBitmapPropertyChanged( wxCommandEvent& event ) +void ObjectInspector::OnBitmapPropertyChanged(wxCommandEvent& event) { - wxLogDebug( wxT("OI::BitmapPropertyChanged: %s"), event.GetString() ); - - wxString propName = event.GetString().BeforeFirst( ':' ); - wxString propVal = event.GetString().AfterFirst( ':' ); - - if( !propVal.IsEmpty() ) - { - wxFBBitmapProperty *bp = wxDynamicCast( m_pg->GetPropertyByLabel( propName ), wxFBBitmapProperty ); - if( bp ) - { - bp->UpdateChildValues( propVal ); - } - } + wxLogDebug(wxT("OI::BitmapPropertyChanged: %s"), event.GetString()); + + wxString propName = event.GetString().BeforeFirst(':'); + wxString propVal = event.GetString().AfterFirst(':'); + + if (!propVal.IsEmpty()) { + wxFBBitmapProperty* bp = wxDynamicCast(m_pg->GetPropertyByLabel(propName), wxFBBitmapProperty); + if (bp) { + bp->UpdateChildValues(propVal); + } + } } -void ObjectInspector::ModifyProperty( PProperty prop, const wxString& str ) +void ObjectInspector::ModifyProperty(PProperty prop, const wxString& str) { - AppData()->RemoveHandler( this->GetEventHandler() ); - AppData()->ModifyProperty( prop, str ); - AppData()->AddHandler( this->GetEventHandler() ); + AppData()->RemoveHandler(this->GetEventHandler()); + AppData()->ModifyProperty(prop, str); + AppData()->AddHandler(this->GetEventHandler()); } -void ObjectInspector::OnChildFocus(wxChildFocusEvent&) { - // do nothing to avoid "scrollbar jump" if wx2.9 is used +void ObjectInspector::OnChildFocus(wxChildFocusEvent&) +{ + // do nothing to avoid "scrollbar jump" if wx2.9 is used } -void ObjectInspector::OnPropertyGridItemSelected( wxPropertyGridEvent& event ) +void ObjectInspector::OnPropertyGridItemSelected(wxPropertyGridEvent& event) { - wxPGProperty *p = event.GetProperty(); - if( p ) - { - if( m_nb->GetSelection() == 0 ) - { - m_strSelPropItem = m_pg->GetPropertyName( p ); - m_pageName = wxT("Properties"); - } - else - { - m_strSelPropItem = m_eg->GetPropertyName( p ); - m_pageName = wxT("Events"); - } - } + wxPGProperty* p = event.GetProperty(); + if (p) { + if (m_nb->GetSelection() == 0) { + m_strSelPropItem = m_pg->GetPropertyName(p); + m_pageName = wxT("Properties"); + } else { + m_strSelPropItem = m_eg->GetPropertyName(p); + m_pageName = wxT("Events"); + } + } } void ObjectInspector::RestoreLastSelectedPropItem() { - if( m_pageName == wxT("Properties") ) - { - wxPGProperty* p = m_pg->GetPropertyByName( m_strSelPropItem ); - if( p ) - { - m_pg->SelectProperty(p, true); - m_pg->SetFocus(); - } - } - else if( m_pageName == wxT("Events") ) - { - wxPGProperty* p = m_eg->GetPropertyByName(m_strSelPropItem); - if( p ) - { - m_eg->SelectProperty(p, true); - m_eg->SetFocus(); - } - } + if (m_pageName == wxT("Properties")) { + wxPGProperty* p = m_pg->GetPropertyByName(m_strSelPropItem); + if (p) { + m_pg->SelectProperty(p, true); + m_pg->SetFocus(); + } + } else if (m_pageName == wxT("Events")) { + wxPGProperty* p = m_eg->GetPropertyByName(m_strSelPropItem); + if (p) { + m_eg->SelectProperty(p, true); + m_eg->SetFocus(); + } + } } diff --git a/src/rad/inspector/objinspect.h b/src/rad/inspector/objinspect.h index b100956cb..eb30de303 100644 --- a/src/rad/inspector/objinspect.h +++ b/src/rad/inspector/objinspect.h @@ -29,13 +29,14 @@ #ifndef RAD_INSPECTOR_OBJINSPECT_H #define RAD_INSPECTOR_OBJINSPECT_H -#include "model/objectbase.h" - #include #include +#include "model/objectbase.h" + + #if !wxUSE_PROPGRID -#error "wxUSE_PROPGRID must be set to 1 in your wxWidgets library." + #error "wxUSE_PROPGRID must be set to 1 in your wxWidgets library." #endif class wxFBEventHandlerEvent; @@ -43,129 +44,125 @@ class wxFBPropertyEvent; class wxFBObjectEvent; class wxFBEvent; -enum { - wxFB_OI_DEFAULT_STYLE, - wxFB_OI_MULTIPAGE_STYLE, - wxFB_OI_SINGLE_PAGE_STYLE -}; +enum { wxFB_OI_DEFAULT_STYLE, wxFB_OI_MULTIPAGE_STYLE, wxFB_OI_SINGLE_PAGE_STYLE }; + class ObjectInspector : public wxPanel { private: - typedef std::map< wxPGProperty*, PProperty> ObjInspectorPropertyMap; - typedef std::map< wxPGProperty*, PEvent> ObjInspectorEventMap; + typedef std::map ObjInspectorPropertyMap; + typedef std::map ObjInspectorEventMap; ObjInspectorPropertyMap m_propMap; ObjInspectorEventMap m_eventMap; PObjectBase m_currentSel; - //save the current selected property - wxString m_strSelPropItem; - wxString m_pageName; + // save the current selected property + wxString m_strSelPropItem; + wxString m_pageName; - wxAuiNotebook* m_nb; + wxAuiNotebook* m_nb; wxPropertyGridManager* m_pg; wxPropertyGridManager* m_eg; int m_style; - int StringToBits( const wxString& strVal, wxPGChoices& constants ); + int StringToBits(const wxString& strVal, wxPGChoices& constants); - typedef std::map< wxString, bool > ExpandMap; + typedef std::map ExpandMap; ExpandMap m_isExpanded; - template < class ValueT > - void CreateCategory( const wxString& name, PObjectBase obj, PObjectInfo obj_info, std::map< wxString, ValueT >& itemMap, bool addingEvents ) + template + void CreateCategory( + const wxString& name, PObjectBase obj, PObjectInfo obj_info, std::map& itemMap, + bool addingEvents) { // Get Category PPropertyCategory category = obj_info->GetCategory(); - if ( !category ) - { + if (!category) { return; } // Prevent page creation if there are no properties - if ( 0 == category->GetCategoryCount() && 0 == ( addingEvents ? category->GetEventCount() : category->GetPropertyCount() ) ) - { + if ( + 0 == category->GetCategoryCount() && + 0 == (addingEvents ? category->GetEventCount() : category->GetPropertyCount())) { return; } wxString pageName; - if ( m_style == wxFB_OI_MULTIPAGE_STYLE ) + if (m_style == wxFB_OI_MULTIPAGE_STYLE) pageName = name; else pageName = wxT("default"); - wxPropertyGridManager* pg = ( addingEvents ? m_eg : m_pg ); - int pageIndex = pg->GetPageByName( pageName ); - if ( wxNOT_FOUND == pageIndex ) - { - pg->AddPage( pageName, obj_info->GetSmallIconFile() ); + wxPropertyGridManager* pg = (addingEvents ? m_eg : m_pg); + int pageIndex = pg->GetPageByName(pageName); + if (wxNOT_FOUND == pageIndex) { + pg->AddPage(pageName, obj_info->GetSmallIconFile()); } const wxString& catName = category->GetName(); - wxPGProperty* id = pg->Append( new wxPropertyCategory( catName ) ); + wxPGProperty* id = pg->Append(new wxPropertyCategory(catName)); - AddItems( name, obj, obj_info, category, itemMap ); + AddItems(name, obj, obj_info, category, itemMap); ExpandMap::iterator it = m_isExpanded.find(catName); - if (it != m_isExpanded.end()) - { - if ( it->second ) - { - pg->Expand( id ); - } - else - { - pg->Collapse( id ); + if (it != m_isExpanded.end()) { + if (it->second) { + pg->Expand(id); + } else { + pg->Collapse(id); } } - pg->SetPropertyAttributeAll( wxPG_BOOL_USE_CHECKBOX, (long)1 ); + pg->SetPropertyAttributeAll(wxPG_BOOL_USE_CHECKBOX, (long)1); } - void AddItems( const wxString& name, PObjectBase obj, PObjectInfo obj_info, PPropertyCategory category, PropertyMap& map ); - void AddItems( const wxString& name, PObjectBase obj, PObjectInfo obj_info, PPropertyCategory category, EventMap& map ); - wxPGProperty* GetProperty( PProperty prop ); + void AddItems( + const wxString& name, PObjectBase obj, PObjectInfo obj_info, PPropertyCategory category, PropertyMap& map); + void AddItems( + const wxString& name, PObjectBase obj, PObjectInfo obj_info, PPropertyCategory category, EventMap& map); + wxPGProperty* GetProperty(PProperty prop); - void Create( bool force = false ); + void Create(bool force = false); - void OnPropertyGridChanging( wxPropertyGridEvent& event ); - void OnPropertyGridChanged( wxPropertyGridEvent& event ); - void OnEventGridChanged( wxPropertyGridEvent& event ); - void OnPropertyGridDblClick( wxPropertyGridEvent& event ); - void OnEventGridDblClick( wxPropertyGridEvent& event ); - void OnPropertyGridExpand( wxPropertyGridEvent& event ); - void OnEventGridExpand( wxPropertyGridEvent& event ); - void OnPropertyGridItemSelected( wxPropertyGridEvent& event ); - void OnReCreateGrid( wxCommandEvent& event ); - void OnBitmapPropertyChanged( wxCommandEvent& event ); + void OnPropertyGridChanging(wxPropertyGridEvent& event); + void OnPropertyGridChanged(wxPropertyGridEvent& event); + void OnEventGridChanged(wxPropertyGridEvent& event); + void OnPropertyGridDblClick(wxPropertyGridEvent& event); + void OnEventGridDblClick(wxPropertyGridEvent& event); + void OnPropertyGridExpand(wxPropertyGridEvent& event); + void OnEventGridExpand(wxPropertyGridEvent& event); + void OnPropertyGridItemSelected(wxPropertyGridEvent& event); + void OnReCreateGrid(wxCommandEvent& event); + void OnBitmapPropertyChanged(wxCommandEvent& event); - void RestoreLastSelectedPropItem(); + void RestoreLastSelectedPropItem(); - void ModifyProperty( PProperty prop, const wxString& str ); + void ModifyProperty(PProperty prop, const wxString& str); - void OnChildFocus( wxChildFocusEvent& event ); + void OnChildFocus(wxChildFocusEvent& event); public: - ObjectInspector(wxWindow *parent, int id, int style = wxFB_OI_DEFAULT_STYLE); - ~ObjectInspector() override; + ObjectInspector(wxWindow* parent, int id, int style = wxFB_OI_DEFAULT_STYLE); + ~ObjectInspector() override; - void OnObjectSelected( wxFBObjectEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnEventHandlerModified( wxFBEventHandlerEvent& event ); + void OnObjectSelected(wxFBObjectEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnEventHandlerModified(wxFBEventHandlerEvent& event); - void AutoGenerateId( PObjectBase objectChanged, PProperty propChanged, wxString reason ); - wxPropertyGridManager* CreatePropertyGridManager( wxWindow *parent, wxWindowID id ); + void AutoGenerateId(PObjectBase objectChanged, PProperty propChanged, wxString reason); + wxPropertyGridManager* CreatePropertyGridManager(wxWindow* parent, wxWindowID id); void SavePosition(); DECLARE_EVENT_TABLE() }; -#endif // RAD_INSPECTOR_OBJINSPECT_H +#endif // RAD_INSPECTOR_OBJINSPECT_H diff --git a/src/rad/inspector/wxfbadvprops.cpp b/src/rad/inspector/wxfbadvprops.cpp index a48e18eb0..a1b54bdcd 100644 --- a/src/rad/inspector/wxfbadvprops.cpp +++ b/src/rad/inspector/wxfbadvprops.cpp @@ -26,12 +26,14 @@ // This code was part of previous objtree.cpp version. // /////////////////////////////////////////////////////////////////////////////// + #include "wxfbadvprops.h" -#include "utils/typeconv.h" +#include + #include "rad/appdata.h" +#include "utils/typeconv.h" -#include // ----------------------------------------------------------------------- // wxFBSizeProperty @@ -39,43 +41,42 @@ #if wxCHECK_VERSION(3, 1, 0) wxPG_IMPLEMENT_PROPERTY_CLASS(wxFBSizeProperty, wxPGProperty, TextCtrl) #else -WX_PG_IMPLEMENT_PROPERTY_CLASS( wxFBSizeProperty, wxPGProperty, wxSize, const wxSize&, TextCtrl ) +WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFBSizeProperty, wxPGProperty, wxSize, const wxSize&, TextCtrl) #endif -wxFBSizeProperty::wxFBSizeProperty( const wxString& label, - const wxString& name, - const wxSize& value ) : wxPGProperty( label, name ) + wxFBSizeProperty::wxFBSizeProperty(const wxString& label, const wxString& name, const wxSize& value) : + wxPGProperty(label, name) { - DoSetValue( value ); - AddPrivateChild( new wxIntProperty( wxT("Width"), wxPG_LABEL, value.x ) ); - AddPrivateChild( new wxIntProperty( wxT("Height"), wxPG_LABEL, value.y ) ); + DoSetValue(value); + AddPrivateChild(new wxIntProperty(wxT("Width"), wxPG_LABEL, value.x)); + AddPrivateChild(new wxIntProperty(wxT("Height"), wxPG_LABEL, value.y)); } void wxFBSizeProperty::RefreshChildren() { - if ( GetChildCount() < 2 ) return; + if (GetChildCount() < 2) + return; - const wxSize& size = wxSizeRefFromVariant( m_value ); + const wxSize& size = wxSizeRefFromVariant(m_value); - Item(0)->SetValue( (long)size.x ); - Item(1)->SetValue( (long)size.y ); + Item(0)->SetValue((long)size.x); + Item(1)->SetValue((long)size.y); } -wxVariant wxFBSizeProperty::ChildChanged(wxVariant& thisValue, const int childIndex, - wxVariant& childValue) const { - wxSize& size = wxSizeRefFromVariant( thisValue ); +wxVariant wxFBSizeProperty::ChildChanged(wxVariant& thisValue, const int childIndex, wxVariant& childValue) const +{ + wxSize& size = wxSizeRefFromVariant(thisValue); wxVariant(); int val = childValue.GetLong(); - switch ( childIndex ) - { - case 0: - size.x = val; - break; - case 1: - size.y = val; - break; + switch (childIndex) { + case 0: + size.x = val; + break; + case 1: + size.y = val; + break; } wxVariant newVariant; @@ -90,45 +91,46 @@ wxVariant wxFBSizeProperty::ChildChanged(wxVariant& thisValue, const int childIn #if wxCHECK_VERSION(3, 1, 0) wxPG_IMPLEMENT_PROPERTY_CLASS(wxFBPointProperty, wxPGProperty, TextCtrl) #else -WX_PG_IMPLEMENT_PROPERTY_CLASS( wxFBPointProperty, wxPGProperty, wxPoint, const wxPoint&, TextCtrl ) +WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFBPointProperty, wxPGProperty, wxPoint, const wxPoint&, TextCtrl) #endif -wxFBPointProperty::wxFBPointProperty( const wxString& label, - const wxString& name, - const wxPoint& value ) : wxPGProperty( label, name ) + wxFBPointProperty::wxFBPointProperty(const wxString& label, const wxString& name, const wxPoint& value) : + wxPGProperty(label, name) { - DoSetValue( value ); - AddPrivateChild( new wxIntProperty( wxT("X"), wxPG_LABEL, value.x ) ); - AddPrivateChild( new wxIntProperty( wxT("Y"), wxPG_LABEL, value.y ) ); + DoSetValue(value); + AddPrivateChild(new wxIntProperty(wxT("X"), wxPG_LABEL, value.x)); + AddPrivateChild(new wxIntProperty(wxT("Y"), wxPG_LABEL, value.y)); } -wxFBPointProperty::~wxFBPointProperty() { } +wxFBPointProperty::~wxFBPointProperty() +{ +} void wxFBPointProperty::RefreshChildren() { - if ( GetChildCount() < 2 ) return; + if (GetChildCount() < 2) + return; - const wxPoint& point = wxPointRefFromVariant( m_value ); + const wxPoint& point = wxPointRefFromVariant(m_value); - Item(0)->SetValue( (long)point.x ); - Item(1)->SetValue( (long)point.y ); + Item(0)->SetValue((long)point.x); + Item(1)->SetValue((long)point.y); } -wxVariant wxFBPointProperty::ChildChanged(wxVariant& thisValue, const int childIndex, - wxVariant& childValue) const { - wxPoint& point = wxPointRefFromVariant( thisValue ); +wxVariant wxFBPointProperty::ChildChanged(wxVariant& thisValue, const int childIndex, wxVariant& childValue) const +{ + wxPoint& point = wxPointRefFromVariant(thisValue); wxVariant(); int val = childValue.GetLong(); - switch ( childIndex ) - { - case 0: - point.x = val; - break; - case 1: - point.y = val; - break; + switch (childIndex) { + case 0: + point.x = val; + break; + case 1: + point.y = val; + break; } wxVariant newVariant; @@ -147,167 +149,149 @@ static wxString gs_imageInitialPath = wxEmptyString; #if wxCHECK_VERSION(3, 1, 0) wxPG_IMPLEMENT_PROPERTY_CLASS(wxFBBitmapProperty, wxPGProperty, TextCtrl) #else -WX_PG_IMPLEMENT_PROPERTY_CLASS( wxFBBitmapProperty, wxPGProperty, - wxString, const wxString&, TextCtrl ) +WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFBBitmapProperty, wxPGProperty, wxString, const wxString&, TextCtrl) #endif -void wxFBBitmapProperty::GetChildValues( const wxString& parentValue, wxArrayString& childValues ) const + void wxFBBitmapProperty::GetChildValues(const wxString& parentValue, wxArrayString& childValues) const { - // some properties can contain value like "[-1;-1]" which must be modified due to use of ";" as a - // string separator - wxString values = parentValue; - - wxRegEx regex( wxT("\\[.+;.+\\]") ); - if( regex.IsValid() ) - { - if( regex.Matches( values ) ) - { - wxString sizeVal = regex.GetMatch( values ); - sizeVal.Replace( wxT(";"), wxT("") ); - sizeVal.Replace( wxT("["), wxT("") ); - sizeVal.Replace( wxT("]"), wxT("") ); - regex.Replace( &values, sizeVal ); - } - } - - childValues = wxStringTokenize( values, wxT(';'), wxTOKEN_RET_EMPTY_ALL ); - for ( wxArrayString::iterator value = childValues.begin(); value != childValues.end(); ++value ) - { - value->Trim( false ); - value->Replace( wxT(""), wxT(";") ); - } + // some properties can contain value like "[-1;-1]" which must be modified due to use of ";" as a + // string separator + wxString values = parentValue; + + wxRegEx regex(wxT("\\[.+;.+\\]")); + if (regex.IsValid()) { + if (regex.Matches(values)) { + wxString sizeVal = regex.GetMatch(values); + sizeVal.Replace(wxT(";"), wxT("")); + sizeVal.Replace(wxT("["), wxT("")); + sizeVal.Replace(wxT("]"), wxT("")); + regex.Replace(&values, sizeVal); + } + } + + childValues = wxStringTokenize(values, wxT(';'), wxTOKEN_RET_EMPTY_ALL); + for (wxArrayString::iterator value = childValues.begin(); value != childValues.end(); ++value) { + value->Trim(false); + value->Replace(wxT(""), wxT(";")); + } } -wxFBBitmapProperty::wxFBBitmapProperty( const wxString& label, - const wxString& name, - const wxString& value ) : wxPGProperty( label, name ) +wxFBBitmapProperty::wxFBBitmapProperty(const wxString& label, const wxString& name, const wxString& value) : + wxPGProperty(label, name) { - SetValue( WXVARIANT( value ) ); + SetValue(WXVARIANT(value)); } void wxFBBitmapProperty::CreateChildren() { - wxString propValue = m_value.GetString(); - wxVariant thisValue = WXVARIANT( propValue ); - wxVariant childValue; - int childIndex = 0; - wxArrayString childVals; - GetChildValues( propValue, childVals ); - wxString source; - if(childVals.Count() > 0) - { - source = childVals.Item(0); - } - else - { - source = _("Load From File"); - } - prevSrc = -1; - if ( source == wxString(_("Load From File") ) ) - { - childIndex = 0; - } - else if ( source == wxString(_("Load From Embedded File") ) ) - { - childIndex = 1; - } - else if ( source == wxString(_("Load From Resource") ) ) - { - childIndex = 2; - } - else if ( source == wxString(_("Load From Icon Resource") ) ) - { - childIndex = 3; - } - else if (source == wxString(_("Load From XRC"))) - { - childIndex = 4; - } - else if (source == wxString(_("Load From Art Provider"))) - { - childIndex = 5; - } - - childValue = WXVARIANT( childIndex ); - - CreatePropertySource( childIndex ); - - ChildChanged( thisValue, 0, childValue ); + wxString propValue = m_value.GetString(); + wxVariant thisValue = WXVARIANT(propValue); + wxVariant childValue; + int childIndex = 0; + wxArrayString childVals; + GetChildValues(propValue, childVals); + wxString source; + if (childVals.Count() > 0) { + source = childVals.Item(0); + } else { + source = _("Load From File"); + } + prevSrc = -1; + if (source == wxString(_("Load From File"))) { + childIndex = 0; + } else if (source == wxString(_("Load From Embedded File"))) { + childIndex = 1; + } else if (source == wxString(_("Load From Resource"))) { + childIndex = 2; + } else if (source == wxString(_("Load From Icon Resource"))) { + childIndex = 3; + } else if (source == wxString(_("Load From XRC"))) { + childIndex = 4; + } else if (source == wxString(_("Load From Art Provider"))) { + childIndex = 5; + } + + childValue = WXVARIANT(childIndex); + + CreatePropertySource(childIndex); + + ChildChanged(thisValue, 0, childValue); } -wxPGProperty *wxFBBitmapProperty::CreatePropertySource( int sourceIndex ) +wxPGProperty* wxFBBitmapProperty::CreatePropertySource(int sourceIndex) { wxPGChoices sourceChoices; // Add 'source' property (common for all other children) - sourceChoices.Add(_("Load From File") ); - sourceChoices.Add(_("Load From Embedded File") ); - sourceChoices.Add(_("Load From Resource") ); - sourceChoices.Add(_("Load From Icon Resource") ); - sourceChoices.Add(_("Load From XRC")); - sourceChoices.Add(_("Load From Art Provider") ); - - wxPGProperty *srcProp = new wxEnumProperty( wxT("source"), wxPG_LABEL, sourceChoices, sourceIndex ); - srcProp->SetHelpString( wxString(_("Load From File:\n") ) + - wxString(_("Load the image from a file on disk.\n\n") ) + - wxString(_("Load From Embedded File:\n") ) + - wxString(_("C++ Only. Embed the image file in the exe and load it.\nFor other languages, behaves like \"Load From File\".\n\n") ) + - wxString(_("Load From Resource:\n") ) + - wxString(_("Windows Only. Load the image from a BITMAP resource in a .rc file\n\n") ) + - wxString(_("Load From Icon Resource:\n") ) + - wxString(_("Windows Only. Load the image from a ICON resource in a .rc file\n\n") ) + - wxString(_("Load From XRC:\n")) + - wxString(_("Load the image from XRC resources. The XRC resources must be initialized by the application code.\n\n")) + - wxString(_("Load From Art Provider:\n") ) + - wxString(_("Query registered providers for bitmap with given ID.\n\n") ) ); - AppendChild( srcProp ); + sourceChoices.Add(_("Load From File")); + sourceChoices.Add(_("Load From Embedded File")); + sourceChoices.Add(_("Load From Resource")); + sourceChoices.Add(_("Load From Icon Resource")); + sourceChoices.Add(_("Load From XRC")); + sourceChoices.Add(_("Load From Art Provider")); + + wxPGProperty* srcProp = new wxEnumProperty(wxT("source"), wxPG_LABEL, sourceChoices, sourceIndex); + srcProp->SetHelpString( + wxString(_("Load From File:\n")) + wxString(_("Load the image from a file on disk.\n\n")) + + wxString(_("Load From Embedded File:\n")) + + wxString(_("C++ Only. Embed the image file in the exe and load it.\nFor other languages, behaves like \"Load " + "From File\".\n\n")) + + wxString(_("Load From Resource:\n")) + + wxString(_("Windows Only. Load the image from a BITMAP resource in a .rc file\n\n")) + + wxString(_("Load From Icon Resource:\n")) + + wxString(_("Windows Only. Load the image from a ICON resource in a .rc file\n\n")) + + wxString(_("Load From XRC:\n")) + + wxString( + _("Load the image from XRC resources. The XRC resources must be initialized by the application code.\n\n")) + + wxString(_("Load From Art Provider:\n")) + + wxString(_("Query registered providers for bitmap with given ID.\n\n"))); + AppendChild(srcProp); return srcProp; } -wxPGProperty *wxFBBitmapProperty::CreatePropertyFilePath() +wxPGProperty* wxFBBitmapProperty::CreatePropertyFilePath() { // Add 'file_path' property (common for 'Load From File' and 'Load From Embedded File' choices) - wxPGProperty *propFilePath = new wxImageFileProperty( wxT("file_path"), wxPG_LABEL ); - propFilePath->SetHelpString(_("Path to the image file.") ); + wxPGProperty* propFilePath = new wxImageFileProperty(wxT("file_path"), wxPG_LABEL); + propFilePath->SetHelpString(_("Path to the image file.")); - if ( !gs_imageInitialPath.IsEmpty() ) - { - //wxVariant initialPath( gs_imageInitialPath ); - //propFilePath->SetAttribute( wxPG_FILE_INITIAL_PATH, initialPath ); + if (!gs_imageInitialPath.IsEmpty()) { + // wxVariant initialPath( gs_imageInitialPath ); + // propFilePath->SetAttribute( wxPG_FILE_INITIAL_PATH, initialPath ); } return propFilePath; } -wxPGProperty *wxFBBitmapProperty::CreatePropertyResourceName() +wxPGProperty* wxFBBitmapProperty::CreatePropertyResourceName() { // Create 'resource_name' property (common for 'Load From Resource' and 'Load From Icon Resource' choices) - wxPGProperty *propResName = new wxStringProperty( wxT("resource_name"), wxPG_LABEL ); - propResName->SetHelpString(_("Windows Only. Name of the resource in the .rc file.") ); + wxPGProperty* propResName = new wxStringProperty(wxT("resource_name"), wxPG_LABEL); + propResName->SetHelpString(_("Windows Only. Name of the resource in the .rc file.")); return propResName; } -wxPGProperty *wxFBBitmapProperty::CreatePropertyIconSize() +wxPGProperty* wxFBBitmapProperty::CreatePropertyIconSize() { // Create 'ico_size' property ('Load From Icon Resource' only) - wxPGProperty *propIcoSize = new wxFBSizeProperty(wxT("ico_size"), wxPG_LABEL, wxDefaultSize); - propIcoSize->SetHelpString(_("The size of the icon to use from a ICON resource with multiple icons in it.") ); + wxPGProperty* propIcoSize = new wxFBSizeProperty(wxT("ico_size"), wxPG_LABEL, wxDefaultSize); + propIcoSize->SetHelpString(_("The size of the icon to use from a ICON resource with multiple icons in it.")); return propIcoSize; } wxPGProperty* wxFBBitmapProperty::CreatePropertyXrcName() { - // Create 'xrc_name' property ('Load From XRC' only) - auto* propXRCName = new wxStringProperty(wxT("xrc_name"), wxPG_LABEL); - propXRCName->SetHelpString(_("Name of the item in the XRC resources.")); + // Create 'xrc_name' property ('Load From XRC' only) + auto* propXRCName = new wxStringProperty(wxT("xrc_name"), wxPG_LABEL); + propXRCName->SetHelpString(_("Name of the item in the XRC resources.")); - return propXRCName; + return propXRCName; } -wxPGProperty *wxFBBitmapProperty::CreatePropertyArtId() +wxPGProperty* wxFBBitmapProperty::CreatePropertyArtId() { wxPGChoices artIdChoices; @@ -468,13 +452,15 @@ wxPGProperty *wxFBBitmapProperty::CreatePropertyArtId() artIdChoices.Add(wxT("gtk-zoom-in")); artIdChoices.Add(wxT("gtk-zoom-out")); - wxPGProperty *propArtId = new wxEditEnumProperty( wxT("id"), wxPG_LABEL, artIdChoices ); - propArtId->SetHelpString(_("Choose a wxArtID unique identifier of the bitmap or enter a wxArtID for your custom wxArtProvider. IDs with prefix 'gtk-' are available under wxGTK only.") ); + wxPGProperty* propArtId = new wxEditEnumProperty(wxT("id"), wxPG_LABEL, artIdChoices); + propArtId->SetHelpString( + _("Choose a wxArtID unique identifier of the bitmap or enter a wxArtID for your custom wxArtProvider. IDs with " + "prefix 'gtk-' are available under wxGTK only.")); return propArtId; } -wxPGProperty *wxFBBitmapProperty::CreatePropertyArtClient() +wxPGProperty* wxFBBitmapProperty::CreatePropertyArtClient() { wxPGChoices artClientChoices; @@ -488,8 +474,10 @@ wxPGProperty *wxFBBitmapProperty::CreatePropertyArtClient() artClientChoices.Add(wxT("wxART_MESSAGE_BOX")); artClientChoices.Add(wxT("wxART_OTHER")); - wxPGProperty *propArtClient = new wxEditEnumProperty( wxT("client"), wxPG_LABEL, artClientChoices ); - propArtClient->SetHelpString(_("Choose a wxArtClient identifier of the client (i.e. who is asking for the bitmap) or enter a wxArtClient for your custom wxArtProvider.") ); + wxPGProperty* propArtClient = new wxEditEnumProperty(wxT("client"), wxPG_LABEL, artClientChoices); + propArtClient->SetHelpString( + _("Choose a wxArtClient identifier of the client (i.e. who is asking for the bitmap) or enter a wxArtClient for " + "your custom wxArtProvider.")); return propArtClient; } @@ -498,183 +486,141 @@ wxFBBitmapProperty::~wxFBBitmapProperty() { } -wxVariant wxFBBitmapProperty::ChildChanged(wxVariant& thisValue, const int childIndex, - wxVariant& childValue) const +wxVariant wxFBBitmapProperty::ChildChanged(wxVariant& thisValue, const int childIndex, wxVariant& childValue) const { - auto* bp = const_cast(this); - - const auto val = thisValue.GetString(); - wxArrayString childVals; - GetChildValues(val, childVals); - auto newVal = val; - - // Find the appropriate new state - switch (childIndex) - { - // source - case 0: - { - const auto count = GetChildCount(); - - // childValue.GetInteger() returns the chosen item index - switch (childValue.GetInteger()) - { - // 'Load From File' and 'Load From Embedded File' - case 0: - case 1: - { - if (prevSrc != 0 && prevSrc!= 1) - { - for (unsigned int i = 1; i < count ; ++i) - { - if (auto* p = Item(i)) - { - wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); - GetGrid()->DeleteProperty(p); - } - } - bp->AppendChild(bp->CreatePropertyFilePath()); - } - - if (childVals.GetCount() == 2) - { - newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1); - } - else if (childVals.GetCount() > 0) - { - newVal = childVals.Item(0) + wxT("; "); - } - break; - } - // 'Load From Resource' - case 2: - { - if (prevSrc != 2) - { - for (unsigned int i = 1; i < count ; ++i) - { - if (auto* p = Item(i)) - { - wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); - GetGrid()->DeleteProperty(p); - } - } - bp->AppendChild(bp->CreatePropertyResourceName()); - } - - if (childVals.GetCount() == 2) - { - newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1); - } - else if (childVals.GetCount() > 0) - { - newVal = childVals.Item(0) + wxT("; "); - } - break; - } - // 'Load From Icon Resource' - case 3: - { - if (prevSrc != 3) - { - for (unsigned int i = 1; i < count ; ++i) - { - if (auto* p = Item(i)) - { - wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); - GetGrid()->DeleteProperty(p); - } - } - bp->AppendChild(bp->CreatePropertyResourceName()); - bp->AppendChild(bp->CreatePropertyIconSize()); - } - - if (childVals.GetCount() == 3) - { - newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1) + wxT("; [") + childVals.Item(2) + wxT("]"); - } - else if (childVals.GetCount() > 0) - { - newVal = childVals.Item(0) + wxT("; ; []"); - } - break; - } - // 'Load From XRC' - case 4: - { - if (prevSrc != 4) - { - for (unsigned int i = 1; i < count; ++i) - { - if (auto* p = Item(i)) - { - wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); - GetGrid()->DeleteProperty(p); - } - } - bp->AppendChild(bp->CreatePropertyXrcName()); - } - - if (childVals.GetCount() == 2) - { - newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1); - } - else if (childVals.GetCount() > 0) - { - newVal = childVals.Item(0) + wxT("; "); - } - break; - } - // 'Load From Art Provider' - case 5: - { - if (prevSrc != 5) - { - for (unsigned int i = 1; i < count ; ++i) - { - if (auto* p = Item(i)) - { - wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); - GetGrid()->DeleteProperty(p); - } - } - bp->AppendChild(bp->CreatePropertyArtId()); - bp->AppendChild(bp->CreatePropertyArtClient()); - } - - if (childVals.GetCount() == 3) - { - newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1) + wxT("; ") + childVals.Item(2); - } - else if (childVals.GetCount() > 0) - { - newVal = childVals.Item(0) + wxT("; ; "); - } - break; - } - } - break; - } + auto* bp = const_cast(this); + + const auto val = thisValue.GetString(); + wxArrayString childVals; + GetChildValues(val, childVals); + auto newVal = val; + + // Find the appropriate new state + switch (childIndex) { + // source + case 0: { + const auto count = GetChildCount(); + + // childValue.GetInteger() returns the chosen item index + switch (childValue.GetInteger()) { + // 'Load From File' and 'Load From Embedded File' + case 0: + case 1: { + if (prevSrc != 0 && prevSrc != 1) { + for (unsigned int i = 1; i < count; ++i) { + if (auto* p = Item(i)) { + wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); + GetGrid()->DeleteProperty(p); + } + } + bp->AppendChild(bp->CreatePropertyFilePath()); + } + + if (childVals.GetCount() == 2) { + newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1); + } else if (childVals.GetCount() > 0) { + newVal = childVals.Item(0) + wxT("; "); + } + break; + } + // 'Load From Resource' + case 2: { + if (prevSrc != 2) { + for (unsigned int i = 1; i < count; ++i) { + if (auto* p = Item(i)) { + wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); + GetGrid()->DeleteProperty(p); + } + } + bp->AppendChild(bp->CreatePropertyResourceName()); + } + + if (childVals.GetCount() == 2) { + newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1); + } else if (childVals.GetCount() > 0) { + newVal = childVals.Item(0) + wxT("; "); + } + break; + } + // 'Load From Icon Resource' + case 3: { + if (prevSrc != 3) { + for (unsigned int i = 1; i < count; ++i) { + if (auto* p = Item(i)) { + wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); + GetGrid()->DeleteProperty(p); + } + } + bp->AppendChild(bp->CreatePropertyResourceName()); + bp->AppendChild(bp->CreatePropertyIconSize()); + } + + if (childVals.GetCount() == 3) { + newVal = + childVals.Item(0) + wxT("; ") + childVals.Item(1) + wxT("; [") + childVals.Item(2) + wxT("]"); + } else if (childVals.GetCount() > 0) { + newVal = childVals.Item(0) + wxT("; ; []"); + } + break; + } + // 'Load From XRC' + case 4: { + if (prevSrc != 4) { + for (unsigned int i = 1; i < count; ++i) { + if (auto* p = Item(i)) { + wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); + GetGrid()->DeleteProperty(p); + } + } + bp->AppendChild(bp->CreatePropertyXrcName()); + } + + if (childVals.GetCount() == 2) { + newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1); + } else if (childVals.GetCount() > 0) { + newVal = childVals.Item(0) + wxT("; "); + } + break; + } + // 'Load From Art Provider' + case 5: { + if (prevSrc != 5) { + for (unsigned int i = 1; i < count; ++i) { + if (auto* p = Item(i)) { + wxLogDebug(wxT("wxFBBP::ChildChanged: Removing:%s"), p->GetLabel()); + GetGrid()->DeleteProperty(p); + } + } + bp->AppendChild(bp->CreatePropertyArtId()); + bp->AppendChild(bp->CreatePropertyArtClient()); + } + + if (childVals.GetCount() == 3) { + newVal = childVals.Item(0) + wxT("; ") + childVals.Item(1) + wxT("; ") + childVals.Item(2); + } else if (childVals.GetCount() > 0) { + newVal = childVals.Item(0) + wxT("; ; "); + } + break; + } + } + break; + } // file_path || id || resource_name || xrc_name - case 1: - { - if ( (Item(0)->GetValueAsString() == _("Load From File")) || (Item(0)->GetValueAsString() == _("Load From Embedded File")) ) - { + case 1: { + if ( + (Item(0)->GetValueAsString() == _("Load From File")) || + (Item(0)->GetValueAsString() == _("Load From Embedded File"))) { // Save the initial file path TODO: Save the image filter index - if ( Item(1) ) - { - wxString img = childValue.GetString(); - img = bp->SetupImage( img ); - wxFileName imgPath( img ); + if (Item(1)) { + wxString img = childValue.GetString(); + img = bp->SetupImage(img); + wxFileName imgPath(img); gs_imageInitialPath = imgPath.GetPath(); - if ( !img.IsEmpty() ) - { - Item(1)->SetValue( WXVARIANT( img ) ); - } - else - { + if (!img.IsEmpty()) { + Item(1)->SetValue(WXVARIANT(img)); + } else { Item(1)->SetValueToUnspecified(); } newVal = Item(0)->GetValueAsString() + wxT("; ") + img; @@ -684,12 +630,11 @@ wxVariant wxFBBitmapProperty::ChildChanged(wxVariant& thisValue, const int child } } - bp->SetPrevSource(childValue.GetInteger()); + bp->SetPrevSource(childValue.GetInteger()); - if ( newVal != val ) - { - wxVariant ret = WXVARIANT( newVal ); - bp->SetValue( ret ); + if (newVal != val) { + wxVariant ret = WXVARIANT(newVal); + bp->SetValue(ret); return ret; } @@ -698,116 +643,93 @@ wxVariant wxFBBitmapProperty::ChildChanged(wxVariant& thisValue, const int child void wxFBBitmapProperty::UpdateChildValues(const wxString& value) { - wxArrayString childVals; - GetChildValues( value, childVals ); - - if( childVals[0].Contains( _("Load From File") ) || childVals[0].Contains( _("Load From Embedded File") ) ) - { - if(childVals.Count() > 1) - { - wxString img = childVals[1]; - img = SetupImage( img ); - wxFileName imgPath( img ); - gs_imageInitialPath = imgPath.GetPath(); - - if ( !img.IsEmpty() ) - { - Item(1)->SetValue( WXVARIANT( img ) ); - } - else - { - Item(1)->SetValueToUnspecified(); - } - } - } - else if( childVals[0].Contains( _("Load From Resource") ) ) - { - if(childVals.Count() > 1) - { - Item(1)->SetValue( childVals[1]); - } - } - else if( childVals[0].Contains( _("Load From Icon Resource") ) ) - { - if(childVals.Count() > 1) - { - Item(1)->SetValue( childVals[1]); - } - - if(childVals.Count() > 2) - { - // This child requires a wxSize as data type, not a wxString - // The string format of a wxSize doesn't match the display format, - // convert it like ObjectInspector does - wxString aux = childVals[2]; - aux.Replace(wxT(";"), wxT(",")); - Item(2)->SetValue(WXVARIANT(TypeConv::StringToSize(aux))); - } - } - else if (childVals[0].Contains(_("Load From XRC"))) - { - if (childVals.Count() > 1) - { - Item(1)->SetValue(childVals[1]); - } - } - else if( childVals[0].Contains( _("Load From Art Provider") ) ) - { - if(childVals.Count() > 1) - { - Item(1)->SetValue( childVals[1]); - } - - if(childVals.Count() > 2) - { - Item(2)->SetValue( childVals[2]); - } - } + wxArrayString childVals; + GetChildValues(value, childVals); + + if (childVals[0].Contains(_("Load From File")) || childVals[0].Contains(_("Load From Embedded File"))) { + if (childVals.Count() > 1) { + wxString img = childVals[1]; + img = SetupImage(img); + wxFileName imgPath(img); + gs_imageInitialPath = imgPath.GetPath(); + + if (!img.IsEmpty()) { + Item(1)->SetValue(WXVARIANT(img)); + } else { + Item(1)->SetValueToUnspecified(); + } + } + } else if (childVals[0].Contains(_("Load From Resource"))) { + if (childVals.Count() > 1) { + Item(1)->SetValue(childVals[1]); + } + } else if (childVals[0].Contains(_("Load From Icon Resource"))) { + if (childVals.Count() > 1) { + Item(1)->SetValue(childVals[1]); + } + + if (childVals.Count() > 2) { + // This child requires a wxSize as data type, not a wxString + // The string format of a wxSize doesn't match the display format, + // convert it like ObjectInspector does + wxString aux = childVals[2]; + aux.Replace(wxT(";"), wxT(",")); + Item(2)->SetValue(WXVARIANT(TypeConv::StringToSize(aux))); + } + } else if (childVals[0].Contains(_("Load From XRC"))) { + if (childVals.Count() > 1) { + Item(1)->SetValue(childVals[1]); + } + } else if (childVals[0].Contains(_("Load From Art Provider"))) { + if (childVals.Count() > 1) { + Item(1)->SetValue(childVals[1]); + } + + if (childVals.Count() > 2) { + Item(2)->SetValue(childVals[2]); + } + } } void wxFBBitmapProperty::OnSetValue() { } -wxString wxFBBitmapProperty::SetupImage( const wxString &imgPath ) +wxString wxFBBitmapProperty::SetupImage(const wxString& imgPath) { - if(!imgPath.IsEmpty()) - { - wxFileName imgName = wxFileName( imgPath ); - - // Allow user to specify any file path he needs (even if it seemingly doesn't exist) - if( !imgName.FileExists() ) return imgPath; - - wxString res = wxT(""); - wxImage img = wxImage( imgPath ); - - if ( !img.IsOk() ) return res; - - // Setup for correct file_path - if ( imgName.IsAbsolute() ) - { - return TypeConv::MakeRelativeURL( imgPath, AppData()->GetProjectPath() ); - } - else - { - imgName.MakeAbsolute( AppData()->GetProjectPath() ); - - if ( !imgName.FileExists() ) return res; - } - } + if (!imgPath.IsEmpty()) { + wxFileName imgName = wxFileName(imgPath); + + // Allow user to specify any file path he needs (even if it seemingly doesn't exist) + if (!imgName.FileExists()) + return imgPath; + + wxString res = wxT(""); + wxImage img = wxImage(imgPath); + + if (!img.IsOk()) + return res; + + // Setup for correct file_path + if (imgName.IsAbsolute()) { + return TypeConv::MakeRelativeURL(imgPath, AppData()->GetProjectPath()); + } else { + imgName.MakeAbsolute(AppData()->GetProjectPath()); + + if (!imgName.FileExists()) + return res; + } + } return imgPath; } -wxString wxFBBitmapProperty::SetupResource( const wxString &resName ) +wxString wxFBBitmapProperty::SetupResource(const wxString& resName) { wxString res = wxEmptyString; // Keep old value from an icon resource only - if ( resName.Contains( wxT(";") ) && resName.Contains( wxT("[") ) ) - { - return resName.BeforeFirst( wxT(';') ); - } - else if ( resName.Contains( wxT(";") ) ) - { + if (resName.Contains(wxT(";")) && resName.Contains(wxT("["))) { + return resName.BeforeFirst(wxT(';')); + } else if (resName.Contains(wxT(";"))) { return res; } return resName; @@ -818,83 +740,71 @@ wxString wxFBBitmapProperty::SetupResource( const wxString &resName ) // ----------------------------------------------------------------------- #ifdef wxUSE_SLIDER -wxIMPLEMENT_DYNAMIC_CLASS( wxPGSliderEditor, wxPGEditor ) +wxIMPLEMENT_DYNAMIC_CLASS(wxPGSliderEditor, wxPGEditor) -wxPGSliderEditor::~wxPGSliderEditor() + wxPGSliderEditor::~wxPGSliderEditor() { } // Create controls and initialize event handling. -wxPGWindowList wxPGSliderEditor::CreateControls( wxPropertyGrid* propgrid, - wxPGProperty* property, - const wxPoint& pos, - const wxSize& sz ) const +wxPGWindowList wxPGSliderEditor::CreateControls( + wxPropertyGrid* propgrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz) const { - wxCHECK_MSG( property->IsKindOf( wxCLASSINFO( wxFloatProperty ) ), - NULL, - wxT("Slider editor can only be used with wxFloatProperty or derivative.") ); + wxCHECK_MSG( + property->IsKindOf(wxCLASSINFO(wxFloatProperty)), NULL, + wxT("Slider editor can only be used with wxFloatProperty or derivative.")); // Use two stage creation to allow cleaner display on wxMSW wxSlider* ctrl = new wxSlider(); -#ifdef __WXMSW__ + #ifdef __WXMSW__ ctrl->Hide(); -#endif + #endif wxString s = property->GetValueAsString(); double v_d = 0; - if ( s.ToDouble( &v_d ) ) - { - if ( v_d < 0 ) + if (s.ToDouble(&v_d)) { + if (v_d < 0) v_d = 0; - else if ( v_d > 1 ) + else if (v_d > 1) v_d = 1; } - ctrl->Create( propgrid->GetPanel(), - wxID_ANY, - (int)(v_d * m_max), - 0, - m_max, - pos, - sz, - wxSL_HORIZONTAL); + ctrl->Create(propgrid->GetPanel(), wxID_ANY, (int)(v_d * m_max), 0, m_max, pos, sz, wxSL_HORIZONTAL); // Connect all required events to grid's OnCustomEditorEvent // (all relevenat wxTextCtrl, wxComboBox and wxButton events are // already connected) -#ifdef __WXMSW__ + #ifdef __WXMSW__ ctrl->Show(); -#endif + #endif return ctrl; } // Copies value from property to control -void wxPGSliderEditor::UpdateControl( wxPGProperty* property, wxWindow* wnd ) const +void wxPGSliderEditor::UpdateControl(wxPGProperty* property, wxWindow* wnd) const { - wxSlider *ctrl = ( wxSlider* ) wnd; - assert(ctrl && ctrl->IsKindOf(CLASSINFO(wxSlider))); + wxSlider* ctrl = (wxSlider*)wnd; + assert(ctrl && ctrl->IsKindOf(CLASSINFO(wxSlider))); double val = property->GetValue().GetDouble(); - if ( val < 0 ) + if (val < 0) val = 0; - else if ( val > 1 ) + else if (val > 1) val = 1; - ctrl->SetValue( (int)( val * m_max ) ); + ctrl->SetValue((int)(val * m_max)); } // Control's events are redirected here -bool wxPGSliderEditor::OnEvent( wxPropertyGrid* WXUNUSED( propgrid ), - wxPGProperty* property, wxWindow* wnd, wxEvent& event ) const -{ - if ( event.GetEventType() == wxEVT_SCROLL_THUMBTRACK ) - { - wxSlider *ctrl = wxDynamicCast( wnd, wxSlider ); - if ( ctrl ) - { - double val = (double)( ctrl->GetValue() ) / (double)(m_max); - property->SetValue( WXVARIANT( val ) ); +bool wxPGSliderEditor::OnEvent( + wxPropertyGrid* WXUNUSED(propgrid), wxPGProperty* property, wxWindow* wnd, wxEvent& event) const +{ + if (event.GetEventType() == wxEVT_SCROLL_THUMBTRACK) { + wxSlider* ctrl = wxDynamicCast(wnd, wxSlider); + if (ctrl) { + double val = (double)(ctrl->GetValue()) / (double)(m_max); + property->SetValue(WXVARIANT(val)); return true; } } @@ -902,21 +812,21 @@ bool wxPGSliderEditor::OnEvent( wxPropertyGrid* WXUNUSED( propgrid ), return false; } -bool wxPGSliderEditor::GetValueFromControl( wxVariant& variant, wxPGProperty* WXUNUSED( property ), wxWindow* wnd ) const +bool wxPGSliderEditor::GetValueFromControl(wxVariant& variant, wxPGProperty* WXUNUSED(property), wxWindow* wnd) const { - wxSlider* ctrl = ( wxSlider* ) wnd; - assert(ctrl && ctrl->IsKindOf(CLASSINFO(wxSlider))); + wxSlider* ctrl = (wxSlider*)wnd; + assert(ctrl && ctrl->IsKindOf(CLASSINFO(wxSlider))); - variant = WXVARIANT( (double)ctrl->GetValue() / (double)(m_max) ); + variant = WXVARIANT((double)ctrl->GetValue() / (double)(m_max)); return true; } -void wxPGSliderEditor::SetValueToUnspecified( wxPGProperty* WXUNUSED( property ), wxWindow* WXUNUSED( ctrl ) ) const +void wxPGSliderEditor::SetValueToUnspecified(wxPGProperty* WXUNUSED(property), wxWindow* WXUNUSED(ctrl)) const { } -#endif //wxUSE_SLIDER +#endif // wxUSE_SLIDER // ----------------------------------------------------------------------- // wxFBFontProperty @@ -925,141 +835,107 @@ void wxPGSliderEditor::SetValueToUnspecified( wxPGProperty* WXUNUSED( property ) #include #include -static const wxChar* gs_fp_es_family_labels[] = { - wxT("Default"), wxT("Decorative"), - wxT("Roman"), wxT("Script"), - wxT("Swiss"), wxT("Modern"), - wxT("Teletype"), wxT("Unknown"), - (const wxChar*) NULL -}; - -static long gs_fp_es_family_values[] = { - wxFONTFAMILY_DEFAULT, wxFONTFAMILY_DECORATIVE, - wxFONTFAMILY_ROMAN, wxFONTFAMILY_SCRIPT, - wxFONTFAMILY_SWISS, wxFONTFAMILY_MODERN, - wxFONTFAMILY_TELETYPE, wxFONTFAMILY_UNKNOWN -}; - -static const wxChar* gs_fp_es_style_labels[] = { - wxT("Normal"), - wxT("Slant"), - wxT("Italic"), - (const wxChar*) NULL -}; - -static long gs_fp_es_style_values[] = { - wxFONTSTYLE_NORMAL, - wxFONTSTYLE_SLANT, - wxFONTSTYLE_ITALIC -}; - -static const wxChar* gs_fp_es_weight_labels[] = { - wxT("Normal"), - wxT("Light"), - wxT("Bold"), - (const wxChar*) NULL -}; - -static long gs_fp_es_weight_values[] = { - wxFONTWEIGHT_NORMAL, - wxFONTWEIGHT_LIGHT, - wxFONTWEIGHT_BOLD -}; +static const wxChar* gs_fp_es_family_labels[] = {wxT("Default"), wxT("Decorative"), wxT("Roman"), + wxT("Script"), wxT("Swiss"), wxT("Modern"), + wxT("Teletype"), wxT("Unknown"), (const wxChar*)NULL}; + +static long gs_fp_es_family_values[] = {wxFONTFAMILY_DEFAULT, wxFONTFAMILY_DECORATIVE, wxFONTFAMILY_ROMAN, + wxFONTFAMILY_SCRIPT, wxFONTFAMILY_SWISS, wxFONTFAMILY_MODERN, + wxFONTFAMILY_TELETYPE, wxFONTFAMILY_UNKNOWN}; + +static const wxChar* gs_fp_es_style_labels[] = {wxT("Normal"), wxT("Slant"), wxT("Italic"), (const wxChar*)NULL}; + +static long gs_fp_es_style_values[] = {wxFONTSTYLE_NORMAL, wxFONTSTYLE_SLANT, wxFONTSTYLE_ITALIC}; + +static const wxChar* gs_fp_es_weight_labels[] = {wxT("Normal"), wxT("Light"), wxT("Bold"), (const wxChar*)NULL}; + +static long gs_fp_es_weight_values[] = {wxFONTWEIGHT_NORMAL, wxFONTWEIGHT_LIGHT, wxFONTWEIGHT_BOLD}; #if wxCHECK_VERSION(3, 1, 0) wxPG_IMPLEMENT_PROPERTY_CLASS(wxFBFontProperty, wxPGProperty, TextCtrlAndButton) #else -WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFBFontProperty,wxPGProperty, - wxFont,const wxFont&,TextCtrlAndButton) +WX_PG_IMPLEMENT_PROPERTY_CLASS(wxFBFontProperty, wxPGProperty, wxFont, const wxFont&, TextCtrlAndButton) #endif -wxFBFontProperty::wxFBFontProperty( const wxString& label, const wxString& name, - const wxFontContainer& value ) - : wxPGProperty(label,name) + wxFBFontProperty::wxFBFontProperty(const wxString& label, const wxString& name, const wxFontContainer& value) : + wxPGProperty(label, name) { - SetValue( WXVARIANT( TypeConv::FontToString(value) ) ); + SetValue(WXVARIANT(TypeConv::FontToString(value))); // Initialize font family choices list - if ( !wxPGGlobalVars->m_fontFamilyChoices ) - { + if (!wxPGGlobalVars->m_fontFamilyChoices) { wxFontEnumerator enumerator; enumerator.EnumerateFacenames(); wxArrayString faceNames = enumerator.GetFacenames(); faceNames.Sort(); - faceNames.Insert( wxEmptyString, 0 ); + faceNames.Insert(wxEmptyString, 0); wxPGGlobalVars->m_fontFamilyChoices = new wxPGChoices(faceNames); } wxString emptyString(wxEmptyString); - AddPrivateChild( new wxIntProperty( _("Point Size"), wxT("Point Size"), - value.m_pointSize) ); + AddPrivateChild(new wxIntProperty(_("Point Size"), wxT("Point Size"), value.m_pointSize)); - AddPrivateChild( new wxEnumProperty(_("Family"), wxT("Family"), - gs_fp_es_family_labels,gs_fp_es_family_values, - value.m_family) ); + AddPrivateChild( + new wxEnumProperty(_("Family"), wxT("Family"), gs_fp_es_family_labels, gs_fp_es_family_values, value.m_family)); wxString faceName = value.m_faceName; // If font was not in there, add it now - if ( faceName.length() && - wxPGGlobalVars->m_fontFamilyChoices->Index(faceName) == wxNOT_FOUND ) + if (faceName.length() && wxPGGlobalVars->m_fontFamilyChoices->Index(faceName) == wxNOT_FOUND) wxPGGlobalVars->m_fontFamilyChoices->AddAsSorted(faceName); - wxPGProperty* p = new wxEnumProperty(_("Face Name"), wxT("Face Name"), - *wxPGGlobalVars->m_fontFamilyChoices); + wxPGProperty* p = new wxEnumProperty(_("Face Name"), wxT("Face Name"), *wxPGGlobalVars->m_fontFamilyChoices); p->SetValueFromString(faceName, wxPG_FULL_VALUE); - AddPrivateChild( p ); + AddPrivateChild(p); - AddPrivateChild( new wxEnumProperty(_("Style"), wxT("Style"), - gs_fp_es_style_labels,gs_fp_es_style_values,value.m_style) ); + AddPrivateChild( + new wxEnumProperty(_("Style"), wxT("Style"), gs_fp_es_style_labels, gs_fp_es_style_values, value.m_style)); - AddPrivateChild( new wxEnumProperty(_("Weight"), wxT("Weight"), - gs_fp_es_weight_labels,gs_fp_es_weight_values,value.m_weight) ); + AddPrivateChild( + new wxEnumProperty(_("Weight"), wxT("Weight"), gs_fp_es_weight_labels, gs_fp_es_weight_values, value.m_weight)); - AddPrivateChild( new wxBoolProperty(_("Underlined"), wxT("Underlined"), - value.m_underlined) ); + AddPrivateChild(new wxBoolProperty(_("Underlined"), wxT("Underlined"), value.m_underlined)); } -wxFBFontProperty::~wxFBFontProperty() { } +wxFBFontProperty::~wxFBFontProperty() +{ +} void wxFBFontProperty::OnSetValue() { - // do nothing + // do nothing } -wxString wxFBFontProperty::GetValueAsString( int argFlags ) const +wxString wxFBFontProperty::GetValueAsString(int argFlags) const { return wxPGProperty::GetValueAsString(argFlags); } -bool wxFBFontProperty::OnEvent( wxPropertyGrid* propgrid, wxWindow* WXUNUSED(primary), - wxEvent& event ) +bool wxFBFontProperty::OnEvent(wxPropertyGrid* propgrid, wxWindow* WXUNUSED(primary), wxEvent& event) { - if ( propgrid->IsMainButtonEvent(event) ) - { + if (propgrid->IsMainButtonEvent(event)) { // Update value from last minute changes wxFontData data; - wxFont font = TypeConv::StringToFont( m_value.GetString() ); + wxFont font = TypeConv::StringToFont(m_value.GetString()); - data.SetInitialFont( font ); + data.SetInitialFont(font); data.SetColour(*wxBLACK); wxFontDialog dlg(propgrid, data); - if ( dlg.ShowModal() == wxID_OK ) - { + if (dlg.ShowModal() == wxID_OK) { propgrid->EditorsValueWasModified(); - wxFontContainer fcont( dlg.GetFontData().GetChosenFont() ); + wxFontContainer fcont(dlg.GetFontData().GetChosenFont()); - wxVariant variant = WXVARIANT( TypeConv::FontToString( fcont ) ); - SetValueInEvent( variant ); + wxVariant variant = WXVARIANT(TypeConv::FontToString(fcont)); + SetValueInEvent(variant); return true; } @@ -1069,67 +945,53 @@ bool wxFBFontProperty::OnEvent( wxPropertyGrid* propgrid, wxWindow* WXUNUSED(pri void wxFBFontProperty::RefreshChildren() { - wxString fstr = m_value.GetString(); - wxFontContainer font = TypeConv::StringToFont( fstr ); - - Item(0)->SetValue( font.m_pointSize ); - Item(1)->SetValue( font.m_family ); - Item(2)->SetValueFromString( font.m_faceName, wxPG_FULL_VALUE ); - Item(3)->SetValue( font.m_style ); - Item(4)->SetValue( font.m_weight ); - Item(5)->SetValue( font.m_underlined ); + wxString fstr = m_value.GetString(); + wxFontContainer font = TypeConv::StringToFont(fstr); + + Item(0)->SetValue(font.m_pointSize); + Item(1)->SetValue(font.m_family); + Item(2)->SetValueFromString(font.m_faceName, wxPG_FULL_VALUE); + Item(3)->SetValue(font.m_style); + Item(4)->SetValue(font.m_weight); + Item(5)->SetValue(font.m_underlined); } - wxVariant -wxFBFontProperty::ChildChanged( wxVariant& thisValue, int ind, wxVariant& childValue ) const +wxVariant wxFBFontProperty::ChildChanged(wxVariant& thisValue, int ind, wxVariant& childValue) const { - wxFontContainer font = TypeConv::StringToFont( thisValue.GetString() ); + wxFontContainer font = TypeConv::StringToFont(thisValue.GetString()); - if ( ind == 0 ) - { - font.m_pointSize = childValue.GetLong(); - } - else if ( ind == 1 ) - { + if (ind == 0) { + font.m_pointSize = childValue.GetLong(); + } else if (ind == 1) { int fam = childValue.GetLong(); - if (fam < wxFONTFAMILY_DEFAULT || fam > wxFONTFAMILY_TELETYPE) { - fam = wxFONTFAMILY_DEFAULT; - } - font.m_family = static_cast(fam); - } - else if ( ind == 2 ) - { + if (fam < wxFONTFAMILY_DEFAULT || fam > wxFONTFAMILY_TELETYPE) { + fam = wxFONTFAMILY_DEFAULT; + } + font.m_family = static_cast(fam); + } else if (ind == 2) { wxString faceName; int faceIndex = childValue.GetLong(); - if ( faceIndex >= 0 ) + if (faceIndex >= 0) faceName = wxPGGlobalVars->m_fontFamilyChoices->GetLabel(faceIndex); - font.m_faceName = faceName; - } - else if ( ind == 3 ) - { + font.m_faceName = faceName; + } else if (ind == 3) { int st = childValue.GetLong(); - if (st != wxFONTSTYLE_NORMAL && st != wxFONTSTYLE_SLANT && st != wxFONTSTYLE_ITALIC) { - st = wxFONTSTYLE_NORMAL; - } - font.m_style = static_cast(st); - } - else if ( ind == 4 ) - { + if (st != wxFONTSTYLE_NORMAL && st != wxFONTSTYLE_SLANT && st != wxFONTSTYLE_ITALIC) { + st = wxFONTSTYLE_NORMAL; + } + font.m_style = static_cast(st); + } else if (ind == 4) { int wt = childValue.GetLong(); - if ( wt != wxFONTWEIGHT_NORMAL && - wt != wxFONTWEIGHT_LIGHT && - wt != wxFONTWEIGHT_BOLD ) - wt = wxFONTWEIGHT_NORMAL; - font.m_weight = static_cast(wt); - } - else if ( ind == 5 ) - { - font.m_underlined = childValue.GetBool(); + if (wt != wxFONTWEIGHT_NORMAL && wt != wxFONTWEIGHT_LIGHT && wt != wxFONTWEIGHT_BOLD) + wt = wxFONTWEIGHT_NORMAL; + font.m_weight = static_cast(wt); + } else if (ind == 5) { + font.m_underlined = childValue.GetBool(); } - thisValue = WXVARIANT( TypeConv::FontToString( font ) ); + thisValue = WXVARIANT(TypeConv::FontToString(font)); - return thisValue; + return thisValue; } diff --git a/src/rad/inspector/wxfbadvprops.h b/src/rad/inspector/wxfbadvprops.h index 99452efef..ff90a5bd9 100644 --- a/src/rad/inspector/wxfbadvprops.h +++ b/src/rad/inspector/wxfbadvprops.h @@ -26,13 +26,15 @@ // This code was part of previous objtree.cpp version. // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_INSPECTOR_WXFBADVPROPS_H #define RAD_INSPECTOR_WXFBADVPROPS_H +#include +#include + #include -#include -#include // ----------------------------------------------------------------------- // wxFBSizeProperty @@ -40,19 +42,17 @@ class wxFBSizeProperty : public wxPGProperty { - WX_PG_DECLARE_PROPERTY_CLASS( wxFBSizeProperty ) + WX_PG_DECLARE_PROPERTY_CLASS(wxFBSizeProperty) public: - wxFBSizeProperty( const wxString& label = wxPG_LABEL, - const wxString& name = wxPG_LABEL, - const wxSize& value = wxSize() ); + wxFBSizeProperty( + const wxString& label = wxPG_LABEL, const wxString& name = wxPG_LABEL, const wxSize& value = wxSize()); - wxVariant ChildChanged(wxVariant& thisValue, int childIndex, - wxVariant& childValue) const override; + wxVariant ChildChanged(wxVariant& thisValue, int childIndex, wxVariant& childValue) const override; - void RefreshChildren() override; + void RefreshChildren() override; protected: - void DoSetValue( const wxSize& value ) { m_value = WXVARIANT( value ); } + void DoSetValue(const wxSize& value) { m_value = WXVARIANT(value); } }; // ----------------------------------------------------------------------- @@ -61,20 +61,18 @@ class wxFBSizeProperty : public wxPGProperty class wxFBPointProperty : public wxPGProperty { - WX_PG_DECLARE_PROPERTY_CLASS( wxFBPointProperty ) + WX_PG_DECLARE_PROPERTY_CLASS(wxFBPointProperty) public: - wxFBPointProperty( const wxString& label = wxPG_LABEL, - const wxString& name = wxPG_LABEL, - const wxPoint& value = wxPoint() ); - ~wxFBPointProperty() override; + wxFBPointProperty( + const wxString& label = wxPG_LABEL, const wxString& name = wxPG_LABEL, const wxPoint& value = wxPoint()); + ~wxFBPointProperty() override; - wxVariant ChildChanged(wxVariant& thisValue, int childIndex, - wxVariant& childValue) const override; + wxVariant ChildChanged(wxVariant& thisValue, int childIndex, wxVariant& childValue) const override; - void RefreshChildren() override; + void RefreshChildren() override; protected: - void DoSetValue( const wxPoint& value ) { m_value = WXVARIANT( value ); } + void DoSetValue(const wxPoint& value) { m_value = WXVARIANT(value); } }; // ----------------------------------------------------------------------- @@ -83,45 +81,41 @@ class wxFBPointProperty : public wxPGProperty class wxFBBitmapProperty : public wxPGProperty { - WX_PG_DECLARE_PROPERTY_CLASS( wxFBBitmapProperty ) + WX_PG_DECLARE_PROPERTY_CLASS(wxFBBitmapProperty) public: - wxFBBitmapProperty( const wxString& label = wxPG_LABEL, - const wxString& name = wxPG_LABEL, - const wxString& value = wxString() ); + wxFBBitmapProperty( + const wxString& label = wxPG_LABEL, const wxString& name = wxPG_LABEL, const wxString& value = wxString()); - ~wxFBBitmapProperty() override; + ~wxFBBitmapProperty() override; - wxPGProperty *CreatePropertySource( int sourceIndex = 0 ); - wxPGProperty *CreatePropertyFilePath() ; - wxPGProperty *CreatePropertyResourceName(); - wxPGProperty *CreatePropertyIconSize(); - wxPGProperty *CreatePropertyXrcName(); - wxPGProperty *CreatePropertyArtId(); - wxPGProperty *CreatePropertyArtClient(); + wxPGProperty* CreatePropertySource(int sourceIndex = 0); + wxPGProperty* CreatePropertyFilePath(); + wxPGProperty* CreatePropertyResourceName(); + wxPGProperty* CreatePropertyIconSize(); + wxPGProperty* CreatePropertyXrcName(); + wxPGProperty* CreatePropertyArtId(); + wxPGProperty* CreatePropertyArtClient(); - wxString SetupImage( const wxString &imgPath = wxEmptyString ) ; - wxString SetupResource( const wxString &resName = wxEmptyString ) ; + wxString SetupImage(const wxString& imgPath = wxEmptyString); + wxString SetupResource(const wxString& resName = wxEmptyString); - int prevSrc; - void SetPrevSource(int src){prevSrc = src;} + int prevSrc; + void SetPrevSource(int src) { prevSrc = src; } - wxVariant ChildChanged(wxVariant& thisValue, int childIndex, - wxVariant& childValue) const override; + wxVariant ChildChanged(wxVariant& thisValue, int childIndex, wxVariant& childValue) const override; - void OnSetValue() override; - void CreateChildren(); + void OnSetValue() override; + void CreateChildren(); - void UpdateChildValues(const wxString& value); -protected: + void UpdateChildValues(const wxString& value); - void GetChildValues( const wxString& parentValue, wxArrayString& childValues ) const; +protected: + void GetChildValues(const wxString& parentValue, wxArrayString& childValues) const; static wxArrayString m_ids; static wxArrayString m_clients; wxArrayString m_strings; - - }; // ----------------------------------------------------------------------- @@ -141,28 +135,23 @@ class wxFBBitmapProperty : public wxPGProperty class wxPGSliderEditor : public wxPGEditor { - wxDECLARE_DYNAMIC_CLASS( wxPGSliderEditor ); + wxDECLARE_DYNAMIC_CLASS(wxPGSliderEditor); + public: - wxPGSliderEditor() - : - m_max( 10000 ) - { - } - - ~wxPGSliderEditor() override; - wxPGWindowList CreateControls(wxPropertyGrid* propgrid, wxPGProperty* property, - const wxPoint& pos, const wxSize& size) const override; - void UpdateControl(wxPGProperty* property, wxWindow* wnd) const override; - bool OnEvent(wxPropertyGrid* propgrid, wxPGProperty* property, wxWindow* wnd, - wxEvent& event) const override; - bool GetValueFromControl(wxVariant& variant, wxPGProperty* property, - wxWindow* ctrl) const override; - void SetValueToUnspecified(wxPGProperty* property, wxWindow* ctrl) const override; + wxPGSliderEditor() : m_max(10000) {} + + ~wxPGSliderEditor() override; + wxPGWindowList CreateControls( + wxPropertyGrid* propgrid, wxPGProperty* property, const wxPoint& pos, const wxSize& size) const override; + void UpdateControl(wxPGProperty* property, wxWindow* wnd) const override; + bool OnEvent(wxPropertyGrid* propgrid, wxPGProperty* property, wxWindow* wnd, wxEvent& event) const override; + bool GetValueFromControl(wxVariant& variant, wxPGProperty* property, wxWindow* ctrl) const override; + void SetValueToUnspecified(wxPGProperty* property, wxWindow* ctrl) const override; private: int m_max; }; -#endif // wxUSE_SLIDER +#endif // wxUSE_SLIDER // ----------------------------------------------------------------------- // wxFBFontProperty @@ -172,19 +161,19 @@ class wxFBFontProperty : public wxPGProperty { WX_PG_DECLARE_PROPERTY_CLASS(wxFBFontProperty) public: + wxFBFontProperty( + const wxString& label = wxPG_LABEL, const wxString& name = wxPG_LABEL, + const wxFontContainer& value = *wxNORMAL_FONT); + ~wxFBFontProperty() override; - wxFBFontProperty( const wxString& label = wxPG_LABEL, const wxString& name = wxPG_LABEL, const wxFontContainer& value = *wxNORMAL_FONT); - ~wxFBFontProperty() override; - - wxVariant ChildChanged(wxVariant& thisValue, int childIndex, - wxVariant& childValue) const override; + wxVariant ChildChanged(wxVariant& thisValue, int childIndex, wxVariant& childValue) const override; - void RefreshChildren() override; + void RefreshChildren() override; - void OnSetValue() override; - wxString GetValueAsString(int argFlags = 0) const override; + void OnSetValue() override; + wxString GetValueAsString(int argFlags = 0) const override; - bool OnEvent(wxPropertyGrid* propgrid, wxWindow* primary, wxEvent& event) override; + bool OnEvent(wxPropertyGrid* propgrid, wxWindow* primary, wxEvent& event) override; }; -#endif // RAD_INSPECTOR_WXFBADVPROPS_H +#endif // RAD_INSPECTOR_WXFBADVPROPS_H diff --git a/src/rad/luapanel/luapanel.cpp b/src/rad/luapanel/luapanel.cpp index 01db6f51d..eb284eeb6 100644 --- a/src/rad/luapanel/luapanel.cpp +++ b/src/rad/luapanel/luapanel.cpp @@ -27,335 +27,302 @@ #include "luapanel.h" +#include +#include + +#include "codegen/codewriter.h" +#include "codegen/luacg.h" +#include "model/objectbase.h" #include "rad/appdata.h" #include "rad/codeeditor/codeeditor.h" #include "rad/wxfbevent.h" - #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "model/objectbase.h" -#include "codegen/codewriter.h" -#include "codegen/luacg.h" +BEGIN_EVENT_TABLE(LuaPanel, wxPanel) +EVT_FB_CODE_GENERATION(LuaPanel::OnCodeGeneration) +EVT_FB_PROJECT_REFRESH(LuaPanel::OnProjectRefresh) +EVT_FB_PROPERTY_MODIFIED(LuaPanel::OnPropertyModified) +EVT_FB_OBJECT_CREATED(LuaPanel::OnObjectChange) +EVT_FB_OBJECT_REMOVED(LuaPanel::OnObjectChange) +EVT_FB_OBJECT_SELECTED(LuaPanel::OnObjectChange) +EVT_FB_EVENT_HANDLER_MODIFIED(LuaPanel::OnEventHandlerModified) -#include - -#include - -BEGIN_EVENT_TABLE ( LuaPanel, wxPanel ) - EVT_FB_CODE_GENERATION( LuaPanel::OnCodeGeneration ) - EVT_FB_PROJECT_REFRESH( LuaPanel::OnProjectRefresh ) - EVT_FB_PROPERTY_MODIFIED( LuaPanel::OnPropertyModified ) - EVT_FB_OBJECT_CREATED( LuaPanel::OnObjectChange ) - EVT_FB_OBJECT_REMOVED( LuaPanel::OnObjectChange ) - EVT_FB_OBJECT_SELECTED( LuaPanel::OnObjectChange ) - EVT_FB_EVENT_HANDLER_MODIFIED( LuaPanel::OnEventHandlerModified ) - - EVT_FIND( wxID_ANY, LuaPanel::OnFind ) - EVT_FIND_NEXT( wxID_ANY, LuaPanel::OnFind ) +EVT_FIND(wxID_ANY, LuaPanel::OnFind) +EVT_FIND_NEXT(wxID_ANY, LuaPanel::OnFind) END_EVENT_TABLE() -LuaPanel::LuaPanel( wxWindow *parent, int id ) -: -wxPanel( parent, id ) + +LuaPanel::LuaPanel(wxWindow* parent, int id) : wxPanel(parent, id) { - AppData()->AddHandler( this->GetEventHandler() ); - wxBoxSizer *top_sizer = new wxBoxSizer( wxVERTICAL ); + AppData()->AddHandler(this->GetEventHandler()); + wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); - m_luaPanel = new CodeEditor( this, wxID_ANY); - InitStyledTextCtrl( m_luaPanel->GetTextCtrl() ); + m_luaPanel = new CodeEditor(this, wxID_ANY); + InitStyledTextCtrl(m_luaPanel->GetTextCtrl()); - top_sizer->Add( m_luaPanel, 1, wxEXPAND, 0 ); + top_sizer->Add(m_luaPanel, 1, wxEXPAND, 0); - SetSizer( top_sizer ); - SetAutoLayout( true ); - //top_sizer->SetSizeHints( this ); - top_sizer->Fit( this ); - top_sizer->Layout(); + SetSizer(top_sizer); + SetAutoLayout(true); + // top_sizer->SetSizeHints( this ); + top_sizer->Fit(this); + top_sizer->Layout(); - m_luaCW = PTCCodeWriter( new TCCodeWriter( m_luaPanel->GetTextCtrl() ) ); + m_luaCW = PTCCodeWriter(new TCCodeWriter(m_luaPanel->GetTextCtrl())); } LuaPanel::~LuaPanel() { - //delete m_icons; - AppData()->RemoveHandler( this->GetEventHandler() ); + // delete m_icons; + AppData()->RemoveHandler(this->GetEventHandler()); } -void LuaPanel::InitStyledTextCtrl( wxStyledTextCtrl *stc ) +void LuaPanel::InitStyledTextCtrl(wxStyledTextCtrl* stc) { - stc->SetLexer( wxSTC_LEX_LUA ); - stc->SetKeyWords( 0, wxT( "and assert break class continue def del elif else \ + stc->SetLexer(wxSTC_LEX_LUA); + stc->SetKeyWords(0, wxT("and assert break class continue def del elif else \ except exec finally for from global if import in \ - is lambda not or pass print raise return try while" ) ); + is lambda not or pass print raise return try while")); #ifdef __WXGTK__ - wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - font.SetFaceName( wxT( "Monospace" ) ); + wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + font.SetFaceName(wxT("Monospace")); #else - wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); #endif - stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); - stc->StyleSetFont( wxSTC_STYLE_DEFAULT, font ); + stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); + stc->StyleSetFont(wxSTC_STYLE_DEFAULT, font); stc->StyleClearAll(); - stc->StyleSetBold( wxSTC_C_WORD, true ); - if (!AppData()->IsDarkMode()) - { - stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); - stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); - } - else - { - stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); - stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); - } - stc->SetUseTabs( true ); - stc->SetTabWidth( 4 ); - stc->SetTabIndents( true ); - stc->SetBackSpaceUnIndents( true ); - stc->SetIndent( 4 ); - stc->SetSelBackground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) ); - stc->SetSelForeground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) ); - - stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->SetCaretWidth( 2 ); - stc->SetReadOnly( true ); + stc->StyleSetBold(wxSTC_C_WORD, true); + if (!AppData()->IsDarkMode()) { + stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); + stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); + } else { + stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); + stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); + } + stc->SetUseTabs(true); + stc->SetTabWidth(4); + stc->SetTabIndents(true); + stc->SetBackSpaceUnIndents(true); + stc->SetIndent(4); + stc->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); + stc->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); + + stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->SetCaretWidth(2); + stc->SetReadOnly(true); } -void LuaPanel::OnFind( wxFindDialogEvent& event ) +void LuaPanel::OnFind(wxFindDialogEvent& event) { - m_luaPanel->GetEventHandler()->ProcessEvent( event ); + m_luaPanel->GetEventHandler()->ProcessEvent(event); } -void LuaPanel::OnPropertyModified( wxFBPropertyEvent& event ) +void LuaPanel::OnPropertyModified(wxFBPropertyEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void LuaPanel::OnProjectRefresh( wxFBEvent& event ) +void LuaPanel::OnProjectRefresh(wxFBEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void LuaPanel::OnObjectChange( wxFBObjectEvent& event ) +void LuaPanel::OnObjectChange(wxFBObjectEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void LuaPanel::OnEventHandlerModified( wxFBEventHandlerEvent& event ) +void LuaPanel::OnEventHandlerModified(wxFBEventHandlerEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void LuaPanel::OnCodeGeneration( wxFBEvent& event ) +void LuaPanel::OnCodeGeneration(wxFBEvent& event) { PObjectBase objectToGenerate; - // Generate code in the panel if the panel is active - bool doPanel = IsShown(); - - // Using the previously unused Id field in the event to carry a boolean - bool panelOnly = ( event.GetId() != 0 ); - - // Only generate to panel + panel is not shown = do nothing - if ( panelOnly && !doPanel ) - { - return; - } - - // For code preview generate only code relevant to selected form, - // otherwise generate full project code. - - // Create copy of the original project due to possible temporary modifications - PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); - - if(panelOnly) - { - objectToGenerate = AppData()->GetSelectedForm(); - } - - if(!panelOnly || !objectToGenerate) - { - objectToGenerate = project; - } - - // If only one project item should be generated then remove the rest items - // from the temporary project - if(doPanel && panelOnly && (objectToGenerate != project)) - { - if( project->GetChildCount() > 0) - { - unsigned int i = 0; - while( project->GetChildCount() > 1 ) - { - if(project->GetChild( i ) != objectToGenerate) - { - project->RemoveChild( i ); - } - else + // Generate code in the panel if the panel is active + bool doPanel = IsShown(); + + // Using the previously unused Id field in the event to carry a boolean + bool panelOnly = (event.GetId() != 0); + + // Only generate to panel + panel is not shown = do nothing + if (panelOnly && !doPanel) { + return; + } + + // For code preview generate only code relevant to selected form, + // otherwise generate full project code. + + // Create copy of the original project due to possible temporary modifications + PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); + + if (panelOnly) { + objectToGenerate = AppData()->GetSelectedForm(); + } + + if (!panelOnly || !objectToGenerate) { + objectToGenerate = project; + } + + // If only one project item should be generated then remove the rest items + // from the temporary project + if (doPanel && panelOnly && (objectToGenerate != project)) { + if (project->GetChildCount() > 0) { + unsigned int i = 0; + while (project->GetChildCount() > 1) { + if (project->GetChild(i) != objectToGenerate) { + project->RemoveChild(i); + } else i++; } - } - } + } + } - if(!project || !objectToGenerate)return; + if (!project || !objectToGenerate) + return; // Get Lua properties from the project - // If Lua generation is not enabled, do not generate the file - bool doFile = false; - PProperty pCodeGen = project->GetProperty( wxT( "code_generation" ) ); - if ( pCodeGen ) - { - doFile = TypeConv::FlagSet( wxT("Lua"), pCodeGen->GetValue() ) && !panelOnly; - } - - if ( !(doPanel || doFile ) ) - { - return; - } - - // Get First ID from Project File - unsigned int firstID = 1000; - PProperty pFirstID = project->GetProperty( wxT("first_id") ); - if ( pFirstID ) - { - firstID = pFirstID->GetValueAsInteger(); - } - - // Get the file name - wxString file; - PProperty pfile = project->GetProperty( wxT( "file" ) ); - if ( pfile ) - { - file = pfile->GetValue(); - } - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Determine if the path is absolute or relative - bool useRelativePath = false; - PProperty pRelPath = project->GetProperty( wxT( "relative_path" ) ); - if ( pRelPath ) - { - useRelativePath = ( pRelPath->GetValueAsInteger() ? true : false ); - } - - // Get the output path - wxString path; - try - { - path = AppData()->GetOutputPath(); - } - catch ( wxFBException& ex ) - { - if ( doFile ) - { - path = wxEmptyString; - wxLogWarning( ex.what() ); - return; - } - } - - // Generate code in the panel - if ( doPanel ) - { - LuaCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - codegen.SetSourceWriter( m_luaCW ); - - Freeze(); + // If Lua generation is not enabled, do not generate the file + bool doFile = false; + PProperty pCodeGen = project->GetProperty(wxT("code_generation")); + if (pCodeGen) { + doFile = TypeConv::FlagSet(wxT("Lua"), pCodeGen->GetValue()) && !panelOnly; + } + + if (!(doPanel || doFile)) { + return; + } + + // Get First ID from Project File + unsigned int firstID = 1000; + PProperty pFirstID = project->GetProperty(wxT("first_id")); + if (pFirstID) { + firstID = pFirstID->GetValueAsInteger(); + } + + // Get the file name + wxString file; + PProperty pfile = project->GetProperty(wxT("file")); + if (pfile) { + file = pfile->GetValue(); + } + if (file.empty()) { + file = wxT("noname"); + } + + // Determine if the path is absolute or relative + bool useRelativePath = false; + PProperty pRelPath = project->GetProperty(wxT("relative_path")); + if (pRelPath) { + useRelativePath = (pRelPath->GetValueAsInteger() ? true : false); + } + + // Get the output path + wxString path; + try { + path = AppData()->GetOutputPath(); + } catch (wxFBException& ex) { + if (doFile) { + path = wxEmptyString; + wxLogWarning(ex.what()); + return; + } + } + + // Generate code in the panel + if (doPanel) { + LuaCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + codegen.SetSourceWriter(m_luaCW); + + Freeze(); wxStyledTextCtrl* luaEditor = m_luaPanel->GetTextCtrl(); - luaEditor->SetReadOnly( false ); - int luaLine = luaEditor->GetFirstVisibleLine() + luaEditor->LinesOnScreen() - 1; - int luaXOffset = luaEditor->GetXOffset(); - - codegen.GenerateCode( project ); - - luaEditor->SetReadOnly( true ); - luaEditor->GotoLine( luaLine ); - luaEditor->SetXOffset( luaXOffset ); - luaEditor->SetAnchor( 0 ); - luaEditor->SetCurrentPos( 0 ); - - Thaw(); - } - - // Generate code in the file - if ( doFile ) - { - try - { - LuaCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - // Determine if Microsoft BOM should be used - bool useMicrosoftBOM = false; - - PProperty pUseMicrosoftBOM = project->GetProperty( wxT( "use_microsoft_bom" ) ); - - if ( pUseMicrosoftBOM ) - { - useMicrosoftBOM = ( pUseMicrosoftBOM->GetValueAsInteger() != 0 ); - } - - // Determine if Utf8 or Ansi is to be created - bool useUtf8 = false; - PProperty pUseUtf8 = project->GetProperty( _("encoding") ); - - if ( pUseUtf8 ) - { - useUtf8 = ( pUseUtf8->GetValueAsString() != wxT("ANSI") ); - } - - PCodeWriter lua_cw( new FileCodeWriter( path + file + wxT( ".lua" ), useMicrosoftBOM, useUtf8 ) ); - - codegen.SetSourceWriter( lua_cw ); - codegen.GenerateCode( project ); - wxLogStatus( wxT( "Code generated on \'%s\'." ), path ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } + luaEditor->SetReadOnly(false); + int luaLine = luaEditor->GetFirstVisibleLine() + luaEditor->LinesOnScreen() - 1; + int luaXOffset = luaEditor->GetXOffset(); + + codegen.GenerateCode(project); + + luaEditor->SetReadOnly(true); + luaEditor->GotoLine(luaLine); + luaEditor->SetXOffset(luaXOffset); + luaEditor->SetAnchor(0); + luaEditor->SetCurrentPos(0); + + Thaw(); + } + + // Generate code in the file + if (doFile) { + try { + LuaCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + // Determine if Microsoft BOM should be used + bool useMicrosoftBOM = false; + + PProperty pUseMicrosoftBOM = project->GetProperty(wxT("use_microsoft_bom")); + + if (pUseMicrosoftBOM) { + useMicrosoftBOM = (pUseMicrosoftBOM->GetValueAsInteger() != 0); + } + + // Determine if Utf8 or Ansi is to be created + bool useUtf8 = false; + PProperty pUseUtf8 = project->GetProperty(_("encoding")); + + if (pUseUtf8) { + useUtf8 = (pUseUtf8->GetValueAsString() != wxT("ANSI")); + } + + PCodeWriter lua_cw(new FileCodeWriter(path + file + wxT(".lua"), useMicrosoftBOM, useUtf8)); + + codegen.SetSourceWriter(lua_cw); + codegen.GenerateCode(project); + wxLogStatus(wxT("Code generated on \'%s\'."), path); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } } diff --git a/src/rad/luapanel/luapanel.h b/src/rad/luapanel/luapanel.h index 06bb5ab9b..9fa9c23fd 100644 --- a/src/rad/luapanel/luapanel.h +++ b/src/rad/luapanel/luapanel.h @@ -35,42 +35,41 @@ #ifndef RAD_LUAPANEL_LUAPANEL_H #define RAD_LUAPANEL_LUAPANEL_H -#include "utils/wxfbdefs.h" - #include -class CodeEditor; - -class wxStyledTextCtrl; +#include "utils/wxfbdefs.h" -class wxFindDialogEvent; +class CodeEditor; class wxFBEvent; -class wxFBPropertyEvent; -class wxFBObjectEvent; class wxFBEventHandlerEvent; +class wxFBObjectEvent; +class wxFBPropertyEvent; +class wxFindDialogEvent; +class wxStyledTextCtrl; + class LuaPanel : public wxPanel { private: - CodeEditor* m_luaPanel; - PTCCodeWriter m_luaCW; + CodeEditor* m_luaPanel; + PTCCodeWriter m_luaCW; - void InitStyledTextCtrl( wxStyledTextCtrl* stc ); + void InitStyledTextCtrl(wxStyledTextCtrl* stc); public: - LuaPanel( wxWindow *parent, int id ); - ~LuaPanel() override; + LuaPanel(wxWindow* parent, int id); + ~LuaPanel() override; - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - void OnCodeGeneration( wxFBEvent& event ); - void OnObjectChange( wxFBObjectEvent& event ); - void OnEventHandlerModified( wxFBEventHandlerEvent& event ); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnCodeGeneration(wxFBEvent& event); + void OnObjectChange(wxFBObjectEvent& event); + void OnEventHandlerModified(wxFBEventHandlerEvent& event); - void OnFind( wxFindDialogEvent& event ); + void OnFind(wxFindDialogEvent& event); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; -#endif // RAD_LUAPANEL_LUAPANEL_H +#endif // RAD_LUAPANEL_LUAPANEL_H diff --git a/src/rad/mainframe.cpp b/src/rad/mainframe.cpp index ace901517..b9b847f23 100644 --- a/src/rad/mainframe.cpp +++ b/src/rad/mainframe.cpp @@ -23,19 +23,19 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "mainframe.h" +#include + #include "model/xrcfilter.h" -#include "utils/stringutils.h" -#include "utils/wxfbexception.h" -#include "rad/revision.h" -#include "rad/version.h" #include "rad/about.h" #include "rad/appdata.h" #include "rad/auitabart.h" #include "rad/bitmaps.h" #include "rad/cpppanel/cpppanel.h" #include "rad/designer/visualeditor.h" +#include "rad/dialogfindcomponent.h" #include "rad/geninheritclass/geninhertclass.h" #include "rad/inspector/objinspect.h" #include "rad/luapanel/luapanel.h" @@ -43,331 +43,334 @@ #include "rad/palette.h" #include "rad/phppanel/phppanel.h" #include "rad/pythonpanel/pythonpanel.h" +#include "rad/revision.h" #include "rad/title.h" -#include +#include "rad/version.h" #include "rad/wxfbevent.h" #include "rad/wxfbmanager.h" #include "rad/xrcpanel/xrcpanel.h" -#include "rad/dialogfindcomponent.h" +#include "utils/stringutils.h" +#include "utils/wxfbexception.h" -enum -{ - ID_SAVE_PRJ = wxID_HIGHEST + 1, - ID_OPEN_PRJ, - ID_NEW_PRJ, - ID_GENERATE_CODE, - ID_IMPORT_XRC, - ID_UNDO, - ID_REDO, - ID_SAVE_AS_PRJ, - ID_CUT, - ID_DELETE, - ID_COPY, - ID_PASTE, - ID_EXPAND, - ID_STRETCH, - ID_MOVE_UP, - ID_MOVE_DOWN, - ID_RECENT_0, // Tienen que tener ids consecutivos - ID_RECENT_1, // ID_RECENT_n+1 == ID_RECENT_n + 1 - ID_RECENT_2, // - ID_RECENT_3, // - ID_RECENT_SEP, - - ID_ALIGN_LEFT, - ID_ALIGN_CENTER_H, - ID_ALIGN_RIGHT, - ID_ALIGN_TOP, - ID_ALIGN_CENTER_V, - ID_ALIGN_BOTTOM, - - ID_BORDER_LEFT, - ID_BORDER_RIGHT, - ID_BORDER_TOP, - ID_BORDER_BOTTOM, - ID_EDITOR_FNB, - ID_MOVE_LEFT, - ID_MOVE_RIGHT, - - ID_PREVIEW_XRC, - ID_GEN_INHERIT_CLS, - - // The preference dialog must use wxID_PREFERENCES for wxMAC - //ID_SETTINGS_GLOBAL, // For the future preference dialogs - ID_SETTINGS_PROJ, // For the future preference dialogs - - ID_FIND, - - ID_CLIPBOARD_COPY, - ID_CLIPBOARD_PASTE, - - //added by tyysoft to define the swap button ID. - ID_WINDOW_SWAP, - - //added by michallukowski to find component from menu. + +enum { + ID_SAVE_PRJ = wxID_HIGHEST + 1, + ID_OPEN_PRJ, + ID_NEW_PRJ, + ID_GENERATE_CODE, + ID_IMPORT_XRC, + ID_UNDO, + ID_REDO, + ID_SAVE_AS_PRJ, + ID_CUT, + ID_DELETE, + ID_COPY, + ID_PASTE, + ID_EXPAND, + ID_STRETCH, + ID_MOVE_UP, + ID_MOVE_DOWN, + ID_RECENT_0, // Tienen que tener ids consecutivos + ID_RECENT_1, // ID_RECENT_n+1 == ID_RECENT_n + 1 + ID_RECENT_2, // + ID_RECENT_3, // + ID_RECENT_SEP, + + ID_ALIGN_LEFT, + ID_ALIGN_CENTER_H, + ID_ALIGN_RIGHT, + ID_ALIGN_TOP, + ID_ALIGN_CENTER_V, + ID_ALIGN_BOTTOM, + + ID_BORDER_LEFT, + ID_BORDER_RIGHT, + ID_BORDER_TOP, + ID_BORDER_BOTTOM, + ID_EDITOR_FNB, + ID_MOVE_LEFT, + ID_MOVE_RIGHT, + + ID_PREVIEW_XRC, + ID_GEN_INHERIT_CLS, + + // The preference dialog must use wxID_PREFERENCES for wxMAC + // ID_SETTINGS_GLOBAL, // For the future preference dialogs + ID_SETTINGS_PROJ, // For the future preference dialogs + + ID_FIND, + + ID_CLIPBOARD_COPY, + ID_CLIPBOARD_PASTE, + + // added by tyysoft to define the swap button ID. + ID_WINDOW_SWAP, + + // added by michallukowski to find component from menu. ID_FIND_COMPONENT, }; #define STATUS_FIELD_OBJECT 2 #define STATUS_FIELD_PATH 1 -BEGIN_EVENT_TABLE( MainFrame, wxFrame ) -EVT_MENU( ID_NEW_PRJ, MainFrame::OnNewProject ) -EVT_MENU( ID_SAVE_PRJ, MainFrame::OnSaveProject ) -EVT_MENU( ID_SAVE_AS_PRJ, MainFrame::OnSaveAsProject ) -EVT_MENU( ID_OPEN_PRJ, MainFrame::OnOpenProject ) -EVT_MENU( wxID_ABOUT, MainFrame::OnAbout ) -EVT_MENU( wxID_EXIT, MainFrame::OnExit ) -EVT_MENU( ID_IMPORT_XRC, MainFrame::OnImportXrc ) -EVT_MENU( ID_GENERATE_CODE, MainFrame::OnGenerateCode ) -EVT_MENU( ID_UNDO, MainFrame::OnUndo ) -EVT_MENU( ID_REDO, MainFrame::OnRedo ) -EVT_MENU( ID_DELETE, MainFrame::OnDelete ) -EVT_MENU( ID_CUT, MainFrame::OnCut ) -EVT_MENU( ID_COPY, MainFrame::OnCopy ) -EVT_MENU( ID_PASTE, MainFrame::OnPaste ) -EVT_MENU( ID_EXPAND, MainFrame::OnToggleExpand ) -EVT_MENU( ID_STRETCH, MainFrame::OnToggleStretch ) -EVT_MENU( ID_MOVE_UP, MainFrame::OnMoveUp ) -EVT_MENU( ID_MOVE_DOWN, MainFrame::OnMoveDown ) -EVT_MENU( ID_MOVE_LEFT, MainFrame::OnMoveLeft ) -EVT_MENU( ID_MOVE_RIGHT, MainFrame::OnMoveRight ) -EVT_MENU( ID_RECENT_0, MainFrame::OnOpenRecent ) -EVT_MENU( ID_RECENT_1, MainFrame::OnOpenRecent ) -EVT_MENU( ID_RECENT_2, MainFrame::OnOpenRecent ) -EVT_MENU( ID_RECENT_3, MainFrame::OnOpenRecent ) -EVT_MENU( ID_ALIGN_RIGHT, MainFrame::OnChangeAlignment ) -EVT_MENU( ID_ALIGN_LEFT, MainFrame::OnChangeAlignment ) -EVT_MENU( ID_ALIGN_CENTER_H, MainFrame::OnChangeAlignment ) -EVT_MENU( ID_ALIGN_TOP, MainFrame::OnChangeAlignment ) -EVT_MENU( ID_ALIGN_BOTTOM, MainFrame::OnChangeAlignment ) -EVT_MENU( ID_ALIGN_CENTER_V, MainFrame::OnChangeAlignment ) -EVT_MENU_RANGE( ID_BORDER_LEFT, ID_BORDER_BOTTOM, MainFrame::OnChangeBorder ) -EVT_MENU( ID_PREVIEW_XRC, MainFrame::OnXrcPreview ) -EVT_MENU( ID_GEN_INHERIT_CLS, MainFrame::OnGenInhertedClass ) -EVT_MENU( ID_CLIPBOARD_COPY, MainFrame::OnClipboardCopy ) -EVT_MENU( ID_CLIPBOARD_PASTE, MainFrame::OnClipboardPaste ) -EVT_MENU( ID_WINDOW_SWAP, MainFrame::OnWindowSwap ) -EVT_MENU( ID_FIND_COMPONENT, MainFrame::OnFindComponent ) - -EVT_UPDATE_UI( ID_CLIPBOARD_PASTE, MainFrame::OnClipboardPasteUpdateUI ) -EVT_CLOSE( MainFrame::OnClose ) - -EVT_FB_CODE_GENERATION( MainFrame::OnCodeGeneration ) -EVT_FB_OBJECT_CREATED( MainFrame::OnObjectCreated ) -EVT_FB_OBJECT_REMOVED( MainFrame::OnObjectRemoved ) -EVT_FB_OBJECT_EXPANDED( MainFrame::OnObjectExpanded ) -EVT_FB_OBJECT_SELECTED( MainFrame::OnObjectSelected ) -EVT_FB_PROJECT_LOADED( MainFrame::OnProjectLoaded ) -EVT_FB_PROJECT_REFRESH( MainFrame::OnProjectRefresh ) -EVT_FB_PROJECT_SAVED( MainFrame::OnProjectSaved ) -EVT_FB_PROPERTY_MODIFIED( MainFrame::OnPropertyModified ) -EVT_FB_EVENT_HANDLER_MODIFIED( MainFrame::OnEventHandlerModified ) - -EVT_MENU( ID_FIND, MainFrame::OnFindDialog ) -EVT_FIND( wxID_ANY, MainFrame::OnFind ) -EVT_FIND_NEXT( wxID_ANY, MainFrame::OnFind ) -EVT_FIND_CLOSE( wxID_ANY, MainFrame::OnFindClose ) - +BEGIN_EVENT_TABLE(MainFrame, wxFrame) +EVT_MENU(ID_NEW_PRJ, MainFrame::OnNewProject) +EVT_MENU(ID_SAVE_PRJ, MainFrame::OnSaveProject) +EVT_MENU(ID_SAVE_AS_PRJ, MainFrame::OnSaveAsProject) +EVT_MENU(ID_OPEN_PRJ, MainFrame::OnOpenProject) +EVT_MENU(wxID_ABOUT, MainFrame::OnAbout) +EVT_MENU(wxID_EXIT, MainFrame::OnExit) +EVT_MENU(ID_IMPORT_XRC, MainFrame::OnImportXrc) +EVT_MENU(ID_GENERATE_CODE, MainFrame::OnGenerateCode) +EVT_MENU(ID_UNDO, MainFrame::OnUndo) +EVT_MENU(ID_REDO, MainFrame::OnRedo) +EVT_MENU(ID_DELETE, MainFrame::OnDelete) +EVT_MENU(ID_CUT, MainFrame::OnCut) +EVT_MENU(ID_COPY, MainFrame::OnCopy) +EVT_MENU(ID_PASTE, MainFrame::OnPaste) +EVT_MENU(ID_EXPAND, MainFrame::OnToggleExpand) +EVT_MENU(ID_STRETCH, MainFrame::OnToggleStretch) +EVT_MENU(ID_MOVE_UP, MainFrame::OnMoveUp) +EVT_MENU(ID_MOVE_DOWN, MainFrame::OnMoveDown) +EVT_MENU(ID_MOVE_LEFT, MainFrame::OnMoveLeft) +EVT_MENU(ID_MOVE_RIGHT, MainFrame::OnMoveRight) +EVT_MENU(ID_RECENT_0, MainFrame::OnOpenRecent) +EVT_MENU(ID_RECENT_1, MainFrame::OnOpenRecent) +EVT_MENU(ID_RECENT_2, MainFrame::OnOpenRecent) +EVT_MENU(ID_RECENT_3, MainFrame::OnOpenRecent) +EVT_MENU(ID_ALIGN_RIGHT, MainFrame::OnChangeAlignment) +EVT_MENU(ID_ALIGN_LEFT, MainFrame::OnChangeAlignment) +EVT_MENU(ID_ALIGN_CENTER_H, MainFrame::OnChangeAlignment) +EVT_MENU(ID_ALIGN_TOP, MainFrame::OnChangeAlignment) +EVT_MENU(ID_ALIGN_BOTTOM, MainFrame::OnChangeAlignment) +EVT_MENU(ID_ALIGN_CENTER_V, MainFrame::OnChangeAlignment) +EVT_MENU_RANGE(ID_BORDER_LEFT, ID_BORDER_BOTTOM, MainFrame::OnChangeBorder) +EVT_MENU(ID_PREVIEW_XRC, MainFrame::OnXrcPreview) +EVT_MENU(ID_GEN_INHERIT_CLS, MainFrame::OnGenInhertedClass) +EVT_MENU(ID_CLIPBOARD_COPY, MainFrame::OnClipboardCopy) +EVT_MENU(ID_CLIPBOARD_PASTE, MainFrame::OnClipboardPaste) +EVT_MENU(ID_WINDOW_SWAP, MainFrame::OnWindowSwap) +EVT_MENU(ID_FIND_COMPONENT, MainFrame::OnFindComponent) + +EVT_UPDATE_UI(ID_CLIPBOARD_PASTE, MainFrame::OnClipboardPasteUpdateUI) +EVT_CLOSE(MainFrame::OnClose) + +EVT_FB_CODE_GENERATION(MainFrame::OnCodeGeneration) +EVT_FB_OBJECT_CREATED(MainFrame::OnObjectCreated) +EVT_FB_OBJECT_REMOVED(MainFrame::OnObjectRemoved) +EVT_FB_OBJECT_EXPANDED(MainFrame::OnObjectExpanded) +EVT_FB_OBJECT_SELECTED(MainFrame::OnObjectSelected) +EVT_FB_PROJECT_LOADED(MainFrame::OnProjectLoaded) +EVT_FB_PROJECT_REFRESH(MainFrame::OnProjectRefresh) +EVT_FB_PROJECT_SAVED(MainFrame::OnProjectSaved) +EVT_FB_PROPERTY_MODIFIED(MainFrame::OnPropertyModified) +EVT_FB_EVENT_HANDLER_MODIFIED(MainFrame::OnEventHandlerModified) + +EVT_MENU(ID_FIND, MainFrame::OnFindDialog) +EVT_FIND(wxID_ANY, MainFrame::OnFind) +EVT_FIND_NEXT(wxID_ANY, MainFrame::OnFind) +EVT_FIND_CLOSE(wxID_ANY, MainFrame::OnFindClose) END_EVENT_TABLE() + // Used to kill focus from propgrid when toolbar or menu items are clicked // This forces the propgrid to save the cell being edited class FocusKillerEvtHandler : public wxEvtHandler { public: - void OnMenuEvent( wxCommandEvent& event ) - { - // Get window with focus - wxWindow* windowWithFocus = wxWindow::FindFocus(); - - // Only send the event if the focus is on the propgrid - while ( windowWithFocus != NULL ) - { - wxPropertyGrid* propgrid = wxDynamicCast( windowWithFocus, wxPropertyGrid ); - if ( propgrid != NULL ) - { - wxFocusEvent focusEvent( wxEVT_KILL_FOCUS ); - propgrid->GetEventHandler()->ProcessEvent( focusEvent ); - break; - } - windowWithFocus = windowWithFocus->GetParent(); - } - - // Add the event to the mainframe's original handler - // Add as pending so propgrid saves the property before the event is processed - GetNextHandler()->AddPendingEvent( event ); - } - - DECLARE_EVENT_TABLE() -}; - -BEGIN_EVENT_TABLE( FocusKillerEvtHandler, wxEvtHandler ) - EVT_MENU( wxID_ANY, FocusKillerEvtHandler::OnMenuEvent ) -END_EVENT_TABLE() - -MainFrame::MainFrame( wxWindow *parent, int id, int style, wxPoint pos, wxSize size ) -: -wxFrame( parent, id, wxEmptyString, pos, size, wxDEFAULT_FRAME_STYLE ), -m_leftSplitterWidth( 300 ), -m_rightSplitterWidth( -300 ), -m_style( style ), -m_page_selection( 0 ), -m_rightSplitter_sash_pos( 300 ), -m_autoSash( false ), // autosash function is temporarily disabled due to possible bug(?) in wxMSW event system (workaround is needed) -m_findData( wxFR_DOWN ), -m_findDialog( NULL ) -{ - - // initialize the splitters, wxAUI doesn't use them - m_leftSplitter = m_rightSplitter = NULL; - - ///////////////////////////////////////////////////////////////////////////// - // Setup frame icons, title bar, status bar, menubar and toolbar - ///////////////////////////////////////////////////////////////////////////// - wxIconBundle bundle; - wxIcon ico16; - ico16.CopyFromBitmap( AppBitmaps::GetBitmap( wxT( "app16" ), 16 ) ); - bundle.AddIcon( ico16 ); - - wxIcon ico32; - ico32.CopyFromBitmap( AppBitmaps::GetBitmap( wxT( "app32" ), 32 ) ); - bundle.AddIcon( ico32 ); - - SetIcons( bundle ); - - SetTitle( wxT( "wxFormBuilder" ) ); - - //SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) ); - - SetMenuBar( CreateFBMenuBar() ); - CreateStatusBar( 3 ); - SetStatusBarPane( 0 ); - int widths[3] = { -1, -1, 300 }; - SetStatusWidths( sizeof( widths ) / sizeof( int ), widths ); - CreateFBToolBar(); - - ///////////////////////////////////////////////////////////////////////////// - // Create the gui - ///////////////////////////////////////////////////////////////////////////// - - /* - // --- wxAUI version -- - wxWindow *objectTree = CreateObjectTree(this); - wxWindow *objectInspector = CreateObjectInspector(this); - wxWindow *palette = CreateComponentPalette(this); - wxWindow *designer = CreateDesignerWindow(this); - - - m_mgr.SetFrame(this); - m_mgr.AddPane(objectTree, - wxPaneInfo().Name(wxT("tree")). - Caption(wxT("Object Tree")). - Left().Layer(1). - BestSize(wxSize(300,400)). - CloseButton(false)); - m_mgr.AddPane(objectInspector, - wxPaneInfo().Name(wxT("inspector")). - Caption(wxT("Object Properties")). - Right().BestSize(wxSize(300,400)). - CloseButton(false)); - - m_mgr.AddPane(designer, - wxPaneInfo().Name(wxT("editor")). - Caption(wxT("Editor")). - Center(). - CloseButton(false)); - - m_mgr.AddPane(palette, - wxPaneInfo().Name(wxT("palette")). - Caption(wxT("Component Palette")). - Top(). - RightDockable(false). - LeftDockable(false). - CloseButton(false)); - - m_mgr.Update();*/ - - RestorePosition( wxT( "mainframe" ) ); - Layout(); - - // Init. m_cpp and m_xrc first - m_cpp = NULL; - m_xrc = NULL; - m_python = NULL; - m_lua = NULL; - m_php = NULL; - - switch ( style ) - { - - case wxFB_DOCKABLE_GUI: - // TO-DO - CreateWideGui(); - - break; - - case wxFB_CLASSIC_GUI: - - /* // --- Classic style Gui -- - // - // +------++-----------------------+ - // | Obj. || Palette | - // | Tree ++-----------------------+ - // | || Editor | - // |______|| | - // |------|| | - // | Obj. || | - // | Insp.|| | - // | || | - // | || | - // +------++-----------------------+ */ - - CreateClassicGui(); - - break; - - case wxFB_DEFAULT_GUI: + void OnMenuEvent(wxCommandEvent& event) + { + // Get window with focus + wxWindow* windowWithFocus = wxWindow::FindFocus(); + + // Only send the event if the focus is on the propgrid + while (windowWithFocus != NULL) { + wxPropertyGrid* propgrid = wxDynamicCast(windowWithFocus, wxPropertyGrid); + if (propgrid != NULL) { + wxFocusEvent focusEvent(wxEVT_KILL_FOCUS); + propgrid->GetEventHandler()->ProcessEvent(focusEvent); + break; + } + windowWithFocus = windowWithFocus->GetParent(); + } - case wxFB_WIDE_GUI: + // Add the event to the mainframe's original handler + // Add as pending so propgrid saves the property before the event is processed + GetNextHandler()->AddPendingEvent(event); + } - default: + DECLARE_EVENT_TABLE() +}; - /* // --- Wide style Gui -- - // - // +------++-----------------------+ - // | Obj. || Palette | - // | Tree ++-------------++--------+ - // | || Editor || Obj. | - // | || || Insp. | - // | || || | - // | || || | - // | || || | - // | || || | - // | || || | - // +------++-------------++--------+ */ +BEGIN_EVENT_TABLE(FocusKillerEvtHandler, wxEvtHandler) +EVT_MENU(wxID_ANY, FocusKillerEvtHandler::OnMenuEvent) +END_EVENT_TABLE() - CreateWideGui(); - } - AppData()->AddHandler( this->GetEventHandler() ); +MainFrame::MainFrame(wxWindow* parent, int id, int style, wxPoint pos, wxSize size) : + wxFrame(parent, id, wxEmptyString, pos, size, wxDEFAULT_FRAME_STYLE), + m_leftSplitterWidth(300), + m_rightSplitterWidth(-300), + m_style(style), + m_page_selection(0), + m_rightSplitter_sash_pos(300), + m_autoSash(false), // autosash function is temporarily disabled due to possible bug(?) in wxMSW event system + // (workaround is needed) + m_findData(wxFR_DOWN), + m_findDialog(NULL) +{ + + // initialize the splitters, wxAUI doesn't use them + m_leftSplitter = m_rightSplitter = NULL; + + ///////////////////////////////////////////////////////////////////////////// + // Setup frame icons, title bar, status bar, menubar and toolbar + ///////////////////////////////////////////////////////////////////////////// + wxIconBundle bundle; + wxIcon ico16; + ico16.CopyFromBitmap(AppBitmaps::GetBitmap(wxT("app16"), 16)); + bundle.AddIcon(ico16); + + wxIcon ico32; + ico32.CopyFromBitmap(AppBitmaps::GetBitmap(wxT("app32"), 32)); + bundle.AddIcon(ico32); + + SetIcons(bundle); + + SetTitle(wxT("wxFormBuilder")); + + // SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) ); + + SetMenuBar(CreateFBMenuBar()); + CreateStatusBar(3); + SetStatusBarPane(0); + int widths[3] = {-1, -1, 300}; + SetStatusWidths(sizeof(widths) / sizeof(int), widths); + CreateFBToolBar(); + + ///////////////////////////////////////////////////////////////////////////// + // Create the gui + ///////////////////////////////////////////////////////////////////////////// + + /* + // --- wxAUI version -- + wxWindow *objectTree = CreateObjectTree(this); + wxWindow *objectInspector = CreateObjectInspector(this); + wxWindow *palette = CreateComponentPalette(this); + wxWindow *designer = CreateDesignerWindow(this); + + + m_mgr.SetFrame(this); + m_mgr.AddPane(objectTree, + wxPaneInfo().Name(wxT("tree")). + Caption(wxT("Object Tree")). + Left().Layer(1). + BestSize(wxSize(300,400)). + CloseButton(false)); + m_mgr.AddPane(objectInspector, + wxPaneInfo().Name(wxT("inspector")). + Caption(wxT("Object Properties")). + Right().BestSize(wxSize(300,400)). + CloseButton(false)); + + m_mgr.AddPane(designer, + wxPaneInfo().Name(wxT("editor")). + Caption(wxT("Editor")). + Center(). + CloseButton(false)); + + m_mgr.AddPane(palette, + wxPaneInfo().Name(wxT("palette")). + Caption(wxT("Component Palette")). + Top(). + RightDockable(false). + LeftDockable(false). + CloseButton(false)); + + m_mgr.Update();*/ + + RestorePosition(wxT("mainframe")); + Layout(); + + // Init. m_cpp and m_xrc first + m_cpp = NULL; + m_xrc = NULL; + m_python = NULL; + m_lua = NULL; + m_php = NULL; + + switch (style) { + + case wxFB_DOCKABLE_GUI: + // TO-DO + CreateWideGui(); + + break; + + case wxFB_CLASSIC_GUI: + + /* // --- Classic style Gui -- + // + // +------++-----------------------+ + // | Obj. || Palette | + // | Tree ++-----------------------+ + // | || Editor | + // |______|| | + // |------|| | + // | Obj. || | + // | Insp.|| | + // | || | + // | || | + // +------++-----------------------+ */ + + CreateClassicGui(); + + break; + + case wxFB_DEFAULT_GUI: + + case wxFB_WIDE_GUI: + + default: + + /* // --- Wide style Gui -- + // + // +------++-----------------------+ + // | Obj. || Palette | + // | Tree ++-------------++--------+ + // | || Editor || Obj. | + // | || || Insp. | + // | || || | + // | || || | + // | || || | + // | || || | + // | || || | + // +------++-------------++--------+ */ + + CreateWideGui(); + } - wxTheApp->SetTopWindow( this ); + AppData()->AddHandler(this->GetEventHandler()); - m_focusKillEvtHandler = new FocusKillerEvtHandler; - PushEventHandler( m_focusKillEvtHandler ); + wxTheApp->SetTopWindow(this); - // So splitter windows can be restored correctly - Connect( wxEVT_IDLE, wxIdleEventHandler( MainFrame::OnIdle ) ); + m_focusKillEvtHandler = new FocusKillerEvtHandler; + PushEventHandler(m_focusKillEvtHandler); - m_notebook->Connect( wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED, wxAuiNotebookEventHandler( MainFrame::OnAuiNotebookPageChanged ), NULL, this ); + // So splitter windows can be restored correctly + Connect(wxEVT_IDLE, wxIdleEventHandler(MainFrame::OnIdle)); + m_notebook->Connect( + wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED, wxAuiNotebookEventHandler(MainFrame::OnAuiNotebookPageChanged), NULL, + this); } MainFrame::~MainFrame() { - m_notebook->Disconnect( wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED, wxAuiNotebookEventHandler( MainFrame::OnAuiNotebookPageChanged ), NULL, this ); + m_notebook->Disconnect( + wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED, wxAuiNotebookEventHandler(MainFrame::OnAuiNotebookPageChanged), NULL, + this); #ifdef __WXMAC__ // work around problem on wxMac @@ -375,1190 +378,1116 @@ MainFrame::~MainFrame() m_notebook->Destroy(); #endif - /*m_mgr.UnInit();*/ + /*m_mgr.UnInit();*/ - // the focus killer event handler - RemoveEventHandler( m_focusKillEvtHandler ); - delete m_focusKillEvtHandler; + // the focus killer event handler + RemoveEventHandler(m_focusKillEvtHandler); + delete m_focusKillEvtHandler; - AppData()->RemoveHandler( this->GetEventHandler() ); - delete m_findDialog; + AppData()->RemoveHandler(this->GetEventHandler()); + delete m_findDialog; } -void MainFrame::RestorePosition( const wxString &name ) +void MainFrame::RestorePosition(const wxString& name) { - m_currentDir = wxT( "./projects" ); + m_currentDir = wxT("./projects"); - wxConfigBase *config = wxConfigBase::Get(); - config->SetPath( name ); + wxConfigBase* config = wxConfigBase::Get(); + config->SetPath(name); - bool maximized; - config->Read( wxT( "IsMaximized" ), &maximized, true ); + bool maximized; + config->Read(wxT("IsMaximized"), &maximized, true); - if ( maximized ) - { - Maximize( maximized ); - } - else - { - bool iconized; - config->Read( wxT( "IsIconized" ), &iconized, false ); + if (maximized) { + Maximize(maximized); + } else { + bool iconized; + config->Read(wxT("IsIconized"), &iconized, false); - if ( iconized ) - { - Iconize( iconized ); - } - } + if (iconized) { + Iconize(iconized); + } + } - config->Read( wxT( "LeftSplitterWidth" ), &m_leftSplitterWidth, 300 ); - config->Read( wxT( "RightSplitterWidth" ), &m_rightSplitterWidth, -300 ); - config->Read( wxT( "RightSplitterType" ), &m_rightSplitterType, _("editor")); + config->Read(wxT("LeftSplitterWidth"), &m_leftSplitterWidth, 300); + config->Read(wxT("RightSplitterWidth"), &m_rightSplitterWidth, -300); + config->Read(wxT("RightSplitterType"), &m_rightSplitterType, _("editor")); - config->Read( wxT( "AutoSash" ), &m_autoSash, false ); // disabled in default due to possible bug(?) in wxMSW + config->Read(wxT("AutoSash"), &m_autoSash, false); // disabled in default due to possible bug(?) in wxMSW - config->Read( wxT( "CurrentDirectory" ), &m_currentDir ); + config->Read(wxT("CurrentDirectory"), &m_currentDir); - config->Read( wxT( "RecentFile0" ), &m_recentProjects[0] ); - config->Read( wxT( "RecentFile1" ), &m_recentProjects[1] ); - config->Read( wxT( "RecentFile2" ), &m_recentProjects[2] ); - config->Read( wxT( "RecentFile3" ), &m_recentProjects[3] ); + config->Read(wxT("RecentFile0"), &m_recentProjects[0]); + config->Read(wxT("RecentFile1"), &m_recentProjects[1]); + config->Read(wxT("RecentFile2"), &m_recentProjects[2]); + config->Read(wxT("RecentFile3"), &m_recentProjects[3]); - config->SetPath( wxT( ".." ) ); - UpdateRecentProjects(); + config->SetPath(wxT("..")); + UpdateRecentProjects(); } -void MainFrame::SavePosition( const wxString &name ) +void MainFrame::SavePosition(const wxString& name) { - m_objInsp->SavePosition(); - m_palette->SavePosition(); - - wxConfigBase *config = wxConfigBase::Get(); - bool isIconized = IsIconized(); - bool isMaximized = IsMaximized(); - - config->SetPath( name ); - - if ( !isMaximized ) - { - config->Write( wxT( "PosX" ), isIconized ? -1 : GetPosition().x ); - config->Write( wxT( "PosY" ), isIconized ? -1 : GetPosition().y ); - config->Write( wxT( "SizeW" ), isIconized ? -1 : GetSize().GetWidth() ); - config->Write( wxT( "SizeH" ), isIconized ? -1 : GetSize().GetHeight() ); - } + m_objInsp->SavePosition(); + m_palette->SavePosition(); - config->Write( wxT( "IsMaximized" ), isMaximized ); + wxConfigBase* config = wxConfigBase::Get(); + bool isIconized = IsIconized(); + bool isMaximized = IsMaximized(); - config->Write( wxT( "IsIconized" ), isIconized ); - config->Write( wxT( "CurrentDirectory" ), m_currentDir ); + config->SetPath(name); - config->Write( wxT( "RecentFile0" ), m_recentProjects[0] ); - config->Write( wxT( "RecentFile1" ), m_recentProjects[1] ); - config->Write( wxT( "RecentFile2" ), m_recentProjects[2] ); - config->Write( wxT( "RecentFile3" ), m_recentProjects[3] ); + if (!isMaximized) { + config->Write(wxT("PosX"), isIconized ? -1 : GetPosition().x); + config->Write(wxT("PosY"), isIconized ? -1 : GetPosition().y); + config->Write(wxT("SizeW"), isIconized ? -1 : GetSize().GetWidth()); + config->Write(wxT("SizeH"), isIconized ? -1 : GetSize().GetHeight()); + } - if ( m_leftSplitter ) - { - int leftSashWidth = m_leftSplitter->GetSashPosition(); - config->Write( wxT( "LeftSplitterWidth" ), leftSashWidth ); - } + config->Write(wxT("IsMaximized"), isMaximized); - if ( m_rightSplitter ) - { - switch ( m_style ) - { + config->Write(wxT("IsIconized"), isIconized); + config->Write(wxT("CurrentDirectory"), m_currentDir); - case wxFB_WIDE_GUI: - { - int rightSash = -1 * ( m_rightSplitter->GetSize().GetWidth() - m_rightSplitter->GetSashPosition() ); - config->Write( wxT( "RightSplitterWidth" ), rightSash ); + config->Write(wxT("RecentFile0"), m_recentProjects[0]); + config->Write(wxT("RecentFile1"), m_recentProjects[1]); + config->Write(wxT("RecentFile2"), m_recentProjects[2]); + config->Write(wxT("RecentFile3"), m_recentProjects[3]); - if(m_rightSplitter->GetWindow1()->GetChildren()[0]->GetChildren()[0]->GetLabel() == _("Editor")) - { - config->Write( wxT( "RightSplitterType" ), _("editor") ); - } - else - { - config->Write( wxT( "RightSplitterType" ), _("prop") ); - } - break; - } - - case wxFB_CLASSIC_GUI: - { - int rightSash = -1 * ( m_rightSplitter->GetSize().GetHeight() - m_rightSplitter->GetSashPosition() ); - config->Write( wxT( "RightSplitterWidth" ), rightSash ); - break; - } + if (m_leftSplitter) { + int leftSashWidth = m_leftSplitter->GetSashPosition(); + config->Write(wxT("LeftSplitterWidth"), leftSashWidth); + } - default: - break; - } - } + if (m_rightSplitter) { + switch (m_style) { + + case wxFB_WIDE_GUI: { + int rightSash = -1 * (m_rightSplitter->GetSize().GetWidth() - m_rightSplitter->GetSashPosition()); + config->Write(wxT("RightSplitterWidth"), rightSash); + + if (m_rightSplitter->GetWindow1()->GetChildren()[0]->GetChildren()[0]->GetLabel() == _("Editor")) { + config->Write(wxT("RightSplitterType"), _("editor")); + } else { + config->Write(wxT("RightSplitterType"), _("prop")); + } + break; + } + + case wxFB_CLASSIC_GUI: { + int rightSash = -1 * (m_rightSplitter->GetSize().GetHeight() - m_rightSplitter->GetSashPosition()); + config->Write(wxT("RightSplitterWidth"), rightSash); + break; + } + + default: + break; + } + } - config->SetPath( wxT( ".." ) ); + config->SetPath(wxT("..")); } -void MainFrame::OnSaveProject( wxCommandEvent &event ) +void MainFrame::OnSaveProject(wxCommandEvent& event) { - wxString filename = AppData()->GetProjectFileName(); + wxString filename = AppData()->GetProjectFileName(); - if ( filename == wxT( "" ) ) - OnSaveAsProject( event ); - else - { - try - { - AppData()->SaveProject( filename ); - InsertRecentProject( filename ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } + if (filename == wxT("")) + OnSaveAsProject(event); + else { + try { + AppData()->SaveProject(filename); + InsertRecentProject(filename); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } } -void MainFrame::OnSaveAsProject( wxCommandEvent & ) +void MainFrame::OnSaveAsProject(wxCommandEvent&) { - wxFileDialog *dialog = new wxFileDialog( this, wxT( "Save Project" ), m_currentDir, - wxT( "" ), wxT( "wxFormBuilder Project File (*.fbp)|*.fbp|All files (*.*)|*.*" ), wxFD_SAVE ); + wxFileDialog* dialog = new wxFileDialog( + this, wxT("Save Project"), m_currentDir, wxT(""), + wxT("wxFormBuilder Project File (*.fbp)|*.fbp|All files (*.*)|*.*"), wxFD_SAVE); - if ( dialog->ShowModal() == wxID_OK ) - { - m_currentDir = dialog->GetDirectory(); - wxString filename = dialog->GetPath(); + if (dialog->ShowModal() == wxID_OK) { + m_currentDir = dialog->GetDirectory(); + wxString filename = dialog->GetPath(); - // Add the default extension if none was chosen - wxFileName file( filename ); + // Add the default extension if none was chosen + wxFileName file(filename); - if ( !file.HasExt() ) - { - file.SetExt( wxT( "fbp" ) ); - filename = file.GetFullPath(); - } + if (!file.HasExt()) { + file.SetExt(wxT("fbp")); + filename = file.GetFullPath(); + } - // Check the file whether exists or not - if ( file.FileExists() == true ) - { - wxMessageDialog msg_box( this, wxT("The file already exists. Do you want to replace it?"), wxT("Overwrite the file"), wxYES_NO|wxICON_INFORMATION|wxNO_DEFAULT ); - if( msg_box.ShowModal() == wxID_NO ) - { - dialog->Destroy(); - return; - } - } + // Check the file whether exists or not + if (file.FileExists() == true) { + wxMessageDialog msg_box( + this, wxT("The file already exists. Do you want to replace it?"), wxT("Overwrite the file"), + wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT); + if (msg_box.ShowModal() == wxID_NO) { + dialog->Destroy(); + return; + } + } - try - { - AppData()->SaveProject( filename ); - InsertRecentProject( filename ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - }; + try { + AppData()->SaveProject(filename); + InsertRecentProject(filename); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + }; - dialog->Destroy(); + dialog->Destroy(); } -void MainFrame::OnOpenProject( wxCommandEvent &) +void MainFrame::OnOpenProject(wxCommandEvent&) { - if ( !SaveWarning() ) - return; + if (!SaveWarning()) + return; - wxFileDialog *dialog = new wxFileDialog( this, wxT( "Open Project" ), m_currentDir, - wxT( "" ), wxT( "wxFormBuilder Project File (*.fbp)|*.fbp|All files (*.*)|*.*" ), wxFD_OPEN ); + wxFileDialog* dialog = new wxFileDialog( + this, wxT("Open Project"), m_currentDir, wxT(""), + wxT("wxFormBuilder Project File (*.fbp)|*.fbp|All files (*.*)|*.*"), wxFD_OPEN); - if ( dialog->ShowModal() == wxID_OK ) - { - m_currentDir = dialog->GetDirectory(); - wxString filename = dialog->GetPath(); + if (dialog->ShowModal() == wxID_OK) { + m_currentDir = dialog->GetDirectory(); + wxString filename = dialog->GetPath(); - if ( AppData()->LoadProject( filename ) ) - InsertRecentProject( filename ); - }; + if (AppData()->LoadProject(filename)) + InsertRecentProject(filename); + }; - dialog->Destroy(); + dialog->Destroy(); } -void MainFrame::OnOpenRecent( wxCommandEvent &event ) +void MainFrame::OnOpenRecent(wxCommandEvent& event) { - if ( !SaveWarning() ) - return; + if (!SaveWarning()) + return; - int i = event.GetId() - ID_RECENT_0; + int i = event.GetId() - ID_RECENT_0; - assert ( i >= 0 && i < 4 ); + assert(i >= 0 && i < 4); - wxFileName filename( m_recentProjects[i] ); + wxFileName filename(m_recentProjects[i]); - if(filename.FileExists()) - { - if ( AppData()->LoadProject( filename.GetFullPath() ) ) - { + if (filename.FileExists()) { + if (AppData()->LoadProject(filename.GetFullPath())) { m_currentDir = filename.GetPath(); - InsertRecentProject( filename.GetFullPath() ); + InsertRecentProject(filename.GetFullPath()); } - } - else - { - if(wxMessageBox(wxString::Format(wxT("The project file '%s' doesn't exist. Would you like to remove it from the recent files list?"), filename.GetName().GetData()), wxT("Open recent project"), wxICON_WARNING | wxYES_NO) == wxYES) - { + } else { + if ( + wxMessageBox( + wxString::Format( + wxT("The project file '%s' doesn't exist. Would you like to remove it from the recent files list?"), + filename.GetName().GetData()), + wxT("Open recent project"), wxICON_WARNING | wxYES_NO) == wxYES) { m_recentProjects[i] = wxT(""); UpdateRecentProjects(); } } } -void MainFrame::OnImportXrc( wxCommandEvent &) +void MainFrame::OnImportXrc(wxCommandEvent&) { - wxFileDialog *dialog = new wxFileDialog( this, wxT( "Import XRC file" ), m_currentDir, - wxT( "example.xrc" ), wxT( "*.xrc" ), wxFD_OPEN ); + wxFileDialog* dialog = + new wxFileDialog(this, wxT("Import XRC file"), m_currentDir, wxT("example.xrc"), wxT("*.xrc"), wxFD_OPEN); - if ( dialog->ShowModal() == wxID_OK ) - { - m_currentDir = dialog->GetDirectory(); + if (dialog->ShowModal() == wxID_OK) { + m_currentDir = dialog->GetDirectory(); - try - { - ticpp::Document doc; - XMLUtils::LoadXMLFile( doc, false, dialog->GetPath() ); + try { + ticpp::Document doc; + XMLUtils::LoadXMLFile(doc, false, dialog->GetPath()); - XrcLoader xrc; - xrc.SetObjectDatabase( AppData()->GetObjectDatabase() ); + XrcLoader xrc; + xrc.SetObjectDatabase(AppData()->GetObjectDatabase()); - PObjectBase project = xrc.GetProject( &doc ); + PObjectBase project = xrc.GetProject(&doc); - if ( project ) - { - AppData()->MergeProject( project ); - } - else - { - wxLogError( wxT( "Error while loading XRC" ) ); - } - } - catch ( wxFBException& ex ) - { - wxLogError( _( "Error Loading XRC: %s" ), ex.what() ); - } - } + if (project) { + AppData()->MergeProject(project); + } else { + wxLogError(wxT("Error while loading XRC")); + } + } catch (wxFBException& ex) { + wxLogError(_("Error Loading XRC: %s"), ex.what()); + } + } - dialog->Destroy(); + dialog->Destroy(); } -void MainFrame::OnNewProject( wxCommandEvent &) +void MainFrame::OnNewProject(wxCommandEvent&) { - if ( !SaveWarning() ) - return; + if (!SaveWarning()) + return; - AppData()->NewProject(); + AppData()->NewProject(); } -void MainFrame::OnGenerateCode( wxCommandEvent &) +void MainFrame::OnGenerateCode(wxCommandEvent&) { - AppData()->GenerateCode( false ); + AppData()->GenerateCode(false); } -void MainFrame::OnAbout( wxCommandEvent &) +void MainFrame::OnAbout(wxCommandEvent&) { - AboutDialog *dlg = new AboutDialog( this ); - dlg->ShowModal(); - dlg->Destroy(); + AboutDialog* dlg = new AboutDialog(this); + dlg->ShowModal(); + dlg->Destroy(); } -void MainFrame::OnExit( wxCommandEvent &) +void MainFrame::OnExit(wxCommandEvent&) { - Close(); + Close(); } -void MainFrame::OnClose( wxCloseEvent &event ) +void MainFrame::OnClose(wxCloseEvent& event) { - if ( !SaveWarning() ) - return; + if (!SaveWarning()) + return; - SavePosition( wxT( "mainframe" ) ); - m_rightSplitter->Disconnect( wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, wxSplitterEventHandler( MainFrame::OnSplitterChanged ) ); - event.Skip(); + SavePosition(wxT("mainframe")); + m_rightSplitter->Disconnect( + wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, wxSplitterEventHandler(MainFrame::OnSplitterChanged)); + event.Skip(); } -void MainFrame::OnProjectLoaded( wxFBEvent& ) +void MainFrame::OnProjectLoaded(wxFBEvent&) { - GetStatusBar()->SetStatusText( wxT( "Project Loaded!" ) ); - PObjectBase project = AppData()->GetProjectData(); + GetStatusBar()->SetStatusText(wxT("Project Loaded!")); + PObjectBase project = AppData()->GetProjectData(); - if ( project ) - { - wxString objDetails = wxString::Format( wxT( "Name: %s | Class: %s" ), project->GetPropertyAsString( wxT( "name" ) ), project->GetClassName() ); - GetStatusBar()->SetStatusText( objDetails, STATUS_FIELD_OBJECT ); - } + if (project) { + wxString objDetails = wxString::Format( + wxT("Name: %s | Class: %s"), project->GetPropertyAsString(wxT("name")), project->GetClassName()); + GetStatusBar()->SetStatusText(objDetails, STATUS_FIELD_OBJECT); + } - UpdateFrame(); + UpdateFrame(); } -void MainFrame::OnProjectSaved( wxFBEvent& ) +void MainFrame::OnProjectSaved(wxFBEvent&) { - GetStatusBar()->SetStatusText( wxT( "Project Saved!" ) ); - UpdateFrame(); + GetStatusBar()->SetStatusText(wxT("Project Saved!")); + UpdateFrame(); } -void MainFrame::OnObjectExpanded( wxFBObjectEvent& ) +void MainFrame::OnObjectExpanded(wxFBObjectEvent&) { - UpdateFrame(); + UpdateFrame(); } -void MainFrame::OnObjectSelected( wxFBObjectEvent& event ) +void MainFrame::OnObjectSelected(wxFBObjectEvent& event) { - PObjectBase obj = event.GetFBObject(); + PObjectBase obj = event.GetFBObject(); - LogDebug( wxT("MainFrame::OnObjectSelected") ); + LogDebug(wxT("MainFrame::OnObjectSelected")); // resize sash position if necessary - if ( m_autoSash ) - { - wxSize panel_size; - int sash_pos; - - if ( m_style != wxFB_CLASSIC_GUI ) - { - switch(m_page_selection) - { - case 1: // CPP panel - break; - - case 2: // Python panel - break; - - case 3: // PHP panel - break; - - case 4: // LUA panel - break; - - case 5: // XRC panel - break; - - default: - if ( m_visualEdit != NULL ) - { - - // If selected object is not a Frame or a Panel or a dialog, we won't - // adjust the sash position - if ( obj->GetObjectTypeName() == wxT("form") || - obj->GetObjectTypeName() == wxT("wizard") || - obj->GetObjectTypeName() == wxT("menubar_form") || - obj->GetObjectTypeName() == wxT("toolbar_form") ) - { - sash_pos = m_rightSplitter->GetSashPosition(); - panel_size = m_visualEdit->GetVirtualSize(); - - LogDebug(wxT("MainFrame::OnObjectSelected > sash pos = %d"), sash_pos); - LogDebug(wxT("MainFrame::OnObjectSelected > virtual width = %d"), panel_size.GetWidth()); - - if ( panel_size.GetWidth() > sash_pos ) - { - //set the sash position - LogDebug(wxT("MainFrame::OnObjectSelected > set sash position")); - m_rightSplitter_sash_pos = panel_size.GetWidth(); - m_rightSplitter->SetSashPosition(m_rightSplitter_sash_pos); - } - } - } - break; - } - } + if (m_autoSash) { + wxSize panel_size; + int sash_pos; + + if (m_style != wxFB_CLASSIC_GUI) { + switch (m_page_selection) { + case 1: // CPP panel + break; + + case 2: // Python panel + break; + + case 3: // PHP panel + break; + + case 4: // LUA panel + break; + + case 5: // XRC panel + break; + + default: + if (m_visualEdit != NULL) { + + // If selected object is not a Frame or a Panel or a dialog, we won't + // adjust the sash position + if ( + obj->GetObjectTypeName() == wxT("form") || obj->GetObjectTypeName() == wxT("wizard") || + obj->GetObjectTypeName() == wxT("menubar_form") || + obj->GetObjectTypeName() == wxT("toolbar_form")) { + sash_pos = m_rightSplitter->GetSashPosition(); + panel_size = m_visualEdit->GetVirtualSize(); + + LogDebug(wxT("MainFrame::OnObjectSelected > sash pos = %d"), sash_pos); + LogDebug(wxT("MainFrame::OnObjectSelected > virtual width = %d"), panel_size.GetWidth()); + + if (panel_size.GetWidth() > sash_pos) { + // set the sash position + LogDebug(wxT("MainFrame::OnObjectSelected > set sash position")); + m_rightSplitter_sash_pos = panel_size.GetWidth(); + m_rightSplitter->SetSashPosition(m_rightSplitter_sash_pos); + } + } + } + break; + } + } } - wxString name; - PProperty prop( obj->GetProperty( wxT( "name" ) ) ); + wxString name; + PProperty prop(obj->GetProperty(wxT("name"))); - if ( prop ) - name = prop->GetValueAsString(); - else - name = wxT( "\"Unknown\"" ); + if (prop) + name = prop->GetValueAsString(); + else + name = wxT("\"Unknown\""); - //GetStatusBar()->SetStatusText( wxT( "Object " ) + name + wxT( " Selected!" ) ); + // GetStatusBar()->SetStatusText( wxT( "Object " ) + name + wxT( " Selected!" ) ); - wxString objDetails = wxString::Format( wxT( "Name: %s | Class: %s" ), name, obj->GetClassName() ); + wxString objDetails = wxString::Format(wxT("Name: %s | Class: %s"), name, obj->GetClassName()); - GetStatusBar()->SetStatusText( objDetails, STATUS_FIELD_OBJECT ); + GetStatusBar()->SetStatusText(objDetails, STATUS_FIELD_OBJECT); - UpdateFrame(); + UpdateFrame(); } -void MainFrame::OnObjectCreated( wxFBObjectEvent& event ) +void MainFrame::OnObjectCreated(wxFBObjectEvent& event) { - wxString message; + wxString message; - LogDebug(wxT("MainFrame::OnObjectCreated")); + LogDebug(wxT("MainFrame::OnObjectCreated")); - if ( event.GetFBObject() ) - { - message.Printf( wxT( "Object '%s' of class '%s' created." ), - event.GetFBObject()->GetPropertyAsString( wxT( "name" ) ), - event.GetFBObject()->GetClassName() ); - } - else - { - message = wxT( "Impossible to create the object. Did you forget to add a sizer/parent object or turn on/off an AUI management?" ); - wxMessageBox( message, wxT("wxFormBuilder"), wxICON_WARNING | wxOK ); - } + if (event.GetFBObject()) { + message.Printf( + wxT("Object '%s' of class '%s' created."), event.GetFBObject()->GetPropertyAsString(wxT("name")), + event.GetFBObject()->GetClassName()); + } else { + message = wxT( + "Impossible to create the object. Did you forget to add a sizer/parent object or turn on/off an AUI " + "management?"); + wxMessageBox(message, wxT("wxFormBuilder"), wxICON_WARNING | wxOK); + } - GetStatusBar()->SetStatusText( message ); + GetStatusBar()->SetStatusText(message); - UpdateFrame(); + UpdateFrame(); } -void MainFrame::OnObjectRemoved( wxFBObjectEvent& event ) +void MainFrame::OnObjectRemoved(wxFBObjectEvent& event) { - wxString message; - message.Printf( wxT( "Object '%s' removed." ), - event.GetFBObject()->GetPropertyAsString( wxT( "name" ) ) ); - GetStatusBar()->SetStatusText( message ); - UpdateFrame(); + wxString message; + message.Printf(wxT("Object '%s' removed."), event.GetFBObject()->GetPropertyAsString(wxT("name"))); + GetStatusBar()->SetStatusText(message); + UpdateFrame(); } -void MainFrame::OnPropertyModified( wxFBPropertyEvent& event ) +void MainFrame::OnPropertyModified(wxFBPropertyEvent& event) { - PProperty prop = event.GetFBProperty(); + PProperty prop = event.GetFBProperty(); - if ( prop ) - { - if ( prop->GetObject() == AppData()->GetSelectedObject() ) - { - if ( 0 == prop->GetName().CmpNoCase( wxT( "name" ) ) ) - { - wxString oldDetails = GetStatusBar()->GetStatusText( STATUS_FIELD_OBJECT ); - wxString newDetails; - size_t pipeIdx = oldDetails.find( wxT( "|" ) ); + if (prop) { + if (prop->GetObject() == AppData()->GetSelectedObject()) { + if (0 == prop->GetName().CmpNoCase(wxT("name"))) { + wxString oldDetails = GetStatusBar()->GetStatusText(STATUS_FIELD_OBJECT); + wxString newDetails; + size_t pipeIdx = oldDetails.find(wxT("|")); - if ( pipeIdx != oldDetails.npos ) - { - newDetails.Printf( wxT( "Name: %s %s" ), prop->GetValueAsString(), oldDetails.substr( pipeIdx ) ); - GetStatusBar()->SetStatusText( newDetails, STATUS_FIELD_OBJECT ); - } - } + if (pipeIdx != oldDetails.npos) { + newDetails.Printf(wxT("Name: %s %s"), prop->GetValueAsString(), oldDetails.substr(pipeIdx)); + GetStatusBar()->SetStatusText(newDetails, STATUS_FIELD_OBJECT); + } + } - GetStatusBar()->SetStatusText( wxT( "Property Modified!" ) ); - } + GetStatusBar()->SetStatusText(wxT("Property Modified!")); + } - // When you change the sizeritem properties, the object modified is not - // the same that the selected object because is a sizeritem object. - // It's necessary to update the frame for the toolbar buttons. - UpdateFrame(); - } + // When you change the sizeritem properties, the object modified is not + // the same that the selected object because is a sizeritem object. + // It's necessary to update the frame for the toolbar buttons. + UpdateFrame(); + } } -void MainFrame::OnEventHandlerModified( wxFBEventHandlerEvent& event ) +void MainFrame::OnEventHandlerModified(wxFBEventHandlerEvent& event) { - wxString message; - message.Printf( wxT( "Event handler '%s' of object '%s' modified." ), - event.GetFBEventHandler()->GetName(), - event.GetFBEventHandler()->GetObject()->GetPropertyAsString( wxT( "name" ) ) ); + wxString message; + message.Printf( + wxT("Event handler '%s' of object '%s' modified."), event.GetFBEventHandler()->GetName(), + event.GetFBEventHandler()->GetObject()->GetPropertyAsString(wxT("name"))); - GetStatusBar()->SetStatusText( message ); - UpdateFrame(); + GetStatusBar()->SetStatusText(message); + UpdateFrame(); } -void MainFrame::OnCodeGeneration( wxFBEvent& event ) +void MainFrame::OnCodeGeneration(wxFBEvent& event) { - // Using the previously unused Id field in the event to carry a boolean - bool panelOnly = ( event.GetId() != 0 ); + // Using the previously unused Id field in the event to carry a boolean + bool panelOnly = (event.GetId() != 0); - if ( panelOnly ) - { - GetStatusBar()->SetStatusText( wxT( "Code Generated!" ) ); - } + if (panelOnly) { + GetStatusBar()->SetStatusText(wxT("Code Generated!")); + } } -void MainFrame::OnProjectRefresh( wxFBEvent& ) +void MainFrame::OnProjectRefresh(wxFBEvent&) { - PObjectBase project = AppData()->GetProjectData(); + PObjectBase project = AppData()->GetProjectData(); - if ( project ) - { - wxString objDetails = wxString::Format( wxT( "Name: %s | Class: %s" ), project->GetPropertyAsString( wxT( "name" ) ), project->GetClassName() ); - GetStatusBar()->SetStatusText( objDetails, STATUS_FIELD_OBJECT ); - } + if (project) { + wxString objDetails = wxString::Format( + wxT("Name: %s | Class: %s"), project->GetPropertyAsString(wxT("name")), project->GetClassName()); + GetStatusBar()->SetStatusText(objDetails, STATUS_FIELD_OBJECT); + } - UpdateFrame(); + UpdateFrame(); } -void MainFrame::OnUndo( wxCommandEvent &) +void MainFrame::OnUndo(wxCommandEvent&) { - AppData()->Undo(); + AppData()->Undo(); } -void MainFrame::OnRedo( wxCommandEvent &) +void MainFrame::OnRedo(wxCommandEvent&) { - AppData()->Redo(); + AppData()->Redo(); } void MainFrame::UpdateLayoutTools() { - int option = -1; - int border = 0; - int flag = 0; - int orient = 0; - - bool gotLayoutSettings = AppData()->GetLayoutSettings( AppData()->GetSelectedObject(), &flag, &option, &border, &orient ); - wxToolBar* toolbar = GetToolBar(); - wxMenu* menuEdit = GetMenuBar()->GetMenu( GetMenuBar()->FindMenu( wxT( "Edit" ) ) ); - - // Enable the layout tools if there are layout settings, else disable the tools - menuEdit->Enable( ID_EXPAND, gotLayoutSettings ); - toolbar->EnableTool( ID_EXPAND, gotLayoutSettings ); - menuEdit->Enable( ID_STRETCH, option >= 0 ); - toolbar->EnableTool( ID_STRETCH, option >= 0 ); - - bool enableHorizontalTools = ( orient != wxHORIZONTAL ) && gotLayoutSettings; - menuEdit->Enable( ID_ALIGN_LEFT, enableHorizontalTools ); - toolbar->EnableTool( ID_ALIGN_LEFT, enableHorizontalTools ); - menuEdit->Enable( ID_ALIGN_CENTER_H, enableHorizontalTools ); - toolbar->EnableTool( ID_ALIGN_CENTER_H, enableHorizontalTools ); - menuEdit->Enable( ID_ALIGN_RIGHT, enableHorizontalTools ); - toolbar->EnableTool( ID_ALIGN_RIGHT, enableHorizontalTools ); - - bool enableVerticalTools = ( orient != wxVERTICAL ) && gotLayoutSettings; - menuEdit->Enable( ID_ALIGN_TOP, enableVerticalTools ); - toolbar->EnableTool( ID_ALIGN_TOP, enableVerticalTools ); - menuEdit->Enable( ID_ALIGN_CENTER_V, enableVerticalTools ); - toolbar->EnableTool( ID_ALIGN_CENTER_V, enableVerticalTools ); - menuEdit->Enable( ID_ALIGN_BOTTOM, enableVerticalTools ); - toolbar->EnableTool( ID_ALIGN_BOTTOM, enableVerticalTools ); - - toolbar->EnableTool( ID_BORDER_TOP, gotLayoutSettings ); - toolbar->EnableTool( ID_BORDER_RIGHT, gotLayoutSettings ); - toolbar->EnableTool( ID_BORDER_LEFT, gotLayoutSettings ); - toolbar->EnableTool( ID_BORDER_BOTTOM, gotLayoutSettings ); - - // Toggle the toolbar buttons according to the properties, if there are layout settings - toolbar->ToggleTool( ID_EXPAND, ( ( flag & wxEXPAND ) != 0 ) && gotLayoutSettings ); - toolbar->ToggleTool( ID_STRETCH, ( option > 0 ) && gotLayoutSettings ); - toolbar->ToggleTool( ID_ALIGN_LEFT, !( ( flag & ( wxALIGN_RIGHT | wxALIGN_CENTER_HORIZONTAL ) ) != 0 ) && enableHorizontalTools ); - toolbar->ToggleTool( ID_ALIGN_CENTER_H, ( ( flag & wxALIGN_CENTER_HORIZONTAL ) != 0 ) && enableHorizontalTools ); - toolbar->ToggleTool( ID_ALIGN_RIGHT, ( ( flag & wxALIGN_RIGHT ) != 0 ) && enableHorizontalTools ); - toolbar->ToggleTool( ID_ALIGN_TOP, !( ( flag & ( wxALIGN_BOTTOM | wxALIGN_CENTER_VERTICAL ) ) != 0 ) && enableVerticalTools ); - toolbar->ToggleTool( ID_ALIGN_CENTER_V, ( ( flag & wxALIGN_CENTER_VERTICAL ) != 0 ) && enableVerticalTools ); - toolbar->ToggleTool( ID_ALIGN_BOTTOM, ( ( flag & wxALIGN_BOTTOM ) != 0 ) && enableVerticalTools ); - - toolbar->ToggleTool( ID_BORDER_TOP, ( ( flag & wxTOP ) != 0 ) && gotLayoutSettings ); - toolbar->ToggleTool( ID_BORDER_RIGHT, ( ( flag & wxRIGHT ) != 0 ) && gotLayoutSettings ); - toolbar->ToggleTool( ID_BORDER_LEFT, ( ( flag & wxLEFT ) != 0 ) && gotLayoutSettings ); - toolbar->ToggleTool( ID_BORDER_BOTTOM, ( ( flag & wxBOTTOM ) != 0 ) && gotLayoutSettings ); + int option = -1; + int border = 0; + int flag = 0; + int orient = 0; + + bool gotLayoutSettings = + AppData()->GetLayoutSettings(AppData()->GetSelectedObject(), &flag, &option, &border, &orient); + wxToolBar* toolbar = GetToolBar(); + wxMenu* menuEdit = GetMenuBar()->GetMenu(GetMenuBar()->FindMenu(wxT("Edit"))); + + // Enable the layout tools if there are layout settings, else disable the tools + menuEdit->Enable(ID_EXPAND, gotLayoutSettings); + toolbar->EnableTool(ID_EXPAND, gotLayoutSettings); + menuEdit->Enable(ID_STRETCH, option >= 0); + toolbar->EnableTool(ID_STRETCH, option >= 0); + + bool enableHorizontalTools = (orient != wxHORIZONTAL) && gotLayoutSettings; + menuEdit->Enable(ID_ALIGN_LEFT, enableHorizontalTools); + toolbar->EnableTool(ID_ALIGN_LEFT, enableHorizontalTools); + menuEdit->Enable(ID_ALIGN_CENTER_H, enableHorizontalTools); + toolbar->EnableTool(ID_ALIGN_CENTER_H, enableHorizontalTools); + menuEdit->Enable(ID_ALIGN_RIGHT, enableHorizontalTools); + toolbar->EnableTool(ID_ALIGN_RIGHT, enableHorizontalTools); + + bool enableVerticalTools = (orient != wxVERTICAL) && gotLayoutSettings; + menuEdit->Enable(ID_ALIGN_TOP, enableVerticalTools); + toolbar->EnableTool(ID_ALIGN_TOP, enableVerticalTools); + menuEdit->Enable(ID_ALIGN_CENTER_V, enableVerticalTools); + toolbar->EnableTool(ID_ALIGN_CENTER_V, enableVerticalTools); + menuEdit->Enable(ID_ALIGN_BOTTOM, enableVerticalTools); + toolbar->EnableTool(ID_ALIGN_BOTTOM, enableVerticalTools); + + toolbar->EnableTool(ID_BORDER_TOP, gotLayoutSettings); + toolbar->EnableTool(ID_BORDER_RIGHT, gotLayoutSettings); + toolbar->EnableTool(ID_BORDER_LEFT, gotLayoutSettings); + toolbar->EnableTool(ID_BORDER_BOTTOM, gotLayoutSettings); + + // Toggle the toolbar buttons according to the properties, if there are layout settings + toolbar->ToggleTool(ID_EXPAND, ((flag & wxEXPAND) != 0) && gotLayoutSettings); + toolbar->ToggleTool(ID_STRETCH, (option > 0) && gotLayoutSettings); + toolbar->ToggleTool( + ID_ALIGN_LEFT, !((flag & (wxALIGN_RIGHT | wxALIGN_CENTER_HORIZONTAL)) != 0) && enableHorizontalTools); + toolbar->ToggleTool(ID_ALIGN_CENTER_H, ((flag & wxALIGN_CENTER_HORIZONTAL) != 0) && enableHorizontalTools); + toolbar->ToggleTool(ID_ALIGN_RIGHT, ((flag & wxALIGN_RIGHT) != 0) && enableHorizontalTools); + toolbar->ToggleTool( + ID_ALIGN_TOP, !((flag & (wxALIGN_BOTTOM | wxALIGN_CENTER_VERTICAL)) != 0) && enableVerticalTools); + toolbar->ToggleTool(ID_ALIGN_CENTER_V, ((flag & wxALIGN_CENTER_VERTICAL) != 0) && enableVerticalTools); + toolbar->ToggleTool(ID_ALIGN_BOTTOM, ((flag & wxALIGN_BOTTOM) != 0) && enableVerticalTools); + + toolbar->ToggleTool(ID_BORDER_TOP, ((flag & wxTOP) != 0) && gotLayoutSettings); + toolbar->ToggleTool(ID_BORDER_RIGHT, ((flag & wxRIGHT) != 0) && gotLayoutSettings); + toolbar->ToggleTool(ID_BORDER_LEFT, ((flag & wxLEFT) != 0) && gotLayoutSettings); + toolbar->ToggleTool(ID_BORDER_BOTTOM, ((flag & wxBOTTOM) != 0) && gotLayoutSettings); } void MainFrame::UpdateFrame() { - // Build the title - wxString filename = AppData()->GetProjectFileName(); - wxString file; + // Build the title + wxString filename = AppData()->GetProjectFileName(); + wxString file; - if ( filename.empty() ) - { - file = wxT("untitled"); - } - else - { - wxFileName fn( filename ); - file = fn.GetName(); - } + if (filename.empty()) { + file = wxT("untitled"); + } else { + wxFileName fn(filename); + file = fn.GetName(); + } - SetTitle(wxString::Format(wxT("%s%s - wxFormBuilder %s%s"), - AppData()->IsModified() ? wxT("*") : wxT(""), file, getVersion(), getReleaseRevision(getVersion()).c_str())); - GetStatusBar()->SetStatusText( filename, STATUS_FIELD_PATH ); + SetTitle(wxString::Format( + wxT("%s%s - wxFormBuilder %s%s"), AppData()->IsModified() ? wxT("*") : wxT(""), file, getVersion(), + getReleaseRevision(getVersion()).c_str())); + GetStatusBar()->SetStatusText(filename, STATUS_FIELD_PATH); - // Enable/Disable toolbar and menu entries - wxToolBar* toolbar = GetToolBar(); + // Enable/Disable toolbar and menu entries + wxToolBar* toolbar = GetToolBar(); - wxMenu* menuFile = GetMenuBar()->GetMenu(GetMenuBar()->FindMenu(_("File"))); - menuFile->Enable(ID_SAVE_PRJ, AppData()->IsModified()); - toolbar->EnableTool(ID_SAVE_PRJ, AppData()->IsModified()); + wxMenu* menuFile = GetMenuBar()->GetMenu(GetMenuBar()->FindMenu(_("File"))); + menuFile->Enable(ID_SAVE_PRJ, AppData()->IsModified()); + toolbar->EnableTool(ID_SAVE_PRJ, AppData()->IsModified()); - wxMenu* menuEdit = GetMenuBar()->GetMenu( GetMenuBar()->FindMenu( wxT( "Edit" ) ) ); + wxMenu* menuEdit = GetMenuBar()->GetMenu(GetMenuBar()->FindMenu(wxT("Edit"))); - bool redo = AppData()->CanRedo(); - menuEdit->Enable( ID_REDO, redo ); - toolbar->EnableTool( ID_REDO, redo ); + bool redo = AppData()->CanRedo(); + menuEdit->Enable(ID_REDO, redo); + toolbar->EnableTool(ID_REDO, redo); - bool undo = AppData()->CanUndo(); - menuEdit->Enable( ID_UNDO, undo ); - toolbar->EnableTool( ID_UNDO, undo ); + bool undo = AppData()->CanUndo(); + menuEdit->Enable(ID_UNDO, undo); + toolbar->EnableTool(ID_UNDO, undo); - bool copy = AppData()->CanCopyObject(); - bool isEditor = ( _("Designer") != m_notebook->GetPageText( m_notebook->GetSelection() ) ); - menuEdit->Enable( ID_FIND, isEditor ); + bool copy = AppData()->CanCopyObject(); + bool isEditor = (_("Designer") != m_notebook->GetPageText(m_notebook->GetSelection())); + menuEdit->Enable(ID_FIND, isEditor); - menuEdit->Enable( ID_CLIPBOARD_COPY, copy ); + menuEdit->Enable(ID_CLIPBOARD_COPY, copy); - menuEdit->Enable( ID_COPY, copy || isEditor ); - toolbar->EnableTool( ID_COPY, copy || isEditor ); + menuEdit->Enable(ID_COPY, copy || isEditor); + toolbar->EnableTool(ID_COPY, copy || isEditor); - menuEdit->Enable( ID_CUT, copy ); - toolbar->EnableTool( ID_CUT, copy ); + menuEdit->Enable(ID_CUT, copy); + toolbar->EnableTool(ID_CUT, copy); - menuEdit->Enable( ID_DELETE, copy ); - toolbar->EnableTool( ID_DELETE, copy ); + menuEdit->Enable(ID_DELETE, copy); + toolbar->EnableTool(ID_DELETE, copy); - menuEdit->Enable( ID_MOVE_UP, copy ); - menuEdit->Enable( ID_MOVE_DOWN, copy ); - menuEdit->Enable( ID_MOVE_LEFT, copy ); - menuEdit->Enable( ID_MOVE_RIGHT, copy ); + menuEdit->Enable(ID_MOVE_UP, copy); + menuEdit->Enable(ID_MOVE_DOWN, copy); + menuEdit->Enable(ID_MOVE_LEFT, copy); + menuEdit->Enable(ID_MOVE_RIGHT, copy); - bool paste = AppData()->CanPasteObject(); - menuEdit->Enable( ID_PASTE, paste ); - toolbar->EnableTool( ID_PASTE, paste ); + bool paste = AppData()->CanPasteObject(); + menuEdit->Enable(ID_PASTE, paste); + toolbar->EnableTool(ID_PASTE, paste); - menuEdit->Enable( ID_CLIPBOARD_PASTE, AppData()->CanPasteObjectFromClipboard() ); + menuEdit->Enable(ID_CLIPBOARD_PASTE, AppData()->CanPasteObjectFromClipboard()); - UpdateLayoutTools(); + UpdateLayoutTools(); } void MainFrame::UpdateRecentProjects() { - wxMenu *menuFile = GetMenuBar()->GetMenu( GetMenuBar()->FindMenu( wxT( "File" ) ) ); + wxMenu* menuFile = GetMenuBar()->GetMenu(GetMenuBar()->FindMenu(wxT("File"))); - // borramos los items del menu de los projectos recientes + // borramos los items del menu de los projectos recientes - for (int i = 0 ; i < 4 ; i++) - { - if ( menuFile->FindItem( ID_RECENT_0 + i ) ) - menuFile->Destroy( ID_RECENT_0 + i ); - } + for (int i = 0; i < 4; i++) { + if (menuFile->FindItem(ID_RECENT_0 + i)) + menuFile->Destroy(ID_RECENT_0 + i); + } - wxMenuItem* mruSep = menuFile->FindItemByPosition( menuFile->GetMenuItemCount() - 1 ); - if ( mruSep->IsSeparator() ) - { - menuFile->Destroy( mruSep ); - } + wxMenuItem* mruSep = menuFile->FindItemByPosition(menuFile->GetMenuItemCount() - 1); + if (mruSep->IsSeparator()) { + menuFile->Destroy(mruSep); + } - // remove empty filenames and 'compress' the rest + // remove empty filenames and 'compress' the rest int fi = 0; - for (int i = 0 ; i < 4 ; i++) - { - if(!m_recentProjects[i].IsEmpty()) - m_recentProjects[fi++] = m_recentProjects[i]; - } - for (int i = fi ; i < 4 ; i++) - m_recentProjects[i] = wxT(""); - - if ( !m_recentProjects[0].IsEmpty() ) - { + for (int i = 0; i < 4; i++) { + if (!m_recentProjects[i].IsEmpty()) + m_recentProjects[fi++] = m_recentProjects[i]; + } + for (int i = fi; i < 4; i++) m_recentProjects[i] = wxT(""); + + if (!m_recentProjects[0].IsEmpty()) { menuFile->AppendSeparator(); } - // creamos los nuevos ficheros recientes - for ( unsigned int i = 0 ; i < 4 && !m_recentProjects[i].IsEmpty() ; i++ ) - menuFile->Append( ID_RECENT_0 + i, m_recentProjects[i], wxT( "" ) ); + // creamos los nuevos ficheros recientes + for (unsigned int i = 0; i < 4 && !m_recentProjects[i].IsEmpty(); i++) + menuFile->Append(ID_RECENT_0 + i, m_recentProjects[i], wxT("")); } -void MainFrame::InsertRecentProject( const wxString &file ) +void MainFrame::InsertRecentProject(const wxString& file) { - bool found = false; - int i; + bool found = false; + int i; - for ( i = 0; i < 4 && !found; i++ ) - found = ( file == m_recentProjects[i] ); + for (i = 0; i < 4 && !found; i++) found = (file == m_recentProjects[i]); - if ( found ) // en i-1 está la posición encontrada (0 < i < 4) - { - // desplazamos desde 0 hasta i-1 una posición a la derecha + if (found) // en i-1 está la posición encontrada (0 < i < 4) + { + // desplazamos desde 0 hasta i-1 una posición a la derecha - for ( i = i - 1; i > 0; i-- ) - m_recentProjects[i] = m_recentProjects[i-1]; - } - else if ( !found ) - { - for ( i = 3; i > 0; i-- ) - m_recentProjects[i] = m_recentProjects[i-1]; - } + for (i = i - 1; i > 0; i--) m_recentProjects[i] = m_recentProjects[i - 1]; + } else if (!found) { + for (i = 3; i > 0; i--) m_recentProjects[i] = m_recentProjects[i - 1]; + } - m_recentProjects[0] = file; + m_recentProjects[0] = file; - UpdateRecentProjects(); + UpdateRecentProjects(); } -void MainFrame::OnCopy( wxCommandEvent &) +void MainFrame::OnCopy(wxCommandEvent&) { - wxWindow *focusedWindow = wxWindow::FindFocus(); + wxWindow* focusedWindow = wxWindow::FindFocus(); - if ( focusedWindow != NULL && focusedWindow->IsKindOf( wxCLASSINFO( wxStyledTextCtrl ) ) ) - { - ( ( wxStyledTextCtrl* )focusedWindow )->Copy(); + if (focusedWindow != NULL && focusedWindow->IsKindOf(wxCLASSINFO(wxStyledTextCtrl))) { + ((wxStyledTextCtrl*)focusedWindow)->Copy(); + } else { + AppData()->CopyObject(AppData()->GetSelectedObject()); + UpdateFrame(); } - else - { - AppData()->CopyObject( AppData()->GetSelectedObject() ); - UpdateFrame(); - } } -void MainFrame::OnCut ( wxCommandEvent &) +void MainFrame::OnCut(wxCommandEvent&) { - wxWindow *focusedWindow = wxWindow::FindFocus(); + wxWindow* focusedWindow = wxWindow::FindFocus(); - if ( focusedWindow != NULL && focusedWindow->IsKindOf( wxCLASSINFO( wxStyledTextCtrl ) ) ) - { - ( ( wxStyledTextCtrl* )focusedWindow )->Cut(); + if (focusedWindow != NULL && focusedWindow->IsKindOf(wxCLASSINFO(wxStyledTextCtrl))) { + ((wxStyledTextCtrl*)focusedWindow)->Cut(); + } else { + AppData()->CutObject(AppData()->GetSelectedObject()); + UpdateFrame(); } - else - { - AppData()->CutObject( AppData()->GetSelectedObject() ); - UpdateFrame(); - } } -void MainFrame::OnDelete ( wxCommandEvent &) +void MainFrame::OnDelete(wxCommandEvent&) { - AppData()->RemoveObject( AppData()->GetSelectedObject() ); - UpdateFrame(); + AppData()->RemoveObject(AppData()->GetSelectedObject()); + UpdateFrame(); } -void MainFrame::OnPaste ( wxCommandEvent &) +void MainFrame::OnPaste(wxCommandEvent&) { - wxWindow *focusedWindow = wxWindow::FindFocus(); + wxWindow* focusedWindow = wxWindow::FindFocus(); - if ( focusedWindow != NULL && focusedWindow->IsKindOf( wxCLASSINFO( wxStyledTextCtrl ) ) ) - { - ( ( wxStyledTextCtrl* )focusedWindow )->Paste(); + if (focusedWindow != NULL && focusedWindow->IsKindOf(wxCLASSINFO(wxStyledTextCtrl))) { + ((wxStyledTextCtrl*)focusedWindow)->Paste(); + } else { + AppData()->PasteObject(AppData()->GetSelectedObject()); + UpdateFrame(); } - else - { - AppData()->PasteObject( AppData()->GetSelectedObject() ); - UpdateFrame(); - } } -void MainFrame::OnClipboardCopy(wxCommandEvent& ) +void MainFrame::OnClipboardCopy(wxCommandEvent&) { - AppData()->CopyObjectToClipboard( AppData()->GetSelectedObject() ); - UpdateFrame(); + AppData()->CopyObjectToClipboard(AppData()->GetSelectedObject()); + UpdateFrame(); } -void MainFrame::OnClipboardPaste(wxCommandEvent& ) +void MainFrame::OnClipboardPaste(wxCommandEvent&) { - AppData()->PasteObjectFromClipboard( AppData()->GetSelectedObject() ); - UpdateFrame(); + AppData()->PasteObjectFromClipboard(AppData()->GetSelectedObject()); + UpdateFrame(); } -void MainFrame::OnClipboardPasteUpdateUI( wxUpdateUIEvent& e ) +void MainFrame::OnClipboardPasteUpdateUI(wxUpdateUIEvent& e) { - e.Enable( AppData()->CanPasteObjectFromClipboard() ); + e.Enable(AppData()->CanPasteObjectFromClipboard()); } -void MainFrame::OnToggleExpand ( wxCommandEvent &) +void MainFrame::OnToggleExpand(wxCommandEvent&) { - AppData()->ToggleExpandLayout( AppData()->GetSelectedObject() ); + AppData()->ToggleExpandLayout(AppData()->GetSelectedObject()); } -void MainFrame::OnToggleStretch ( wxCommandEvent &) +void MainFrame::OnToggleStretch(wxCommandEvent&) { - AppData()->ToggleStretchLayout( AppData()->GetSelectedObject() ); + AppData()->ToggleStretchLayout(AppData()->GetSelectedObject()); } -void MainFrame::OnMoveUp ( wxCommandEvent &) +void MainFrame::OnMoveUp(wxCommandEvent&) { - AppData()->MovePosition( AppData()->GetSelectedObject(), false, 1 ); + AppData()->MovePosition(AppData()->GetSelectedObject(), false, 1); } -void MainFrame::OnMoveDown ( wxCommandEvent &) +void MainFrame::OnMoveDown(wxCommandEvent&) { - AppData()->MovePosition( AppData()->GetSelectedObject(), true, 1 ); + AppData()->MovePosition(AppData()->GetSelectedObject(), true, 1); } -void MainFrame::OnMoveLeft ( wxCommandEvent &) +void MainFrame::OnMoveLeft(wxCommandEvent&) { - AppData()->MoveHierarchy( AppData()->GetSelectedObject(), true ); + AppData()->MoveHierarchy(AppData()->GetSelectedObject(), true); } -void MainFrame::OnMoveRight ( wxCommandEvent & ) +void MainFrame::OnMoveRight(wxCommandEvent&) { - AppData()->MoveHierarchy( AppData()->GetSelectedObject(), false ); + AppData()->MoveHierarchy(AppData()->GetSelectedObject(), false); } -void MainFrame::OnChangeAlignment ( wxCommandEvent &event ) +void MainFrame::OnChangeAlignment(wxCommandEvent& event) { - int align = 0; - bool vertical = ( event.GetId() == ID_ALIGN_TOP || - event.GetId() == ID_ALIGN_BOTTOM || - event.GetId() == ID_ALIGN_CENTER_V ); + int align = 0; + bool vertical = + (event.GetId() == ID_ALIGN_TOP || event.GetId() == ID_ALIGN_BOTTOM || event.GetId() == ID_ALIGN_CENTER_V); - switch ( event.GetId() ) - { + switch (event.GetId()) { - case ID_ALIGN_RIGHT: - align = wxALIGN_RIGHT; + case ID_ALIGN_RIGHT: + align = wxALIGN_RIGHT; - break; + break; - case ID_ALIGN_CENTER_H: - align = wxALIGN_CENTER_HORIZONTAL; + case ID_ALIGN_CENTER_H: + align = wxALIGN_CENTER_HORIZONTAL; - break; + break; - case ID_ALIGN_BOTTOM: - align = wxALIGN_BOTTOM; + case ID_ALIGN_BOTTOM: + align = wxALIGN_BOTTOM; - break; + break; - case ID_ALIGN_CENTER_V: - align = wxALIGN_CENTER_VERTICAL; + case ID_ALIGN_CENTER_V: + align = wxALIGN_CENTER_VERTICAL; - break; - } + break; + } - AppData()->ChangeAlignment( AppData()->GetSelectedObject(), align, vertical ); + AppData()->ChangeAlignment(AppData()->GetSelectedObject(), align, vertical); - UpdateLayoutTools(); + UpdateLayoutTools(); } -void MainFrame::OnChangeBorder( wxCommandEvent& e ) +void MainFrame::OnChangeBorder(wxCommandEvent& e) { - int border; + int border; - switch ( e.GetId() ) - { - case ID_BORDER_LEFT: - border = wxLEFT; - break; + switch (e.GetId()) { + case ID_BORDER_LEFT: + border = wxLEFT; + break; - case ID_BORDER_RIGHT: - border = wxRIGHT; - break; + case ID_BORDER_RIGHT: + border = wxRIGHT; + break; - case ID_BORDER_TOP: - border = wxTOP; - break; + case ID_BORDER_TOP: + border = wxTOP; + break; - case ID_BORDER_BOTTOM: - border = wxBOTTOM; - break; + case ID_BORDER_BOTTOM: + border = wxBOTTOM; + break; - default: - border = 0; - break; - } + default: + border = 0; + break; + } - AppData()->ToggleBorderFlag( AppData()->GetSelectedObject(), border ); + AppData()->ToggleBorderFlag(AppData()->GetSelectedObject(), border); - UpdateLayoutTools(); + UpdateLayoutTools(); } -void MainFrame::OnXrcPreview( wxCommandEvent& WXUNUSED( e ) ) +void MainFrame::OnXrcPreview(wxCommandEvent& WXUNUSED(e)) { - AppData()->ShowXrcPreview(); - - /*wxPaneInfoArray& all_panes = m_mgr.GetAllPanes(); - for ( int i = 0, count = all_panes.GetCount(); i < count; ++i ) - { - wxPaneInfo info = all_panes.Item( i ); - }*/ + AppData()->ShowXrcPreview(); + /*wxPaneInfoArray& all_panes = m_mgr.GetAllPanes(); + for ( int i = 0, count = all_panes.GetCount(); i < count; ++i ) + { + wxPaneInfo info = all_panes.Item( i ); + }*/ } -void MainFrame::OnGenInhertedClass( wxCommandEvent& WXUNUSED( e ) ) +void MainFrame::OnGenInhertedClass(wxCommandEvent& WXUNUSED(e)) { - wxString filePath; - try - { - // Get the output path - filePath = AppData()->GetOutputPath(); - } - catch ( wxFBException& ex ) - { - wxLogWarning( ex.what() ); - return; - } + wxString filePath; + try { + // Get the output path + filePath = AppData()->GetOutputPath(); + } catch (wxFBException& ex) { + wxLogWarning(ex.what()); + return; + } - // Show the dialog - PObjectBase project = AppData()->GetProjectData(); - if ( project->IsNull( _("file") ) ) - { - wxLogWarning( _("You must set the \"file\" property of the project before generating inherited classes.") ); - return; - } - GenInheritedClassDlg dlg( this, project ); + // Show the dialog + PObjectBase project = AppData()->GetProjectData(); + if (project->IsNull(_("file"))) { + wxLogWarning(_("You must set the \"file\" property of the project before generating inherited classes.")); + return; + } + GenInheritedClassDlg dlg(this, project); - if ( wxID_OK != dlg.ShowModal() ) - { - return; - } + if (wxID_OK != dlg.ShowModal()) { + return; + } - std::vector< GenClassDetails > selectedForms; - dlg.GetFormsSelected( &selectedForms ); + std::vector selectedForms; + dlg.GetFormsSelected(&selectedForms); - for ( size_t i = 0; i < selectedForms.size(); ++i ) - { - const GenClassDetails& details = selectedForms[i]; + for (size_t i = 0; i < selectedForms.size(); ++i) { + const GenClassDetails& details = selectedForms[i]; - // Create the class and files. - AppData()->GenerateInheritedClass( details.m_form, details.m_className, filePath, details.m_fileName ); - } + // Create the class and files. + AppData()->GenerateInheritedClass(details.m_form, details.m_className, filePath, details.m_fileName); + } - wxMessageBox( wxString::Format( wxT( "Class(es) generated to \'%s\'." ), filePath ), wxT("wxFormBuilder") ); + wxMessageBox(wxString::Format(wxT("Class(es) generated to \'%s\'."), filePath), wxT("wxFormBuilder")); } bool MainFrame::SaveWarning() { - int result = wxYES; - - if ( AppData()->IsModified() ) - { - result = ::wxMessageBox( wxT( "Current project file has been modified...\n" ) - wxT( "Do you want to save the changes?" ), - wxT( "Save project" ), - wxYES | wxNO | wxCANCEL, - this ); - - if ( result == wxYES ) - { - wxCommandEvent dummy; - OnSaveProject( dummy ); - } - } - - return ( result != wxCANCEL ); -} - -void MainFrame::OnAuiNotebookPageChanged( wxAuiNotebookEvent& event ) -{ - UpdateFrame(); - - if ( m_autoSash ) - { - m_page_selection = event.GetSelection(); - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > selection = %d"), m_page_selection); - - wxSize panel_size; - int sash_pos; - - if(m_style != wxFB_CLASSIC_GUI) - { - switch( m_page_selection ) - { - case 1: // CPP panel - if( (m_cpp != NULL) && (m_rightSplitter != NULL) ) - { - panel_size = m_cpp->GetClientSize(); - sash_pos = m_rightSplitter->GetSashPosition(); - - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > CPP panel: width = %d sash pos = %d"), panel_size.GetWidth(), sash_pos); - - if(panel_size.GetWidth() > sash_pos) - { - // set the sash position - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); - m_rightSplitter->SetSashPosition(panel_size.GetWidth()); - } - } - break; - - case 2: // Python panel - if( (m_python != NULL) && (m_rightSplitter != NULL) ) - { - panel_size = m_python->GetClientSize(); - sash_pos = m_rightSplitter->GetSashPosition(); - - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > Python panel: width = %d sash pos = %d"), panel_size.GetWidth(), sash_pos); - - if(panel_size.GetWidth() > sash_pos) - { - // set the sash position - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); - m_rightSplitter->SetSashPosition(panel_size.GetWidth()); - } - } - break; - - case 3: // PHP panel - if( (m_php != NULL) && (m_rightSplitter != NULL) ) - { - panel_size = m_xrc->GetClientSize(); - sash_pos = m_rightSplitter->GetSashPosition(); - - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > PHP panel: width = %d sash pos = %d"), panel_size.GetWidth(), sash_pos); - - if(panel_size.GetWidth() > sash_pos) - { - // set the sash position - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); - m_rightSplitter->SetSashPosition(panel_size.GetWidth()); - } - } - break; - - case 4: // Lua panel - if( (m_lua != NULL) && (m_rightSplitter != NULL) ) - { - panel_size = m_lua->GetClientSize(); - sash_pos = m_rightSplitter->GetSashPosition(); - - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > Lua panel: width = %d sash pos = %d"), panel_size.GetWidth(), sash_pos); - - if(panel_size.GetWidth() > sash_pos) - { - // set the sash position - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); - m_rightSplitter->SetSashPosition(panel_size.GetWidth()); - } - } - break; - - case 5: // XRC panel - if((m_xrc != NULL) && (m_rightSplitter != NULL)) - { - panel_size = m_xrc->GetClientSize(); - sash_pos = m_rightSplitter->GetSashPosition(); - - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > XRC panel: width = %d sash pos = %d"), panel_size.GetWidth(), sash_pos); - - if(panel_size.GetWidth() > sash_pos) - { - // set the sash position - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); - m_rightSplitter->SetSashPosition(panel_size.GetWidth()); - } - } - break; - - - - default: - if(m_visualEdit != NULL) - { - sash_pos = m_rightSplitter->GetSashPosition(); - - if(m_rightSplitter_sash_pos < sash_pos) - { - //restore the sash position - LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > restore sash position: sash pos = %d"), m_rightSplitter_sash_pos); - m_rightSplitter->SetSashPosition(m_rightSplitter_sash_pos); - } - else - { - // update position - m_rightSplitter_sash_pos = sash_pos; - } - } - break; - } - } - } - - AppData()->GenerateCode( true ); -} - -void MainFrame::OnFindDialog( wxCommandEvent& ) -{ - if ( NULL == m_findDialog ) - { - m_findDialog = new wxFindReplaceDialog( this, &m_findData, wxT("Find") ); - m_findDialog->Centre( wxCENTRE_ON_SCREEN | wxBOTH ); - } - m_findDialog->Show( true ); -} - -void MainFrame::OnFindClose( wxFindDialogEvent& ) -{ - m_findDialog->Destroy(); - m_findDialog = 0; -} - -void MainFrame::OnFind( wxFindDialogEvent& event ) -{ - /*for ( int page = 0; page < m_notebook->GetPageCount(); ++page ) - { - event.StopPropagation(); - event.SetClientData( m_findDialog ); - m_notebook->GetPage( page )->GetEventHandler()->ProcessEvent( event ); - }*/ - - wxWindow *page = m_notebook->GetCurrentPage(); - if( page ) - { - event.StopPropagation(); - event.SetClientData( m_findDialog ); - page->GetEventHandler()->ProcessEvent( event ); - } + int result = wxYES; + + if (AppData()->IsModified()) { + result = ::wxMessageBox( + wxT("Current project file has been modified...\n") wxT("Do you want to save the changes?"), + wxT("Save project"), wxYES | wxNO | wxCANCEL, this); + + if (result == wxYES) { + wxCommandEvent dummy; + OnSaveProject(dummy); + } + } + + return (result != wxCANCEL); +} + +void MainFrame::OnAuiNotebookPageChanged(wxAuiNotebookEvent& event) +{ + UpdateFrame(); + + if (m_autoSash) { + m_page_selection = event.GetSelection(); + LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > selection = %d"), m_page_selection); + + wxSize panel_size; + int sash_pos; + + if (m_style != wxFB_CLASSIC_GUI) { + switch (m_page_selection) { + case 1: // CPP panel + if ((m_cpp != NULL) && (m_rightSplitter != NULL)) { + panel_size = m_cpp->GetClientSize(); + sash_pos = m_rightSplitter->GetSashPosition(); + + LogDebug( + wxT("MainFrame::OnFlatNotebookPageChanged > CPP panel: width = %d sash pos = %d"), + panel_size.GetWidth(), sash_pos); + + if (panel_size.GetWidth() > sash_pos) { + // set the sash position + LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); + m_rightSplitter->SetSashPosition(panel_size.GetWidth()); + } + } + break; + + case 2: // Python panel + if ((m_python != NULL) && (m_rightSplitter != NULL)) { + panel_size = m_python->GetClientSize(); + sash_pos = m_rightSplitter->GetSashPosition(); + + LogDebug( + wxT("MainFrame::OnFlatNotebookPageChanged > Python panel: width = %d sash pos = %d"), + panel_size.GetWidth(), sash_pos); + + if (panel_size.GetWidth() > sash_pos) { + // set the sash position + LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); + m_rightSplitter->SetSashPosition(panel_size.GetWidth()); + } + } + break; + + case 3: // PHP panel + if ((m_php != NULL) && (m_rightSplitter != NULL)) { + panel_size = m_xrc->GetClientSize(); + sash_pos = m_rightSplitter->GetSashPosition(); + + LogDebug( + wxT("MainFrame::OnFlatNotebookPageChanged > PHP panel: width = %d sash pos = %d"), + panel_size.GetWidth(), sash_pos); + + if (panel_size.GetWidth() > sash_pos) { + // set the sash position + LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); + m_rightSplitter->SetSashPosition(panel_size.GetWidth()); + } + } + break; + + case 4: // Lua panel + if ((m_lua != NULL) && (m_rightSplitter != NULL)) { + panel_size = m_lua->GetClientSize(); + sash_pos = m_rightSplitter->GetSashPosition(); + + LogDebug( + wxT("MainFrame::OnFlatNotebookPageChanged > Lua panel: width = %d sash pos = %d"), + panel_size.GetWidth(), sash_pos); + + if (panel_size.GetWidth() > sash_pos) { + // set the sash position + LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); + m_rightSplitter->SetSashPosition(panel_size.GetWidth()); + } + } + break; + + case 5: // XRC panel + if ((m_xrc != NULL) && (m_rightSplitter != NULL)) { + panel_size = m_xrc->GetClientSize(); + sash_pos = m_rightSplitter->GetSashPosition(); + + LogDebug( + wxT("MainFrame::OnFlatNotebookPageChanged > XRC panel: width = %d sash pos = %d"), + panel_size.GetWidth(), sash_pos); + + if (panel_size.GetWidth() > sash_pos) { + // set the sash position + LogDebug(wxT("MainFrame::OnFlatNotebookPageChanged > reset sash position")); + m_rightSplitter->SetSashPosition(panel_size.GetWidth()); + } + } + break; + + + default: + if (m_visualEdit != NULL) { + sash_pos = m_rightSplitter->GetSashPosition(); + + if (m_rightSplitter_sash_pos < sash_pos) { + // restore the sash position + LogDebug( + wxT("MainFrame::OnFlatNotebookPageChanged > restore sash position: sash pos = %d"), + m_rightSplitter_sash_pos); + m_rightSplitter->SetSashPosition(m_rightSplitter_sash_pos); + } else { + // update position + m_rightSplitter_sash_pos = sash_pos; + } + } + break; + } + } + } + + AppData()->GenerateCode(true); +} + +void MainFrame::OnFindDialog(wxCommandEvent&) +{ + if (NULL == m_findDialog) { + m_findDialog = new wxFindReplaceDialog(this, &m_findData, wxT("Find")); + m_findDialog->Centre(wxCENTRE_ON_SCREEN | wxBOTH); + } + m_findDialog->Show(true); +} + +void MainFrame::OnFindClose(wxFindDialogEvent&) +{ + m_findDialog->Destroy(); + m_findDialog = 0; +} + +void MainFrame::OnFind(wxFindDialogEvent& event) +{ + /*for ( int page = 0; page < m_notebook->GetPageCount(); ++page ) + { + event.StopPropagation(); + event.SetClientData( m_findDialog ); + m_notebook->GetPage( page )->GetEventHandler()->ProcessEvent( event ); + }*/ + + wxWindow* page = m_notebook->GetCurrentPage(); + if (page) { + event.StopPropagation(); + event.SetClientData(m_findDialog); + page->GetEventHandler()->ProcessEvent(event); + } } ///////////////////////////////////////////////////////////////////////////// -wxMenuBar * MainFrame::CreateFBMenuBar() -{ - wxMenu *menuFile = new wxMenu; - menuFile->Append( ID_NEW_PRJ, wxT( "&New Project\tCtrl+N" ), wxT( "Create an empty project" ) ); - menuFile->Append( ID_OPEN_PRJ, wxT( "&Open...\tCtrl+O" ), wxT( "Open a project" ) ); - - menuFile->Append( ID_SAVE_PRJ, wxT( "&Save\tCtrl+S" ), wxT( "Save current project" ) ); - menuFile->Append( ID_SAVE_AS_PRJ, wxT( "Save &As...\tCtrl-Shift+S" ), wxT( "Save current project as..." ) ); - menuFile->AppendSeparator(); - menuFile->Append( ID_IMPORT_XRC, wxT( "&Import XRC..." ), wxT( "Import XRC file" ) ); - menuFile->AppendSeparator(); - menuFile->Append( ID_GENERATE_CODE, wxT( "&Generate Code\tF8" ), wxT( "Generate Code" ) ); - menuFile->AppendSeparator(); - menuFile->Append( wxID_EXIT, wxT( "E&xit\tAlt-F4" ), wxT( "Quit wxFormBuilder" ) ); - - wxMenu *menuEdit = new wxMenu; - menuEdit->Append( ID_UNDO, wxT( "&Undo \tCtrl+Z" ), wxT( "Undo changes" ) ); - menuEdit->Append( ID_REDO, wxT( "&Redo \tCtrl+Y" ), wxT( "Redo changes" ) ); - menuEdit->AppendSeparator(); - menuEdit->Append( ID_COPY, wxT( "&Copy \tCtrl+C" ), wxT( "Copy selected object" ) ); - menuEdit->Append( ID_CUT, wxT( "Cut \tCtrl+X" ), wxT( "Cut selected object" ) ); - menuEdit->Append( ID_PASTE, wxT( "&Paste \tCtrl+V" ), wxT( "Paste on selected object" ) ); - menuEdit->Append( ID_DELETE, wxT( "&Delete \tCtrl+D" ), wxT( "Delete selected object" ) ); - menuEdit->AppendSeparator(); - menuEdit->Append( ID_CLIPBOARD_COPY, wxT("Copy Object To Clipboard\tCtrl+Shift+C"), wxT("Copy Object to Clipboard") ); - menuEdit->Append( ID_CLIPBOARD_PASTE, wxT("Paste Object From Clipboard\tCtrl+Shift+V"), wxT("Paste Object from Clipboard") ); - menuEdit->AppendSeparator(); - menuEdit->Append( ID_EXPAND, wxT( "Toggle &Expand\tAlt+W" ), wxT( "Toggle wxEXPAND flag of sizeritem properties" ) ); - menuEdit->Append( ID_STRETCH, wxT( "Toggle &Stretch\tAlt+S" ), wxT( "Toggle option property of sizeritem properties" ) ); - menuEdit->Append( ID_MOVE_UP, wxT( "Move Up\tAlt+Up" ), wxT( "Move Up selected object" ) ); - menuEdit->Append( ID_MOVE_DOWN, wxT( "Move Down\tAlt+Down" ), wxT( "Move Down selected object" ) ); - menuEdit->Append( ID_MOVE_LEFT, wxT( "Move Left\tAlt+Left" ), wxT( "Move Left selected object" ) ); - menuEdit->Append( ID_MOVE_RIGHT, wxT( "Move Right\tAlt+Right" ), wxT( "Move Right selected object" ) ); - menuEdit->AppendSeparator(); - menuEdit->Append( ID_FIND, wxT( "&Find\tCtrl+F" ), wxT( "Find text in the active code viewer" ) ); - menuEdit->AppendSeparator(); - menuEdit->Append( ID_ALIGN_LEFT, wxT( "&Align &Left\tAlt+Shift+Left" ), wxT( "Align item to the left" ) ); - menuEdit->Append( ID_ALIGN_CENTER_H, wxT( "&Align Center &Horizontal\tAlt+Shift+H" ), wxT( "Align item to the center horizontally" ) ); - menuEdit->Append( ID_ALIGN_RIGHT, wxT( "&Align &Right\tAlt+Shift+Right" ), wxT( "Align item to the right" ) ); - menuEdit->Append( ID_ALIGN_TOP, wxT( "&Align &Top\tAlt+Shift+Up" ), wxT( "Align item to the top" ) ); - menuEdit->Append( ID_ALIGN_CENTER_V, wxT( "&Align Center &Vertical\tAlt+Shift+V" ), wxT( "Align item to the center vertically" ) ); - menuEdit->Append( ID_ALIGN_BOTTOM, wxT( "&Align &Bottom\tAlt+Shift+Down" ), wxT( "Align item to the bottom" ) ); - - wxMenu *menuComponents = CreateMenuComponents(); - - wxMenu *menuView = new wxMenu; - menuView->Append( ID_PREVIEW_XRC, wxT( "&XRC Window\tF5" ), wxT( "Show a preview of the XRC window" ) ); - menuView->AppendSeparator(); - menuView->Append( ID_WINDOW_SWAP, wxT( "&Swap The Editor and Properties Window\tF12" ), wxT( "Swap The Editor and Properties Window" ) ); - - wxMenu *menuTools = new wxMenu; - menuTools->Append( ID_GEN_INHERIT_CLS, wxT( "&Generate Inherited Class\tF6" ), wxT( "Creates the needed files and class for proper inheritance of your designed GUI" ) ); - - wxMenu *menuHelp = new wxMenu; - menuHelp->Append( wxID_ABOUT, wxT( "&About...\tF1" ), wxT( "Show about dialog" ) ); - - // now append the freshly created menu to the menu bar... - wxMenuBar *menuBar = new wxMenuBar(); - menuBar->Append( menuFile, wxT( "&File" ) ); - menuBar->Append( menuEdit, wxT( "&Edit" ) ); - menuBar->Append( menuComponents, wxT( "&Components" ) ); - menuBar->Append( menuView, wxT( "&View" ) ); - menuBar->Append( menuTools, wxT( "&Tools" ) ); - menuBar->Append( menuHelp, wxT( "&Help" ) ); +wxMenuBar* MainFrame::CreateFBMenuBar() +{ + wxMenu* menuFile = new wxMenu; + menuFile->Append(ID_NEW_PRJ, wxT("&New Project\tCtrl+N"), wxT("Create an empty project")); + menuFile->Append(ID_OPEN_PRJ, wxT("&Open...\tCtrl+O"), wxT("Open a project")); + + menuFile->Append(ID_SAVE_PRJ, wxT("&Save\tCtrl+S"), wxT("Save current project")); + menuFile->Append(ID_SAVE_AS_PRJ, wxT("Save &As...\tCtrl-Shift+S"), wxT("Save current project as...")); + menuFile->AppendSeparator(); + menuFile->Append(ID_IMPORT_XRC, wxT("&Import XRC..."), wxT("Import XRC file")); + menuFile->AppendSeparator(); + menuFile->Append(ID_GENERATE_CODE, wxT("&Generate Code\tF8"), wxT("Generate Code")); + menuFile->AppendSeparator(); + menuFile->Append(wxID_EXIT, wxT("E&xit\tAlt-F4"), wxT("Quit wxFormBuilder")); + + wxMenu* menuEdit = new wxMenu; + menuEdit->Append(ID_UNDO, wxT("&Undo \tCtrl+Z"), wxT("Undo changes")); + menuEdit->Append(ID_REDO, wxT("&Redo \tCtrl+Y"), wxT("Redo changes")); + menuEdit->AppendSeparator(); + menuEdit->Append(ID_COPY, wxT("&Copy \tCtrl+C"), wxT("Copy selected object")); + menuEdit->Append(ID_CUT, wxT("Cut \tCtrl+X"), wxT("Cut selected object")); + menuEdit->Append(ID_PASTE, wxT("&Paste \tCtrl+V"), wxT("Paste on selected object")); + menuEdit->Append(ID_DELETE, wxT("&Delete \tCtrl+D"), wxT("Delete selected object")); + menuEdit->AppendSeparator(); + menuEdit->Append(ID_CLIPBOARD_COPY, wxT("Copy Object To Clipboard\tCtrl+Shift+C"), wxT("Copy Object to Clipboard")); + menuEdit->Append( + ID_CLIPBOARD_PASTE, wxT("Paste Object From Clipboard\tCtrl+Shift+V"), wxT("Paste Object from Clipboard")); + menuEdit->AppendSeparator(); + menuEdit->Append(ID_EXPAND, wxT("Toggle &Expand\tAlt+W"), wxT("Toggle wxEXPAND flag of sizeritem properties")); + menuEdit->Append(ID_STRETCH, wxT("Toggle &Stretch\tAlt+S"), wxT("Toggle option property of sizeritem properties")); + menuEdit->Append(ID_MOVE_UP, wxT("Move Up\tAlt+Up"), wxT("Move Up selected object")); + menuEdit->Append(ID_MOVE_DOWN, wxT("Move Down\tAlt+Down"), wxT("Move Down selected object")); + menuEdit->Append(ID_MOVE_LEFT, wxT("Move Left\tAlt+Left"), wxT("Move Left selected object")); + menuEdit->Append(ID_MOVE_RIGHT, wxT("Move Right\tAlt+Right"), wxT("Move Right selected object")); + menuEdit->AppendSeparator(); + menuEdit->Append(ID_FIND, wxT("&Find\tCtrl+F"), wxT("Find text in the active code viewer")); + menuEdit->AppendSeparator(); + menuEdit->Append(ID_ALIGN_LEFT, wxT("&Align &Left\tAlt+Shift+Left"), wxT("Align item to the left")); + menuEdit->Append( + ID_ALIGN_CENTER_H, wxT("&Align Center &Horizontal\tAlt+Shift+H"), wxT("Align item to the center horizontally")); + menuEdit->Append(ID_ALIGN_RIGHT, wxT("&Align &Right\tAlt+Shift+Right"), wxT("Align item to the right")); + menuEdit->Append(ID_ALIGN_TOP, wxT("&Align &Top\tAlt+Shift+Up"), wxT("Align item to the top")); + menuEdit->Append( + ID_ALIGN_CENTER_V, wxT("&Align Center &Vertical\tAlt+Shift+V"), wxT("Align item to the center vertically")); + menuEdit->Append(ID_ALIGN_BOTTOM, wxT("&Align &Bottom\tAlt+Shift+Down"), wxT("Align item to the bottom")); + + wxMenu* menuComponents = CreateMenuComponents(); + + wxMenu* menuView = new wxMenu; + menuView->Append(ID_PREVIEW_XRC, wxT("&XRC Window\tF5"), wxT("Show a preview of the XRC window")); + menuView->AppendSeparator(); + menuView->Append( + ID_WINDOW_SWAP, wxT("&Swap The Editor and Properties Window\tF12"), wxT("Swap The Editor and Properties Window")); + + wxMenu* menuTools = new wxMenu; + menuTools->Append( + ID_GEN_INHERIT_CLS, wxT("&Generate Inherited Class\tF6"), + wxT("Creates the needed files and class for proper inheritance of your designed GUI")); + + wxMenu* menuHelp = new wxMenu; + menuHelp->Append(wxID_ABOUT, wxT("&About...\tF1"), wxT("Show about dialog")); + + // now append the freshly created menu to the menu bar... + wxMenuBar* menuBar = new wxMenuBar(); + menuBar->Append(menuFile, wxT("&File")); + menuBar->Append(menuEdit, wxT("&Edit")); + menuBar->Append(menuComponents, wxT("&Components")); + menuBar->Append(menuView, wxT("&View")); + menuBar->Append(menuTools, wxT("&Tools")); + menuBar->Append(menuHelp, wxT("&Help")); return menuBar; } -wxMenu * MainFrame::CreateMenuComponents() +wxMenu* MainFrame::CreateMenuComponents() { - wxMenu *menuComponents = new wxMenu; + wxMenu* menuComponents = new wxMenu; menuComponents->Append(ID_FIND_COMPONENT, _("&Find Component...\tCtrl+Shift+F"), _("Show Component Search Dialog")); @@ -1568,53 +1497,48 @@ wxMenu * MainFrame::CreateMenuComponents() std::map packages; // List of pages to add to the menu in the same order like notebook std::vector> pages; - pages.reserve( pkg_count ); + pages.reserve(pkg_count); // Fill lookup map of packages - for ( unsigned int i = 0; i < pkg_count; ++i ) - { - auto pkg = AppData()->GetPackage( i ); - packages.insert( std::make_pair( pkg->GetPackageName(), pkg ) ); + for (unsigned int i = 0; i < pkg_count; ++i) { + auto pkg = AppData()->GetPackage(i); + packages.insert(std::make_pair(pkg->GetPackageName(), pkg)); } // Read the page order from settings and build the list of pages from it - auto *config = wxConfigBase::Get(); - wxStringTokenizer pageOrder( config->Read( wxT( "/palette/pageOrder" ), - wxT( "Common,Additional,Data,Containers,Menu/Toolbar," - "Layout,Forms,Ribbon" ) ), wxT( "," ) ); - while ( pageOrder.HasMoreTokens() ) - { + auto* config = wxConfigBase::Get(); + wxStringTokenizer pageOrder( + config->Read( + wxT("/palette/pageOrder"), wxT("Common,Additional,Data,Containers,Menu/Toolbar," + "Layout,Forms,Ribbon")), + wxT(",")); + while (pageOrder.HasMoreTokens()) { const auto packageName = pageOrder.GetNextToken(); - auto package = packages.find( packageName ); - if ( packages.end() == package ) - { + auto package = packages.find(packageName); + if (packages.end() == package) { // Plugin missing - move on continue; } // Add package to pages list and remove from lookup map - pages.push_back( std::make_pair( package->first, package->second ) ); - packages.erase( package ); + pages.push_back(std::make_pair(package->first, package->second)); + packages.erase(package); } // The remaining packages from the lookup map need to be added to the page list - for ( auto& package : packages ) - { - pages.push_back( std::make_pair( package.first, package.second ) ); - } + for (auto& package : packages) { pages.push_back(std::make_pair(package.first, package.second)); } packages.clear(); - for ( size_t i = 0; i < pages.size(); ++i ) - { + for (size_t i = 0; i < pages.size(); ++i) { const auto& page = pages[i]; auto* submenu = CreateSubmenuComponents(page.second); - wxMenuItem *menuItem = new wxMenuItem( menuComponents, wxID_ANY, page.first, wxEmptyString, - wxITEM_NORMAL, submenu ); + wxMenuItem* menuItem = + new wxMenuItem(menuComponents, wxID_ANY, page.first, wxEmptyString, wxITEM_NORMAL, submenu); -// menuComponents->AppendSubMenu( submenu, page.first ); - menuItem->SetBitmap( page.second->GetPackageIcon() ); - menuComponents->Append( menuItem ); + // menuComponents->AppendSubMenu( submenu, page.first ); + menuItem->SetBitmap(page.second->GetPackageIcon()); + menuComponents->Append(menuItem); } return menuComponents; @@ -1622,245 +1546,285 @@ wxMenu * MainFrame::CreateMenuComponents() wxMenu* MainFrame::CreateSubmenuComponents(PObjectPackage pkg) { - wxMenu *submenu = new wxMenu; + wxMenu* submenu = new wxMenu; unsigned int j = 0; - while ( j < pkg->GetObjectCount() ) - { - PObjectInfo info = pkg->GetObjectInfo( j ); + while (j < pkg->GetObjectCount()) { + PObjectInfo info = pkg->GetObjectInfo(j); - if ( info->IsStartOfGroup() ) - { + if (info->IsStartOfGroup()) { submenu->AppendSeparator(); } - if ( nullptr == info->GetComponent() ) - { - LogDebug( _( "Missing Component for Class \"" + info->GetClassName() + - "\" of Package \"" + pkg->GetPackageName() + "\"." ) ); - } - else - { + if (nullptr == info->GetComponent()) { + LogDebug( + _("Missing Component for Class \"" + info->GetClassName() + "\" of Package \"" + pkg->GetPackageName() + + "\".")); + } else { auto* item = new wxMenuItem(submenu, wxID_ANY, info->GetClassName()); - item->SetBitmap(info->GetIconFile()); - submenu->Append(item); + item->SetBitmap(info->GetIconFile()); + submenu->Append(item); } j++; } - submenu->Bind(wxEVT_MENU, &MainFrame::OnMenuComponentsClick, this); + submenu->Bind(wxEVT_MENU, &MainFrame::OnMenuComponentsClick, this); return submenu; } -wxToolBar * MainFrame::CreateFBToolBar() -{ - wxToolBar* toolbar = CreateToolBar(); - toolbar->SetToolBitmapSize( wxSize( TOOL_SIZE, TOOL_SIZE ) ); - toolbar->AddTool( ID_NEW_PRJ, wxT( "New Project" ), AppBitmaps::GetBitmap( wxT( "new" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "New Project (Ctrl+N)" ), wxT( "Start a new project." ) ); - toolbar->AddTool( ID_OPEN_PRJ, wxT( "Open Project" ), AppBitmaps::GetBitmap( wxT( "open" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Open Project (Ctrl+O)" ), wxT( "Open an existing project." ) ); - toolbar->AddTool( ID_SAVE_PRJ, wxT( "Save Project" ), AppBitmaps::GetBitmap( wxT( "save" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Save Project (Ctrl+S)" ), wxT( "Save the current project." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_UNDO, wxT( "Undo" ), AppBitmaps::GetBitmap( wxT( "undo" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Undo (Ctrl+Z)" ), wxT( "Undo the last action." ) ); - toolbar->AddTool( ID_REDO, wxT( "Redo" ), AppBitmaps::GetBitmap( wxT( "redo" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Redo (Ctrl+Y)" ), wxT( "Redo the last action that was undone." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_CUT, wxT( "Cut" ), AppBitmaps::GetBitmap( wxT( "cut" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Cut (Ctrl+X)" ), wxT( "Remove the selected object and place it on the clipboard." ) ); - toolbar->AddTool( ID_COPY, wxT( "Copy" ), AppBitmaps::GetBitmap( wxT( "copy" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Copy (Ctrl+C)" ), wxT( "Copy the selected object to the clipboard." ) ); - toolbar->AddTool( ID_PASTE, wxT( "Paste" ), AppBitmaps::GetBitmap( wxT( "paste" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Paste (Ctrl+V)" ), wxT( "Insert an object from the clipboard." ) ); - toolbar->AddTool( ID_DELETE, wxT( "Delete" ), AppBitmaps::GetBitmap( wxT( "delete" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Delete (Ctrl+D)" ), wxT( "Remove the selected object." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_GENERATE_CODE, wxT( "Generate Code" ), AppBitmaps::GetBitmap( wxT( "generate" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Generate Code (F8)" ), wxT( "Create code from the current project." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_ALIGN_LEFT, wxT( "" ), AppBitmaps::GetBitmap( wxT( "lalign" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Align Left" ), wxT( "The item will be aligned to the left of the space allotted to it by the sizer." ) ); - toolbar->AddTool( ID_ALIGN_CENTER_H, wxT( "" ), AppBitmaps::GetBitmap( wxT( "chalign" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Align Center Horizontally" ), wxT( "The item will be centered horizontally in the space allotted to it by the sizer." ) ); - toolbar->AddTool( ID_ALIGN_RIGHT, wxT( "" ), AppBitmaps::GetBitmap( wxT( "ralign" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Align Right" ), wxT( "The item will be aligned to the right of the space allotted to it by the sizer." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_ALIGN_TOP, wxT( "" ), AppBitmaps::GetBitmap( wxT( "talign" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Align Top" ), wxT( "The item will be aligned to the top of the space allotted to it by the sizer." ) ); - toolbar->AddTool( ID_ALIGN_CENTER_V, wxT( "" ), AppBitmaps::GetBitmap( wxT( "cvalign" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Align Center Vertically" ), wxT( "The item will be centered vertically within space allotted to it by the sizer." ) ); - toolbar->AddTool( ID_ALIGN_BOTTOM, wxT( "" ), AppBitmaps::GetBitmap( wxT( "balign" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Align Bottom" ), wxT( "The item will be aligned to the bottom of the space allotted to it by the sizer." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_EXPAND, wxT( "" ), AppBitmaps::GetBitmap( wxT( "expand" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Expand (Alt+W)" ), wxT( "The item will be expanded to fill the space assigned to the item." ) ); - toolbar->AddTool( ID_STRETCH, wxT( "" ), AppBitmaps::GetBitmap( wxT( "stretch" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Stretch (Alt+S)" ), wxT( "The item will grow and shrink with the sizer." ) ); - toolbar->AddSeparator(); - toolbar->AddTool( ID_BORDER_LEFT, wxT( "" ), AppBitmaps::GetBitmap( wxT( "left" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Left Border" ), wxT( "A border will be added on the left side of the item." ) ); - toolbar->AddTool( ID_BORDER_RIGHT, wxT( "" ), AppBitmaps::GetBitmap( wxT( "right" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Right Border" ), wxT( "A border will be added on the right side of the item." ) ); - toolbar->AddTool( ID_BORDER_TOP, wxT( "" ), AppBitmaps::GetBitmap( wxT( "top" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Top Border" ), wxT( "A border will be added on the top of the item." ) ); - toolbar->AddTool( ID_BORDER_BOTTOM, wxT( "" ), AppBitmaps::GetBitmap( wxT( "bottom" ), TOOL_SIZE ), wxNullBitmap, wxITEM_CHECK, wxT( "Bottom Border" ), wxT( "A border will be added on the bottom of the item." ) ); +wxToolBar* MainFrame::CreateFBToolBar() +{ + wxToolBar* toolbar = CreateToolBar(); + toolbar->SetToolBitmapSize(wxSize(TOOL_SIZE, TOOL_SIZE)); + toolbar->AddTool( + ID_NEW_PRJ, wxT("New Project"), AppBitmaps::GetBitmap(wxT("new"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("New Project (Ctrl+N)"), wxT("Start a new project.")); + toolbar->AddTool( + ID_OPEN_PRJ, wxT("Open Project"), AppBitmaps::GetBitmap(wxT("open"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Open Project (Ctrl+O)"), wxT("Open an existing project.")); + toolbar->AddTool( + ID_SAVE_PRJ, wxT("Save Project"), AppBitmaps::GetBitmap(wxT("save"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Save Project (Ctrl+S)"), wxT("Save the current project.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_UNDO, wxT("Undo"), AppBitmaps::GetBitmap(wxT("undo"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Undo (Ctrl+Z)"), wxT("Undo the last action.")); + toolbar->AddTool( + ID_REDO, wxT("Redo"), AppBitmaps::GetBitmap(wxT("redo"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Redo (Ctrl+Y)"), wxT("Redo the last action that was undone.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_CUT, wxT("Cut"), AppBitmaps::GetBitmap(wxT("cut"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Cut (Ctrl+X)"), wxT("Remove the selected object and place it on the clipboard.")); + toolbar->AddTool( + ID_COPY, wxT("Copy"), AppBitmaps::GetBitmap(wxT("copy"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Copy (Ctrl+C)"), wxT("Copy the selected object to the clipboard.")); + toolbar->AddTool( + ID_PASTE, wxT("Paste"), AppBitmaps::GetBitmap(wxT("paste"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Paste (Ctrl+V)"), wxT("Insert an object from the clipboard.")); + toolbar->AddTool( + ID_DELETE, wxT("Delete"), AppBitmaps::GetBitmap(wxT("delete"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Delete (Ctrl+D)"), wxT("Remove the selected object.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_GENERATE_CODE, wxT("Generate Code"), AppBitmaps::GetBitmap(wxT("generate"), TOOL_SIZE), wxNullBitmap, + wxITEM_NORMAL, wxT("Generate Code (F8)"), wxT("Create code from the current project.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_ALIGN_LEFT, wxT(""), AppBitmaps::GetBitmap(wxT("lalign"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Align Left"), wxT("The item will be aligned to the left of the space allotted to it by the sizer.")); + toolbar->AddTool( + ID_ALIGN_CENTER_H, wxT(""), AppBitmaps::GetBitmap(wxT("chalign"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Align Center Horizontally"), + wxT("The item will be centered horizontally in the space allotted to it by the sizer.")); + toolbar->AddTool( + ID_ALIGN_RIGHT, wxT(""), AppBitmaps::GetBitmap(wxT("ralign"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Align Right"), wxT("The item will be aligned to the right of the space allotted to it by the sizer.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_ALIGN_TOP, wxT(""), AppBitmaps::GetBitmap(wxT("talign"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Align Top"), wxT("The item will be aligned to the top of the space allotted to it by the sizer.")); + toolbar->AddTool( + ID_ALIGN_CENTER_V, wxT(""), AppBitmaps::GetBitmap(wxT("cvalign"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Align Center Vertically"), + wxT("The item will be centered vertically within space allotted to it by the sizer.")); + toolbar->AddTool( + ID_ALIGN_BOTTOM, wxT(""), AppBitmaps::GetBitmap(wxT("balign"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Align Bottom"), wxT("The item will be aligned to the bottom of the space allotted to it by the sizer.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_EXPAND, wxT(""), AppBitmaps::GetBitmap(wxT("expand"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Expand (Alt+W)"), wxT("The item will be expanded to fill the space assigned to the item.")); + toolbar->AddTool( + ID_STRETCH, wxT(""), AppBitmaps::GetBitmap(wxT("stretch"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Stretch (Alt+S)"), wxT("The item will grow and shrink with the sizer.")); toolbar->AddSeparator(); - toolbar->AddTool( ID_WINDOW_SWAP, wxT( "" ), AppBitmaps::GetBitmap( wxT( "swap" ), TOOL_SIZE ), wxNullBitmap, wxITEM_NORMAL, wxT( "Swap The Editor and Properties Window (F12)" ), wxT( "Swap the design window and properties window." ) ); - toolbar->Realize(); + toolbar->AddTool( + ID_BORDER_LEFT, wxT(""), AppBitmaps::GetBitmap(wxT("left"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Left Border"), wxT("A border will be added on the left side of the item.")); + toolbar->AddTool( + ID_BORDER_RIGHT, wxT(""), AppBitmaps::GetBitmap(wxT("right"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Right Border"), wxT("A border will be added on the right side of the item.")); + toolbar->AddTool( + ID_BORDER_TOP, wxT(""), AppBitmaps::GetBitmap(wxT("top"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Top Border"), wxT("A border will be added on the top of the item.")); + toolbar->AddTool( + ID_BORDER_BOTTOM, wxT(""), AppBitmaps::GetBitmap(wxT("bottom"), TOOL_SIZE), wxNullBitmap, wxITEM_CHECK, + wxT("Bottom Border"), wxT("A border will be added on the bottom of the item.")); + toolbar->AddSeparator(); + toolbar->AddTool( + ID_WINDOW_SWAP, wxT(""), AppBitmaps::GetBitmap(wxT("swap"), TOOL_SIZE), wxNullBitmap, wxITEM_NORMAL, + wxT("Swap The Editor and Properties Window (F12)"), wxT("Swap the design window and properties window.")); + toolbar->Realize(); - return toolbar; + return toolbar; } -wxWindow * MainFrame::CreateDesignerWindow( wxWindow *parent ) +wxWindow* MainFrame::CreateDesignerWindow(wxWindow* parent) { - m_notebook = new wxAuiNotebook( parent, ID_EDITOR_FNB, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP ); - m_notebook->SetArtProvider( new AuiTabArt() ); + m_notebook = new wxAuiNotebook(parent, ID_EDITOR_FNB, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP); + m_notebook->SetArtProvider(new AuiTabArt()); - m_visualEdit = new VisualEditor( m_notebook ); - AppData()->GetManager()->SetVisualEditor( m_visualEdit ); + m_visualEdit = new VisualEditor(m_notebook); + AppData()->GetManager()->SetVisualEditor(m_visualEdit); - m_notebook->InsertPage( 0, m_visualEdit, wxT( "Designer" ), false ); - m_notebook->SetPageBitmap( 0, AppBitmaps::GetBitmap( wxT( "designer" ), 16 ) ); + m_notebook->InsertPage(0, m_visualEdit, wxT("Designer"), false); + m_notebook->SetPageBitmap(0, AppBitmaps::GetBitmap(wxT("designer"), 16)); - m_cpp = new CppPanel( m_notebook, wxID_ANY); - m_notebook->InsertPage( 1, m_cpp, wxT( "C++" ), false ); - m_notebook->SetPageBitmap( 1, AppBitmaps::GetBitmap( wxT( "c++" ), 16 ) ); + m_cpp = new CppPanel(m_notebook, wxID_ANY); + m_notebook->InsertPage(1, m_cpp, wxT("C++"), false); + m_notebook->SetPageBitmap(1, AppBitmaps::GetBitmap(wxT("c++"), 16)); - m_python = new PythonPanel( m_notebook, wxID_ANY); - m_notebook->InsertPage( 2, m_python, wxT( "Python" ), false ); - m_notebook->SetPageBitmap( 2, AppBitmaps::GetBitmap( wxT( "python" ), 16 ) ); + m_python = new PythonPanel(m_notebook, wxID_ANY); + m_notebook->InsertPage(2, m_python, wxT("Python"), false); + m_notebook->SetPageBitmap(2, AppBitmaps::GetBitmap(wxT("python"), 16)); - m_php = new PHPPanel( m_notebook, wxID_ANY); - m_notebook->InsertPage( 3, m_php, wxT( "PHP" ), false ); - m_notebook->SetPageBitmap( 3, AppBitmaps::GetBitmap( wxT( "php" ), 16 ) ); + m_php = new PHPPanel(m_notebook, wxID_ANY); + m_notebook->InsertPage(3, m_php, wxT("PHP"), false); + m_notebook->SetPageBitmap(3, AppBitmaps::GetBitmap(wxT("php"), 16)); - m_lua = new LuaPanel(m_notebook, wxID_ANY); - m_notebook->InsertPage( 4, m_lua,wxT( "Lua" ), false ); - m_notebook->SetPageBitmap( 4, AppBitmaps::GetBitmap( wxT( "lua" ), 16 ) ); + m_lua = new LuaPanel(m_notebook, wxID_ANY); + m_notebook->InsertPage(4, m_lua, wxT("Lua"), false); + m_notebook->SetPageBitmap(4, AppBitmaps::GetBitmap(wxT("lua"), 16)); - m_xrc = new XrcPanel( m_notebook, wxID_ANY); - m_notebook->InsertPage( 5, m_xrc, wxT( "XRC" ), false ); - m_notebook->SetPageBitmap( 5, AppBitmaps::GetBitmap( wxT( "xrc" ), 16 ) ); + m_xrc = new XrcPanel(m_notebook, wxID_ANY); + m_notebook->InsertPage(5, m_xrc, wxT("XRC"), false); + m_notebook->SetPageBitmap(5, AppBitmaps::GetBitmap(wxT("xrc"), 16)); - return m_notebook; + return m_notebook; } -wxWindow * MainFrame::CreateComponentPalette ( wxWindow *parent ) +wxWindow* MainFrame::CreateComponentPalette(wxWindow* parent) { - // la paleta de componentes, no es un observador propiamente dicho, ya - // que no responde ante los eventos de la aplicación - m_palette = new wxFbPalette( parent, wxID_ANY); - m_palette->Create(); - //m_palette->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_3DFACE ) ); + // la paleta de componentes, no es un observador propiamente dicho, ya + // que no responde ante los eventos de la aplicación + m_palette = new wxFbPalette(parent, wxID_ANY); + m_palette->Create(); + // m_palette->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_3DFACE ) ); - return m_palette; + return m_palette; } -wxWindow * MainFrame::CreateObjectTree( wxWindow *parent ) +wxWindow* MainFrame::CreateObjectTree(wxWindow* parent) { - m_objTree = new ObjectTree( parent, wxID_ANY); - m_objTree->Create(); + m_objTree = new ObjectTree(parent, wxID_ANY); + m_objTree->Create(); - return m_objTree; + return m_objTree; } -wxWindow * MainFrame::CreateObjectInspector( wxWindow *parent ) +wxWindow* MainFrame::CreateObjectInspector(wxWindow* parent) { - //TO-DO: make object inspector style selectable. - int style = ( m_style == wxFB_CLASSIC_GUI ? wxFB_OI_MULTIPAGE_STYLE : wxFB_OI_SINGLE_PAGE_STYLE ); - m_objInsp = new ObjectInspector( parent, wxID_ANY, style ); - return m_objInsp; + // TO-DO: make object inspector style selectable. + int style = (m_style == wxFB_CLASSIC_GUI ? wxFB_OI_MULTIPAGE_STYLE : wxFB_OI_SINGLE_PAGE_STYLE); + m_objInsp = new ObjectInspector(parent, wxID_ANY, style); + return m_objInsp; } void MainFrame::CreateWideGui() { - // MainFrame only contains m_leftSplitter window - m_leftSplitter = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); + // MainFrame only contains m_leftSplitter window + m_leftSplitter = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); - wxWindow *objectTree = Title::CreateTitle( CreateObjectTree( m_leftSplitter ), wxT( "Object Tree" ) ); + wxWindow* objectTree = Title::CreateTitle(CreateObjectTree(m_leftSplitter), wxT("Object Tree")); - // panel1 contains Palette and splitter2 (m_rightSplitter) - wxPanel *panel1 = new wxPanel( m_leftSplitter, wxID_ANY); + // panel1 contains Palette and splitter2 (m_rightSplitter) + wxPanel* panel1 = new wxPanel(m_leftSplitter, wxID_ANY); - wxWindow *palette = Title::CreateTitle( CreateComponentPalette( panel1 ), wxT( "Component Palette" ) ); - m_rightSplitter = new wxSplitterWindow( panel1, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); + wxWindow* palette = Title::CreateTitle(CreateComponentPalette(panel1), wxT("Component Palette")); + m_rightSplitter = new wxSplitterWindow(panel1, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); - wxBoxSizer *panel1_sizer = new wxBoxSizer( wxVERTICAL ); - panel1_sizer->Add( palette, 0, wxEXPAND ); - panel1_sizer->Add( m_rightSplitter, 1, wxEXPAND ); - panel1->SetSizer( panel1_sizer ); + wxBoxSizer* panel1_sizer = new wxBoxSizer(wxVERTICAL); + panel1_sizer->Add(palette, 0, wxEXPAND); + panel1_sizer->Add(m_rightSplitter, 1, wxEXPAND); + panel1->SetSizer(panel1_sizer); - // splitter2 contains the editor and the object inspector - wxWindow *designer = Title::CreateTitle( CreateDesignerWindow( m_rightSplitter ), wxT( "Editor" ) ); - wxWindow *objectInspector = Title::CreateTitle( CreateObjectInspector( m_rightSplitter ), wxT( "Object Properties" ) ); + // splitter2 contains the editor and the object inspector + wxWindow* designer = Title::CreateTitle(CreateDesignerWindow(m_rightSplitter), wxT("Editor")); + wxWindow* objectInspector = Title::CreateTitle(CreateObjectInspector(m_rightSplitter), wxT("Object Properties")); - m_leftSplitter->SplitVertically( objectTree, panel1, m_leftSplitterWidth ); + m_leftSplitter->SplitVertically(objectTree, panel1, m_leftSplitterWidth); - // Need to update the left splitter so the right one is drawn correctly - wxSizeEvent update( GetSize(), GetId() ); - ProcessEvent( update ); - m_leftSplitter->UpdateSize(); - m_leftSplitter->SetMinimumPaneSize( 2 ); + // Need to update the left splitter so the right one is drawn correctly + wxSizeEvent update(GetSize(), GetId()); + ProcessEvent(update); + m_leftSplitter->UpdateSize(); + m_leftSplitter->SetMinimumPaneSize(2); - //modified by tyysoft to restore the last layout. - if(m_rightSplitterType == _("editor")) - { - m_rightSplitter->SplitVertically( designer, objectInspector, m_rightSplitterWidth ); - } - else - { - m_rightSplitter->SplitVertically( objectInspector, designer, m_rightSplitterWidth ); + // modified by tyysoft to restore the last layout. + if (m_rightSplitterType == _("editor")) { + m_rightSplitter->SplitVertically(designer, objectInspector, m_rightSplitterWidth); + } else { + m_rightSplitter->SplitVertically(objectInspector, designer, m_rightSplitterWidth); } - m_rightSplitter->SetSashGravity( 1 ); - m_rightSplitter->SetMinimumPaneSize( 2 ); + m_rightSplitter->SetSashGravity(1); + m_rightSplitter->SetMinimumPaneSize(2); - m_style = wxFB_WIDE_GUI; + m_style = wxFB_WIDE_GUI; - SetMinSize( wxSize( 700, 380 ) ); + SetMinSize(wxSize(700, 380)); } void MainFrame::CreateClassicGui() { - // Give ID to left splitter - //m_leftSplitter = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); - m_leftSplitter = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); - m_rightSplitter = new wxSplitterWindow( m_leftSplitter, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); - wxWindow *objectTree = Title::CreateTitle( CreateObjectTree( m_rightSplitter ), wxT( "Object Tree" ) ); - wxWindow *objectInspector = Title::CreateTitle( CreateObjectInspector( m_rightSplitter ), wxT( "Object Properties" ) ); + // Give ID to left splitter + // m_leftSplitter = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE ); + m_leftSplitter = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); + m_rightSplitter = + new wxSplitterWindow(m_leftSplitter, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_LIVE_UPDATE); + wxWindow* objectTree = Title::CreateTitle(CreateObjectTree(m_rightSplitter), wxT("Object Tree")); + wxWindow* objectInspector = Title::CreateTitle(CreateObjectInspector(m_rightSplitter), wxT("Object Properties")); - // panel1 contains palette and designer - wxPanel *panel1 = new wxPanel( m_leftSplitter, wxID_ANY); + // panel1 contains palette and designer + wxPanel* panel1 = new wxPanel(m_leftSplitter, wxID_ANY); - wxWindow *palette = Title::CreateTitle( CreateComponentPalette( panel1 ), wxT( "Component Palette" ) ); - wxWindow *designer = Title::CreateTitle( CreateDesignerWindow( panel1 ), wxT( "Editor" ) ); + wxWindow* palette = Title::CreateTitle(CreateComponentPalette(panel1), wxT("Component Palette")); + wxWindow* designer = Title::CreateTitle(CreateDesignerWindow(panel1), wxT("Editor")); - wxBoxSizer *panel1_sizer = new wxBoxSizer( wxVERTICAL ); - panel1_sizer->Add( palette, 0, wxEXPAND ); - panel1_sizer->Add( designer, 1, wxEXPAND ); - panel1->SetSizer( panel1_sizer ); + wxBoxSizer* panel1_sizer = new wxBoxSizer(wxVERTICAL); + panel1_sizer->Add(palette, 0, wxEXPAND); + panel1_sizer->Add(designer, 1, wxEXPAND); + panel1->SetSizer(panel1_sizer); - m_leftSplitter->SplitVertically( m_rightSplitter, panel1, m_leftSplitterWidth ); + m_leftSplitter->SplitVertically(m_rightSplitter, panel1, m_leftSplitterWidth); - // Need to update the left splitter so the right one is drawn correctly - wxSizeEvent update( GetSize(), GetId() ); - ProcessEvent( update ); - m_leftSplitter->UpdateSize(); + // Need to update the left splitter so the right one is drawn correctly + wxSizeEvent update(GetSize(), GetId()); + ProcessEvent(update); + m_leftSplitter->UpdateSize(); - m_rightSplitter->SplitHorizontally( objectTree, objectInspector, m_rightSplitterWidth ); - m_rightSplitter->SetMinimumPaneSize( 2 ); + m_rightSplitter->SplitHorizontally(objectTree, objectInspector, m_rightSplitterWidth); + m_rightSplitter->SetMinimumPaneSize(2); - SetMinSize( wxSize( 700, 465 ) ); + SetMinSize(wxSize(700, 465)); } -void MainFrame::OnIdle( wxIdleEvent& ) +void MainFrame::OnIdle(wxIdleEvent&) { - if ( m_leftSplitter ) - { - m_leftSplitter->SetSashPosition( m_leftSplitterWidth ); - } + if (m_leftSplitter) { + m_leftSplitter->SetSashPosition(m_leftSplitterWidth); + } - if ( m_rightSplitter ) - { - m_rightSplitter->SetSashPosition( m_rightSplitterWidth ); - } + if (m_rightSplitter) { + m_rightSplitter->SetSashPosition(m_rightSplitterWidth); + } - Disconnect( wxEVT_IDLE, wxIdleEventHandler( MainFrame::OnIdle ) ); + Disconnect(wxEVT_IDLE, wxIdleEventHandler(MainFrame::OnIdle)); - if ( m_autoSash ) - { - // Init. m_rightSplitter_sash_pos - m_rightSplitter_sash_pos = m_rightSplitter->GetSashPosition(); - m_rightSplitter->Connect( wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, wxSplitterEventHandler( MainFrame::OnSplitterChanged ) ); - } + if (m_autoSash) { + // Init. m_rightSplitter_sash_pos + m_rightSplitter_sash_pos = m_rightSplitter->GetSashPosition(); + m_rightSplitter->Connect( + wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, wxSplitterEventHandler(MainFrame::OnSplitterChanged)); + } } -void MainFrame::OnSplitterChanged( wxSplitterEvent &event ) +void MainFrame::OnSplitterChanged(wxSplitterEvent& event) { - LogDebug(wxT("MainFrame::OnSplitterChanged > pos = %d"), event.GetSashPosition()); + LogDebug(wxT("MainFrame::OnSplitterChanged > pos = %d"), event.GetSashPosition()); - // update position - m_rightSplitter_sash_pos = event.GetSashPosition(); + // update position + m_rightSplitter_sash_pos = event.GetSashPosition(); } void MainFrame::OnWindowSwap(wxCommandEvent&) @@ -1885,10 +1849,10 @@ void MainFrame::OnFindComponent(wxCommandEvent& WXUNUSED(event)) } } -void MainFrame::OnMenuComponentsClick( wxCommandEvent &e ) +void MainFrame::OnMenuComponentsClick(wxCommandEvent& e) { - wxMenu *menu = static_cast( e.GetEventObject() ); - wxMenuItem *item = menu->FindChildItem( e.GetId() ); + wxMenu* menu = static_cast(e.GetEventObject()); + wxMenuItem* item = menu->FindChildItem(e.GetId()); - AppData()->CreateObject( item->GetItemLabelText() ); + AppData()->CreateObject(item->GetItemLabelText()); } diff --git a/src/rad/mainframe.h b/src/rad/mainframe.h index adf0b24d6..e2450d582 100644 --- a/src/rad/mainframe.h +++ b/src/rad/mainframe.h @@ -26,161 +26,159 @@ #ifndef RAD_MAINFRAME_H #define RAD_MAINFRAME_H -#include #include - #include #include +#include #include "utils/wxfbdefs.h" -class wxFBEvent; -class wxFBObjectEvent; -class wxFBPropertyEvent; -class wxFBEventHandlerEvent; class CppPanel; -class PythonPanel; class LuaPanel; -class PHPPanel; -class XrcPanel; -class ObjectTree; class ObjectInspector; -class wxFbPalette; +class ObjectTree; +class PHPPanel; +class PythonPanel; class VisualEditor; +class wxFBEvent; +class wxFBEventHandlerEvent; +class wxFBObjectEvent; +class wxFbPalette; +class wxFBPropertyEvent; +class XrcPanel; + /** * wxFormBuilder GUI styles. */ -enum { - wxFB_DEFAULT_GUI, - wxFB_DOCKABLE_GUI, - wxFB_CLASSIC_GUI, - wxFB_WIDE_GUI -}; +enum { wxFB_DEFAULT_GUI, wxFB_DOCKABLE_GUI, wxFB_CLASSIC_GUI, wxFB_WIDE_GUI }; + class MainFrame : public wxFrame { - private: - wxSplitterWindow *m_leftSplitter; - wxSplitterWindow *m_rightSplitter; - int m_leftSplitterWidth; - int m_rightSplitterWidth; - wxString m_rightSplitterType; - - //wxFrameManager m_mgr; - wxAuiNotebook *m_notebook; - wxFbPalette *m_palette; - ObjectTree *m_objTree; - ObjectInspector *m_objInsp; - VisualEditor *m_visualEdit; - CppPanel *m_cpp; - PythonPanel *m_python; - LuaPanel *m_lua; - PHPPanel *m_php; - XrcPanel *m_xrc; - int m_style; - - // Save which page is selected - int m_page_selection; - - // Save right splitter's sash position - int m_rightSplitter_sash_pos; - - // Automatically update sash in splitter window base on user action - bool m_autoSash; - - wxString m_currentDir; - wxString m_recentProjects[4]; - - void UpdateFrame(); - - // Actualiza los projectos más recientes en el menu - void UpdateRecentProjects(); - void OnOpenRecent(wxCommandEvent &event); - void UpdateLayoutTools(); - - // Used to correctly restore splitter position - void OnIdle( wxIdleEvent& ); - - wxFindReplaceData m_findData; - wxFindReplaceDialog* m_findDialog; - - // Used to force propgrid to save on lost focus - wxEvtHandler* m_focusKillEvtHandler; - - DECLARE_EVENT_TABLE() - public: - MainFrame(wxWindow *parent, int id = wxID_ANY, int style = wxFB_DEFAULT_GUI, wxPoint pos = wxDefaultPosition, wxSize size = wxSize( 1000, 800 ) ); - ~MainFrame() override; - void RestorePosition(const wxString &name); - void SavePosition(const wxString &name); - void OnSaveProject(wxCommandEvent &event); - void OnSaveAsProject(wxCommandEvent &event); - void OnOpenProject(wxCommandEvent &event); - void OnNewProject(wxCommandEvent &event); - void OnGenerateCode(wxCommandEvent &event); - void OnAbout(wxCommandEvent &event); - void OnExit(wxCommandEvent &event); - void OnClose(wxCloseEvent &event); - void OnImportXrc(wxCommandEvent &event); - void OnUndo(wxCommandEvent &event); - void OnRedo(wxCommandEvent &event); - void OnCopy (wxCommandEvent &event); - void OnPaste (wxCommandEvent &event); - void OnCut (wxCommandEvent &event); - void OnDelete (wxCommandEvent &event); - void OnClipboardCopy(wxCommandEvent& e); - void OnClipboardPaste(wxCommandEvent& e); - void OnClipboardPasteUpdateUI( wxUpdateUIEvent& e ); - void OnToggleExpand (wxCommandEvent &event); - void OnToggleStretch (wxCommandEvent &event); - void OnMoveUp (wxCommandEvent &event); - void OnMoveDown (wxCommandEvent &event); - void OnMoveLeft (wxCommandEvent &event); - void OnMoveRight (wxCommandEvent &event); - void OnChangeAlignment (wxCommandEvent &event); - void OnChangeBorder(wxCommandEvent& e); - void OnXrcPreview(wxCommandEvent& e); - void OnGenInhertedClass(wxCommandEvent& e); - void OnWindowSwap(wxCommandEvent& e); - void OnFindComponent(wxCommandEvent& e); - void OnMenuComponentsClick(wxCommandEvent& e); - - void OnAuiNotebookPageChanged( wxAuiNotebookEvent& event ); - - void OnProjectLoaded( wxFBEvent& event ); - void OnProjectSaved( wxFBEvent& event ); - void OnObjectExpanded( wxFBObjectEvent& event ); - void OnObjectSelected( wxFBObjectEvent& event ); - void OnObjectCreated( wxFBObjectEvent& event ); - void OnObjectRemoved( wxFBObjectEvent& event ); - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnEventHandlerModified( wxFBEventHandlerEvent& event ); - void OnCodeGeneration( wxFBEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - - void OnSplitterChanged( wxSplitterEvent &event ); - - void InsertRecentProject(const wxString &file); - - wxWindow *CreateComponentPalette (wxWindow *parent); - wxWindow *CreateDesignerWindow (wxWindow *parent); - wxWindow *CreateObjectTree (wxWindow *parent); - wxWindow *CreateObjectInspector (wxWindow *parent); - wxMenuBar *CreateFBMenuBar(); - wxMenu *CreateMenuComponents(); - wxMenu *CreateSubmenuComponents(PObjectPackage pkg); - wxToolBar *CreateFBToolBar(); - - void CreateWideGui(); - void CreateClassicGui(); - - void OnFindDialog( wxCommandEvent& event ); - void OnFind( wxFindDialogEvent& event ); - void OnFindClose( wxFindDialogEvent& event ); - - bool SaveWarning(); - }; - -#endif // RAD_MAINFRAME_H +private: + wxSplitterWindow* m_leftSplitter; + wxSplitterWindow* m_rightSplitter; + int m_leftSplitterWidth; + int m_rightSplitterWidth; + wxString m_rightSplitterType; + + // wxFrameManager m_mgr; + wxAuiNotebook* m_notebook; + wxFbPalette* m_palette; + ObjectTree* m_objTree; + ObjectInspector* m_objInsp; + VisualEditor* m_visualEdit; + CppPanel* m_cpp; + PythonPanel* m_python; + LuaPanel* m_lua; + PHPPanel* m_php; + XrcPanel* m_xrc; + int m_style; + + // Save which page is selected + int m_page_selection; + + // Save right splitter's sash position + int m_rightSplitter_sash_pos; + + // Automatically update sash in splitter window base on user action + bool m_autoSash; + + wxString m_currentDir; + wxString m_recentProjects[4]; + + void UpdateFrame(); + + // Actualiza los projectos más recientes en el menu + void UpdateRecentProjects(); + void OnOpenRecent(wxCommandEvent& event); + void UpdateLayoutTools(); + + // Used to correctly restore splitter position + void OnIdle(wxIdleEvent&); + + wxFindReplaceData m_findData; + wxFindReplaceDialog* m_findDialog; + + // Used to force propgrid to save on lost focus + wxEvtHandler* m_focusKillEvtHandler; + + DECLARE_EVENT_TABLE() +public: + MainFrame( + wxWindow* parent, int id = wxID_ANY, int style = wxFB_DEFAULT_GUI, wxPoint pos = wxDefaultPosition, + wxSize size = wxSize(1000, 800)); + ~MainFrame() override; + void RestorePosition(const wxString& name); + void SavePosition(const wxString& name); + void OnSaveProject(wxCommandEvent& event); + void OnSaveAsProject(wxCommandEvent& event); + void OnOpenProject(wxCommandEvent& event); + void OnNewProject(wxCommandEvent& event); + void OnGenerateCode(wxCommandEvent& event); + void OnAbout(wxCommandEvent& event); + void OnExit(wxCommandEvent& event); + void OnClose(wxCloseEvent& event); + void OnImportXrc(wxCommandEvent& event); + void OnUndo(wxCommandEvent& event); + void OnRedo(wxCommandEvent& event); + void OnCopy(wxCommandEvent& event); + void OnPaste(wxCommandEvent& event); + void OnCut(wxCommandEvent& event); + void OnDelete(wxCommandEvent& event); + void OnClipboardCopy(wxCommandEvent& e); + void OnClipboardPaste(wxCommandEvent& e); + void OnClipboardPasteUpdateUI(wxUpdateUIEvent& e); + void OnToggleExpand(wxCommandEvent& event); + void OnToggleStretch(wxCommandEvent& event); + void OnMoveUp(wxCommandEvent& event); + void OnMoveDown(wxCommandEvent& event); + void OnMoveLeft(wxCommandEvent& event); + void OnMoveRight(wxCommandEvent& event); + void OnChangeAlignment(wxCommandEvent& event); + void OnChangeBorder(wxCommandEvent& e); + void OnXrcPreview(wxCommandEvent& e); + void OnGenInhertedClass(wxCommandEvent& e); + void OnWindowSwap(wxCommandEvent& e); + void OnFindComponent(wxCommandEvent& e); + void OnMenuComponentsClick(wxCommandEvent& e); + + void OnAuiNotebookPageChanged(wxAuiNotebookEvent& event); + + void OnProjectLoaded(wxFBEvent& event); + void OnProjectSaved(wxFBEvent& event); + void OnObjectExpanded(wxFBObjectEvent& event); + void OnObjectSelected(wxFBObjectEvent& event); + void OnObjectCreated(wxFBObjectEvent& event); + void OnObjectRemoved(wxFBObjectEvent& event); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnEventHandlerModified(wxFBEventHandlerEvent& event); + void OnCodeGeneration(wxFBEvent& event); + void OnProjectRefresh(wxFBEvent& event); + + void OnSplitterChanged(wxSplitterEvent& event); + + void InsertRecentProject(const wxString& file); + + wxWindow* CreateComponentPalette(wxWindow* parent); + wxWindow* CreateDesignerWindow(wxWindow* parent); + wxWindow* CreateObjectTree(wxWindow* parent); + wxWindow* CreateObjectInspector(wxWindow* parent); + wxMenuBar* CreateFBMenuBar(); + wxMenu* CreateMenuComponents(); + wxMenu* CreateSubmenuComponents(PObjectPackage pkg); + wxToolBar* CreateFBToolBar(); + + void CreateWideGui(); + void CreateClassicGui(); + + void OnFindDialog(wxCommandEvent& event); + void OnFind(wxFindDialogEvent& event); + void OnFindClose(wxFindDialogEvent& event); + + bool SaveWarning(); +}; + +#endif // RAD_MAINFRAME_H diff --git a/src/rad/menueditor.cpp b/src/rad/menueditor.cpp index d38e082fa..77c239a42 100644 --- a/src/rad/menueditor.cpp +++ b/src/rad/menueditor.cpp @@ -27,176 +27,167 @@ #include "model/objectbase.h" -enum -{ - ID_ADDMENUITEM = wxID_HIGHEST + 1, - ID_ADDSEPARATOR, - ID_MENUDOWN, - ID_MENULEFT, - ID_MENURIGHT, - ID_MENUUP, - ID_REMOVEMENUITEM, - ID_LABEL, - ID_MODIFYMENUITEM, + +enum { + ID_ADDMENUITEM = wxID_HIGHEST + 1, + ID_ADDSEPARATOR, + ID_MENUDOWN, + ID_MENULEFT, + ID_MENURIGHT, + ID_MENUUP, + ID_REMOVEMENUITEM, + ID_LABEL, + ID_MODIFYMENUITEM, }; #define IDENTATION 4 BEGIN_EVENT_TABLE(MenuEditor, wxDialog) - EVT_BUTTON(ID_ADDMENUITEM, MenuEditor::OnAddMenuItem) - EVT_BUTTON(ID_ADDSEPARATOR, MenuEditor::OnAddSeparator) - EVT_BUTTON(ID_MODIFYMENUITEM, MenuEditor::OnModifyMenuItem) - EVT_BUTTON(ID_REMOVEMENUITEM, MenuEditor::OnRemoveMenuItem) - EVT_BUTTON(ID_MENUDOWN, MenuEditor::OnMenuDown) - EVT_BUTTON(ID_MENULEFT, MenuEditor::OnMenuLeft) - EVT_BUTTON(ID_MENURIGHT, MenuEditor::OnMenuRight) - EVT_BUTTON(ID_MENUUP, MenuEditor::OnMenuUp) - EVT_UPDATE_UI_RANGE(ID_MENUDOWN, ID_MENUUP, MenuEditor::OnUpdateMovers) - EVT_TEXT_ENTER(wxID_ANY, MenuEditor::OnEnter) - EVT_TEXT(ID_LABEL, MenuEditor::OnLabelChanged) - EVT_LIST_ITEM_ACTIVATED(wxID_ANY, MenuEditor::OnItemActivated) +EVT_BUTTON(ID_ADDMENUITEM, MenuEditor::OnAddMenuItem) +EVT_BUTTON(ID_ADDSEPARATOR, MenuEditor::OnAddSeparator) +EVT_BUTTON(ID_MODIFYMENUITEM, MenuEditor::OnModifyMenuItem) +EVT_BUTTON(ID_REMOVEMENUITEM, MenuEditor::OnRemoveMenuItem) +EVT_BUTTON(ID_MENUDOWN, MenuEditor::OnMenuDown) +EVT_BUTTON(ID_MENULEFT, MenuEditor::OnMenuLeft) +EVT_BUTTON(ID_MENURIGHT, MenuEditor::OnMenuRight) +EVT_BUTTON(ID_MENUUP, MenuEditor::OnMenuUp) +EVT_UPDATE_UI_RANGE(ID_MENUDOWN, ID_MENUUP, MenuEditor::OnUpdateMovers) +EVT_TEXT_ENTER(wxID_ANY, MenuEditor::OnEnter) +EVT_TEXT(ID_LABEL, MenuEditor::OnLabelChanged) +EVT_LIST_ITEM_ACTIVATED(wxID_ANY, MenuEditor::OnItemActivated) END_EVENT_TABLE() -MenuEditor::MenuEditor(wxWindow *parent, int id) : wxDialog(parent,id,wxT("Menu Editor"),wxDefaultPosition,wxDefaultSize) + +MenuEditor::MenuEditor(wxWindow* parent, int id) : + wxDialog(parent, id, wxT("Menu Editor"), wxDefaultPosition, wxDefaultSize) { - wxBoxSizer *mainSizer; - mainSizer = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *sizerTop; - sizerTop = new wxBoxSizer(wxHORIZONTAL); - m_menuList = new wxListCtrl(this,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxLC_REPORT | wxLC_SINGLE_SEL | wxSTATIC_BORDER); - m_menuList->InsertColumn(0, wxT("Label"), wxLIST_FORMAT_LEFT, 150); - m_menuList->InsertColumn(1, wxT("Shortcut"), wxLIST_FORMAT_LEFT, 80); - m_menuList->InsertColumn(2, wxT("Id"), wxLIST_FORMAT_LEFT, 80); - m_menuList->InsertColumn(3, wxT("Name"), wxLIST_FORMAT_LEFT, 50); - m_menuList->InsertColumn(4, wxT("Help String"), wxLIST_FORMAT_LEFT, 150); - m_menuList->InsertColumn(5, wxT("Kind"), wxLIST_FORMAT_LEFT, 120); - int width = 0; - for ( int i = 0; i < m_menuList->GetColumnCount(); ++i ) - { - width += m_menuList->GetColumnWidth( i ); - } - m_menuList->SetMinSize( wxSize( width, -1 ) ); - sizerTop->Add(m_menuList, 1, wxALL|wxEXPAND, 5); - wxStaticBoxSizer *sizer1; - sizer1 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wxT("Menu item")), wxVERTICAL); - const auto sizer11 = new wxFlexGridSizer(2, 0, 0); - sizer11->AddGrowableCol(1); - - wxStaticText *m_stLabel; - m_stLabel = new wxStaticText(this,wxID_ANY,wxT("Label"),wxDefaultPosition,wxDefaultSize,0); - sizer11->Add(m_stLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); - m_tcLabel = new wxTextCtrl(this,ID_LABEL,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER); - sizer11->Add(m_tcLabel, 0, wxALL | wxEXPAND, 5); - - wxStaticText *m_stShortcut; - m_stShortcut = new wxStaticText(this,wxID_ANY,wxT("Shortcut"),wxDefaultPosition,wxDefaultSize,0); - sizer11->Add(m_stShortcut, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); - m_tcShortcut = new wxTextCtrl(this,ID_LABEL,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER); - sizer11->Add(m_tcShortcut, 0, wxALL | wxEXPAND, 5); - - wxStaticText *m_stId; - m_stId = new wxStaticText(this,wxID_ANY,wxT("Id"),wxDefaultPosition,wxDefaultSize,0); - sizer11->Add(m_stId, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); - m_tcId = new wxTextCtrl(this,wxID_ANY,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER); - sizer11->Add(m_tcId, 0, wxALL | wxEXPAND, 5); - - wxStaticText *m_stName; - m_stName = new wxStaticText(this,wxID_ANY,wxT("Name"),wxDefaultPosition,wxDefaultSize,0); - sizer11->Add(m_stName, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); - m_tcName = new wxTextCtrl(this,wxID_ANY,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER); - sizer11->Add(m_tcName, 0, wxALL | wxEXPAND, 5); - - wxStaticText *m_stHelpString; - m_stHelpString = new wxStaticText(this,wxID_ANY,wxT("Help String"),wxDefaultPosition,wxDefaultSize,0); - sizer11->Add(m_stHelpString, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); - m_tcHelpString = new wxTextCtrl(this,wxID_ANY,wxT(""),wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER); - sizer11->Add(m_tcHelpString, 0, wxALL | wxEXPAND, 5); - - sizer1->Add(sizer11, 0, wxALL | wxEXPAND, 0); - - wxString choices[] = {wxT("Normal"), wxT("Check"), wxT("Radio")}; - m_rbItemKind = new wxRadioBox(this, wxID_ANY, wxT("Kind"), wxDefaultPosition, wxDefaultSize, - 3, choices, 1, wxRA_SPECIFY_ROWS); - sizer1->Add(m_rbItemKind, 0, wxALL | wxEXPAND, 5); - - wxBoxSizer *sizer4; - sizer4 = new wxBoxSizer(wxHORIZONTAL); - - wxButton *m_bAdd; - m_bAdd = new wxButton(this,ID_ADDMENUITEM,wxT("&Add"),wxDefaultPosition,wxDefaultSize,0); - sizer4->Add(m_bAdd, 1, wxALL, 5); - - wxButton *m_bModify; - m_bModify = new wxButton(this,ID_MODIFYMENUITEM,wxT("&Modify"),wxDefaultPosition,wxDefaultSize,0); - sizer4->Add(m_bModify, 1, wxALL, 5); - - wxButton *m_bRemove; - m_bRemove = new wxButton(this,ID_REMOVEMENUITEM,wxT("&Remove"),wxDefaultPosition,wxDefaultSize,0); - sizer4->Add(m_bRemove, 1, wxALL, 5); - - sizer1->Add(sizer4, 0, wxEXPAND, 5); - - wxButton *m_bAddSep; - m_bAddSep = new wxButton(this,ID_ADDSEPARATOR,wxT("Add &Separator"),wxDefaultPosition,wxDefaultSize,0); - sizer1->Add(m_bAddSep, 0, wxALL|wxEXPAND, 5); - sizerTop->Add(sizer1, 0, wxALL | wxEXPAND, 5); - mainSizer->Add(sizerTop, 1, wxEXPAND, 5); - wxBoxSizer *sizerMoveButtons; - sizerMoveButtons = new wxBoxSizer(wxHORIZONTAL); - wxButton *m_bUp; - m_bUp = new wxButton(this,ID_MENUUP,wxT("&Up"),wxDefaultPosition,wxDefaultSize,0); - sizerMoveButtons->Add(m_bUp, 0, wxALL, 5); - wxButton *m_bDown; - m_bDown = new wxButton(this,ID_MENUDOWN,wxT("&Down"),wxDefaultPosition,wxDefaultSize,0); - sizerMoveButtons->Add(m_bDown, 0, wxALL, 5); - wxButton *m_bLeft; - m_bLeft = new wxButton(this,ID_MENULEFT,wxT("<"),wxDefaultPosition,wxDefaultSize,0); - sizerMoveButtons->Add(m_bLeft, 0, wxALL, 5); - wxButton *m_bRight; - m_bRight = new wxButton(this,ID_MENURIGHT,wxT(">"),wxDefaultPosition,wxDefaultSize,0); - sizerMoveButtons->Add(m_bRight, 0, wxALL, 5); - wxStdDialogButtonSizer* sizerOkCancel = new wxStdDialogButtonSizer(); - sizerOkCancel->AddButton( new wxButton( this, wxID_OK ) ); - sizerOkCancel->AddButton( new wxButton( this, wxID_CANCEL ) ); - sizerOkCancel->Realize(); - sizerMoveButtons->Add(sizerOkCancel, 1, wxALL, 5); - mainSizer->Add(sizerMoveButtons, 0, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5); - this->SetSizer(mainSizer); - mainSizer->SetSizeHints( this ); - this->SetAutoLayout(true); - this->Layout(); - //SetClientSize(560, 368); - CenterOnScreen(); + wxBoxSizer* mainSizer; + mainSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer* sizerTop; + sizerTop = new wxBoxSizer(wxHORIZONTAL); + m_menuList = + new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_SINGLE_SEL | wxSTATIC_BORDER); + m_menuList->InsertColumn(0, wxT("Label"), wxLIST_FORMAT_LEFT, 150); + m_menuList->InsertColumn(1, wxT("Shortcut"), wxLIST_FORMAT_LEFT, 80); + m_menuList->InsertColumn(2, wxT("Id"), wxLIST_FORMAT_LEFT, 80); + m_menuList->InsertColumn(3, wxT("Name"), wxLIST_FORMAT_LEFT, 50); + m_menuList->InsertColumn(4, wxT("Help String"), wxLIST_FORMAT_LEFT, 150); + m_menuList->InsertColumn(5, wxT("Kind"), wxLIST_FORMAT_LEFT, 120); + int width = 0; + for (int i = 0; i < m_menuList->GetColumnCount(); ++i) { width += m_menuList->GetColumnWidth(i); } + m_menuList->SetMinSize(wxSize(width, -1)); + sizerTop->Add(m_menuList, 1, wxALL | wxEXPAND, 5); + wxStaticBoxSizer* sizer1; + sizer1 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wxT("Menu item")), wxVERTICAL); + const auto sizer11 = new wxFlexGridSizer(2, 0, 0); + sizer11->AddGrowableCol(1); + + wxStaticText* m_stLabel; + m_stLabel = new wxStaticText(this, wxID_ANY, wxT("Label"), wxDefaultPosition, wxDefaultSize, 0); + sizer11->Add(m_stLabel, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); + m_tcLabel = new wxTextCtrl(this, ID_LABEL, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); + sizer11->Add(m_tcLabel, 0, wxALL | wxEXPAND, 5); + + wxStaticText* m_stShortcut; + m_stShortcut = new wxStaticText(this, wxID_ANY, wxT("Shortcut"), wxDefaultPosition, wxDefaultSize, 0); + sizer11->Add(m_stShortcut, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); + m_tcShortcut = new wxTextCtrl(this, ID_LABEL, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); + sizer11->Add(m_tcShortcut, 0, wxALL | wxEXPAND, 5); + + wxStaticText* m_stId; + m_stId = new wxStaticText(this, wxID_ANY, wxT("Id"), wxDefaultPosition, wxDefaultSize, 0); + sizer11->Add(m_stId, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); + m_tcId = new wxTextCtrl(this, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); + sizer11->Add(m_tcId, 0, wxALL | wxEXPAND, 5); + + wxStaticText* m_stName; + m_stName = new wxStaticText(this, wxID_ANY, wxT("Name"), wxDefaultPosition, wxDefaultSize, 0); + sizer11->Add(m_stName, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); + m_tcName = new wxTextCtrl(this, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); + sizer11->Add(m_tcName, 0, wxALL | wxEXPAND, 5); + + wxStaticText* m_stHelpString; + m_stHelpString = new wxStaticText(this, wxID_ANY, wxT("Help String"), wxDefaultPosition, wxDefaultSize, 0); + sizer11->Add(m_stHelpString, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); + m_tcHelpString = new wxTextCtrl(this, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); + sizer11->Add(m_tcHelpString, 0, wxALL | wxEXPAND, 5); + + sizer1->Add(sizer11, 0, wxALL | wxEXPAND, 0); + + wxString choices[] = {wxT("Normal"), wxT("Check"), wxT("Radio")}; + m_rbItemKind = + new wxRadioBox(this, wxID_ANY, wxT("Kind"), wxDefaultPosition, wxDefaultSize, 3, choices, 1, wxRA_SPECIFY_ROWS); + sizer1->Add(m_rbItemKind, 0, wxALL | wxEXPAND, 5); + + wxBoxSizer* sizer4; + sizer4 = new wxBoxSizer(wxHORIZONTAL); + + wxButton* m_bAdd; + m_bAdd = new wxButton(this, ID_ADDMENUITEM, wxT("&Add"), wxDefaultPosition, wxDefaultSize, 0); + sizer4->Add(m_bAdd, 1, wxALL, 5); + + wxButton* m_bModify; + m_bModify = new wxButton(this, ID_MODIFYMENUITEM, wxT("&Modify"), wxDefaultPosition, wxDefaultSize, 0); + sizer4->Add(m_bModify, 1, wxALL, 5); + + wxButton* m_bRemove; + m_bRemove = new wxButton(this, ID_REMOVEMENUITEM, wxT("&Remove"), wxDefaultPosition, wxDefaultSize, 0); + sizer4->Add(m_bRemove, 1, wxALL, 5); + + sizer1->Add(sizer4, 0, wxEXPAND, 5); + + wxButton* m_bAddSep; + m_bAddSep = new wxButton(this, ID_ADDSEPARATOR, wxT("Add &Separator"), wxDefaultPosition, wxDefaultSize, 0); + sizer1->Add(m_bAddSep, 0, wxALL | wxEXPAND, 5); + sizerTop->Add(sizer1, 0, wxALL | wxEXPAND, 5); + mainSizer->Add(sizerTop, 1, wxEXPAND, 5); + wxBoxSizer* sizerMoveButtons; + sizerMoveButtons = new wxBoxSizer(wxHORIZONTAL); + wxButton* m_bUp; + m_bUp = new wxButton(this, ID_MENUUP, wxT("&Up"), wxDefaultPosition, wxDefaultSize, 0); + sizerMoveButtons->Add(m_bUp, 0, wxALL, 5); + wxButton* m_bDown; + m_bDown = new wxButton(this, ID_MENUDOWN, wxT("&Down"), wxDefaultPosition, wxDefaultSize, 0); + sizerMoveButtons->Add(m_bDown, 0, wxALL, 5); + wxButton* m_bLeft; + m_bLeft = new wxButton(this, ID_MENULEFT, wxT("<"), wxDefaultPosition, wxDefaultSize, 0); + sizerMoveButtons->Add(m_bLeft, 0, wxALL, 5); + wxButton* m_bRight; + m_bRight = new wxButton(this, ID_MENURIGHT, wxT(">"), wxDefaultPosition, wxDefaultSize, 0); + sizerMoveButtons->Add(m_bRight, 0, wxALL, 5); + wxStdDialogButtonSizer* sizerOkCancel = new wxStdDialogButtonSizer(); + sizerOkCancel->AddButton(new wxButton(this, wxID_OK)); + sizerOkCancel->AddButton(new wxButton(this, wxID_CANCEL)); + sizerOkCancel->Realize(); + sizerMoveButtons->Add(sizerOkCancel, 1, wxALL, 5); + mainSizer->Add(sizerMoveButtons, 0, wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + this->SetSizer(mainSizer); + mainSizer->SetSizeHints(this); + this->SetAutoLayout(true); + this->Layout(); + // SetClientSize(560, 368); + CenterOnScreen(); } void MenuEditor::AddChild(long& n, int ident, PObjectBase obj) { - for (unsigned int i = 0; i < obj->GetChildCount(); i++) - { + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { PObjectBase childObj = obj->GetChild(i); - if (childObj->GetClassName() == wxT("wxMenuItem") ) - { - InsertItem(n++, wxString(wxChar(' '), ident * IDENTATION) + childObj->GetPropertyAsString(wxT("label")), - childObj->GetPropertyAsString(wxT("shortcut")), - childObj->GetPropertyAsString(wxT("id")), - childObj->GetPropertyAsString(wxT("name")), - childObj->GetPropertyAsString(wxT("help")), - childObj->GetPropertyAsString(wxT("kind")), - childObj); - } - else if (childObj->GetClassName() == wxT("separator") ) - { - InsertItem(n++, wxString(wxChar(' '), ident * IDENTATION) + wxT("---"), wxT(""), wxT(""), wxT(""), wxT(""), wxT(""), childObj); - } - else - { - InsertItem(n++, wxString(wxChar(' '), ident * IDENTATION) + childObj->GetPropertyAsString(wxT("label")), - wxT(""), - childObj->GetPropertyAsString(wxT("id")), - childObj->GetPropertyAsString(wxT("name")), - childObj->GetPropertyAsString(wxT("help")), - wxT(""), - childObj); + if (childObj->GetClassName() == wxT("wxMenuItem")) { + InsertItem( + n++, wxString(wxChar(' '), ident * IDENTATION) + childObj->GetPropertyAsString(wxT("label")), + childObj->GetPropertyAsString(wxT("shortcut")), childObj->GetPropertyAsString(wxT("id")), + childObj->GetPropertyAsString(wxT("name")), childObj->GetPropertyAsString(wxT("help")), + childObj->GetPropertyAsString(wxT("kind")), childObj); + } else if (childObj->GetClassName() == wxT("separator")) { + InsertItem( + n++, wxString(wxChar(' '), ident * IDENTATION) + wxT("---"), wxT(""), wxT(""), wxT(""), wxT(""), wxT(""), + childObj); + } else { + InsertItem( + n++, wxString(wxChar(' '), ident * IDENTATION) + childObj->GetPropertyAsString(wxT("label")), wxT(""), + childObj->GetPropertyAsString(wxT("id")), childObj->GetPropertyAsString(wxT("name")), + childObj->GetPropertyAsString(wxT("help")), wxT(""), childObj); AddChild(n, ident + 1, childObj); } } @@ -204,7 +195,7 @@ void MenuEditor::AddChild(long& n, int ident, PObjectBase obj) void MenuEditor::Populate(PObjectBase obj) { - assert(obj && obj->GetClassName() == wxT("wxMenuBar") ); + assert(obj && obj->GetClassName() == wxT("wxMenuBar")); long n = 0; AddChild(n, 0, obj); } @@ -219,80 +210,70 @@ bool MenuEditor::HasChildren(long n) PObjectBase MenuEditor::GetMenu(long& n, PObjectDatabase base, bool isSubMenu) { - // Get item from list control + // Get item from list control wxString label, shortcut, id, name, help, kind; - PObjectBase menu; + PObjectBase menu; GetItem(n, label, shortcut, id, name, help, kind, &menu); - bool createNew = true; - if ( menu ) - { - createNew = ( menu->GetClassName() != (isSubMenu ? wxT("submenu") : wxT("wxMenu")) ); - } + bool createNew = true; + if (menu) { + createNew = (menu->GetClassName() != (isSubMenu ? wxT("submenu") : wxT("wxMenu"))); + } // preserve original menu if the object types match // this preserves properties that are not exposed in the menu editor - like C++ scope - if ( createNew ) - { - PObjectInfo info = base->GetObjectInfo(isSubMenu ? wxT("submenu") : wxT("wxMenu") ); - menu = base->NewObject(info); + if (createNew) { + PObjectInfo info = base->GetObjectInfo(isSubMenu ? wxT("submenu") : wxT("wxMenu")); + menu = base->NewObject(info); } - label.Trim(true); label.Trim(false); - menu->GetProperty( wxT("label") )->SetValue(label); - menu->GetProperty( wxT("name") )->SetValue(name); + label.Trim(true); + label.Trim(false); + menu->GetProperty(wxT("label"))->SetValue(label); + menu->GetProperty(wxT("name"))->SetValue(name); int ident = GetItemIdentation(n); n++; - while (n < m_menuList->GetItemCount() && GetItemIdentation(n) > ident) - { - PObjectBase menuitem; + while (n < m_menuList->GetItemCount() && GetItemIdentation(n) > ident) { + PObjectBase menuitem; GetItem(n, label, shortcut, id, name, help, kind, &menuitem); - createNew = true; - - label.Trim(true); label.Trim(false); - if (label == wxT("---")) - { - if ( menuitem ) - { - createNew = ( menuitem->GetClassName() != wxT("separator") ); - } - - if ( createNew ) - { - PObjectInfo info = base->GetObjectInfo( wxT("separator") ); - menuitem = base->NewObject(info); - } + createNew = true; + + label.Trim(true); + label.Trim(false); + if (label == wxT("---")) { + if (menuitem) { + createNew = (menuitem->GetClassName() != wxT("separator")); + } + + if (createNew) { + PObjectInfo info = base->GetObjectInfo(wxT("separator")); + menuitem = base->NewObject(info); + } menu->AddChild(menuitem); menuitem->SetParent(menu); n++; - } - else if (HasChildren(n)) - { + } else if (HasChildren(n)) { PObjectBase child = GetMenu(n, base); menu->AddChild(child); child->SetParent(menu); - } - else - { - if ( menuitem ) - { - createNew = ( menuitem->GetClassName() != wxT("wxMenuItem") ); - } - - if ( createNew ) - { - PObjectInfo info = base->GetObjectInfo( wxT("wxMenuItem") ); - menuitem = base->NewObject(info); - } - menuitem->GetProperty( wxT("label") )->SetValue(label); - menuitem->GetProperty( wxT("shortcut") )->SetValue(shortcut); - menuitem->GetProperty( wxT("name") )->SetValue(name); - menuitem->GetProperty( wxT("help") )->SetValue(help); - menuitem->GetProperty( wxT("id") )->SetValue(id); - menuitem->GetProperty( wxT("kind") )->SetValue(kind); + } else { + if (menuitem) { + createNew = (menuitem->GetClassName() != wxT("wxMenuItem")); + } + + if (createNew) { + PObjectInfo info = base->GetObjectInfo(wxT("wxMenuItem")); + menuitem = base->NewObject(info); + } + menuitem->GetProperty(wxT("label"))->SetValue(label); + menuitem->GetProperty(wxT("shortcut"))->SetValue(shortcut); + menuitem->GetProperty(wxT("name"))->SetValue(name); + menuitem->GetProperty(wxT("help"))->SetValue(help); + menuitem->GetProperty(wxT("id"))->SetValue(id); + menuitem->GetProperty(wxT("kind"))->SetValue(kind); menu->AddChild(menuitem); menuitem->SetParent(menu); n++; @@ -304,22 +285,19 @@ PObjectBase MenuEditor::GetMenu(long& n, PObjectDatabase base, bool isSubMenu) PObjectBase MenuEditor::GetMenubar(PObjectDatabase base) { - // Disconnect all parent/child relationships in original objects - for ( std::vector< WPObjectBase >::iterator it = m_originalItems.begin(); it != m_originalItems.end(); ++it ) - { - PObjectBase obj = it->lock(); - if ( obj ) - { - obj->RemoveAllChildren(); - obj->SetParent( PObjectBase() ); - } - } - - PObjectInfo info = base->GetObjectInfo( wxT("wxMenuBar" )); + // Disconnect all parent/child relationships in original objects + for (std::vector::iterator it = m_originalItems.begin(); it != m_originalItems.end(); ++it) { + PObjectBase obj = it->lock(); + if (obj) { + obj->RemoveAllChildren(); + obj->SetParent(PObjectBase()); + } + } + + PObjectInfo info = base->GetObjectInfo(wxT("wxMenuBar")); PObjectBase menubar = base->NewObject(info); long n = 0; - while (n < m_menuList->GetItemCount()) - { + while (n < m_menuList->GetItemCount()) { PObjectBase child = GetMenu(n, base, false); menubar->AddChild(child); child->SetParent(menubar); @@ -342,9 +320,9 @@ int MenuEditor::GetItemIdentation(long n) return (int)curIdent; } -long MenuEditor::InsertItem(long n, const wxString& label, const wxString& shortcut, - const wxString& id, const wxString& name, const wxString& helpString, - const wxString& kind, PObjectBase obj) +long MenuEditor::InsertItem( + long n, const wxString& label, const wxString& shortcut, const wxString& id, const wxString& name, + const wxString& helpString, const wxString& kind, PObjectBase obj) { long index = m_menuList->InsertItem(n, label); m_menuList->SetItem(index, 1, shortcut); @@ -354,28 +332,28 @@ long MenuEditor::InsertItem(long n, const wxString& label, const wxString& short m_menuList->SetItem(index, 5, kind); // Prevent loss of data not exposed by menu editor. For Example: bitmaps, events, etc. - if ( obj ) - { - m_originalItems.push_back( obj ); - m_menuList->SetItemData( index, m_originalItems.size() - 1 ); - } - else - { - m_menuList->SetItemData( index, -1 ); + if (obj) { + m_originalItems.push_back(obj); + m_menuList->SetItemData(index, m_originalItems.size() - 1); + } else { + m_menuList->SetItemData(index, -1); } return index; } -void MenuEditor::AddItem(const wxString& label, const wxString& shortcut, - const wxString& id, const wxString& name, const wxString &help, const wxString &kind) +void MenuEditor::AddItem( + const wxString& label, const wxString& shortcut, const wxString& id, const wxString& name, const wxString& help, + const wxString& kind) { int sel = GetSelectedItem(); int identation = 0; - if (sel >= 0) identation = GetItemIdentation(sel); + if (sel >= 0) + identation = GetItemIdentation(sel); wxString labelAux = label; labelAux.Trim(true); labelAux.Trim(false); - if (sel < 0) sel = m_menuList->GetItemCount() - 1; + if (sel < 0) + sel = m_menuList->GetItemCount() - 1; labelAux = wxString(wxChar(' '), identation * IDENTATION) + labelAux; @@ -383,8 +361,9 @@ void MenuEditor::AddItem(const wxString& label, const wxString& shortcut, m_menuList->SetItemState(index, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); } -void MenuEditor::GetItem(long n, wxString& label, wxString& shortcut, - wxString& id, wxString& name, wxString& help, wxString& kind, PObjectBase* obj ) +void MenuEditor::GetItem( + long n, wxString& label, wxString& shortcut, wxString& id, wxString& name, wxString& help, wxString& kind, + PObjectBase* obj) { label = m_menuList->GetItemText(n); wxListItem item; @@ -396,9 +375,8 @@ void MenuEditor::GetItem(long n, wxString& label, wxString& shortcut, item.m_col++; m_menuList->GetItem(item); id = item.GetText(); - if ( id.empty() ) - { - id = wxT("wxID_ANY"); + if (id.empty()) { + id = wxT("wxID_ANY"); } item.m_col++; m_menuList->GetItem(item); @@ -409,31 +387,34 @@ void MenuEditor::GetItem(long n, wxString& label, wxString& shortcut, item.m_col++; m_menuList->GetItem(item); kind = item.GetText(); - if ( kind.empty() ) - { - kind = wxT("wxITEM_NORMAL"); + if (kind.empty()) { + kind = wxT("wxITEM_NORMAL"); } - if ( NULL != obj ) - { - int origIndex = m_menuList->GetItemData( item ); - if ( origIndex >= 0 && origIndex < (int)m_originalItems.size() ) - { - *obj = m_originalItems[ origIndex ].lock(); - } + if (NULL != obj) { + int origIndex = m_menuList->GetItemData(item); + if (origIndex >= 0 && origIndex < (int)m_originalItems.size()) { + *obj = m_originalItems[origIndex].lock(); + } } } void MenuEditor::AddNewItem() { wxString kind; - switch (m_rbItemKind->GetSelection()) - { - case 0: kind = wxT("wxITEM_NORMAL"); break; - case 1: kind = wxT("wxITEM_CHECK"); break; - case 2: kind = wxT("wxITEM_RADIO"); break; + switch (m_rbItemKind->GetSelection()) { + case 0: + kind = wxT("wxITEM_NORMAL"); + break; + case 1: + kind = wxT("wxITEM_CHECK"); + break; + case 2: + kind = wxT("wxITEM_RADIO"); + break; } - AddItem(m_tcLabel->GetValue(), m_tcShortcut->GetValue(), m_tcId->GetValue(), - m_tcName->GetValue(), m_tcHelpString->GetValue(), kind); + AddItem( + m_tcLabel->GetValue(), m_tcShortcut->GetValue(), m_tcId->GetValue(), m_tcName->GetValue(), + m_tcHelpString->GetValue(), kind); m_tcLabel->SetValue(wxT("")); m_tcShortcut->SetValue(wxT("")); m_tcId->SetValue(wxT("")); @@ -443,26 +424,31 @@ void MenuEditor::AddNewItem() m_tcLabel->SetFocus(); } -void MenuEditor::OnAddMenuItem(wxCommandEvent& ) +void MenuEditor::OnAddMenuItem(wxCommandEvent&) { AddNewItem(); } -void MenuEditor::OnAddSeparator(wxCommandEvent& ) +void MenuEditor::OnAddSeparator(wxCommandEvent&) { AddItem(wxT("---"), wxT(""), wxT(""), wxT(""), wxT(""), wxT("")); } -void MenuEditor::OnModifyMenuItem(wxCommandEvent& ) +void MenuEditor::OnModifyMenuItem(wxCommandEvent&) { long index = GetSelectedItem(); int identation = GetItemIdentation(index); wxString kind; - switch (m_rbItemKind->GetSelection()) - { - case 0: kind = wxT("wxITEM_NORMAL"); break; - case 1: kind = wxT("wxITEM_CHECK"); break; - case 2: kind = wxT("wxITEM_RADIO"); break; + switch (m_rbItemKind->GetSelection()) { + case 0: + kind = wxT("wxITEM_NORMAL"); + break; + case 1: + kind = wxT("wxITEM_CHECK"); + break; + case 2: + kind = wxT("wxITEM_RADIO"); + break; } m_menuList->SetItem(index, 0, wxString(wxChar(' '), identation * IDENTATION) + m_tcLabel->GetValue()); @@ -473,32 +459,29 @@ void MenuEditor::OnModifyMenuItem(wxCommandEvent& ) m_menuList->SetItem(index, 5, kind); } -void MenuEditor::OnRemoveMenuItem(wxCommandEvent& ) +void MenuEditor::OnRemoveMenuItem(wxCommandEvent&) { long sel = GetSelectedItem(); - if (sel < m_menuList->GetItemCount() - 1) - { + if (sel < m_menuList->GetItemCount() - 1) { int curIdent = GetItemIdentation(sel); int nextIdent = GetItemIdentation(sel + 1); - if (nextIdent > curIdent) - { + if (nextIdent > curIdent) { int res = wxMessageBox( - wxT("The children of the selected item will be eliminated too. Are you sure you want to continue?"), - wxT("wxFormBuilder"), wxYES_NO); - if (res == wxYES) - { + wxT("The children of the selected item will be eliminated too. Are you sure you want to continue?"), + wxT("wxFormBuilder"), wxYES_NO); + if (res == wxYES) { long item = sel + 1; while (item < m_menuList->GetItemCount() && GetItemIdentation(item) > curIdent) m_menuList->DeleteItem(item); m_menuList->DeleteItem(sel); } - }else + } else m_menuList->DeleteItem(sel); - }else + } else m_menuList->DeleteItem(sel); } -void MenuEditor::OnMenuLeft(wxCommandEvent& ) +void MenuEditor::OnMenuLeft(wxCommandEvent&) { int sel = GetSelectedItem(); int curIdent = GetItemIdentation(sel) - 1; @@ -514,7 +497,7 @@ void MenuEditor::OnMenuLeft(wxCommandEvent& ) m_menuList->SetItemText(sel, label); } -void MenuEditor::OnMenuRight(wxCommandEvent& ) +void MenuEditor::OnMenuRight(wxCommandEvent&) { int sel = GetSelectedItem(); int curIdent = GetItemIdentation(sel) + 1; @@ -530,15 +513,15 @@ void MenuEditor::OnMenuRight(wxCommandEvent& ) m_menuList->SetItemText(sel, label); } -void MenuEditor::OnMenuUp(wxCommandEvent& ) +void MenuEditor::OnMenuUp(wxCommandEvent&) { long sel = GetSelectedItem(); long prev = sel - 1; int prevIdent = GetItemIdentation(prev); int curIdent = GetItemIdentation(sel); - if (prevIdent < curIdent) return; - while (prevIdent > curIdent) - prevIdent = GetItemIdentation(--prev); + if (prevIdent < curIdent) + return; + while (prevIdent > curIdent) prevIdent = GetItemIdentation(--prev); PObjectBase obj; wxString label, shortcut, id, name, help, kind; @@ -546,18 +529,19 @@ void MenuEditor::OnMenuUp(wxCommandEvent& ) m_menuList->DeleteItem(sel); long newSel = InsertItem(prev, label, shortcut, id, name, help, kind, obj); - sel++; prev++; - if (sel < m_menuList->GetItemCount()) - { + sel++; + prev++; + if (sel < m_menuList->GetItemCount()) { long childIdent = GetItemIdentation(sel); - while (sel < m_menuList->GetItemCount() && childIdent > curIdent) - { - PObjectBase childObj; + while (sel < m_menuList->GetItemCount() && childIdent > curIdent) { + PObjectBase childObj; GetItem(sel, label, shortcut, id, name, help, kind, &childObj); m_menuList->DeleteItem(sel); InsertItem(prev, label, shortcut, id, name, help, kind, childObj); - sel++; prev++; - if (sel < m_menuList->GetItemCount()) childIdent = GetItemIdentation(sel); + sel++; + prev++; + if (sel < m_menuList->GetItemCount()) + childIdent = GetItemIdentation(sel); } } m_menuList->SetItemState(newSel, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); @@ -568,18 +552,20 @@ long MenuEditor::GetEndIndex(long n) long res = n; int ident = GetItemIdentation(n); res++; - if (res >= m_menuList->GetItemCount()) return n; + if (res >= m_menuList->GetItemCount()) + return n; while (GetItemIdentation(res) > ident) res++; return res - 1; } -void MenuEditor::OnMenuDown(wxCommandEvent& ) +void MenuEditor::OnMenuDown(wxCommandEvent&) { long sel = GetSelectedItem(); int selIdent = GetItemIdentation(sel); long selAux = sel + 1; while (GetItemIdentation(selAux) > selIdent) selAux++; - if (GetItemIdentation(selAux) < selIdent) return; + if (GetItemIdentation(selAux) < selIdent) + return; long endIndex = GetEndIndex(selAux) + 1; wxString label, shortcut, id, name, help, kind; @@ -589,9 +575,8 @@ void MenuEditor::OnMenuDown(wxCommandEvent& ) m_menuList->DeleteItem(sel); endIndex--; long first = InsertItem(endIndex, label, shortcut, id, name, help, kind, obj); - while (GetItemIdentation(sel) > selIdent) - { - PObjectBase childObj; + while (GetItemIdentation(sel) > selIdent) { + PObjectBase childObj; GetItem(sel, label, shortcut, id, name, help, kind, &childObj); m_menuList->DeleteItem(sel); InsertItem(endIndex, label, shortcut, id, name, help, kind, childObj); @@ -600,50 +585,50 @@ void MenuEditor::OnMenuDown(wxCommandEvent& ) m_menuList->SetItemState(first, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); } -void MenuEditor::OnEnter(wxCommandEvent& ) +void MenuEditor::OnEnter(wxCommandEvent&) { - AddNewItem(); + AddNewItem(); } -void MenuEditor::OnLabelChanged(wxCommandEvent&) { - wxString label = m_tcLabel->GetValue(); - wxString id, name; - bool nextUpper = false; - if (!label.IsEmpty()) { - id = wxT("ID_"); - } - int tabPos = label.Find(wxT("\\t")); - if (tabPos >= 0) { - label = label.Left(tabPos); - } - - for (size_t i = 0; i < label.Len(); i++) { - if (isalnum(label[i]) != 0) { - name += (nextUpper ? toupper(label[i]) : tolower(label[i])); - nextUpper = false; - id += toupper(label[i]); - } else if (label[i] == wxChar(' ')) { - nextUpper = true; - id += wxT("_"); - } - } - if (name.Len() > 0 && isdigit(name[0]) != 0) { - name = wxT("n") + name; - } - m_tcId->SetValue(id); - m_tcName->SetValue(name); +void MenuEditor::OnLabelChanged(wxCommandEvent&) +{ + wxString label = m_tcLabel->GetValue(); + wxString id, name; + bool nextUpper = false; + if (!label.IsEmpty()) { + id = wxT("ID_"); + } + int tabPos = label.Find(wxT("\\t")); + if (tabPos >= 0) { + label = label.Left(tabPos); + } + + for (size_t i = 0; i < label.Len(); i++) { + if (isalnum(label[i]) != 0) { + name += (nextUpper ? toupper(label[i]) : tolower(label[i])); + nextUpper = false; + id += toupper(label[i]); + } else if (label[i] == wxChar(' ')) { + nextUpper = true; + id += wxT("_"); + } + } + if (name.Len() > 0 && isdigit(name[0]) != 0) { + name = wxT("n") + name; + } + m_tcId->SetValue(id); + m_tcName->SetValue(name); } void MenuEditor::OnUpdateMovers(wxUpdateUIEvent& e) { - switch (e.GetId()) - { + switch (e.GetId()) { case ID_MENUUP: e.Enable(GetSelectedItem() > 0); break; case ID_MENUDOWN: e.Enable(GetSelectedItem() < m_menuList->GetItemCount() - 1); - break; + break; default: break; } @@ -651,20 +636,21 @@ void MenuEditor::OnUpdateMovers(wxUpdateUIEvent& e) void MenuEditor::OnItemActivated(wxListEvent& e) { - wxString label, shortcut, id, name, helpString, kind; - GetItem(e.GetIndex(), label, shortcut, id, name, helpString, kind); - - label.Trim(true); label.Trim(false); - m_tcLabel->SetValue(label); - m_tcShortcut->SetValue(shortcut); - m_tcId->SetValue(id); - m_tcName->SetValue(name); - m_tcHelpString->SetValue(helpString); - - if (kind == wxT("wxITEM_CHECK")) - m_rbItemKind->SetSelection(1); - else if (kind == wxT("wxITEM_RADIO")) - m_rbItemKind->SetSelection(2); - else - m_rbItemKind->SetSelection(0); + wxString label, shortcut, id, name, helpString, kind; + GetItem(e.GetIndex(), label, shortcut, id, name, helpString, kind); + + label.Trim(true); + label.Trim(false); + m_tcLabel->SetValue(label); + m_tcShortcut->SetValue(shortcut); + m_tcId->SetValue(id); + m_tcName->SetValue(name); + m_tcHelpString->SetValue(helpString); + + if (kind == wxT("wxITEM_CHECK")) + m_rbItemKind->SetSelection(1); + else if (kind == wxT("wxITEM_RADIO")) + m_rbItemKind->SetSelection(2); + else + m_rbItemKind->SetSelection(0); } diff --git a/src/rad/menueditor.h b/src/rad/menueditor.h index 33ca5ad76..591186dac 100644 --- a/src/rad/menueditor.h +++ b/src/rad/menueditor.h @@ -26,16 +26,17 @@ #ifndef RAD_MENUEDITOR_H #define RAD_MENUEDITOR_H +#include + #include "model/database.h" -#include /** * Class MenuEditor */ class MenuEditor : public wxDialog { - private: +private: /** Devuelve el índice del elemento seleccionado en el wxListCtrl */ long GetSelectedItem(); @@ -45,19 +46,19 @@ class MenuEditor : public wxDialog /** Inserta en la posición "n" un elemento en el wxListCtrl. No añade sangría en el campo label. @param obj Pointer to the original object to be saved with SetItemData - If the item is still an item when the dialog is closed, this - is used to preserve data like bitmaps and events. + If the item is still an item when the dialog is closed, this + is used to preserve data like bitmaps and events. */ - long InsertItem(long n, const wxString& label, const wxString& shortcut, - const wxString& id, const wxString& name, const wxString& helpString, - const wxString& kind, PObjectBase obj = PObjectBase() ); + long InsertItem( + long n, const wxString& label, const wxString& shortcut, const wxString& id, const wxString& name, + const wxString& helpString, const wxString& kind, PObjectBase obj = PObjectBase()); /** Inserta debajo del elemento seleccionado (o en la última posición en caso de no haber selección) un nuevo elemento en el wxListCtrl. El campo label se sangra al mismo nivel que el elemento que le precede */ - void AddItem(const wxString& label, const wxString& shortcut, - const wxString& id, const wxString& name, const wxString &help, - const wxString& kind); + void AddItem( + const wxString& label, const wxString& shortcut, const wxString& id, const wxString& name, const wxString& help, + const wxString& kind); /** Determina el índice en el que acaba el menú que empieza en la posición "n" */ @@ -66,11 +67,12 @@ class MenuEditor : public wxDialog /** Devuelve los campos del wxListCtrl del elemento "n". El campo label lo devuelve con sangría @param obj Pointer to the original object to be retrieved with GetItemData - If the item is still an item when the dialog is closed, this - is used to preserve data like bitmaps and events. + If the item is still an item when the dialog is closed, this + is used to preserve data like bitmaps and events. */ - void GetItem(long n, wxString& label, wxString& shortcut, wxString& id, - wxString& name, wxString& help, wxString& kind, PObjectBase* obj = NULL ); + void GetItem( + long n, wxString& label, wxString& shortcut, wxString& id, wxString& name, wxString& help, wxString& kind, + PObjectBase* obj = NULL); using wxNavigationEnabled::AddChild; /** Inserta en la posición "n" del wxListCtrl, los hijos de "obj". El primer @@ -94,23 +96,22 @@ class MenuEditor : public wxDialog y pone el foco en el campo "label". */ void AddNewItem(); - protected: - wxListCtrl *m_menuList; - wxTextCtrl *m_tcId; - wxTextCtrl *m_tcLabel; - wxTextCtrl *m_tcName; - wxTextCtrl *m_tcHelpString; - wxTextCtrl *m_tcShortcut; - wxRadioBox *m_rbItemKind; +protected: + wxListCtrl* m_menuList; + wxTextCtrl* m_tcId; + wxTextCtrl* m_tcLabel; + wxTextCtrl* m_tcName; + wxTextCtrl* m_tcHelpString; + wxTextCtrl* m_tcShortcut; + wxRadioBox* m_rbItemKind; - std::vector< WPObjectBase > m_originalItems; + std::vector m_originalItems; DECLARE_EVENT_TABLE() - public: - +public: /** Constructor */ - MenuEditor(wxWindow *parent, int id = wxID_ANY); + MenuEditor(wxWindow* parent, int id = wxID_ANY); /** Rellena el wxListCtrl con los datos de "obj", que debe ser de tipo menubar */ @@ -136,4 +137,4 @@ class MenuEditor : public wxDialog void OnItemActivated(wxListEvent& e); }; -#endif // RAD_MENUEDITOR_H +#endif // RAD_MENUEDITOR_H diff --git a/src/rad/objecttree/objecttree.cpp b/src/rad/objecttree/objecttree.cpp index 074ff3a85..0af00bed1 100644 --- a/src/rad/objecttree/objecttree.cpp +++ b/src/rad/objecttree/objecttree.cpp @@ -25,670 +25,618 @@ #include "objecttree.h" +#include + #include "model/objectbase.h" #include "rad/appdata.h" #include "rad/bitmaps.h" #include "rad/menueditor.h" #include "rad/wxfbevent.h" -#include - -BEGIN_EVENT_TABLE( ObjectTree, wxPanel ) - EVT_TREE_SEL_CHANGED(wxID_ANY, ObjectTree::OnSelChanged) - EVT_TREE_ITEM_RIGHT_CLICK(wxID_ANY, ObjectTree::OnRightClick) - EVT_TREE_BEGIN_DRAG(wxID_ANY, ObjectTree::OnBeginDrag) - EVT_TREE_END_DRAG(wxID_ANY, ObjectTree::OnEndDrag) - EVT_TREE_KEY_DOWN(wxID_ANY, ObjectTree::OnKeyDown) - EVT_FB_PROJECT_LOADED( ObjectTree::OnProjectLoaded ) - EVT_FB_PROJECT_SAVED( ObjectTree::OnProjectSaved ) - EVT_FB_OBJECT_CREATED( ObjectTree::OnObjectCreated ) - EVT_FB_OBJECT_REMOVED( ObjectTree::OnObjectRemoved ) - EVT_FB_PROPERTY_MODIFIED( ObjectTree::OnPropertyModified ) - EVT_FB_PROJECT_REFRESH( ObjectTree::OnProjectRefresh ) +BEGIN_EVENT_TABLE(ObjectTree, wxPanel) +EVT_TREE_SEL_CHANGED(wxID_ANY, ObjectTree::OnSelChanged) +EVT_TREE_ITEM_RIGHT_CLICK(wxID_ANY, ObjectTree::OnRightClick) +EVT_TREE_BEGIN_DRAG(wxID_ANY, ObjectTree::OnBeginDrag) +EVT_TREE_END_DRAG(wxID_ANY, ObjectTree::OnEndDrag) +EVT_TREE_KEY_DOWN(wxID_ANY, ObjectTree::OnKeyDown) +EVT_FB_PROJECT_LOADED(ObjectTree::OnProjectLoaded) +EVT_FB_PROJECT_SAVED(ObjectTree::OnProjectSaved) +EVT_FB_OBJECT_CREATED(ObjectTree::OnObjectCreated) +EVT_FB_OBJECT_REMOVED(ObjectTree::OnObjectRemoved) +EVT_FB_PROPERTY_MODIFIED(ObjectTree::OnPropertyModified) +EVT_FB_PROJECT_REFRESH(ObjectTree::OnProjectRefresh) END_EVENT_TABLE() -ObjectTree::ObjectTree( wxWindow *parent, int id ) -: -wxPanel( parent, id ) + +ObjectTree::ObjectTree(wxWindow* parent, int id) : wxPanel(parent, id) { - AppData()->AddHandler( this->GetEventHandler() ); - m_tcObjects = new wxTreeCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS|wxTR_LINES_AT_ROOT|wxTR_DEFAULT_STYLE|wxSIMPLE_BORDER); + AppData()->AddHandler(this->GetEventHandler()); + m_tcObjects = new wxTreeCtrl( + this, wxID_ANY, wxDefaultPosition, wxDefaultSize, + wxTR_HAS_BUTTONS | wxTR_LINES_AT_ROOT | wxTR_DEFAULT_STYLE | wxSIMPLE_BORDER); - wxBoxSizer* sizer_1 = new wxBoxSizer(wxVERTICAL); + wxBoxSizer* sizer_1 = new wxBoxSizer(wxVERTICAL); sizer_1->Add(m_tcObjects, 1, wxEXPAND, 0); SetAutoLayout(true); SetSizer(sizer_1); sizer_1->Fit(this); sizer_1->SetSizeHints(this); - Connect( wxID_ANY, wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler( ObjectTree::OnObjectExpanded ) ); - Connect( wxID_ANY, wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler( ObjectTree::OnObjectSelected ) ); - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); + Connect(wxID_ANY, wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler(ObjectTree::OnObjectExpanded)); + Connect(wxID_ANY, wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler(ObjectTree::OnObjectSelected)); + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); m_altKeyIsDown = false; } -void ObjectTree::OnKeyDown(wxTreeEvent &event ) +void ObjectTree::OnKeyDown(wxTreeEvent& event) { - if( event.GetKeyEvent().AltDown() && event.GetKeyCode() != WXK_ALT) - { + if (event.GetKeyEvent().AltDown() && event.GetKeyCode() != WXK_ALT) { #ifdef __WXGTK__ - switch (event.GetKeyCode()) - { - case WXK_UP: - AppData()->MovePosition(GetObjectFromTreeItem(m_tcObjects->GetSelection()),false); - return; - case WXK_DOWN: - AppData()->MovePosition(GetObjectFromTreeItem(m_tcObjects->GetSelection()),true); - return; - case WXK_RIGHT: - AppData()->MoveHierarchy(GetObjectFromTreeItem(m_tcObjects->GetSelection()),false); - return; - case WXK_LEFT: - AppData()->MoveHierarchy(GetObjectFromTreeItem(m_tcObjects->GetSelection()),true); - return; - } + switch (event.GetKeyCode()) { + case WXK_UP: + AppData()->MovePosition(GetObjectFromTreeItem(m_tcObjects->GetSelection()), false); + return; + case WXK_DOWN: + AppData()->MovePosition(GetObjectFromTreeItem(m_tcObjects->GetSelection()), true); + return; + case WXK_RIGHT: + AppData()->MoveHierarchy(GetObjectFromTreeItem(m_tcObjects->GetSelection()), false); + return; + case WXK_LEFT: + AppData()->MoveHierarchy(GetObjectFromTreeItem(m_tcObjects->GetSelection()), true); + return; + } #endif - event.Skip(); - } - else - { - event.Skip(); - } + event.Skip(); + } else { + event.Skip(); + } } ObjectTree::~ObjectTree() { - AppData()->RemoveHandler( this->GetEventHandler() ); + AppData()->RemoveHandler(this->GetEventHandler()); } -PObjectBase ObjectTree::GetObjectFromTreeItem( wxTreeItemId item ) +PObjectBase ObjectTree::GetObjectFromTreeItem(wxTreeItemId item) { - if ( item.IsOk() ) - { - wxTreeItemData* item_data = m_tcObjects->GetItemData( item ); - if ( item_data ) - { - PObjectBase obj( ((ObjectTreeItemData* )item_data)->GetObject() ); - return obj; - } - } - return PObjectBase( (ObjectBase*)NULL ); + if (item.IsOk()) { + wxTreeItemData* item_data = m_tcObjects->GetItemData(item); + if (item_data) { + PObjectBase obj(((ObjectTreeItemData*)item_data)->GetObject()); + return obj; + } + } + return PObjectBase((ObjectBase*)NULL); } void ObjectTree::RebuildTree() { - m_tcObjects->Freeze(); + m_tcObjects->Freeze(); - Disconnect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - Disconnect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); + Disconnect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + Disconnect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); - PObjectBase project = AppData()->GetProjectData(); + PObjectBase project = AppData()->GetProjectData(); - // Clear the old tree and map - m_tcObjects->DeleteAllItems(); - m_map.clear(); + // Clear the old tree and map + m_tcObjects->DeleteAllItems(); + m_map.clear(); - if (project) - { - wxTreeItemId dummy; - AddChildren(project, dummy, true ); + if (project) { + wxTreeItemId dummy; + AddChildren(project, dummy, true); - // Expand items that were previously expanded - RestoreItemStatus(project); - } + // Expand items that were previously expanded + RestoreItemStatus(project); + } - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); - m_tcObjects->Thaw(); + m_tcObjects->Thaw(); } -void ObjectTree::OnSelChanged(wxTreeEvent &event) +void ObjectTree::OnSelChanged(wxTreeEvent& event) { - wxTreeItemId id = event.GetItem(); - if (!id.IsOk()) return; - - // Make selected items bold - wxTreeItemId oldId = event.GetOldItem(); - if ( oldId.IsOk() ) - { - m_tcObjects->SetItemBold( oldId, false ); - } - m_tcObjects->SetItemBold( id ); - - wxTreeItemData *item_data = m_tcObjects->GetItemData(id); - - if (item_data) - { - PObjectBase obj(((ObjectTreeItemData *)item_data)->GetObject()); - assert(obj); - Disconnect( wxID_ANY, wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler( ObjectTree::OnObjectSelected ) ); - AppData()->SelectObject(obj); - Connect( wxID_ANY, wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler( ObjectTree::OnObjectSelected ) ); - } + wxTreeItemId id = event.GetItem(); + if (!id.IsOk()) + return; + + // Make selected items bold + wxTreeItemId oldId = event.GetOldItem(); + if (oldId.IsOk()) { + m_tcObjects->SetItemBold(oldId, false); + } + m_tcObjects->SetItemBold(id); + + wxTreeItemData* item_data = m_tcObjects->GetItemData(id); + + if (item_data) { + PObjectBase obj(((ObjectTreeItemData*)item_data)->GetObject()); + assert(obj); + Disconnect(wxID_ANY, wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler(ObjectTree::OnObjectSelected)); + AppData()->SelectObject(obj); + Connect(wxID_ANY, wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler(ObjectTree::OnObjectSelected)); + } } -void ObjectTree::OnRightClick(wxTreeEvent &event) +void ObjectTree::OnRightClick(wxTreeEvent& event) { - wxTreeItemId id = event.GetItem(); - wxTreeItemData *item_data = m_tcObjects->GetItemData(id); - if (item_data) - { - PObjectBase obj(((ObjectTreeItemData *)item_data)->GetObject()); - assert(obj); - wxMenu * menu = new ItemPopupMenu(obj); - wxPoint pos = event.GetPoint(); - menu->UpdateUI(menu); - PopupMenu(menu,pos.x, pos.y); - } + wxTreeItemId id = event.GetItem(); + wxTreeItemData* item_data = m_tcObjects->GetItemData(id); + if (item_data) { + PObjectBase obj(((ObjectTreeItemData*)item_data)->GetObject()); + assert(obj); + wxMenu* menu = new ItemPopupMenu(obj); + wxPoint pos = event.GetPoint(); + menu->UpdateUI(menu); + PopupMenu(menu, pos.x, pos.y); + } } -void ObjectTree::OnBeginDrag(wxTreeEvent &event) +void ObjectTree::OnBeginDrag(wxTreeEvent& event) { - // need to explicitly allow drag - if ( event.GetItem() == m_tcObjects->GetRootItem() ) - { - return; + // need to explicitly allow drag + if (event.GetItem() == m_tcObjects->GetRootItem()) { + return; } - m_draggedItem = event.GetItem(); - event.Allow(); + m_draggedItem = event.GetItem(); + event.Allow(); } void ObjectTree::OnEndDrag(wxTreeEvent& event) { - bool copy = ::wxGetKeyState( WXK_CONTROL ); + bool copy = ::wxGetKeyState(WXK_CONTROL); - wxTreeItemId itemSrc = m_draggedItem, - itemDst = event.GetItem(); + wxTreeItemId itemSrc = m_draggedItem, itemDst = event.GetItem(); m_draggedItem = (wxTreeItemId)0l; - // ensure that itemDst is not itemSrc or a child of itemSrc - wxTreeItemId item = itemDst; - while ( item.IsOk() ) - { - if ( item == itemSrc ) - { - return; - } - item = m_tcObjects->GetItemParent( item ); - } - - PObjectBase objSrc = GetObjectFromTreeItem( itemSrc ); - if ( !objSrc ) - { - return; - } - - PObjectBase objDst = GetObjectFromTreeItem( itemDst ); - if ( !objDst ) - { - return; - } - - // backup clipboard - PObjectBase clipboard = AppData()->GetClipboardObject(); - - // set object to clipboard - if ( copy ) - { - AppData()->CopyObject( objSrc ); - } - else - { - AppData()->CutObject( objSrc ); - } - - if ( !AppData()->PasteObject( objDst ) && !copy ) - { - AppData()->Undo(); - } - - AppData()->SetClipboardObject( clipboard ); + // ensure that itemDst is not itemSrc or a child of itemSrc + wxTreeItemId item = itemDst; + while (item.IsOk()) { + if (item == itemSrc) { + return; + } + item = m_tcObjects->GetItemParent(item); + } + + PObjectBase objSrc = GetObjectFromTreeItem(itemSrc); + if (!objSrc) { + return; + } + + PObjectBase objDst = GetObjectFromTreeItem(itemDst); + if (!objDst) { + return; + } + + // backup clipboard + PObjectBase clipboard = AppData()->GetClipboardObject(); + + // set object to clipboard + if (copy) { + AppData()->CopyObject(objSrc); + } else { + AppData()->CutObject(objSrc); + } + + if (!AppData()->PasteObject(objDst) && !copy) { + AppData()->Undo(); + } + + AppData()->SetClipboardObject(clipboard); } -void ObjectTree::OnExpansionChange(wxTreeEvent &event) +void ObjectTree::OnExpansionChange(wxTreeEvent& event) { - wxTreeItemId id = event.GetItem(); - wxTreeItemData *item_data = m_tcObjects->GetItemData(id); - if (item_data) - { - PObjectBase obj(((ObjectTreeItemData *)item_data)->GetObject()); - assert(obj); + wxTreeItemId id = event.GetItem(); + wxTreeItemData* item_data = m_tcObjects->GetItemData(id); + if (item_data) { + PObjectBase obj(((ObjectTreeItemData*)item_data)->GetObject()); + assert(obj); - Disconnect( wxID_ANY, wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler( ObjectTree::OnObjectExpanded ) ); - Disconnect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); + Disconnect(wxID_ANY, wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler(ObjectTree::OnObjectExpanded)); + Disconnect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); - AppData()->ExpandObject( obj, m_tcObjects->IsExpanded( id ) ); + AppData()->ExpandObject(obj, m_tcObjects->IsExpanded(id)); - Connect( wxID_ANY, wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler( ObjectTree::OnObjectExpanded ) ); - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - } + Connect(wxID_ANY, wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler(ObjectTree::OnObjectExpanded)); + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + } } -void ObjectTree::AddChildren(PObjectBase obj, wxTreeItemId &parent, bool is_root) +void ObjectTree::AddChildren(PObjectBase obj, wxTreeItemId& parent, bool is_root) { - if (obj->GetObjectInfo()->GetObjectType()->IsItem()) - { - if (obj->GetChildCount() > 0) - AddChildren(obj->GetChild(0),parent); - else - { - // Si hemos llegado aquí ha sido porque el arbol no está bien formado - // y habrá que revisar cómo se ha creado. - wxString msg; - PObjectBase itemParent = obj->GetParent(); - assert(parent); - - msg = wxString::Format(wxT("Item without object as child of \'%s:%s\'"), - itemParent->GetPropertyAsString(wxT("name")), - itemParent->GetClassName()); - - wxLogError(msg); - } - } - else - { - wxTreeItemId new_parent; - - ObjectTreeItemData *item_data = new ObjectTreeItemData(obj); - - if (is_root) - new_parent = m_tcObjects->AddRoot(wxT(""),-1,-1,item_data); - else - { - unsigned int pos = 0; - - PObjectBase parent_obj = obj->GetParent(); - // find a proper position where the added object should be displayed at - if( parent_obj->GetObjectInfo()->GetObjectType()->IsItem() ) - { - parent_obj = parent_obj->GetParent(); - pos = parent_obj->GetChildPosition( obj->GetParent() ); - } - else - pos = parent_obj->GetChildPosition( obj ); - - // insert tree item to proper position - if( pos > 0 ) - new_parent = m_tcObjects->InsertItem(parent, pos, wxT(""), -1, -1, item_data); - else - new_parent = m_tcObjects->AppendItem(parent,wxT(""),-1,-1,item_data); - } - - // Add the item to the map - m_map.insert( ObjectItemMap::value_type( obj, new_parent ) ); - - // Set the image - int image_idx = GetImageIndex( obj->GetObjectInfo()->GetClassName() ); - - m_tcObjects->SetItemImage(new_parent,image_idx); - - // Set the name - UpdateItem( new_parent, obj ); - - // Add the rest of the children - unsigned int count = obj->GetChildCount(); - unsigned int i; - for (i = 0; i < count ; i++) - { - PObjectBase child = obj->GetChild(i); - AddChildren(child, new_parent); - } - } + if (obj->GetObjectInfo()->GetObjectType()->IsItem()) { + if (obj->GetChildCount() > 0) + AddChildren(obj->GetChild(0), parent); + else { + // Si hemos llegado aquí ha sido porque el arbol no está bien formado + // y habrá que revisar cómo se ha creado. + wxString msg; + PObjectBase itemParent = obj->GetParent(); + assert(parent); + + msg = wxString::Format( + wxT("Item without object as child of \'%s:%s\'"), itemParent->GetPropertyAsString(wxT("name")), + itemParent->GetClassName()); + + wxLogError(msg); + } + } else { + wxTreeItemId new_parent; + + ObjectTreeItemData* item_data = new ObjectTreeItemData(obj); + + if (is_root) + new_parent = m_tcObjects->AddRoot(wxT(""), -1, -1, item_data); + else { + unsigned int pos = 0; + + PObjectBase parent_obj = obj->GetParent(); + // find a proper position where the added object should be displayed at + if (parent_obj->GetObjectInfo()->GetObjectType()->IsItem()) { + parent_obj = parent_obj->GetParent(); + pos = parent_obj->GetChildPosition(obj->GetParent()); + } else + pos = parent_obj->GetChildPosition(obj); + + // insert tree item to proper position + if (pos > 0) + new_parent = m_tcObjects->InsertItem(parent, pos, wxT(""), -1, -1, item_data); + else + new_parent = m_tcObjects->AppendItem(parent, wxT(""), -1, -1, item_data); + } + + // Add the item to the map + m_map.insert(ObjectItemMap::value_type(obj, new_parent)); + + // Set the image + int image_idx = GetImageIndex(obj->GetObjectInfo()->GetClassName()); + + m_tcObjects->SetItemImage(new_parent, image_idx); + + // Set the name + UpdateItem(new_parent, obj); + + // Add the rest of the children + unsigned int count = obj->GetChildCount(); + unsigned int i; + for (i = 0; i < count; i++) { + PObjectBase child = obj->GetChild(i); + AddChildren(child, new_parent); + } + } } -int ObjectTree::GetImageIndex (wxString name) +int ObjectTree::GetImageIndex(wxString name) { - int index = 0; //default icon + int index = 0; // default icon - IconIndexMap::iterator it = m_iconIdx.find(name); - if (it != m_iconIdx.end()) - index = it->second; + IconIndexMap::iterator it = m_iconIdx.find(name); + if (it != m_iconIdx.end()) + index = it->second; - return index; + return index; } void ObjectTree::UpdateItem(wxTreeItemId id, PObjectBase obj) { - // mostramos el nombre - wxString class_name( obj->GetClassName() ); - PProperty prop = obj->GetProperty( wxT("name") ); - wxString obj_name; - if (prop) - { - obj_name =prop->GetValue(); - } - - wxString text = obj_name + wxT(" : ") + class_name; - - // actualizamos el item - m_tcObjects->SetItemText(id,text); + // mostramos el nombre + wxString class_name(obj->GetClassName()); + PProperty prop = obj->GetProperty(wxT("name")); + wxString obj_name; + if (prop) { + obj_name = prop->GetValue(); + } + + wxString text = obj_name + wxT(" : ") + class_name; + + // actualizamos el item + m_tcObjects->SetItemText(id, text); } void ObjectTree::Create() { - // Cramos la lista de iconos obteniendo los iconos de los paquetes. - unsigned int index = 0; - m_iconList = new wxImageList(ICON_SIZE,ICON_SIZE); - - { - wxBitmap icon = AppBitmaps::GetBitmap(wxT("project"), ICON_SIZE); - m_iconList->Add(icon); - m_iconIdx.insert(IconIndexMap::value_type( wxT("_default_"),index++)); - } - - unsigned int pkg_count = AppData()->GetPackageCount(); - for (unsigned int i = 0; i< pkg_count;i++) - { - PObjectPackage pkg = AppData()->GetPackage(i); - - unsigned int j; - for (j=0;jGetObjectCount();j++) - { - wxString comp_name(pkg->GetObjectInfo(j)->GetClassName()); - m_iconList->Add( pkg->GetObjectInfo(j)->GetIconFile() ); - m_iconIdx.insert(IconIndexMap::value_type(comp_name,index++)); - } - } - - m_tcObjects->AssignImageList(m_iconList); + // Cramos la lista de iconos obteniendo los iconos de los paquetes. + unsigned int index = 0; + m_iconList = new wxImageList(ICON_SIZE, ICON_SIZE); + + { + wxBitmap icon = AppBitmaps::GetBitmap(wxT("project"), ICON_SIZE); + m_iconList->Add(icon); + m_iconIdx.insert(IconIndexMap::value_type(wxT("_default_"), index++)); + } + + unsigned int pkg_count = AppData()->GetPackageCount(); + for (unsigned int i = 0; i < pkg_count; i++) { + PObjectPackage pkg = AppData()->GetPackage(i); + + unsigned int j; + for (j = 0; j < pkg->GetObjectCount(); j++) { + wxString comp_name(pkg->GetObjectInfo(j)->GetClassName()); + m_iconList->Add(pkg->GetObjectInfo(j)->GetIconFile()); + m_iconIdx.insert(IconIndexMap::value_type(comp_name, index++)); + } + } + + m_tcObjects->AssignImageList(m_iconList); } void ObjectTree::RestoreItemStatus(PObjectBase obj) { - ObjectItemMap::iterator item_it = m_map.find(obj); - if (item_it != m_map.end()) - { - wxTreeItemId id = item_it->second; - - if ( obj->GetExpanded() ) - m_tcObjects->Expand(id); - /*else - m_tcObjects->Collapse(id);*/ - } - - unsigned int i,count = obj->GetChildCount(); - for (i = 0; iGetChild(i)); + ObjectItemMap::iterator item_it = m_map.find(obj); + if (item_it != m_map.end()) { + wxTreeItemId id = item_it->second; + + if (obj->GetExpanded()) + m_tcObjects->Expand(id); + /*else + m_tcObjects->Collapse(id);*/ + } + + unsigned int i, count = obj->GetChildCount(); + for (i = 0; i < count; i++) RestoreItemStatus(obj->GetChild(i)); } void ObjectTree::AddItem(PObjectBase item, PObjectBase parent) { - if( item && parent ) - { - // find parent item displayed in the object tree - while( parent && parent->GetObjectInfo()->GetObjectType()->IsItem() ) parent = parent->GetParent(); - - // add new item to the object tree - ObjectItemMap::iterator it = m_map.find( parent ); - if( (it != m_map.end()) && it->second.IsOk() ) - { - AddChildren( item, it->second, false ); - } - } + if (item && parent) { + // find parent item displayed in the object tree + while (parent && parent->GetObjectInfo()->GetObjectType()->IsItem()) parent = parent->GetParent(); + + // add new item to the object tree + ObjectItemMap::iterator it = m_map.find(parent); + if ((it != m_map.end()) && it->second.IsOk()) { + AddChildren(item, it->second, false); + } + } } void ObjectTree::RemoveItem(PObjectBase item) { - // remove affected object tree items only - ObjectItemMap::iterator it = m_map.find( item ); - if( (it != m_map.end()) && it->second.IsOk() ) - { - m_tcObjects->Delete( it->second ); - // clear map records for all item's children - ClearMap( it->first ); - } + // remove affected object tree items only + ObjectItemMap::iterator it = m_map.find(item); + if ((it != m_map.end()) && it->second.IsOk()) { + m_tcObjects->Delete(it->second); + // clear map records for all item's children + ClearMap(it->first); + } } void ObjectTree::ClearMap(PObjectBase obj) { - m_map.erase( obj ); + m_map.erase(obj); - for ( unsigned int i = 0; i < obj->GetChildCount(); i++ ) - { - ClearMap( obj->GetChild( i ) ); - } + for (unsigned int i = 0; i < obj->GetChildCount(); i++) { ClearMap(obj->GetChild(i)); } } ///////////////////////////////////////////////////////////////////////////// // wxFormBuilder Event Handlers ///////////////////////////////////////////////////////////////////////////// -void ObjectTree::OnProjectLoaded( wxFBEvent &) +void ObjectTree::OnProjectLoaded(wxFBEvent&) { - RebuildTree(); + RebuildTree(); } -void ObjectTree::OnProjectSaved( wxFBEvent &) +void ObjectTree::OnProjectSaved(wxFBEvent&) { } -void ObjectTree::OnObjectExpanded( wxFBObjectEvent& event ) +void ObjectTree::OnObjectExpanded(wxFBObjectEvent& event) { - PObjectBase obj = event.GetFBObject(); - ObjectItemMap::iterator it = m_map.find( obj ); - if ( it != m_map.end() ) - { - if ( m_tcObjects->IsExpanded( it->second ) != obj->GetExpanded() ) - { - if ( obj->GetExpanded() ) - { - m_tcObjects->Expand( it->second ); - } - else - { - m_tcObjects->Collapse( it->second ); - } - } - } + PObjectBase obj = event.GetFBObject(); + ObjectItemMap::iterator it = m_map.find(obj); + if (it != m_map.end()) { + if (m_tcObjects->IsExpanded(it->second) != obj->GetExpanded()) { + if (obj->GetExpanded()) { + m_tcObjects->Expand(it->second); + } else { + m_tcObjects->Collapse(it->second); + } + } + } } -void ObjectTree::OnObjectSelected( wxFBObjectEvent &event ) +void ObjectTree::OnObjectSelected(wxFBObjectEvent& event) { PObjectBase obj = event.GetFBObject(); - // Find the tree item associated with the object and select it - ObjectItemMap::iterator it = m_map.find(obj); - if ( it != m_map.end() ) - { - // Ignore expand/collapse events - Disconnect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - Disconnect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - - m_tcObjects->EnsureVisible( it->second ); - m_tcObjects->SelectItem( it->second ); - - // Restore event handling - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - Connect( wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler( ObjectTree::OnExpansionChange ) ); - } - else - { - wxLogError( wxT("There is no tree item associated with this object.\n\tClass: %s\n\tName: %s"), obj->GetClassName(), obj->GetPropertyAsString(wxT("name")) ); - } + // Find the tree item associated with the object and select it + ObjectItemMap::iterator it = m_map.find(obj); + if (it != m_map.end()) { + // Ignore expand/collapse events + Disconnect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + Disconnect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + + m_tcObjects->EnsureVisible(it->second); + m_tcObjects->SelectItem(it->second); + + // Restore event handling + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + Connect(wxID_ANY, wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxTreeEventHandler(ObjectTree::OnExpansionChange)); + } else { + wxLogError( + wxT("There is no tree item associated with this object.\n\tClass: %s\n\tName: %s"), obj->GetClassName(), + obj->GetPropertyAsString(wxT("name"))); + } } -void ObjectTree::OnObjectCreated ( wxFBObjectEvent &event ) +void ObjectTree::OnObjectCreated(wxFBObjectEvent& event) { - //RebuildTree(); + // RebuildTree(); - if( event.GetFBObject() ) AddItem( event.GetFBObject(), event.GetFBObject()->GetParent() ); + if (event.GetFBObject()) + AddItem(event.GetFBObject(), event.GetFBObject()->GetParent()); } -void ObjectTree::OnObjectRemoved ( wxFBObjectEvent &event ) +void ObjectTree::OnObjectRemoved(wxFBObjectEvent& event) { - //RebuildTree(); + // RebuildTree(); - RemoveItem( event.GetFBObject() ); + RemoveItem(event.GetFBObject()); } -void ObjectTree::OnPropertyModified ( wxFBPropertyEvent &event ) +void ObjectTree::OnPropertyModified(wxFBPropertyEvent& event) { - PProperty prop = event.GetFBProperty(); - - if (prop->GetName() == wxT("name") ) - { - ObjectItemMap::iterator it = m_map.find(prop->GetObject()); - if (it != m_map.end()) - { - UpdateItem(it->second,it->first); - } - } + PProperty prop = event.GetFBProperty(); + + if (prop->GetName() == wxT("name")) { + ObjectItemMap::iterator it = m_map.find(prop->GetObject()); + if (it != m_map.end()) { + UpdateItem(it->second, it->first); + } + } } -void ObjectTree::OnProjectRefresh ( wxFBEvent &) +void ObjectTree::OnProjectRefresh(wxFBEvent&) { - RebuildTree(); + RebuildTree(); } /////////////////////////////////////////////////////////////////////////////// ObjectTreeItemData::ObjectTreeItemData(PObjectBase obj) : m_object(obj) -{} +{ +} /////////////////////////////////////////////////////////////////////////////// enum { - MENU_MOVE_UP = wxID_HIGHEST + 2000, - MENU_MOVE_DOWN, - MENU_MOVE_RIGHT, - MENU_MOVE_LEFT, - MENU_CUT, - MENU_PASTE, - MENU_EDIT_MENUS, - MENU_COPY, - MENU_MOVE_NEW_BOXSIZER, - MENU_DELETE, + MENU_MOVE_UP = wxID_HIGHEST + 2000, + MENU_MOVE_DOWN, + MENU_MOVE_RIGHT, + MENU_MOVE_LEFT, + MENU_CUT, + MENU_PASTE, + MENU_EDIT_MENUS, + MENU_COPY, + MENU_MOVE_NEW_BOXSIZER, + MENU_DELETE, }; -BEGIN_EVENT_TABLE(ItemPopupMenu,wxMenu) - EVT_MENU(wxID_ANY, ItemPopupMenu::OnMenuEvent) - EVT_UPDATE_UI(wxID_ANY, ItemPopupMenu::OnUpdateEvent) +BEGIN_EVENT_TABLE(ItemPopupMenu, wxMenu) +EVT_MENU(wxID_ANY, ItemPopupMenu::OnMenuEvent) +EVT_UPDATE_UI(wxID_ANY, ItemPopupMenu::OnUpdateEvent) END_EVENT_TABLE() -ItemPopupMenu::ItemPopupMenu(PObjectBase obj) : m_object(obj) { - Append(MENU_CUT, wxT("Cut\tCtrl+X")); - Append(MENU_COPY, wxT("Copy\tCtrl+C")); - Append(MENU_PASTE, wxT("Paste\tCtrl+V")); - AppendSeparator(); - Append(MENU_DELETE, wxT("Delete\tCtrl+D")); - AppendSeparator(); - Append(MENU_MOVE_UP, wxT("Move Up\tAlt+Up")); - Append(MENU_MOVE_DOWN, wxT("Move Down\tAlt+Down")); - Append(MENU_MOVE_LEFT, wxT("Move Left\tAlt+Left")); - Append(MENU_MOVE_RIGHT, wxT("Move Right\tAlt+Right")); - AppendSeparator(); - Append(MENU_MOVE_NEW_BOXSIZER, wxT("Move into a new wxBoxSizer")); - AppendSeparator(); - Append(MENU_EDIT_MENUS, wxT("Menu Editor...")); +ItemPopupMenu::ItemPopupMenu(PObjectBase obj) : m_object(obj) +{ + Append(MENU_CUT, wxT("Cut\tCtrl+X")); + Append(MENU_COPY, wxT("Copy\tCtrl+C")); + Append(MENU_PASTE, wxT("Paste\tCtrl+V")); + AppendSeparator(); + Append(MENU_DELETE, wxT("Delete\tCtrl+D")); + AppendSeparator(); + Append(MENU_MOVE_UP, wxT("Move Up\tAlt+Up")); + Append(MENU_MOVE_DOWN, wxT("Move Down\tAlt+Down")); + Append(MENU_MOVE_LEFT, wxT("Move Left\tAlt+Left")); + Append(MENU_MOVE_RIGHT, wxT("Move Right\tAlt+Right")); + AppendSeparator(); + Append(MENU_MOVE_NEW_BOXSIZER, wxT("Move into a new wxBoxSizer")); + AppendSeparator(); + Append(MENU_EDIT_MENUS, wxT("Menu Editor...")); } -void ItemPopupMenu::OnMenuEvent (wxCommandEvent & event) +void ItemPopupMenu::OnMenuEvent(wxCommandEvent& event) { - int id = event.GetId(); - - switch (id) - { - case MENU_CUT: - AppData()->CutObject(m_object); - break; - case MENU_COPY: - AppData()->CopyObject(m_object); - break; - case MENU_PASTE: - AppData()->PasteObject(m_object); - break; - case MENU_DELETE: - AppData()->RemoveObject(m_object); - break; - case MENU_MOVE_UP: - AppData()->MovePosition(m_object,false); - break; - case MENU_MOVE_DOWN: - AppData()->MovePosition(m_object,true); - break; - case MENU_MOVE_RIGHT: - AppData()->MoveHierarchy(m_object,false); - break; - case MENU_MOVE_LEFT: - AppData()->MoveHierarchy(m_object,true); - break; - case MENU_MOVE_NEW_BOXSIZER: - AppData()->CreateBoxSizerWithObject(m_object); - break; - case MENU_EDIT_MENUS: - { - PObjectBase obj = m_object; - if (obj && (obj->GetClassName() == wxT("wxMenuBar") || obj->GetClassName() == wxT("Frame") ) ) - { - MenuEditor me(NULL); - if (obj->GetClassName() == wxT("Frame") ) - { - bool found = false; - PObjectBase menubar; - for (unsigned int i = 0; i < obj->GetChildCount() && !found; i++) - { - menubar = obj->GetChild(i); - found = menubar->GetClassName() == wxT("wxMenuBar"); - } - if (found) obj = menubar; - } - - if (obj->GetClassName() == wxT("wxMenuBar")) me.Populate(obj); - if (me.ShowModal() == wxID_OK) - { - if (obj->GetClassName() == wxT("wxMenuBar")) - { - PObjectBase menubar = me.GetMenubar(AppData()->GetObjectDatabase()); - while (obj->GetChildCount() > 0) - { - PObjectBase child = obj->GetChild(0); - obj->RemoveChild(0); - child->SetParent(PObjectBase()); - } - for (unsigned int i = 0; i < menubar->GetChildCount(); i++) - { - PObjectBase child = menubar->GetChild(i); - AppData()->InsertObject(child,obj); - } - } - else - AppData()->InsertObject(me.GetMenubar(AppData()->GetObjectDatabase()),AppData()->GetSelectedForm()); - } - } - } - break; - default: - break; - } + int id = event.GetId(); + + switch (id) { + case MENU_CUT: + AppData()->CutObject(m_object); + break; + case MENU_COPY: + AppData()->CopyObject(m_object); + break; + case MENU_PASTE: + AppData()->PasteObject(m_object); + break; + case MENU_DELETE: + AppData()->RemoveObject(m_object); + break; + case MENU_MOVE_UP: + AppData()->MovePosition(m_object, false); + break; + case MENU_MOVE_DOWN: + AppData()->MovePosition(m_object, true); + break; + case MENU_MOVE_RIGHT: + AppData()->MoveHierarchy(m_object, false); + break; + case MENU_MOVE_LEFT: + AppData()->MoveHierarchy(m_object, true); + break; + case MENU_MOVE_NEW_BOXSIZER: + AppData()->CreateBoxSizerWithObject(m_object); + break; + case MENU_EDIT_MENUS: { + PObjectBase obj = m_object; + if (obj && (obj->GetClassName() == wxT("wxMenuBar") || obj->GetClassName() == wxT("Frame"))) { + MenuEditor me(NULL); + if (obj->GetClassName() == wxT("Frame")) { + bool found = false; + PObjectBase menubar; + for (unsigned int i = 0; i < obj->GetChildCount() && !found; i++) { + menubar = obj->GetChild(i); + found = menubar->GetClassName() == wxT("wxMenuBar"); + } + if (found) + obj = menubar; + } + + if (obj->GetClassName() == wxT("wxMenuBar")) + me.Populate(obj); + if (me.ShowModal() == wxID_OK) { + if (obj->GetClassName() == wxT("wxMenuBar")) { + PObjectBase menubar = me.GetMenubar(AppData()->GetObjectDatabase()); + while (obj->GetChildCount() > 0) { + PObjectBase child = obj->GetChild(0); + obj->RemoveChild(0); + child->SetParent(PObjectBase()); + } + for (unsigned int i = 0; i < menubar->GetChildCount(); i++) { + PObjectBase child = menubar->GetChild(i); + AppData()->InsertObject(child, obj); + } + } else + AppData()->InsertObject( + me.GetMenubar(AppData()->GetObjectDatabase()), AppData()->GetSelectedForm()); + } + } + } break; + default: + break; + } } void ItemPopupMenu::OnUpdateEvent(wxUpdateUIEvent& e) { - switch (e.GetId()) - { - case MENU_EDIT_MENUS: - e.Enable(m_object && (m_object->GetClassName() == wxT("wxMenuBar" ) - || m_object->GetClassName() == wxT("Frame"))); - break; - case MENU_CUT: - case MENU_COPY: - case MENU_DELETE: - case MENU_MOVE_UP: - case MENU_MOVE_DOWN: - case MENU_MOVE_LEFT: - case MENU_MOVE_RIGHT: - case MENU_MOVE_NEW_BOXSIZER: - e.Enable(AppData()->CanCopyObject()); - break; - case MENU_PASTE: - e.Enable(AppData()->CanPasteObject()); - break; - } + switch (e.GetId()) { + case MENU_EDIT_MENUS: + e.Enable( + m_object && (m_object->GetClassName() == wxT("wxMenuBar") || m_object->GetClassName() == wxT("Frame"))); + break; + case MENU_CUT: + case MENU_COPY: + case MENU_DELETE: + case MENU_MOVE_UP: + case MENU_MOVE_DOWN: + case MENU_MOVE_LEFT: + case MENU_MOVE_RIGHT: + case MENU_MOVE_NEW_BOXSIZER: + e.Enable(AppData()->CanCopyObject()); + break; + case MENU_PASTE: + e.Enable(AppData()->CanPasteObject()); + break; + } } diff --git a/src/rad/objecttree/objecttree.h b/src/rad/objecttree/objecttree.h index a46c44f1b..6dfcbe2e8 100644 --- a/src/rad/objecttree/objecttree.h +++ b/src/rad/objecttree/objecttree.h @@ -26,70 +26,72 @@ #ifndef RAD_OBJECTTREE_OBJECTTREE_H #define RAD_OBJECTTREE_OBJECTTREE_H -#include "utils/wxfbdefs.h" +#include + #include "rad/customkeys.h" +#include "utils/wxfbdefs.h" -#include class wxFBEvent; -class wxFBPropertyEvent; class wxFBObjectEvent; +class wxFBPropertyEvent; + class ObjectTree : public wxPanel { private: - typedef std::map< PObjectBase, wxTreeItemId> ObjectItemMap; - typedef std::map IconIndexMap; + typedef std::map ObjectItemMap; + typedef std::map IconIndexMap; - ObjectItemMap m_map; + ObjectItemMap m_map; - wxImageList *m_iconList; - IconIndexMap m_iconIdx; + wxImageList* m_iconList; + IconIndexMap m_iconIdx; - wxTreeCtrl* m_tcObjects; + wxTreeCtrl* m_tcObjects; - wxTreeItemId m_draggedItem; + wxTreeItemId m_draggedItem; - bool m_altKeyIsDown; + bool m_altKeyIsDown; - /** - * Crea el arbol completamente. - */ - void RebuildTree(); - void AddChildren(PObjectBase child, wxTreeItemId &parent, bool is_root = false); - int GetImageIndex (wxString type); - void UpdateItem(wxTreeItemId id, PObjectBase obj); - void RestoreItemStatus(PObjectBase obj); - void AddItem(PObjectBase item, PObjectBase parent); - void RemoveItem(PObjectBase item); - void ClearMap(PObjectBase obj); + /** + * Crea el arbol completamente. + */ + void RebuildTree(); + void AddChildren(PObjectBase child, wxTreeItemId& parent, bool is_root = false); + int GetImageIndex(wxString type); + void UpdateItem(wxTreeItemId id, PObjectBase obj); + void RestoreItemStatus(PObjectBase obj); + void AddItem(PObjectBase item, PObjectBase parent); + void RemoveItem(PObjectBase item); + void ClearMap(PObjectBase obj); - PObjectBase GetObjectFromTreeItem( wxTreeItemId item ); + PObjectBase GetObjectFromTreeItem(wxTreeItemId item); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() public: - ObjectTree(wxWindow *parent, int id); - ~ObjectTree() override; - void Create(); - - void OnSelChanged(wxTreeEvent &event); - void OnRightClick(wxTreeEvent &event); - void OnBeginDrag(wxTreeEvent &event); - void OnEndDrag(wxTreeEvent &event); - void OnExpansionChange(wxTreeEvent &event); - - void OnProjectLoaded ( wxFBEvent &event ); - void OnProjectSaved ( wxFBEvent &event ); - void OnObjectExpanded( wxFBObjectEvent& event ); - void OnObjectSelected( wxFBObjectEvent &event ); - void OnObjectCreated ( wxFBObjectEvent &event ); - void OnObjectRemoved ( wxFBObjectEvent &event ); - void OnPropertyModified ( wxFBPropertyEvent &event ); - void OnProjectRefresh ( wxFBEvent &event); - void OnKeyDown ( wxTreeEvent &event); - - void AddCustomKeysHandler(CustomKeysEvtHandler *h) { m_tcObjects->PushEventHandler(h); } + ObjectTree(wxWindow* parent, int id); + ~ObjectTree() override; + void Create(); + + void OnSelChanged(wxTreeEvent& event); + void OnRightClick(wxTreeEvent& event); + void OnBeginDrag(wxTreeEvent& event); + void OnEndDrag(wxTreeEvent& event); + void OnExpansionChange(wxTreeEvent& event); + + void OnProjectLoaded(wxFBEvent& event); + void OnProjectSaved(wxFBEvent& event); + void OnObjectExpanded(wxFBObjectEvent& event); + void OnObjectSelected(wxFBObjectEvent& event); + void OnObjectCreated(wxFBObjectEvent& event); + void OnObjectRemoved(wxFBObjectEvent& event); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnKeyDown(wxTreeEvent& event); + + void AddCustomKeysHandler(CustomKeysEvtHandler* h) { m_tcObjects->PushEventHandler(h); } }; /** @@ -99,11 +101,12 @@ class ObjectTree : public wxPanel */ class ObjectTreeItemData : public wxTreeItemData { - private: - PObjectBase m_object; - public: - ObjectTreeItemData(PObjectBase obj); - PObjectBase GetObject() { return m_object; } +private: + PObjectBase m_object; + +public: + ObjectTreeItemData(PObjectBase obj); + PObjectBase GetObject() { return m_object; } }; /** @@ -114,15 +117,15 @@ class ObjectTreeItemData : public wxTreeItemData */ class ItemPopupMenu : public wxMenu { - private: - PObjectBase m_object; +private: + PObjectBase m_object; - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() - public: - void OnUpdateEvent(wxUpdateUIEvent& e); - ItemPopupMenu(PObjectBase obj); - void OnMenuEvent (wxCommandEvent & event); +public: + void OnUpdateEvent(wxUpdateUIEvent& e); + ItemPopupMenu(PObjectBase obj); + void OnMenuEvent(wxCommandEvent& event); }; -#endif // RAD_OBJECTTREE_OBJECTTREE_H +#endif // RAD_OBJECTTREE_OBJECTTREE_H diff --git a/src/rad/palette.cpp b/src/rad/palette.cpp index e969de3f6..c0599b3c3 100644 --- a/src/rad/palette.cpp +++ b/src/rad/palette.cpp @@ -25,205 +25,198 @@ #include "palette.h" -#include "model/objectbase.h" -#include "utils/debug.h" -#include "rad/appdata.h" -#include "rad/auitabart.h" - #include #include #include #include +#include "model/objectbase.h" +#include "rad/appdata.h" +#include "rad/auitabart.h" +#include "utils/debug.h" + #ifdef __WXMAC__ - #include + #include #endif + #define DRAG_OPTION 0 wxWindowID wxFbPalette::nextId = wxID_HIGHEST + 3000; -BEGIN_EVENT_TABLE( wxFbPalette, wxPanel ) - #ifdef __WXMAC__ - EVT_BUTTON(wxID_ANY, wxFbPalette::OnButtonClick) - #else - EVT_TOOL(wxID_ANY, wxFbPalette::OnButtonClick) - #endif - EVT_SPIN_UP(wxID_ANY, wxFbPalette::OnSpinUp) - EVT_SPIN_DOWN(wxID_ANY, wxFbPalette::OnSpinDown) +BEGIN_EVENT_TABLE(wxFbPalette, wxPanel) +#ifdef __WXMAC__ +EVT_BUTTON(wxID_ANY, wxFbPalette::OnButtonClick) +#else +EVT_TOOL(wxID_ANY, wxFbPalette::OnButtonClick) +#endif +EVT_SPIN_UP(wxID_ANY, wxFbPalette::OnSpinUp) +EVT_SPIN_DOWN(wxID_ANY, wxFbPalette::OnSpinDown) END_EVENT_TABLE() -wxFbPalette::wxFbPalette( wxWindow *parent, int id ) - : wxPanel( parent, id ), m_notebook( NULL ) + +wxFbPalette::wxFbPalette(wxWindow* parent, int id) : wxPanel(parent, id), m_notebook(NULL) { } -void wxFbPalette::PopulateToolbar( PObjectPackage pkg, wxAuiToolBar *toolbar ) +void wxFbPalette::PopulateToolbar(PObjectPackage pkg, wxAuiToolBar* toolbar) { - unsigned int j = 0; - while ( j < pkg->GetObjectCount() ) - { - PObjectInfo info = pkg->GetObjectInfo( j ); - if ( info->IsStartOfGroup() ) - { - toolbar->AddSeparator(); - } - if ( NULL == info->GetComponent() ) - { - LogDebug(_("Missing Component for Class \"" + info->GetClassName() + "\" of Package \"" + pkg->GetPackageName() + "\".") ); - } - else - { - wxString widget( info->GetClassName() ); - - wxBitmap icon = info->GetIconFile(); - - #ifdef __WXMAC__ - wxBitmapButton* button = new wxBitmapButton( toolbar, nextId++, icon ); - button->SetToolTip( widget ); - toolbar->AddControl( button ); - #else - toolbar->AddTool(nextId++, widget, icon, widget); - #endif - - toolbar->Realize(); - } - j++; - } + unsigned int j = 0; + while (j < pkg->GetObjectCount()) { + PObjectInfo info = pkg->GetObjectInfo(j); + if (info->IsStartOfGroup()) { + toolbar->AddSeparator(); + } + if (NULL == info->GetComponent()) { + LogDebug( + _("Missing Component for Class \"" + info->GetClassName() + "\" of Package \"" + pkg->GetPackageName() + + "\".")); + } else { + wxString widget(info->GetClassName()); + + wxBitmap icon = info->GetIconFile(); + +#ifdef __WXMAC__ + wxBitmapButton* button = new wxBitmapButton(toolbar, nextId++, icon); + button->SetToolTip(widget); + toolbar->AddControl(button); +#else + toolbar->AddTool(nextId++, widget, icon, widget); +#endif + + toolbar->Realize(); + } + j++; + } } void wxFbPalette::SavePosition() { - auto* config = wxConfigBase::Get(); - wxString pageOrder; - - for (size_t i = 0; i < m_notebook->GetPageCount(); ++i) - { - if (!pageOrder.empty()) - { - pageOrder.append(wxT(",")); - } - pageOrder.append(m_notebook->GetPageText(i)); - } - - config->Write(wxT("/palette/pageOrder"), pageOrder); + auto* config = wxConfigBase::Get(); + wxString pageOrder; + + for (size_t i = 0; i < m_notebook->GetPageCount(); ++i) { + if (!pageOrder.empty()) { + pageOrder.append(wxT(",")); + } + pageOrder.append(m_notebook->GetPageText(i)); + } + + config->Write(wxT("/palette/pageOrder"), pageOrder); } void wxFbPalette::Create() { - // Package count - unsigned int pkg_count = AppData()->GetPackageCount(); - // Lookup map of all packages - std::map packages; - // List of pages to add to the notebook in desired order - std::vector> pages; - pages.reserve(pkg_count); - - LogDebug( wxT( "[Palette] Pages %d" ), pkg_count ); - - // Fill lookup map of packages - for (unsigned int i = 0; i < pkg_count; ++i) - { - auto pkg = AppData()->GetPackage(i); - packages.insert(std::make_pair(pkg->GetPackageName(), pkg)); - } - - // Read the page order from settings and build the list of pages from it - auto* config = wxConfigBase::Get(); - wxStringTokenizer pageOrder(config->Read(wxT("/palette/pageOrder"), wxT("Common,Additional,Data,Containers,Menu/Toolbar,Layout,Forms,Ribbon")), wxT(",")); - while (pageOrder.HasMoreTokens()) - { - const auto packageName = pageOrder.GetNextToken(); - auto package = packages.find(packageName); - if (packages.end() == package) - { - // Plugin missing - move on - continue; - } - - // Add package to pages list and remove from lookup map - pages.push_back(std::make_pair(package->first, package->second)); - packages.erase(package); - } - - // The remaining packages from the lookup map need to be added to the page list - for (auto& package : packages) - { - pages.push_back(std::make_pair(package.first, package.second)); - } - packages.clear(); - - wxBoxSizer *top_sizer = new wxBoxSizer(wxVERTICAL); - - m_notebook = new wxAuiNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP | wxAUI_NB_SCROLL_BUTTONS | wxAUI_NB_TAB_MOVE); - m_notebook->SetArtProvider(new AuiTabArt()); - - wxSize minsize; - - for (size_t i = 0; i < pages.size(); ++i) - { - const auto& page = pages[i]; - - wxPanel *panel = new wxPanel( m_notebook, wxID_ANY); - //panel->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_3DFACE ) ); - wxBoxSizer *sizer = new wxBoxSizer( wxHORIZONTAL ); - - wxAuiToolBar *toolbar = new wxAuiToolBar( panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_OVERFLOW | wxNO_BORDER ); - toolbar->SetToolBitmapSize( wxSize( 22, 22 ) ); - PopulateToolbar(page.second, toolbar); - m_tv.push_back( toolbar ); - - sizer->Add( toolbar, 1, wxEXPAND, 0 ); - - panel->SetAutoLayout( true ); - panel->SetSizer( sizer ); - sizer->Fit( panel ); - sizer->SetSizeHints( panel ); - - wxSize cursize = panel->GetSize(); - if( cursize.x > minsize.x ) minsize.x = cursize.x; - if( cursize.y > minsize.y ) minsize.y = cursize.y + 30; - - m_notebook->InsertPage(i, panel, page.first, false); - m_notebook->SetPageBitmap(i, page.second->GetPackageIcon()); - } - - //Title *title = new Title( this, wxT("Component Palette") ); - //top_sizer->Add(title,0,wxEXPAND,0); - top_sizer->Add( m_notebook, 1, wxEXPAND, 0 ); - SetSizer( top_sizer ); - SetSize( minsize ); - SetMinSize( minsize ); - Layout(); - Fit(); + // Package count + unsigned int pkg_count = AppData()->GetPackageCount(); + // Lookup map of all packages + std::map packages; + // List of pages to add to the notebook in desired order + std::vector> pages; + pages.reserve(pkg_count); + + LogDebug(wxT("[Palette] Pages %d"), pkg_count); + + // Fill lookup map of packages + for (unsigned int i = 0; i < pkg_count; ++i) { + auto pkg = AppData()->GetPackage(i); + packages.insert(std::make_pair(pkg->GetPackageName(), pkg)); + } + + // Read the page order from settings and build the list of pages from it + auto* config = wxConfigBase::Get(); + wxStringTokenizer pageOrder( + config->Read( + wxT("/palette/pageOrder"), wxT("Common,Additional,Data,Containers,Menu/Toolbar,Layout,Forms,Ribbon")), + wxT(",")); + while (pageOrder.HasMoreTokens()) { + const auto packageName = pageOrder.GetNextToken(); + auto package = packages.find(packageName); + if (packages.end() == package) { + // Plugin missing - move on + continue; + } + + // Add package to pages list and remove from lookup map + pages.push_back(std::make_pair(package->first, package->second)); + packages.erase(package); + } + + // The remaining packages from the lookup map need to be added to the page list + for (auto& package : packages) { pages.push_back(std::make_pair(package.first, package.second)); } + packages.clear(); + + wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); + + m_notebook = new wxAuiNotebook( + this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_NB_TOP | wxAUI_NB_SCROLL_BUTTONS | wxAUI_NB_TAB_MOVE); + m_notebook->SetArtProvider(new AuiTabArt()); + + wxSize minsize; + + for (size_t i = 0; i < pages.size(); ++i) { + const auto& page = pages[i]; + + wxPanel* panel = new wxPanel(m_notebook, wxID_ANY); + // panel->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_3DFACE ) ); + wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); + + wxAuiToolBar* toolbar = new wxAuiToolBar( + panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_OVERFLOW | wxNO_BORDER); + toolbar->SetToolBitmapSize(wxSize(22, 22)); + PopulateToolbar(page.second, toolbar); + m_tv.push_back(toolbar); + + sizer->Add(toolbar, 1, wxEXPAND, 0); + + panel->SetAutoLayout(true); + panel->SetSizer(sizer); + sizer->Fit(panel); + sizer->SetSizeHints(panel); + + wxSize cursize = panel->GetSize(); + if (cursize.x > minsize.x) + minsize.x = cursize.x; + if (cursize.y > minsize.y) + minsize.y = cursize.y + 30; + + m_notebook->InsertPage(i, panel, page.first, false); + m_notebook->SetPageBitmap(i, page.second->GetPackageIcon()); + } + + // Title *title = new Title( this, wxT("Component Palette") ); + // top_sizer->Add(title,0,wxEXPAND,0); + top_sizer->Add(m_notebook, 1, wxEXPAND, 0); + SetSizer(top_sizer); + SetSize(minsize); + SetMinSize(minsize); + Layout(); + Fit(); } -void wxFbPalette::OnSpinUp( wxSpinEvent& ) +void wxFbPalette::OnSpinUp(wxSpinEvent&) { } -void wxFbPalette::OnSpinDown( wxSpinEvent& ) +void wxFbPalette::OnSpinDown(wxSpinEvent&) { } -void wxFbPalette::OnButtonClick( wxCommandEvent &event ) +void wxFbPalette::OnButtonClick(wxCommandEvent& event) { - #ifdef __WXMAC__ - wxWindow* win = dynamic_cast< wxWindow* >( event.GetEventObject() ); - if ( win != 0 ) - { - AppData()->CreateObject( win->GetToolTip()->GetTip() ); - } - #else - for ( unsigned int i = 0; i < m_tv.size(); i++ ) - { - if ( m_tv[i]->GetToolIndex( event.GetId() ) != wxNOT_FOUND ) - { - wxString name = m_tv[i]->GetToolShortHelp( event.GetId() ); - AppData()->CreateObject( name ); - return; - } - } - #endif +#ifdef __WXMAC__ + wxWindow* win = dynamic_cast(event.GetEventObject()); + if (win != 0) { + AppData()->CreateObject(win->GetToolTip()->GetTip()); + } +#else + for (unsigned int i = 0; i < m_tv.size(); i++) { + if (m_tv[i]->GetToolIndex(event.GetId()) != wxNOT_FOUND) { + wxString name = m_tv[i]->GetToolShortHelp(event.GetId()); + AppData()->CreateObject(name); + return; + } + } +#endif } diff --git a/src/rad/palette.h b/src/rad/palette.h index 644af02b9..5c2feb7fc 100644 --- a/src/rad/palette.h +++ b/src/rad/palette.h @@ -26,39 +26,41 @@ #ifndef RAD_PALETTE_H #define RAD_PALETTE_H -#include "model/database.h" - #include #include #include +#include "model/database.h" + + typedef std::vector ToolbarVector; + class wxFbPalette : public wxPanel { - private: - ToolbarVector m_tv; - wxAuiNotebook *m_notebook; - static wxWindowID nextId; - std::vector m_posVector; +private: + ToolbarVector m_tv; + wxAuiNotebook* m_notebook; + static wxWindowID nextId; + std::vector m_posVector; - void PopulateToolbar(PObjectPackage pkg, wxAuiToolBar *toolbar); + void PopulateToolbar(PObjectPackage pkg, wxAuiToolBar* toolbar); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() - public: - wxFbPalette(wxWindow *parent,int id); +public: + wxFbPalette(wxWindow* parent, int id); - void SavePosition(); + void SavePosition(); - /** - * Crea la paleta, previamente se ha debido configurar el objeto - * DataObservable. - */ - void Create(); - void OnSpinUp(wxSpinEvent& e); - void OnSpinDown(wxSpinEvent& e); - void OnButtonClick(wxCommandEvent &event); + /** + * Crea la paleta, previamente se ha debido configurar el objeto + * DataObservable. + */ + void Create(); + void OnSpinUp(wxSpinEvent& e); + void OnSpinDown(wxSpinEvent& e); + void OnButtonClick(wxCommandEvent& event); }; /* class PaletteButton : public wxBitmapButton @@ -98,4 +100,5 @@ class PaletteButtonEventHandler : public wxEvtHandler void OnButtonClick(wxCommandEvent &event); }; */ -#endif // RAD_PALETTE_H + +#endif // RAD_PALETTE_H diff --git a/src/rad/phppanel/phppanel.cpp b/src/rad/phppanel/phppanel.cpp index 7a4ea20c8..63a9b84f9 100644 --- a/src/rad/phppanel/phppanel.cpp +++ b/src/rad/phppanel/phppanel.cpp @@ -27,65 +27,61 @@ #include "phppanel.h" +#include +#include + +#include "codegen/codewriter.h" +#include "codegen/phpcg.h" +#include "model/objectbase.h" #include "rad/appdata.h" #include "rad/codeeditor/codeeditor.h" #include "rad/wxfbevent.h" - #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "model/objectbase.h" -#include "codegen/codewriter.h" -#include "codegen/phpcg.h" +BEGIN_EVENT_TABLE(PHPPanel, wxPanel) +EVT_FB_CODE_GENERATION(PHPPanel::OnCodeGeneration) +EVT_FB_PROJECT_REFRESH(PHPPanel::OnProjectRefresh) +EVT_FB_PROPERTY_MODIFIED(PHPPanel::OnPropertyModified) +EVT_FB_OBJECT_CREATED(PHPPanel::OnObjectChange) +EVT_FB_OBJECT_REMOVED(PHPPanel::OnObjectChange) +EVT_FB_OBJECT_SELECTED(PHPPanel::OnObjectChange) +EVT_FB_EVENT_HANDLER_MODIFIED(PHPPanel::OnEventHandlerModified) -#include - -#include - -BEGIN_EVENT_TABLE ( PHPPanel, wxPanel ) - EVT_FB_CODE_GENERATION( PHPPanel::OnCodeGeneration ) - EVT_FB_PROJECT_REFRESH( PHPPanel::OnProjectRefresh ) - EVT_FB_PROPERTY_MODIFIED( PHPPanel::OnPropertyModified ) - EVT_FB_OBJECT_CREATED( PHPPanel::OnObjectChange ) - EVT_FB_OBJECT_REMOVED( PHPPanel::OnObjectChange ) - EVT_FB_OBJECT_SELECTED( PHPPanel::OnObjectChange ) - EVT_FB_EVENT_HANDLER_MODIFIED( PHPPanel::OnEventHandlerModified ) - - EVT_FIND( wxID_ANY, PHPPanel::OnFind ) - EVT_FIND_NEXT( wxID_ANY, PHPPanel::OnFind ) +EVT_FIND(wxID_ANY, PHPPanel::OnFind) +EVT_FIND_NEXT(wxID_ANY, PHPPanel::OnFind) END_EVENT_TABLE() -PHPPanel::PHPPanel( wxWindow *parent, int id ) -: -wxPanel( parent, id ) + +PHPPanel::PHPPanel(wxWindow* parent, int id) : wxPanel(parent, id) { - AppData()->AddHandler( this->GetEventHandler() ); - wxBoxSizer *top_sizer = new wxBoxSizer( wxVERTICAL ); + AppData()->AddHandler(this->GetEventHandler()); + wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); - m_phpPanel = new CodeEditor( this, wxID_ANY); - InitStyledTextCtrl( m_phpPanel->GetTextCtrl() ); + m_phpPanel = new CodeEditor(this, wxID_ANY); + InitStyledTextCtrl(m_phpPanel->GetTextCtrl()); - top_sizer->Add( m_phpPanel, 1, wxEXPAND, 0 ); + top_sizer->Add(m_phpPanel, 1, wxEXPAND, 0); - SetSizer( top_sizer ); - SetAutoLayout( true ); - //top_sizer->SetSizeHints( this ); - top_sizer->Fit( this ); - top_sizer->Layout(); + SetSizer(top_sizer); + SetAutoLayout(true); + // top_sizer->SetSizeHints( this ); + top_sizer->Fit(this); + top_sizer->Layout(); - m_phpCW = PTCCodeWriter( new TCCodeWriter( m_phpPanel->GetTextCtrl() ) ); + m_phpCW = PTCCodeWriter(new TCCodeWriter(m_phpPanel->GetTextCtrl())); } PHPPanel::~PHPPanel() { - //delete m_icons; - AppData()->RemoveHandler( this->GetEventHandler() ); + // delete m_icons; + AppData()->RemoveHandler(this->GetEventHandler()); } -void PHPPanel::InitStyledTextCtrl( wxStyledTextCtrl *stc ) +void PHPPanel::InitStyledTextCtrl(wxStyledTextCtrl* stc) { - stc->SetLexer( wxSTC_LEX_CPP ); - stc->SetKeyWords( 0, wxT( "php abstract and array as break case catch cfunction \ + stc->SetLexer(wxSTC_LEX_CPP); + stc->SetKeyWords(0, wxT("php abstract and array as break case catch cfunction \ class clone const continue declare default do \ else elseif enddeclare endfor endforeach \ endif endswitch endwhile extends final for foreach function \ @@ -94,276 +90,247 @@ void PHPPanel::InitStyledTextCtrl( wxStyledTextCtrl *stc ) static switch throw try use var while xor __class__ __dir__ \ __file__ __line__ __function__ __method__ __namespace__ \ die echo empty eval exit include include_once isset list require \ - require_once return print unset null" ) ); + require_once return print unset null")); #ifdef __WXGTK__ - // Debe haber un bug en wxGTK ya que la familia wxMODERN no es de ancho fijo. - wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - font.SetFaceName( wxT( "Monospace" ) ); + // Debe haber un bug en wxGTK ya que la familia wxMODERN no es de ancho fijo. + wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + font.SetFaceName(wxT("Monospace")); #else - wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); #endif - stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); - stc->StyleSetFont( wxSTC_STYLE_DEFAULT, font ); + stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); + stc->StyleSetFont(wxSTC_STYLE_DEFAULT, font); stc->StyleClearAll(); - stc->StyleSetBold( wxSTC_C_WORD, true ); - if (!AppData()->IsDarkMode()) - { - stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); - stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); - } - else - { - stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); - stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); - } - stc->SetUseTabs( true ); - stc->SetTabWidth( 4 ); - stc->SetTabIndents( true ); - stc->SetBackSpaceUnIndents( true ); - stc->SetIndent( 4 ); - stc->SetSelBackground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) ); - stc->SetSelForeground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) ); - - stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->SetCaretWidth( 2 ); - stc->SetReadOnly( true ); + stc->StyleSetBold(wxSTC_C_WORD, true); + if (!AppData()->IsDarkMode()) { + stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); + stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); + } else { + stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); + stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); + } + stc->SetUseTabs(true); + stc->SetTabWidth(4); + stc->SetTabIndents(true); + stc->SetBackSpaceUnIndents(true); + stc->SetIndent(4); + stc->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); + stc->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); + + stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->SetCaretWidth(2); + stc->SetReadOnly(true); } -void PHPPanel::OnFind( wxFindDialogEvent& event ) +void PHPPanel::OnFind(wxFindDialogEvent& event) { - m_phpPanel->GetEventHandler()->ProcessEvent( event ); + m_phpPanel->GetEventHandler()->ProcessEvent(event); } -void PHPPanel::OnPropertyModified( wxFBPropertyEvent& event ) +void PHPPanel::OnPropertyModified(wxFBPropertyEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PHPPanel::OnProjectRefresh( wxFBEvent& event ) +void PHPPanel::OnProjectRefresh(wxFBEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PHPPanel::OnObjectChange( wxFBObjectEvent& event ) +void PHPPanel::OnObjectChange(wxFBObjectEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PHPPanel::OnEventHandlerModified( wxFBEventHandlerEvent& event ) +void PHPPanel::OnEventHandlerModified(wxFBEventHandlerEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PHPPanel::OnCodeGeneration( wxFBEvent& event ) +void PHPPanel::OnCodeGeneration(wxFBEvent& event) { PObjectBase objectToGenerate; - // Generate code in the panel if the panel is active - bool doPanel = IsShown(); - - // Using the previously unused Id field in the event to carry a boolean - bool panelOnly = ( event.GetId() != 0 ); - - // Only generate to panel + panel is not shown = do nothing - if ( panelOnly && !doPanel ) - { - return; - } - - // For code preview generate only code relevant to selected form, - // otherwise generate full project code. - - // Create copy of the original project due to possible temporary modifications - PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); - - if(panelOnly) - { - objectToGenerate = AppData()->GetSelectedForm(); - } - - if(!panelOnly || !objectToGenerate) - { - objectToGenerate = project; - } - - // If only one project item should be generated then remove the rest items - // from the temporary project - if(doPanel && panelOnly && (objectToGenerate != project)) - { - if( project->GetChildCount() > 0) - { - unsigned int i = 0; - while( project->GetChildCount() > 1 ) - { - if(project->GetChild( i ) != objectToGenerate) - { - project->RemoveChild( i ); - } - else + // Generate code in the panel if the panel is active + bool doPanel = IsShown(); + + // Using the previously unused Id field in the event to carry a boolean + bool panelOnly = (event.GetId() != 0); + + // Only generate to panel + panel is not shown = do nothing + if (panelOnly && !doPanel) { + return; + } + + // For code preview generate only code relevant to selected form, + // otherwise generate full project code. + + // Create copy of the original project due to possible temporary modifications + PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); + + if (panelOnly) { + objectToGenerate = AppData()->GetSelectedForm(); + } + + if (!panelOnly || !objectToGenerate) { + objectToGenerate = project; + } + + // If only one project item should be generated then remove the rest items + // from the temporary project + if (doPanel && panelOnly && (objectToGenerate != project)) { + if (project->GetChildCount() > 0) { + unsigned int i = 0; + while (project->GetChildCount() > 1) { + if (project->GetChild(i) != objectToGenerate) { + project->RemoveChild(i); + } else i++; } - } - } + } + } - if(!project || !objectToGenerate)return; + if (!project || !objectToGenerate) + return; // Get PHP properties from the project - // If PHP generation is not enabled, do not generate the file - bool doFile = false; - PProperty pCodeGen = project->GetProperty( wxT( "code_generation" ) ); - if ( pCodeGen ) - { - //doFile = TypeConv::FlagSet( wxT("C++"), pCodeGen->GetValue() ) && !panelOnly; - doFile = TypeConv::FlagSet( wxT("PHP"), pCodeGen->GetValue() ) && !panelOnly; - } - - if ( !(doPanel || doFile ) ) - { - return; - } - - // Get First ID from Project File - unsigned int firstID = 1000; - PProperty pFirstID = project->GetProperty( wxT("first_id") ); - if ( pFirstID ) - { - firstID = pFirstID->GetValueAsInteger(); - } - - // Get the file name - wxString file; - PProperty pfile = project->GetProperty( wxT( "file" ) ); - if ( pfile ) - { - file = pfile->GetValue(); - } - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Determine if the path is absolute or relative - bool useRelativePath = false; - PProperty pRelPath = project->GetProperty( wxT( "relative_path" ) ); - if ( pRelPath ) - { - useRelativePath = ( pRelPath->GetValueAsInteger() ? true : false ); - } - - // Get the output path - wxString path; - try - { - path = AppData()->GetOutputPath(); - } - catch ( wxFBException& ex ) - { - if ( doFile ) - { - path = wxEmptyString; - wxLogWarning( ex.what() ); - return; - } - } - - // Generate code in the panel - if ( doPanel ) - { - PHPCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - codegen.SetSourceWriter( m_phpCW ); - - Freeze(); + // If PHP generation is not enabled, do not generate the file + bool doFile = false; + PProperty pCodeGen = project->GetProperty(wxT("code_generation")); + if (pCodeGen) { + // doFile = TypeConv::FlagSet( wxT("C++"), pCodeGen->GetValue() ) && !panelOnly; + doFile = TypeConv::FlagSet(wxT("PHP"), pCodeGen->GetValue()) && !panelOnly; + } + + if (!(doPanel || doFile)) { + return; + } + + // Get First ID from Project File + unsigned int firstID = 1000; + PProperty pFirstID = project->GetProperty(wxT("first_id")); + if (pFirstID) { + firstID = pFirstID->GetValueAsInteger(); + } + + // Get the file name + wxString file; + PProperty pfile = project->GetProperty(wxT("file")); + if (pfile) { + file = pfile->GetValue(); + } + if (file.empty()) { + file = wxT("noname"); + } + + // Determine if the path is absolute or relative + bool useRelativePath = false; + PProperty pRelPath = project->GetProperty(wxT("relative_path")); + if (pRelPath) { + useRelativePath = (pRelPath->GetValueAsInteger() ? true : false); + } + + // Get the output path + wxString path; + try { + path = AppData()->GetOutputPath(); + } catch (wxFBException& ex) { + if (doFile) { + path = wxEmptyString; + wxLogWarning(ex.what()); + return; + } + } + + // Generate code in the panel + if (doPanel) { + PHPCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + codegen.SetSourceWriter(m_phpCW); + + Freeze(); wxStyledTextCtrl* phpEditor = m_phpPanel->GetTextCtrl(); - phpEditor->SetReadOnly( false ); - int phpLine = phpEditor->GetFirstVisibleLine() + phpEditor->LinesOnScreen() - 1; - int phpXOffset = phpEditor->GetXOffset(); - - codegen.GenerateCode( project ); - - phpEditor->SetReadOnly( true ); - phpEditor->GotoLine( phpLine ); - phpEditor->SetXOffset( phpXOffset ); - phpEditor->SetAnchor( 0 ); - phpEditor->SetCurrentPos( 0 ); - - Thaw(); - } - - // Generate code in the file - if ( doFile ) - { - try - { - PHPCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - // Determine if Microsoft BOM should be used - bool useMicrosoftBOM = false; - - PProperty pUseMicrosoftBOM = project->GetProperty( wxT( "use_microsoft_bom" ) ); - - if ( pUseMicrosoftBOM ) - { - useMicrosoftBOM = ( pUseMicrosoftBOM->GetValueAsInteger() != 0 ); - } - - // Determine if Utf8 or Ansi is to be created - bool useUtf8 = false; - PProperty pUseUtf8 = project->GetProperty( _("encoding") ); - - if ( pUseUtf8 ) - { - useUtf8 = ( pUseUtf8->GetValueAsString() != wxT("ANSI") ); - } - - PCodeWriter php_cw( new FileCodeWriter( path + file + wxT( ".php" ), useMicrosoftBOM, useUtf8 ) ); - - codegen.SetSourceWriter( php_cw ); - codegen.GenerateCode( project ); - wxLogStatus( wxT( "Code generated on \'%s\'." ), path ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } + phpEditor->SetReadOnly(false); + int phpLine = phpEditor->GetFirstVisibleLine() + phpEditor->LinesOnScreen() - 1; + int phpXOffset = phpEditor->GetXOffset(); + + codegen.GenerateCode(project); + + phpEditor->SetReadOnly(true); + phpEditor->GotoLine(phpLine); + phpEditor->SetXOffset(phpXOffset); + phpEditor->SetAnchor(0); + phpEditor->SetCurrentPos(0); + + Thaw(); + } + + // Generate code in the file + if (doFile) { + try { + PHPCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + // Determine if Microsoft BOM should be used + bool useMicrosoftBOM = false; + + PProperty pUseMicrosoftBOM = project->GetProperty(wxT("use_microsoft_bom")); + + if (pUseMicrosoftBOM) { + useMicrosoftBOM = (pUseMicrosoftBOM->GetValueAsInteger() != 0); + } + + // Determine if Utf8 or Ansi is to be created + bool useUtf8 = false; + PProperty pUseUtf8 = project->GetProperty(_("encoding")); + + if (pUseUtf8) { + useUtf8 = (pUseUtf8->GetValueAsString() != wxT("ANSI")); + } + + PCodeWriter php_cw(new FileCodeWriter(path + file + wxT(".php"), useMicrosoftBOM, useUtf8)); + + codegen.SetSourceWriter(php_cw); + codegen.GenerateCode(project); + wxLogStatus(wxT("Code generated on \'%s\'."), path); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } } diff --git a/src/rad/phppanel/phppanel.h b/src/rad/phppanel/phppanel.h index cd1f425af..a68cfee98 100644 --- a/src/rad/phppanel/phppanel.h +++ b/src/rad/phppanel/phppanel.h @@ -35,42 +35,41 @@ #ifndef RAD_PHPPANEL_PHPPANEL_H #define RAD_PHPPANEL_PHPPANEL_H -#include "utils/wxfbdefs.h" - #include -class CodeEditor; - -class wxStyledTextCtrl; +#include "utils/wxfbdefs.h" -class wxFindDialogEvent; +class CodeEditor; class wxFBEvent; -class wxFBPropertyEvent; -class wxFBObjectEvent; class wxFBEventHandlerEvent; +class wxFBObjectEvent; +class wxFBPropertyEvent; +class wxFindDialogEvent; +class wxStyledTextCtrl; + class PHPPanel : public wxPanel { private: - CodeEditor* m_phpPanel; - PTCCodeWriter m_phpCW; + CodeEditor* m_phpPanel; + PTCCodeWriter m_phpCW; - void InitStyledTextCtrl( wxStyledTextCtrl* stc ); + void InitStyledTextCtrl(wxStyledTextCtrl* stc); public: - PHPPanel( wxWindow *parent, int id ); - ~PHPPanel() override; + PHPPanel(wxWindow* parent, int id); + ~PHPPanel() override; - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - void OnCodeGeneration( wxFBEvent& event ); - void OnObjectChange( wxFBObjectEvent& event ); - void OnEventHandlerModified( wxFBEventHandlerEvent& event ); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnCodeGeneration(wxFBEvent& event); + void OnObjectChange(wxFBObjectEvent& event); + void OnEventHandlerModified(wxFBEventHandlerEvent& event); - void OnFind( wxFindDialogEvent& event ); + void OnFind(wxFindDialogEvent& event); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; -#endif // RAD_PHPPANEL_PHPPANEL_H +#endif // RAD_PHPPANEL_PHPPANEL_H diff --git a/src/rad/pythonpanel/pythonpanel.cpp b/src/rad/pythonpanel/pythonpanel.cpp index 56af282bc..989e3e255 100644 --- a/src/rad/pythonpanel/pythonpanel.cpp +++ b/src/rad/pythonpanel/pythonpanel.cpp @@ -27,354 +27,319 @@ #include "pythonpanel.h" +#include +#include + +#include "codegen/codewriter.h" +#include "codegen/pythoncg.h" +#include "model/objectbase.h" #include "rad/appdata.h" #include "rad/codeeditor/codeeditor.h" #include "rad/wxfbevent.h" - #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include "model/objectbase.h" - -#include "codegen/codewriter.h" -#include "codegen/pythoncg.h" - -#include -#include +BEGIN_EVENT_TABLE(PythonPanel, wxPanel) +EVT_FB_CODE_GENERATION(PythonPanel::OnCodeGeneration) +EVT_FB_PROJECT_REFRESH(PythonPanel::OnProjectRefresh) +EVT_FB_PROPERTY_MODIFIED(PythonPanel::OnPropertyModified) +EVT_FB_OBJECT_CREATED(PythonPanel::OnObjectChange) +EVT_FB_OBJECT_REMOVED(PythonPanel::OnObjectChange) +EVT_FB_OBJECT_SELECTED(PythonPanel::OnObjectChange) +EVT_FB_EVENT_HANDLER_MODIFIED(PythonPanel::OnEventHandlerModified) -BEGIN_EVENT_TABLE ( PythonPanel, wxPanel ) - EVT_FB_CODE_GENERATION( PythonPanel::OnCodeGeneration ) - EVT_FB_PROJECT_REFRESH( PythonPanel::OnProjectRefresh ) - EVT_FB_PROPERTY_MODIFIED( PythonPanel::OnPropertyModified ) - EVT_FB_OBJECT_CREATED( PythonPanel::OnObjectChange ) - EVT_FB_OBJECT_REMOVED( PythonPanel::OnObjectChange ) - EVT_FB_OBJECT_SELECTED( PythonPanel::OnObjectChange ) - EVT_FB_EVENT_HANDLER_MODIFIED( PythonPanel::OnEventHandlerModified ) - - EVT_FIND( wxID_ANY, PythonPanel::OnFind ) - EVT_FIND_NEXT( wxID_ANY, PythonPanel::OnFind ) +EVT_FIND(wxID_ANY, PythonPanel::OnFind) +EVT_FIND_NEXT(wxID_ANY, PythonPanel::OnFind) END_EVENT_TABLE() -PythonPanel::PythonPanel( wxWindow *parent, int id ) -: -wxPanel( parent, id ) + +PythonPanel::PythonPanel(wxWindow* parent, int id) : wxPanel(parent, id) { - AppData()->AddHandler( this->GetEventHandler() ); - wxBoxSizer *top_sizer = new wxBoxSizer( wxVERTICAL ); + AppData()->AddHandler(this->GetEventHandler()); + wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); - m_pythonPanel = new CodeEditor( this, wxID_ANY); - InitStyledTextCtrl( m_pythonPanel->GetTextCtrl() ); + m_pythonPanel = new CodeEditor(this, wxID_ANY); + InitStyledTextCtrl(m_pythonPanel->GetTextCtrl()); - top_sizer->Add( m_pythonPanel, 1, wxEXPAND, 0 ); + top_sizer->Add(m_pythonPanel, 1, wxEXPAND, 0); - SetSizer( top_sizer ); - SetAutoLayout( true ); - //top_sizer->SetSizeHints( this ); - top_sizer->Fit( this ); - top_sizer->Layout(); + SetSizer(top_sizer); + SetAutoLayout(true); + // top_sizer->SetSizeHints( this ); + top_sizer->Fit(this); + top_sizer->Layout(); - m_pythonCW = PTCCodeWriter( new TCCodeWriter( m_pythonPanel->GetTextCtrl() ) ); + m_pythonCW = PTCCodeWriter(new TCCodeWriter(m_pythonPanel->GetTextCtrl())); } PythonPanel::~PythonPanel() { - //delete m_icons; - AppData()->RemoveHandler( this->GetEventHandler() ); + // delete m_icons; + AppData()->RemoveHandler(this->GetEventHandler()); } -void PythonPanel::InitStyledTextCtrl( wxStyledTextCtrl *stc ) +void PythonPanel::InitStyledTextCtrl(wxStyledTextCtrl* stc) { - stc->SetLexer( wxSTC_LEX_PYTHON ); - stc->SetKeyWords( 0, wxT( "and assert break class continue def del elif else \ + stc->SetLexer(wxSTC_LEX_PYTHON); + stc->SetKeyWords(0, wxT("and assert break class continue def del elif else \ except exec finally for from global if import in \ - is lambda not or pass print raise return try while" ) ); + is lambda not or pass print raise return try while")); #ifdef __WXGTK__ - wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - font.SetFaceName( wxT( "Monospace" ) ); + wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + font.SetFaceName(wxT("Monospace")); #else - wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); #endif - stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); - stc->StyleSetFont( wxSTC_STYLE_DEFAULT, font ); + stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); + stc->StyleSetFont(wxSTC_STYLE_DEFAULT, font); stc->StyleClearAll(); - stc->StyleSetBold( wxSTC_C_WORD, true ); - if (!AppData()->IsDarkMode()) - { - stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); - stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0 )); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); - stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); - } - else - { - stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); - stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); - stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); - stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); - } - stc->SetUseTabs( true ); - stc->SetTabWidth( 4 ); - stc->SetTabIndents( true ); - stc->SetBackSpaceUnIndents( true ); - stc->SetIndent( 4 ); - stc->SetSelBackground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) ); - stc->SetSelForeground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) ); - - stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->SetCaretWidth( 2 ); - stc->SetReadOnly( true ); + stc->StyleSetBold(wxSTC_C_WORD, true); + if (!AppData()->IsDarkMode()) { + stc->StyleSetForeground(wxSTC_C_WORD, *wxBLUE); + stc->StyleSetForeground(wxSTC_C_STRING, *wxRED); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, *wxRED); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(49, 106, 197)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(0, 128, 0)); + stc->StyleSetForeground(wxSTC_C_NUMBER, *wxBLUE); + } else { + stc->StyleSetForeground(wxSTC_C_WORD, wxColour(221, 40, 103)); + stc->StyleSetForeground(wxSTC_C_STRING, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_STRINGEOL, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_C_PREPROCESSOR, wxColour(204, 129, 186)); + stc->StyleSetForeground(wxSTC_C_COMMENT, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_COMMENTLINEDOC, wxColour(98, 98, 98)); + stc->StyleSetForeground(wxSTC_C_NUMBER, wxColour(104, 151, 187)); + } + stc->SetUseTabs(true); + stc->SetTabWidth(4); + stc->SetTabIndents(true); + stc->SetBackSpaceUnIndents(true); + stc->SetIndent(4); + stc->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); + stc->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); + + stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->SetCaretWidth(2); + stc->SetReadOnly(true); } -void PythonPanel::OnFind( wxFindDialogEvent& event ) +void PythonPanel::OnFind(wxFindDialogEvent& event) { - m_pythonPanel->GetEventHandler()->ProcessEvent( event ); + m_pythonPanel->GetEventHandler()->ProcessEvent(event); } -void PythonPanel::OnPropertyModified( wxFBPropertyEvent& event ) +void PythonPanel::OnPropertyModified(wxFBPropertyEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PythonPanel::OnProjectRefresh( wxFBEvent& event ) +void PythonPanel::OnProjectRefresh(wxFBEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PythonPanel::OnObjectChange( wxFBObjectEvent& event ) +void PythonPanel::OnObjectChange(wxFBObjectEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PythonPanel::OnEventHandlerModified( wxFBEventHandlerEvent& event ) +void PythonPanel::OnEventHandlerModified(wxFBEventHandlerEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void PythonPanel::OnCodeGeneration( wxFBEvent& event ) +void PythonPanel::OnCodeGeneration(wxFBEvent& event) { PObjectBase objectToGenerate; - // Generate code in the panel if the panel is active - bool doPanel = IsShown(); - - // Using the previously unused Id field in the event to carry a boolean - bool panelOnly = ( event.GetId() != 0 ); - - // Only generate to panel + panel is not shown = do nothing - if ( panelOnly && !doPanel ) - { - return; - } - - // For code preview generate only code relevant to selected form, - // otherwise generate full project code. - - // Create copy of the original project due to possible temporary modifications - PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); - - if(panelOnly) - { - objectToGenerate = AppData()->GetSelectedForm(); - } - - if(!panelOnly || !objectToGenerate) - { - objectToGenerate = project; - } - - // If only one project item should be generated then remove the rest items - // from the temporary project - if(doPanel && panelOnly && (objectToGenerate != project)) - { - if( project->GetChildCount() > 0) - { - unsigned int i = 0; - while( project->GetChildCount() > 1 ) - { - if(project->GetChild( i ) != objectToGenerate) - { - project->RemoveChild( i ); - } - else + // Generate code in the panel if the panel is active + bool doPanel = IsShown(); + + // Using the previously unused Id field in the event to carry a boolean + bool panelOnly = (event.GetId() != 0); + + // Only generate to panel + panel is not shown = do nothing + if (panelOnly && !doPanel) { + return; + } + + // For code preview generate only code relevant to selected form, + // otherwise generate full project code. + + // Create copy of the original project due to possible temporary modifications + PObjectBase project = PObjectBase(new ObjectBase(*AppData()->GetProjectData())); + + if (panelOnly) { + objectToGenerate = AppData()->GetSelectedForm(); + } + + if (!panelOnly || !objectToGenerate) { + objectToGenerate = project; + } + + // If only one project item should be generated then remove the rest items + // from the temporary project + if (doPanel && panelOnly && (objectToGenerate != project)) { + if (project->GetChildCount() > 0) { + unsigned int i = 0; + while (project->GetChildCount() > 1) { + if (project->GetChild(i) != objectToGenerate) { + project->RemoveChild(i); + } else i++; } - } - } + } + } - if(!project || !objectToGenerate)return; + if (!project || !objectToGenerate) + return; // Get Python properties from the project - // If Python generation is not enabled, do not generate the file - bool doFile = false; - PProperty pCodeGen = project->GetProperty( wxT( "code_generation" ) ); - if ( pCodeGen ) - { - //doFile = TypeConv::FlagSet( wxT("C++"), pCodeGen->GetValue() ) && !panelOnly; - doFile = TypeConv::FlagSet( wxT("Python"), pCodeGen->GetValue() ) && !panelOnly; - } - - if ( !(doPanel || doFile ) ) - { - return; - } - - // Get First ID from Project File - unsigned int firstID = 1000; - PProperty pFirstID = project->GetProperty( wxT("first_id") ); - if ( pFirstID ) - { - firstID = pFirstID->GetValueAsInteger(); - } - - // Get the file name - wxString file; - PProperty pfile = project->GetProperty( wxT( "file" ) ); - if ( pfile ) - { - file = pfile->GetValue(); - } - if ( file.empty() ) - { - file = wxT("noname"); - } - - // Determine if the path is absolute or relative - bool useRelativePath = false; - PProperty pRelPath = project->GetProperty( wxT( "relative_path" ) ); - if ( pRelPath ) - { - useRelativePath = ( pRelPath->GetValueAsInteger() ? true : false ); - } - - // Get the output path - wxString path; - try - { - path = AppData()->GetOutputPath(); - } - catch ( wxFBException& ex ) - { - if ( doFile ) - { - path = wxEmptyString; - wxLogWarning( ex.what() ); - return; - } - } - - bool useSpaces = false; - PProperty pUseSpaces = project->GetProperty( wxT( "indent_with_spaces" ) ); - if (pUseSpaces) - { - useSpaces = ( pUseSpaces->GetValueAsInteger() ? true : false ); - } - m_pythonCW->SetIndentWithSpaces(useSpaces); - - wxString imagePathWrapperFunctionName; - PProperty pImagePathWrapperFunctionName = project->GetProperty( wxT( "image_path_wrapper_function_name" ) ); - if (pImagePathWrapperFunctionName) - { - imagePathWrapperFunctionName = pImagePathWrapperFunctionName->GetValueAsString(); - } - - // Generate code in the panel - if ( doPanel ) - { - PythonCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - codegen.SetImagePathWrapperFunctionName( imagePathWrapperFunctionName ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - codegen.SetSourceWriter( m_pythonCW ); - - Freeze(); + // If Python generation is not enabled, do not generate the file + bool doFile = false; + PProperty pCodeGen = project->GetProperty(wxT("code_generation")); + if (pCodeGen) { + // doFile = TypeConv::FlagSet( wxT("C++"), pCodeGen->GetValue() ) && !panelOnly; + doFile = TypeConv::FlagSet(wxT("Python"), pCodeGen->GetValue()) && !panelOnly; + } + + if (!(doPanel || doFile)) { + return; + } + + // Get First ID from Project File + unsigned int firstID = 1000; + PProperty pFirstID = project->GetProperty(wxT("first_id")); + if (pFirstID) { + firstID = pFirstID->GetValueAsInteger(); + } + + // Get the file name + wxString file; + PProperty pfile = project->GetProperty(wxT("file")); + if (pfile) { + file = pfile->GetValue(); + } + if (file.empty()) { + file = wxT("noname"); + } + + // Determine if the path is absolute or relative + bool useRelativePath = false; + PProperty pRelPath = project->GetProperty(wxT("relative_path")); + if (pRelPath) { + useRelativePath = (pRelPath->GetValueAsInteger() ? true : false); + } + + // Get the output path + wxString path; + try { + path = AppData()->GetOutputPath(); + } catch (wxFBException& ex) { + if (doFile) { + path = wxEmptyString; + wxLogWarning(ex.what()); + return; + } + } + + bool useSpaces = false; + PProperty pUseSpaces = project->GetProperty(wxT("indent_with_spaces")); + if (pUseSpaces) { + useSpaces = (pUseSpaces->GetValueAsInteger() ? true : false); + } + m_pythonCW->SetIndentWithSpaces(useSpaces); + + wxString imagePathWrapperFunctionName; + PProperty pImagePathWrapperFunctionName = project->GetProperty(wxT("image_path_wrapper_function_name")); + if (pImagePathWrapperFunctionName) { + imagePathWrapperFunctionName = pImagePathWrapperFunctionName->GetValueAsString(); + } + + // Generate code in the panel + if (doPanel) { + PythonCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + codegen.SetImagePathWrapperFunctionName(imagePathWrapperFunctionName); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + codegen.SetSourceWriter(m_pythonCW); + + Freeze(); wxStyledTextCtrl* pythonEditor = m_pythonPanel->GetTextCtrl(); - pythonEditor->SetReadOnly( false ); - int pythonLine = pythonEditor->GetFirstVisibleLine() + pythonEditor->LinesOnScreen() - 1; - int pythonXOffset = pythonEditor->GetXOffset(); - - codegen.GenerateCode( project ); - - pythonEditor->SetReadOnly( true ); - pythonEditor->GotoLine( pythonLine ); - pythonEditor->SetXOffset( pythonXOffset ); - pythonEditor->SetAnchor( 0 ); - pythonEditor->SetCurrentPos( 0 ); - - Thaw(); - } - - // Generate code in the file - if ( doFile ) - { - try - { - PythonCodeGenerator codegen; - codegen.UseRelativePath( useRelativePath, path ); - codegen.SetImagePathWrapperFunctionName( imagePathWrapperFunctionName ); - - if ( pFirstID ) - { - codegen.SetFirstID( firstID ); - } - - // Determine if Microsoft BOM should be used - bool useMicrosoftBOM = false; - - PProperty pUseMicrosoftBOM = project->GetProperty( wxT( "use_microsoft_bom" ) ); - - if ( pUseMicrosoftBOM ) - { - useMicrosoftBOM = ( pUseMicrosoftBOM->GetValueAsInteger() != 0 ); - } - - // Determine if Utf8 or Ansi is to be created - bool useUtf8 = false; - PProperty pUseUtf8 = project->GetProperty( _("encoding") ); - - if ( pUseUtf8 ) - { - useUtf8 = ( pUseUtf8->GetValueAsString() != wxT("ANSI") ); - } - - PCodeWriter python_cw( new FileCodeWriter( path + file + wxT( ".py" ), useMicrosoftBOM, useUtf8 ) ); - python_cw->SetIndentWithSpaces( useSpaces ); - - codegen.SetSourceWriter( python_cw ); - codegen.GenerateCode( project ); - wxLogStatus( wxT( "Code generated on \'%s\'." ), path ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } + pythonEditor->SetReadOnly(false); + int pythonLine = pythonEditor->GetFirstVisibleLine() + pythonEditor->LinesOnScreen() - 1; + int pythonXOffset = pythonEditor->GetXOffset(); + + codegen.GenerateCode(project); + + pythonEditor->SetReadOnly(true); + pythonEditor->GotoLine(pythonLine); + pythonEditor->SetXOffset(pythonXOffset); + pythonEditor->SetAnchor(0); + pythonEditor->SetCurrentPos(0); + + Thaw(); + } + + // Generate code in the file + if (doFile) { + try { + PythonCodeGenerator codegen; + codegen.UseRelativePath(useRelativePath, path); + codegen.SetImagePathWrapperFunctionName(imagePathWrapperFunctionName); + + if (pFirstID) { + codegen.SetFirstID(firstID); + } + + // Determine if Microsoft BOM should be used + bool useMicrosoftBOM = false; + + PProperty pUseMicrosoftBOM = project->GetProperty(wxT("use_microsoft_bom")); + + if (pUseMicrosoftBOM) { + useMicrosoftBOM = (pUseMicrosoftBOM->GetValueAsInteger() != 0); + } + + // Determine if Utf8 or Ansi is to be created + bool useUtf8 = false; + PProperty pUseUtf8 = project->GetProperty(_("encoding")); + + if (pUseUtf8) { + useUtf8 = (pUseUtf8->GetValueAsString() != wxT("ANSI")); + } + + PCodeWriter python_cw(new FileCodeWriter(path + file + wxT(".py"), useMicrosoftBOM, useUtf8)); + python_cw->SetIndentWithSpaces(useSpaces); + + codegen.SetSourceWriter(python_cw); + codegen.GenerateCode(project); + wxLogStatus(wxT("Code generated on \'%s\'."), path); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } } diff --git a/src/rad/pythonpanel/pythonpanel.h b/src/rad/pythonpanel/pythonpanel.h index 5cb39bbd4..cc16f5b7d 100644 --- a/src/rad/pythonpanel/pythonpanel.h +++ b/src/rad/pythonpanel/pythonpanel.h @@ -35,46 +35,45 @@ #ifndef RAD_PYTHONPANEL_PYTHONPANEL_H #define RAD_PYTHONPANEL_PYTHONPANEL_H -#include "utils/wxfbdefs.h" - #include -class CodeEditor; - -class wxStyledTextCtrl; +#include "utils/wxfbdefs.h" -class wxFindDialogEvent; +class CodeEditor; class wxFBEvent; -class wxFBPropertyEvent; -class wxFBObjectEvent; class wxFBEventHandlerEvent; +class wxFBObjectEvent; +class wxFBPropertyEvent; +class wxFindDialogEvent; +class wxStyledTextCtrl; + class PythonPanel : public wxPanel { private: - CodeEditor* m_pythonPanel; - PTCCodeWriter m_pythonCW; + CodeEditor* m_pythonPanel; + PTCCodeWriter m_pythonCW; - void InitStyledTextCtrl( wxStyledTextCtrl* stc ); + void InitStyledTextCtrl(wxStyledTextCtrl* stc); public: - PythonPanel( wxWindow *parent, int id ); - ~PythonPanel() override; - PythonPanel(const PythonPanel&) = delete; - PythonPanel& operator=(const PythonPanel&) = delete; - PythonPanel(PythonPanel&&) = delete; - PythonPanel& operator=(PythonPanel&&) = delete; + PythonPanel(wxWindow* parent, int id); + ~PythonPanel() override; + PythonPanel(const PythonPanel&) = delete; + PythonPanel& operator=(const PythonPanel&) = delete; + PythonPanel(PythonPanel&&) = delete; + PythonPanel& operator=(PythonPanel&&) = delete; - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - void OnCodeGeneration( wxFBEvent& event ); - void OnObjectChange( wxFBObjectEvent& event ); - void OnEventHandlerModified( wxFBEventHandlerEvent& event ); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnCodeGeneration(wxFBEvent& event); + void OnObjectChange(wxFBObjectEvent& event); + void OnEventHandlerModified(wxFBEventHandlerEvent& event); - void OnFind( wxFindDialogEvent& event ); + void OnFind(wxFindDialogEvent& event); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; -#endif // RAD_PYTHONPANEL_PYTHONPANEL_H +#endif // RAD_PYTHONPANEL_PYTHONPANEL_H diff --git a/src/rad/revision.h b/src/rad/revision.h index cf450118e..f96b8dd13 100644 --- a/src/rad/revision.h +++ b/src/rad/revision.h @@ -19,4 +19,4 @@ std::string getPostfixRevision(const char* version); std::string getReleaseRevision(const char* version); -#endif // RAD_REVISION_H +#endif // RAD_REVISION_H diff --git a/src/rad/title.cpp b/src/rad/title.cpp index 5726871cd..0545b8c44 100644 --- a/src/rad/title.cpp +++ b/src/rad/title.cpp @@ -25,34 +25,34 @@ #include "title.h" -Title::Title(wxWindow *parent,const wxString &title) : wxPanel(parent, wxID_ANY) + +Title::Title(wxWindow* parent, const wxString& title) : wxPanel(parent, wxID_ANY) { - wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL ); - - wxStaticText *text = new wxStaticText(this, wxID_ANY,title);//,wxDefaultPosition,wxDefaultSize,wxSIMPLE_BORDER); - SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_ACTIVECAPTION ) ); - text->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_ACTIVECAPTION ) ); - text->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_CAPTIONTEXT ) ); - text->SetFont( - wxFont(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxString())); - - sizer->Add(text,0,wxALL | wxEXPAND,2); - SetSizer(sizer); - Fit(); + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + + wxStaticText* text = new wxStaticText(this, wxID_ANY, title); //,wxDefaultPosition,wxDefaultSize,wxSIMPLE_BORDER); + SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_ACTIVECAPTION)); + text->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_ACTIVECAPTION)); + text->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_CAPTIONTEXT)); + text->SetFont(wxFont(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxString())); + + sizer->Add(text, 0, wxALL | wxEXPAND, 2); + SetSizer(sizer); + Fit(); } -wxWindow * Title::CreateTitle (wxWindow *inner, const wxString &title) +wxWindow* Title::CreateTitle(wxWindow* inner, const wxString& title) { - wxWindow *parent = inner->GetParent(); + wxWindow* parent = inner->GetParent(); - wxPanel *container = new wxPanel(parent, wxID_ANY); - Title *titleWin = new Title(container,title); - inner->Reparent(container); + wxPanel* container = new wxPanel(parent, wxID_ANY); + Title* titleWin = new Title(container, title); + inner->Reparent(container); - wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL); - sizer->Add(titleWin,0,wxEXPAND); - sizer->Add(inner,1,wxEXPAND); - container->SetSizer(sizer); + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(titleWin, 0, wxEXPAND); + sizer->Add(inner, 1, wxEXPAND); + container->SetSizer(sizer); - return container; + return container; } diff --git a/src/rad/title.h b/src/rad/title.h index 6a0149078..c6f419ee5 100644 --- a/src/rad/title.h +++ b/src/rad/title.h @@ -28,16 +28,15 @@ #include + class Title : public wxPanel { - private: -// DECLARE_EVENT_TABLE() - public: - Title(wxWindow *parent,const wxString &title=wxT("No title")); +private: + // DECLARE_EVENT_TABLE() +public: + Title(wxWindow* parent, const wxString& title = wxT("No title")); - static wxWindow* CreateTitle (wxWindow *inner, const wxString &title); + static wxWindow* CreateTitle(wxWindow* inner, const wxString& title); }; - - -#endif // RAD_TITLE_H +#endif // RAD_TITLE_H diff --git a/src/rad/version.h b/src/rad/version.h index ed72c01e8..4639f4662 100644 --- a/src/rad/version.h +++ b/src/rad/version.h @@ -1,7 +1,6 @@ #ifndef RAD_VERSION_H #define RAD_VERSION_H - const char* getVersion(); -#endif // RAD_VERSION_H +#endif // RAD_VERSION_H diff --git a/src/rad/wxfbevent.cpp b/src/rad/wxfbevent.cpp index 17c80ce3b..06a5033c9 100644 --- a/src/rad/wxfbevent.cpp +++ b/src/rad/wxfbevent.cpp @@ -25,6 +25,7 @@ #include "wxfbevent.h" + wxDEFINE_EVENT(wxEVT_FB_PROJECT_LOADED, wxFBEvent); wxDEFINE_EVENT(wxEVT_FB_PROJECT_SAVED, wxFBEvent); wxDEFINE_EVENT(wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEvent); @@ -36,110 +37,96 @@ wxDEFINE_EVENT(wxEVT_FB_PROJECT_REFRESH, wxFBEvent); wxDEFINE_EVENT(wxEVT_FB_CODE_GENERATION, wxFBEvent); wxDEFINE_EVENT(wxEVT_FB_EVENT_HANDLER_MODIFIED, wxFBEventHandlerEvent); -wxFBEvent::wxFBEvent( wxEventType commandType ) -: -wxEvent( wxID_ANY, commandType ) + +wxFBEvent::wxFBEvent(wxEventType commandType) : wxEvent(wxID_ANY, commandType) { - //ctor + // ctor } // required for sending with wxPostEvent() wxEvent* wxFBEvent::Clone() const { - return new wxFBEvent( *this ); + return new wxFBEvent(*this); } -wxFBEvent::wxFBEvent( const wxFBEvent& event ) -: -wxEvent( event ), -m_string( event.m_string ) +wxFBEvent::wxFBEvent(const wxFBEvent& event) : wxEvent(event), m_string(event.m_string) { } wxFBEvent::~wxFBEvent() { - //dtor + // dtor } -#define CASE( EVENT ) \ - if ( EVENT == m_eventType ) \ - { \ - return wxT( #EVENT ); \ - } +#define CASE(EVENT) \ + if (EVENT == m_eventType) { \ + return wxT(#EVENT); \ + } wxString wxFBEvent::GetEventName() { - CASE( wxEVT_FB_PROJECT_LOADED ) - CASE( wxEVT_FB_PROJECT_SAVED ) - CASE( wxEVT_FB_OBJECT_EXPANDED ) - CASE( wxEVT_FB_OBJECT_SELECTED ) - CASE( wxEVT_FB_OBJECT_CREATED ) - CASE( wxEVT_FB_OBJECT_REMOVED ) - CASE( wxEVT_FB_PROPERTY_MODIFIED ) - CASE( wxEVT_FB_EVENT_HANDLER_MODIFIED ) - CASE( wxEVT_FB_PROJECT_REFRESH ) - CASE( wxEVT_FB_CODE_GENERATION ) + CASE(wxEVT_FB_PROJECT_LOADED) + CASE(wxEVT_FB_PROJECT_SAVED) + CASE(wxEVT_FB_OBJECT_EXPANDED) + CASE(wxEVT_FB_OBJECT_SELECTED) + CASE(wxEVT_FB_OBJECT_CREATED) + CASE(wxEVT_FB_OBJECT_REMOVED) + CASE(wxEVT_FB_PROPERTY_MODIFIED) + CASE(wxEVT_FB_EVENT_HANDLER_MODIFIED) + CASE(wxEVT_FB_PROJECT_REFRESH) + CASE(wxEVT_FB_CODE_GENERATION) - return wxT( "Unknown Type" ); + return wxT("Unknown Type"); } -void wxFBEvent::SetString( const wxString& newString ) +void wxFBEvent::SetString(const wxString& newString) { - m_string = newString; + m_string = newString; } wxString wxFBEvent::GetString() { - return m_string; + return m_string; } -wxFBPropertyEvent::wxFBPropertyEvent(wxEventType commandType, PProperty property) - : wxFBEvent(commandType), m_property(property) +wxFBPropertyEvent::wxFBPropertyEvent(wxEventType commandType, PProperty property) : + wxFBEvent(commandType), m_property(property) { } -wxFBPropertyEvent::wxFBPropertyEvent( const wxFBPropertyEvent& event ) -: -wxFBEvent( event ), -m_property( event.m_property ) +wxFBPropertyEvent::wxFBPropertyEvent(const wxFBPropertyEvent& event) : wxFBEvent(event), m_property(event.m_property) { } wxEvent* wxFBPropertyEvent::Clone() const { - return new wxFBPropertyEvent( *this ); + return new wxFBPropertyEvent(*this); } -wxFBObjectEvent::wxFBObjectEvent(wxEventType commandType, PObjectBase object) - : wxFBEvent(commandType), m_object(object) +wxFBObjectEvent::wxFBObjectEvent(wxEventType commandType, PObjectBase object) : wxFBEvent(commandType), m_object(object) { } -wxFBObjectEvent::wxFBObjectEvent( const wxFBObjectEvent& event ) -: -wxFBEvent( event ), -m_object( event.m_object ) +wxFBObjectEvent::wxFBObjectEvent(const wxFBObjectEvent& event) : wxFBEvent(event), m_object(event.m_object) { } wxEvent* wxFBObjectEvent::Clone() const { - return new wxFBObjectEvent( *this ); + return new wxFBObjectEvent(*this); } -wxFBEventHandlerEvent::wxFBEventHandlerEvent(wxEventType commandType, PEvent event) - : wxFBEvent(commandType), m_event(event) +wxFBEventHandlerEvent::wxFBEventHandlerEvent(wxEventType commandType, PEvent event) : + wxFBEvent(commandType), m_event(event) { } -wxFBEventHandlerEvent::wxFBEventHandlerEvent( const wxFBEventHandlerEvent& event ) -: -wxFBEvent( event ), -m_event( event.m_event ) +wxFBEventHandlerEvent::wxFBEventHandlerEvent(const wxFBEventHandlerEvent& event) : + wxFBEvent(event), m_event(event.m_event) { } wxEvent* wxFBEventHandlerEvent::Clone() const { - return new wxFBEventHandlerEvent( *this ); + return new wxFBEventHandlerEvent(*this); } diff --git a/src/rad/wxfbevent.h b/src/rad/wxfbevent.h index e5f26e3bb..a0f016371 100644 --- a/src/rad/wxfbevent.h +++ b/src/rad/wxfbevent.h @@ -26,61 +26,64 @@ #ifndef RAD_WXFBEVENT_H #define RAD_WXFBEVENT_H +#include + #include "utils/wxfbdefs.h" -#include class wxFBEvent : public wxEvent { - private: - wxString m_string; +private: + wxString m_string; - public: - wxFBEvent( wxEventType commandType = wxEVT_NULL ); - wxFBEvent( const wxFBEvent& event ); - ~wxFBEvent() override; +public: + wxFBEvent(wxEventType commandType = wxEVT_NULL); + wxFBEvent(const wxFBEvent& event); + ~wxFBEvent() override; - wxString GetEventName(); + wxString GetEventName(); - void SetString( const wxString& newString ); - wxString GetString(); + void SetString(const wxString& newString); + wxString GetString(); - // required for sending with wxPostEvent() - wxEvent* Clone() const override; + // required for sending with wxPostEvent() + wxEvent* Clone() const override; }; class wxFBPropertyEvent : public wxFBEvent { public: - wxFBPropertyEvent(wxEventType commandType, PProperty property); - wxFBPropertyEvent( const wxFBPropertyEvent& event ); - wxEvent* Clone() const override; - PProperty GetFBProperty() { return m_property; } + wxFBPropertyEvent(wxEventType commandType, PProperty property); + wxFBPropertyEvent(const wxFBPropertyEvent& event); + wxEvent* Clone() const override; + PProperty GetFBProperty() { return m_property; } + private: - PProperty m_property; + PProperty m_property; }; class wxFBEventHandlerEvent : public wxFBEvent { public: - wxFBEventHandlerEvent (wxEventType commandType, PEvent event); - wxFBEventHandlerEvent( const wxFBEventHandlerEvent& event ); - wxEvent* Clone() const override; - PEvent GetFBEventHandler() { return m_event; } + wxFBEventHandlerEvent(wxEventType commandType, PEvent event); + wxFBEventHandlerEvent(const wxFBEventHandlerEvent& event); + wxEvent* Clone() const override; + PEvent GetFBEventHandler() { return m_event; } + private: - PEvent m_event; + PEvent m_event; }; class wxFBObjectEvent : public wxFBEvent { public: - wxFBObjectEvent(wxEventType commandType, PObjectBase object); - wxFBObjectEvent( const wxFBObjectEvent& event ); - wxEvent* Clone() const override; - PObjectBase GetFBObject() { return m_object; } + wxFBObjectEvent(wxEventType commandType, PObjectBase object); + wxFBObjectEvent(const wxFBObjectEvent& event); + wxEvent* Clone() const override; + PObjectBase GetFBObject() { return m_object; } private: - PObjectBase m_object; + PObjectBase m_object; }; @@ -105,34 +108,25 @@ wxDECLARE_EVENT(wxEVT_FB_PROJECT_REFRESH, wxFBEvent); wxDECLARE_EVENT(wxEVT_FB_CODE_GENERATION, wxFBEvent); wxDECLARE_EVENT(wxEVT_FB_EVENT_HANDLER_MODIFIED, wxFBEventHandlerEvent); -#define EVT_FB_PROJECT_LOADED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_PROJECT_LOADED,wxFBEventHandler(fn)) +#define EVT_FB_PROJECT_LOADED(fn) wx__DECLARE_EVT0(wxEVT_FB_PROJECT_LOADED, wxFBEventHandler(fn)) -#define EVT_FB_PROJECT_SAVED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_PROJECT_SAVED,wxFBEventHandler(fn)) +#define EVT_FB_PROJECT_SAVED(fn) wx__DECLARE_EVT0(wxEVT_FB_PROJECT_SAVED, wxFBEventHandler(fn)) -#define EVT_FB_OBJECT_EXPANDED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_OBJECT_EXPANDED,wxFBObjectEventHandler(fn)) +#define EVT_FB_OBJECT_EXPANDED(fn) wx__DECLARE_EVT0(wxEVT_FB_OBJECT_EXPANDED, wxFBObjectEventHandler(fn)) -#define EVT_FB_OBJECT_SELECTED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_OBJECT_SELECTED,wxFBObjectEventHandler(fn)) +#define EVT_FB_OBJECT_SELECTED(fn) wx__DECLARE_EVT0(wxEVT_FB_OBJECT_SELECTED, wxFBObjectEventHandler(fn)) -#define EVT_FB_OBJECT_CREATED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_OBJECT_CREATED,wxFBObjectEventHandler(fn)) +#define EVT_FB_OBJECT_CREATED(fn) wx__DECLARE_EVT0(wxEVT_FB_OBJECT_CREATED, wxFBObjectEventHandler(fn)) -#define EVT_FB_OBJECT_REMOVED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_OBJECT_REMOVED,wxFBObjectEventHandler(fn)) +#define EVT_FB_OBJECT_REMOVED(fn) wx__DECLARE_EVT0(wxEVT_FB_OBJECT_REMOVED, wxFBObjectEventHandler(fn)) -#define EVT_FB_PROPERTY_MODIFIED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_PROPERTY_MODIFIED,wxFBPropertyEventHandler(fn)) +#define EVT_FB_PROPERTY_MODIFIED(fn) wx__DECLARE_EVT0(wxEVT_FB_PROPERTY_MODIFIED, wxFBPropertyEventHandler(fn)) #define EVT_FB_EVENT_HANDLER_MODIFIED(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_EVENT_HANDLER_MODIFIED,wxFBEventHandlerEventHandler(fn)) + wx__DECLARE_EVT0(wxEVT_FB_EVENT_HANDLER_MODIFIED, wxFBEventHandlerEventHandler(fn)) -#define EVT_FB_PROJECT_REFRESH(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_PROJECT_REFRESH,wxFBEventHandler(fn)) +#define EVT_FB_PROJECT_REFRESH(fn) wx__DECLARE_EVT0(wxEVT_FB_PROJECT_REFRESH, wxFBEventHandler(fn)) -#define EVT_FB_CODE_GENERATION(fn) \ - wx__DECLARE_EVT0(wxEVT_FB_CODE_GENERATION,wxFBEventHandler(fn)) +#define EVT_FB_CODE_GENERATION(fn) wx__DECLARE_EVT0(wxEVT_FB_CODE_GENERATION, wxFBEventHandler(fn)) -#endif // RAD_WXFBEVENT_H +#endif // RAD_WXFBEVENT_H diff --git a/src/rad/wxfbmanager.cpp b/src/rad/wxfbmanager.cpp index 11115e510..483da8c59 100644 --- a/src/rad/wxfbmanager.cpp +++ b/src/rad/wxfbmanager.cpp @@ -21,184 +21,171 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "wxfbmanager.h" #include "model/objectbase.h" #include "rad/appdata.h" #include "rad/designer/visualeditor.h" -#define CHECK_NULL( THING, THING_NAME, RETURN ) \ - if ( !THING ) \ - { \ - wxLogError( _("%s is NULL! <%s,%i>"), THING_NAME, __TFILE__, __LINE__ ); \ - return RETURN; \ - } -#define CHECK_VISUAL_EDITOR( RETURN ) \ - CHECK_NULL( m_visualEdit, _("Visual Editor"), RETURN ) +#define CHECK_NULL(THING, THING_NAME, RETURN) \ + if (!THING) { \ + wxLogError(_("%s is NULL! <%s,%i>"), THING_NAME, __TFILE__, __LINE__); \ + return RETURN; \ + } + +#define CHECK_VISUAL_EDITOR(RETURN) CHECK_NULL(m_visualEdit, _("Visual Editor"), RETURN) -#define CHECK_WX_OBJECT( RETURN ) \ - CHECK_NULL( wxobject, _("wxObject"), RETURN ) +#define CHECK_WX_OBJECT(RETURN) CHECK_NULL(wxobject, _("wxObject"), RETURN) + +#define CHECK_OBJECT_BASE(RETURN) CHECK_NULL(obj, _("ObjectBase"), RETURN) -#define CHECK_OBJECT_BASE( RETURN ) \ - CHECK_NULL( obj, _("ObjectBase"), RETURN ) // Classes to unset flags in VisualEditor during the destructor - this prevents // forgetting to unset the flag class FlagFlipper { private: - VisualEditor* m_visualEditor; - void (VisualEditor::*m_flagFunction)( bool ); + VisualEditor* m_visualEditor; + void (VisualEditor::*m_flagFunction)(bool); public: - FlagFlipper( VisualEditor* visualEdit, void (VisualEditor::*flagFunction)( bool ) ) - : - m_visualEditor( visualEdit ), - m_flagFunction( flagFunction ) - { - ( m_visualEditor->*m_flagFunction )( true ); - } - - ~FlagFlipper() - { - ( m_visualEditor->*m_flagFunction )( false ); - } + FlagFlipper(VisualEditor* visualEdit, void (VisualEditor::*flagFunction)(bool)) : + m_visualEditor(visualEdit), m_flagFunction(flagFunction) + { + (m_visualEditor->*m_flagFunction)(true); + } + + ~FlagFlipper() { (m_visualEditor->*m_flagFunction)(false); } }; -wxFBManager::wxFBManager() -: -m_visualEdit( NULL ) +wxFBManager::wxFBManager() : m_visualEdit(NULL) { } -void wxFBManager::SetVisualEditor( VisualEditor* visualEdit ) +void wxFBManager::SetVisualEditor(VisualEditor* visualEdit) { - m_visualEdit = visualEdit; + m_visualEdit = visualEdit; } -IObject* wxFBManager::GetIObject( wxObject* wxobject ) +IObject* wxFBManager::GetIObject(wxObject* wxobject) { - CHECK_VISUAL_EDITOR( NULL ) + CHECK_VISUAL_EDITOR(NULL) - CHECK_WX_OBJECT( NULL ) + CHECK_WX_OBJECT(NULL) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE( NULL ) + CHECK_OBJECT_BASE(NULL) - return obj.get(); + return obj.get(); } -size_t wxFBManager::GetChildCount( wxObject* wxobject ) +size_t wxFBManager::GetChildCount(wxObject* wxobject) { - CHECK_VISUAL_EDITOR( 0 ) + CHECK_VISUAL_EDITOR(0) - CHECK_WX_OBJECT( 0 ) + CHECK_WX_OBJECT(0) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE( 0 ) + CHECK_OBJECT_BASE(0) - return obj->GetChildCount(); + return obj->GetChildCount(); } -wxObject* wxFBManager::GetChild( wxObject* wxobject, size_t childIndex ) +wxObject* wxFBManager::GetChild(wxObject* wxobject, size_t childIndex) { - CHECK_VISUAL_EDITOR( NULL ) + CHECK_VISUAL_EDITOR(NULL) - CHECK_WX_OBJECT( NULL ) + CHECK_WX_OBJECT(NULL) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE( NULL ) + CHECK_OBJECT_BASE(NULL) - if ( childIndex >= obj->GetChildCount() ) - { - return NULL; - } + if (childIndex >= obj->GetChildCount()) { + return NULL; + } - return m_visualEdit->GetWxObject( obj->GetChild( childIndex ) ); + return m_visualEdit->GetWxObject(obj->GetChild(childIndex)); } -IObject* wxFBManager::GetIParent( wxObject* wxobject ) +IObject* wxFBManager::GetIParent(wxObject* wxobject) { - CHECK_VISUAL_EDITOR( NULL ) + CHECK_VISUAL_EDITOR(NULL) - CHECK_WX_OBJECT( NULL ) + CHECK_WX_OBJECT(NULL) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE( NULL ) + CHECK_OBJECT_BASE(NULL) - return obj->GetParent().get(); + return obj->GetParent().get(); } -wxObject* wxFBManager::GetParent( wxObject* wxobject ) +wxObject* wxFBManager::GetParent(wxObject* wxobject) { - CHECK_VISUAL_EDITOR( NULL ) + CHECK_VISUAL_EDITOR(NULL) - CHECK_WX_OBJECT( NULL ) + CHECK_WX_OBJECT(NULL) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE( NULL ) + CHECK_OBJECT_BASE(NULL) - return m_visualEdit->GetWxObject( obj->GetParent() ); + return m_visualEdit->GetWxObject(obj->GetParent()); } -wxObject* wxFBManager::GetWxObject( PObjectBase obj ) +wxObject* wxFBManager::GetWxObject(PObjectBase obj) { - CHECK_OBJECT_BASE( NULL ) + CHECK_OBJECT_BASE(NULL) - return m_visualEdit->GetWxObject( obj ); + return m_visualEdit->GetWxObject(obj); } -void wxFBManager::ModifyProperty( wxObject* wxobject, wxString property, wxString value, bool allowUndo ) +void wxFBManager::ModifyProperty(wxObject* wxobject, wxString property, wxString value, bool allowUndo) { - CHECK_VISUAL_EDITOR(void()) + CHECK_VISUAL_EDITOR(void()) - // Prevent modified event in visual editor - no need to redraw when the change is happening in the editor! - FlagFlipper stopModifiedEvent( m_visualEdit, &VisualEditor::PreventOnModified ); + // Prevent modified event in visual editor - no need to redraw when the change is happening in the editor! + FlagFlipper stopModifiedEvent(m_visualEdit, &VisualEditor::PreventOnModified); - CHECK_WX_OBJECT(void()) + CHECK_WX_OBJECT(void()) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE(void()) + CHECK_OBJECT_BASE(void()) - PProperty prop = obj->GetProperty( property ); + PProperty prop = obj->GetProperty(property); - if ( !prop ) - { - wxLogError( _("%s has no property named %s"), obj->GetClassName(), property ); - return; - } + if (!prop) { + wxLogError(_("%s has no property named %s"), obj->GetClassName(), property); + return; + } - if ( allowUndo ) - { - AppData()->ModifyProperty( prop, value ); - } - else - { - prop->SetValue( value ); - } + if (allowUndo) { + AppData()->ModifyProperty(prop, value); + } else { + prop->SetValue(value); + } } -bool wxFBManager::SelectObject( wxObject* wxobject ) +bool wxFBManager::SelectObject(wxObject* wxobject) { - CHECK_VISUAL_EDITOR( false ) + CHECK_VISUAL_EDITOR(false) - // Prevent loop of selection events - FlagFlipper stopSelectedEvent( m_visualEdit, &VisualEditor::PreventOnSelected ); + // Prevent loop of selection events + FlagFlipper stopSelectedEvent(m_visualEdit, &VisualEditor::PreventOnSelected); - CHECK_WX_OBJECT( false ) + CHECK_WX_OBJECT(false) - PObjectBase obj = m_visualEdit->GetObjectBase( wxobject ); + PObjectBase obj = m_visualEdit->GetObjectBase(wxobject); - CHECK_OBJECT_BASE( false ) + CHECK_OBJECT_BASE(false) - return AppData()->SelectObject( obj ); + return AppData()->SelectObject(obj); } wxNoObject* wxFBManager::NewNoObject() diff --git a/src/rad/wxfbmanager.h b/src/rad/wxfbmanager.h index ad06c027e..634a1a63a 100644 --- a/src/rad/wxfbmanager.h +++ b/src/rad/wxfbmanager.h @@ -21,37 +21,39 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_WXFBMANAGER_H #define RAD_WXFBMANAGER_H +#include + #include "utils/wxfbdefs.h" -#include -class VisualEditor; class ObjectBase; +class VisualEditor; + class wxFBManager : public IManager { private: - VisualEditor* m_visualEdit; + VisualEditor* m_visualEdit; public: - wxFBManager(); - void SetVisualEditor( VisualEditor* visualEdit ); - size_t GetChildCount(wxObject* wxobject) override; - wxObject* GetChild(wxObject* wxobject, size_t childIndex) override; - wxObject* GetParent(wxObject* wxobject) override; - IObject* GetIParent(wxObject* wxobject) override; - IObject* GetIObject(wxObject* wxobject) override; - wxObject* GetWxObject( PObjectBase obj ); - wxNoObject* NewNoObject() override; - - void ModifyProperty(wxObject* wxobject, wxString property, wxString value, - bool allowUndo = true) override; - - // Returns true if selection changed, false if already selected - bool SelectObject(wxObject* wxobject) override; + wxFBManager(); + void SetVisualEditor(VisualEditor* visualEdit); + size_t GetChildCount(wxObject* wxobject) override; + wxObject* GetChild(wxObject* wxobject, size_t childIndex) override; + wxObject* GetParent(wxObject* wxobject) override; + IObject* GetIParent(wxObject* wxobject) override; + IObject* GetIObject(wxObject* wxobject) override; + wxObject* GetWxObject(PObjectBase obj); + wxNoObject* NewNoObject() override; + + void ModifyProperty(wxObject* wxobject, wxString property, wxString value, bool allowUndo = true) override; + + // Returns true if selection changed, false if already selected + bool SelectObject(wxObject* wxobject) override; }; -#endif // RAD_WXFBMANAGER_H +#endif // RAD_WXFBMANAGER_H diff --git a/src/rad/xrcpanel/xrcpanel.cpp b/src/rad/xrcpanel/xrcpanel.cpp index 109a49f6c..1ea0aadba 100644 --- a/src/rad/xrcpanel/xrcpanel.cpp +++ b/src/rad/xrcpanel/xrcpanel.cpp @@ -27,238 +27,221 @@ #include "xrcpanel.h" +#include +#include + #include "codegen/codewriter.h" #include "codegen/xrccg.h" - #include "model/objectbase.h" -#include "utils/typeconv.h" -#include "utils/wxfbexception.h" #include "rad/appdata.h" #include "rad/codeeditor/codeeditor.h" #include "rad/wxfbevent.h" +#include "utils/typeconv.h" +#include "utils/wxfbexception.h" -#include - -#include -BEGIN_EVENT_TABLE( XrcPanel, wxPanel ) - EVT_FB_CODE_GENERATION( XrcPanel::OnCodeGeneration ) - EVT_FB_PROJECT_REFRESH( XrcPanel::OnProjectRefresh ) - EVT_FB_PROPERTY_MODIFIED( XrcPanel::OnPropertyModified ) - EVT_FB_OBJECT_CREATED( XrcPanel::OnObjectChange ) - EVT_FB_OBJECT_REMOVED( XrcPanel::OnObjectChange ) - EVT_FB_OBJECT_SELECTED( XrcPanel::OnObjectChange ) +BEGIN_EVENT_TABLE(XrcPanel, wxPanel) +EVT_FB_CODE_GENERATION(XrcPanel::OnCodeGeneration) +EVT_FB_PROJECT_REFRESH(XrcPanel::OnProjectRefresh) +EVT_FB_PROPERTY_MODIFIED(XrcPanel::OnPropertyModified) +EVT_FB_OBJECT_CREATED(XrcPanel::OnObjectChange) +EVT_FB_OBJECT_REMOVED(XrcPanel::OnObjectChange) +EVT_FB_OBJECT_SELECTED(XrcPanel::OnObjectChange) - EVT_FIND( wxID_ANY, XrcPanel::OnFind ) - EVT_FIND_NEXT( wxID_ANY, XrcPanel::OnFind ) +EVT_FIND(wxID_ANY, XrcPanel::OnFind) +EVT_FIND_NEXT(wxID_ANY, XrcPanel::OnFind) END_EVENT_TABLE() -XrcPanel::XrcPanel( wxWindow *parent, int id ) - : wxPanel ( parent, id ) + +XrcPanel::XrcPanel(wxWindow* parent, int id) : wxPanel(parent, id) { - AppData()->AddHandler( this->GetEventHandler() ); - wxBoxSizer *top_sizer = new wxBoxSizer( wxVERTICAL ); + AppData()->AddHandler(this->GetEventHandler()); + wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); - m_xrcPanel = new CodeEditor( this, wxID_ANY); - InitStyledTextCtrl( m_xrcPanel->GetTextCtrl() ); + m_xrcPanel = new CodeEditor(this, wxID_ANY); + InitStyledTextCtrl(m_xrcPanel->GetTextCtrl()); - top_sizer->Add( m_xrcPanel, 1, wxEXPAND, 0 ); + top_sizer->Add(m_xrcPanel, 1, wxEXPAND, 0); - SetSizer( top_sizer ); - SetAutoLayout( true ); - //top_sizer->SetSizeHints( this ); - top_sizer->Fit( this ); - top_sizer->Layout(); + SetSizer(top_sizer); + SetAutoLayout(true); + // top_sizer->SetSizeHints( this ); + top_sizer->Fit(this); + top_sizer->Layout(); - m_cw = PTCCodeWriter( new TCCodeWriter( m_xrcPanel->GetTextCtrl() ) ); + m_cw = PTCCodeWriter(new TCCodeWriter(m_xrcPanel->GetTextCtrl())); } XrcPanel::~XrcPanel() { - AppData()->RemoveHandler( this->GetEventHandler() ); + AppData()->RemoveHandler(this->GetEventHandler()); } -void XrcPanel::InitStyledTextCtrl( wxStyledTextCtrl *stc ) +void XrcPanel::InitStyledTextCtrl(wxStyledTextCtrl* stc) { - stc->SetLexer( wxSTC_LEX_XML ); + stc->SetLexer(wxSTC_LEX_XML); #ifdef __WXGTK__ - // Debe haber un bug en wxGTK ya que la familia wxMODERN no es de ancho fijo. - wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - font.SetFaceName( wxT( "Monospace" ) ); + // Debe haber un bug en wxGTK ya que la familia wxMODERN no es de ancho fijo. + wxFont font(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + font.SetFaceName(wxT("Monospace")); #else - wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + wxFont font(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); #endif - stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); - stc->StyleSetFont( wxSTC_STYLE_DEFAULT, font ); + stc->StyleSetForeground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->StyleSetBackground(wxSTC_STYLE_DEFAULT, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); + stc->StyleSetFont(wxSTC_STYLE_DEFAULT, font); stc->StyleClearAll(); - if (!AppData()->IsDarkMode()) - { - stc->StyleSetForeground(wxSTC_H_DOUBLESTRING, *wxRED); - stc->StyleSetForeground(wxSTC_H_TAG, wxColour(0, 0, 128)); - stc->StyleSetForeground(wxSTC_H_ATTRIBUTE, wxColour(128, 0, 128)); - } - else - { - stc->StyleSetForeground(wxSTC_H_DOUBLESTRING, wxColour(23, 198, 163)); - stc->StyleSetForeground(wxSTC_H_TAG, wxColour(18, 144, 195)); - stc->StyleSetForeground(wxSTC_H_ATTRIBUTE, wxColour(221, 40, 103)); - } - stc->SetUseTabs( false ); - stc->SetTabWidth( 4 ); - stc->SetTabIndents( true ); - stc->SetBackSpaceUnIndents( true ); - stc->SetIndent( 4 ); - stc->SetSelBackground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) ); - stc->SetSelForeground( true, wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) ); - - stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); - stc->SetCaretWidth( 2 ); - stc->SetReadOnly( true ); + if (!AppData()->IsDarkMode()) { + stc->StyleSetForeground(wxSTC_H_DOUBLESTRING, *wxRED); + stc->StyleSetForeground(wxSTC_H_TAG, wxColour(0, 0, 128)); + stc->StyleSetForeground(wxSTC_H_ATTRIBUTE, wxColour(128, 0, 128)); + } else { + stc->StyleSetForeground(wxSTC_H_DOUBLESTRING, wxColour(23, 198, 163)); + stc->StyleSetForeground(wxSTC_H_TAG, wxColour(18, 144, 195)); + stc->StyleSetForeground(wxSTC_H_ATTRIBUTE, wxColour(221, 40, 103)); + } + stc->SetUseTabs(false); + stc->SetTabWidth(4); + stc->SetTabIndents(true); + stc->SetBackSpaceUnIndents(true); + stc->SetIndent(4); + stc->SetSelBackground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); + stc->SetSelForeground(true, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); + + stc->SetCaretForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); + stc->SetCaretWidth(2); + stc->SetReadOnly(true); } -void XrcPanel::OnFind( wxFindDialogEvent& event ) +void XrcPanel::OnFind(wxFindDialogEvent& event) { - wxAuiNotebook* notebook = wxDynamicCast( this->GetParent(), wxAuiNotebook ); - if ( NULL == notebook ) - { - return; - } - - int selection = notebook->GetSelection(); - if ( selection < 0 ) - { - return; - } - - wxString text = notebook->GetPageText( selection ); - if ( wxT("XRC") == text ) - { - m_xrcPanel->GetEventHandler()->ProcessEvent( event ); - } + wxAuiNotebook* notebook = wxDynamicCast(this->GetParent(), wxAuiNotebook); + if (NULL == notebook) { + return; + } + + int selection = notebook->GetSelection(); + if (selection < 0) { + return; + } + + wxString text = notebook->GetPageText(selection); + if (wxT("XRC") == text) { + m_xrcPanel->GetEventHandler()->ProcessEvent(event); + } } -void XrcPanel::OnPropertyModified( wxFBPropertyEvent& event ) +void XrcPanel::OnPropertyModified(wxFBPropertyEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void XrcPanel::OnProjectRefresh( wxFBEvent& event ) +void XrcPanel::OnProjectRefresh(wxFBEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void XrcPanel::OnObjectChange( wxFBObjectEvent& event ) +void XrcPanel::OnObjectChange(wxFBObjectEvent& event) { - // Generate code to the panel only - event.SetId( 1 ); - OnCodeGeneration( event ); + // Generate code to the panel only + event.SetId(1); + OnCodeGeneration(event); } -void XrcPanel::OnCodeGeneration( wxFBEvent& event ) +void XrcPanel::OnCodeGeneration(wxFBEvent& event) { PObjectBase project; - // Using the previously unused Id field in the event to carry a boolean - bool panelOnly = ( event.GetId() != 0 ); - - // Generate code in the panel if the panel is active - bool doPanel = IsShown(); - - // Only generate to panel + panel is not shown = do nothing - if ( panelOnly && !doPanel ) - { - return; - } - - // For code preview generate only code relevant to selected form, - // otherwise generate full project code. - if(panelOnly) - { - project = AppData()->GetSelectedForm(); - } - - if(!panelOnly || !project) - { - project = AppData()->GetProjectData(); - } - //PObjectBase project = AppData()->GetProjectData(); - - if(!project)return; - - // Generate code in the panel if the panel is active - if ( IsShown() ) - { - Freeze(); + // Using the previously unused Id field in the event to carry a boolean + bool panelOnly = (event.GetId() != 0); + + // Generate code in the panel if the panel is active + bool doPanel = IsShown(); + + // Only generate to panel + panel is not shown = do nothing + if (panelOnly && !doPanel) { + return; + } + + // For code preview generate only code relevant to selected form, + // otherwise generate full project code. + if (panelOnly) { + project = AppData()->GetSelectedForm(); + } + + if (!panelOnly || !project) { + project = AppData()->GetProjectData(); + } + // PObjectBase project = AppData()->GetProjectData(); + + if (!project) + return; + + // Generate code in the panel if the panel is active + if (IsShown()) { + Freeze(); wxStyledTextCtrl* editor = m_xrcPanel->GetTextCtrl(); - editor->SetReadOnly( false ); - int line = editor->GetFirstVisibleLine() + editor->LinesOnScreen() - 1; - int xOffset = editor->GetXOffset(); - - XrcCodeGenerator codegen; - codegen.SetWriter( m_cw ); - codegen.GenerateCode( project ); - editor->SetReadOnly( true ); - editor->GotoLine( line ); - editor->SetXOffset( xOffset ); - editor->SetAnchor( 0 ); - editor->SetCurrentPos( 0 ); - Thaw(); - } - - if ( panelOnly ) - { - return; - } - - PProperty pCodeGen = project->GetProperty( wxT("code_generation") ); - if ( pCodeGen ) - { - if ( !TypeConv::FlagSet ( wxT("XRC"), pCodeGen->GetValue() ) ) - { - return; - } - } - - // And now in the file. - { - XrcCodeGenerator codegen; - - wxString file, pathEntry; - - wxString path; - - try - { - // Get the output path - path = AppData()->GetOutputPath(); - - PProperty pfile = project->GetProperty( wxT( "file" ) ); - - if ( pfile ) - file = pfile->GetValue(); - - if ( file.empty() ) - { - file = wxT( "noname" ); - } - - wxString filePath; - - filePath << path << file << wxT( ".xrc" ); - PCodeWriter cw( new FileCodeWriter( filePath ) ); - - codegen.SetWriter( cw ); - codegen.GenerateCode( project ); - wxLogStatus( wxT( "Code generated on \'%s\'." ), path ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - } - } + editor->SetReadOnly(false); + int line = editor->GetFirstVisibleLine() + editor->LinesOnScreen() - 1; + int xOffset = editor->GetXOffset(); + + XrcCodeGenerator codegen; + codegen.SetWriter(m_cw); + codegen.GenerateCode(project); + editor->SetReadOnly(true); + editor->GotoLine(line); + editor->SetXOffset(xOffset); + editor->SetAnchor(0); + editor->SetCurrentPos(0); + Thaw(); + } + + if (panelOnly) { + return; + } + + PProperty pCodeGen = project->GetProperty(wxT("code_generation")); + if (pCodeGen) { + if (!TypeConv::FlagSet(wxT("XRC"), pCodeGen->GetValue())) { + return; + } + } + + // And now in the file. + { + XrcCodeGenerator codegen; + + wxString file, pathEntry; + + wxString path; + + try { + // Get the output path + path = AppData()->GetOutputPath(); + + PProperty pfile = project->GetProperty(wxT("file")); + + if (pfile) + file = pfile->GetValue(); + + if (file.empty()) { + file = wxT("noname"); + } + + wxString filePath; + + filePath << path << file << wxT(".xrc"); + PCodeWriter cw(new FileCodeWriter(filePath)); + + codegen.SetWriter(cw); + codegen.GenerateCode(project); + wxLogStatus(wxT("Code generated on \'%s\'."), path); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + } + } } diff --git a/src/rad/xrcpanel/xrcpanel.h b/src/rad/xrcpanel/xrcpanel.h index 6f41c94fe..f471f6461 100644 --- a/src/rad/xrcpanel/xrcpanel.h +++ b/src/rad/xrcpanel/xrcpanel.h @@ -26,10 +26,10 @@ #ifndef RAD_XRCPANEL_XRCPANEL_H #define RAD_XRCPANEL_XRCPANEL_H -#include "utils/wxfbdefs.h" - -#include #include +#include + +#include "utils/wxfbdefs.h" class CodeEditor; class wxFBEvent; @@ -37,27 +37,27 @@ class wxFBObjectEvent; class wxFBPropertyEvent; class wxFindDialogEvent; + class XrcPanel : public wxPanel { private: - CodeEditor* m_xrcPanel; - PTCCodeWriter m_cw; + CodeEditor* m_xrcPanel; + PTCCodeWriter m_cw; - void InitStyledTextCtrl( wxStyledTextCtrl* stc ); + void InitStyledTextCtrl(wxStyledTextCtrl* stc); public: - XrcPanel( wxWindow *parent, int id ); - ~XrcPanel() override; + XrcPanel(wxWindow* parent, int id); + ~XrcPanel() override; - void OnPropertyModified( wxFBPropertyEvent& event ); - void OnProjectRefresh( wxFBEvent& event ); - void OnCodeGeneration( wxFBEvent& event ); - void OnObjectChange( wxFBObjectEvent& event ); + void OnPropertyModified(wxFBPropertyEvent& event); + void OnProjectRefresh(wxFBEvent& event); + void OnCodeGeneration(wxFBEvent& event); + void OnObjectChange(wxFBObjectEvent& event); - void OnFind( wxFindDialogEvent& event ); + void OnFind(wxFindDialogEvent& event); - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; - -#endif // RAD_XRCPANEL_XRCPANEL_H +#endif // RAD_XRCPANEL_XRCPANEL_H diff --git a/src/rad/xrcpreview/xrcpreview.cpp b/src/rad/xrcpreview/xrcpreview.cpp index 558709a05..55b5f94e5 100644 --- a/src/rad/xrcpreview/xrcpreview.cpp +++ b/src/rad/xrcpreview/xrcpreview.cpp @@ -21,8 +21,13 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #include "xrcpreview.h" +#include +#include +#include + #include "codegen/codewriter.h" #include "codegen/xrccg.h" #include "model/objectbase.h" @@ -30,245 +35,207 @@ #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include -#include -#include #define MENU_DELETE 109 + class XrcPreviewPopupMenu : public wxMenu { - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() private: - wxWindow* m_window; + wxWindow* m_window; public: - XrcPreviewPopupMenu(wxWindow* window) : m_window(window) { - Append( MENU_DELETE, wxT("Close Preview") ); - } - - void OnMenuEvent ( wxCommandEvent& event ) - { - int id = event.GetId(); - - switch ( id ) - { - case MENU_DELETE: - m_window->Close(); - break; - default: - break; - } - } + XrcPreviewPopupMenu(wxWindow* window) : m_window(window) { Append(MENU_DELETE, wxT("Close Preview")); } + + void OnMenuEvent(wxCommandEvent& event) + { + int id = event.GetId(); + + switch (id) { + case MENU_DELETE: + m_window->Close(); + break; + default: + break; + } + } }; -BEGIN_EVENT_TABLE( XrcPreviewPopupMenu, wxMenu ) - EVT_MENU( wxID_ANY, XrcPreviewPopupMenu::OnMenuEvent ) +BEGIN_EVENT_TABLE(XrcPreviewPopupMenu, wxMenu) +EVT_MENU(wxID_ANY, XrcPreviewPopupMenu::OnMenuEvent) END_EVENT_TABLE() class XRCPreviewEvtHandler : public wxEvtHandler { private: - wxWindow* m_window; + wxWindow* m_window; public: - XRCPreviewEvtHandler( wxWindow* win ) - : - m_window( win ) - { - } + XRCPreviewEvtHandler(wxWindow* win) : m_window(win) {} protected: - void OnKeyUp( wxKeyEvent& event ) - { - if ( event.GetKeyCode() == WXK_ESCAPE ) - { - m_window->Close(); - } - } - - void OnRightDown( wxMouseEvent& event ) - { - wxMenu* menu = new XrcPreviewPopupMenu( m_window ); - wxPoint pos = event.GetPosition(); - m_window->PopupMenu( menu, pos.x, pos.y ); - } - - void RemoveEventHandler( wxWindow* window ) + void OnKeyUp(wxKeyEvent& event) { - const wxWindowList& children = window->GetChildren(); - for ( size_t i = 0; i < children.GetCount(); ++i ) - { - RemoveEventHandler( children.Item( i )->GetData() ); + if (event.GetKeyCode() == WXK_ESCAPE) { + m_window->Close(); } + } + + void OnRightDown(wxMouseEvent& event) + { + wxMenu* menu = new XrcPreviewPopupMenu(m_window); + wxPoint pos = event.GetPosition(); + m_window->PopupMenu(menu, pos.x, pos.y); + } + + void RemoveEventHandler(wxWindow* window) + { + const wxWindowList& children = window->GetChildren(); + for (size_t i = 0; i < children.GetCount(); ++i) { RemoveEventHandler(children.Item(i)->GetData()); } wxEvtHandler* handler = window->PopEventHandler(); - if ( handler != this ) - { + if (handler != this) { delete handler; } } - void OnClose( wxCloseEvent& ) - { - RemoveEventHandler( m_window ); - m_window->Destroy(); - delete this; - } + void OnClose(wxCloseEvent&) + { + RemoveEventHandler(m_window); + m_window->Destroy(); + delete this; + } - DECLARE_EVENT_TABLE() + DECLARE_EVENT_TABLE() }; -BEGIN_EVENT_TABLE( XRCPreviewEvtHandler, wxEvtHandler ) - EVT_KEY_UP( XRCPreviewEvtHandler::OnKeyUp ) - EVT_RIGHT_DOWN( XRCPreviewEvtHandler::OnRightDown ) - EVT_CLOSE ( XRCPreviewEvtHandler::OnClose ) +BEGIN_EVENT_TABLE(XRCPreviewEvtHandler, wxEvtHandler) +EVT_KEY_UP(XRCPreviewEvtHandler::OnKeyUp) +EVT_RIGHT_DOWN(XRCPreviewEvtHandler::OnRightDown) +EVT_CLOSE(XRCPreviewEvtHandler::OnClose) END_EVENT_TABLE() -void XRCPreview::Show( PObjectBase form, const wxString& projectPath ) +void XRCPreview::Show(PObjectBase form, const wxString& projectPath) { - AnnoyingDialog dlg(_("WARNING - For XRC Developers ONLY!!"), - wxGetTranslation( wxT("The XRC language is not as powerful as C++.\n") - wxT("It has limitations that will affect the GUI\n") - wxT("layout. This preview will ONLY show how the\n") - wxT("generated XRC will look, and it will probably\n") - wxT("be different from the Designer.\n\n") - wxT("If you are not using XRC, do NOT use the XRC\n") - wxT("preview, it will only confuse you.") - ), - wxART_WARNING, - AnnoyingDialog::OK_CANCEL, - wxID_CANCEL); - - if ( wxID_CANCEL == dlg.ShowModal() ) - { - return; - } - - wxString className = form->GetClassName(); - - PStringCodeWriter cw( new StringCodeWriter ); - try - { - XrcCodeGenerator codegen; - codegen.SetWriter( cw ); - codegen.GenerateCode( form ); - } - catch ( wxFBException& ex ) - { - wxLogError( ex.what() ); - return; - } - - wxString workingDir = ::wxGetCwd(); - // We change the current directory so that the relative paths work properly - if( !projectPath.IsEmpty() ) ::wxSetWorkingDirectory( projectPath ); - wxXmlResource *res = wxXmlResource::Get(); - res->InitAllHandlers(); - - const std::string& data = _STDSTR( cw->GetString() ); - wxMemoryFSHandler::AddFile(wxT("xrcpreview.xrc"), data.c_str(), data.size() ); - res->Load( wxT("memory:xrcpreview.xrc") ); - - wxWindow* window = NULL; - if ( className == wxT( "Frame" ) ) - { - wxFrame* frame = new wxFrame(); - res->LoadFrame( frame, wxTheApp->GetTopWindow(), form->GetPropertyAsString( wxT( "name" ) ) ); - // Prevent events from propagating up to wxFB's frame - frame->SetExtraStyle( frame->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS ); - frame->Show(); - window = frame; - } - else if ( className == wxT( "Dialog" ) ) - { - wxDialog* dialog = new wxDialog; - res->LoadDialog( dialog, wxTheApp->GetTopWindow(), form->GetPropertyAsString( wxT( "name" ) ) ); - // Prevent events from propagating up to wxFB's frame - dialog->SetExtraStyle( dialog->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS ); - dialog->Show(); - window = dialog; - } - else if ( className == wxT("Wizard") ) - { - wxString wizName = form->GetPropertyAsString( wxT("name") ); - wxString pgName; - wxObject *wizObj = res->LoadObject( NULL, wizName, wxT("wxWizard") ); - wxWizard *wizard = wxDynamicCast( wizObj, wxWizard ); - wxWizardPageSimple *wizpge = NULL; - - if ( wizard ) - { - wizard->SetExtraStyle( wizard->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS ); + AnnoyingDialog dlg( + _("WARNING - For XRC Developers ONLY!!"), + wxGetTranslation( + wxT("The XRC language is not as powerful as C++.\n") wxT("It has limitations that will affect the GUI\n") + wxT("layout. This preview will ONLY show how the\n") wxT("generated XRC will look, and it will probably\n") + wxT("be different from the Designer.\n\n") wxT("If you are not using XRC, do NOT use the XRC\n") + wxT("preview, it will only confuse you.")), + wxART_WARNING, AnnoyingDialog::OK_CANCEL, wxID_CANCEL); + + if (wxID_CANCEL == dlg.ShowModal()) { + return; + } + + wxString className = form->GetClassName(); + + PStringCodeWriter cw(new StringCodeWriter); + try { + XrcCodeGenerator codegen; + codegen.SetWriter(cw); + codegen.GenerateCode(form); + } catch (wxFBException& ex) { + wxLogError(ex.what()); + return; + } + + wxString workingDir = ::wxGetCwd(); + // We change the current directory so that the relative paths work properly + if (!projectPath.IsEmpty()) + ::wxSetWorkingDirectory(projectPath); + wxXmlResource* res = wxXmlResource::Get(); + res->InitAllHandlers(); + + const std::string& data = _STDSTR(cw->GetString()); + wxMemoryFSHandler::AddFile(wxT("xrcpreview.xrc"), data.c_str(), data.size()); + res->Load(wxT("memory:xrcpreview.xrc")); + + wxWindow* window = NULL; + if (className == wxT("Frame")) { + wxFrame* frame = new wxFrame(); + res->LoadFrame(frame, wxTheApp->GetTopWindow(), form->GetPropertyAsString(wxT("name"))); + // Prevent events from propagating up to wxFB's frame + frame->SetExtraStyle(frame->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS); + frame->Show(); + window = frame; + } else if (className == wxT("Dialog")) { + wxDialog* dialog = new wxDialog; + res->LoadDialog(dialog, wxTheApp->GetTopWindow(), form->GetPropertyAsString(wxT("name"))); + // Prevent events from propagating up to wxFB's frame + dialog->SetExtraStyle(dialog->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS); + dialog->Show(); + window = dialog; + } else if (className == wxT("Wizard")) { + wxString wizName = form->GetPropertyAsString(wxT("name")); + wxString pgName; + wxObject* wizObj = res->LoadObject(NULL, wizName, wxT("wxWizard")); + wxWizard* wizard = wxDynamicCast(wizObj, wxWizard); + wxWizardPageSimple* wizpge = NULL; + + if (wizard) { + wizard->SetExtraStyle(wizard->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS); } - if ( form->GetChildCount() > 0 ) - { - pgName = form->GetChild(0)->GetPropertyAsString( wxT("name") ); - wizpge = ( wxWizardPageSimple * )wizard->FindWindow( pgName ); + if (form->GetChildCount() > 0) { + pgName = form->GetChild(0)->GetPropertyAsString(wxT("name")); + wizpge = (wxWizardPageSimple*)wizard->FindWindow(pgName); } - if ( wizpge ) - { - wizard->RunWizard( wizpge ); + if (wizpge) { + wizard->RunWizard(wizpge); wizard->Destroy(); window = NULL; } - } - else if ( className == wxT( "Panel" ) ) - { - wxDialog* dialog = new wxDialog( wxTheApp->GetTopWindow(), wxID_ANY, wxT( "Dialog" ), wxDefaultPosition, - wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER ); - // Prevent events from propagating up to wxFB's frame - dialog->SetExtraStyle( wxWS_EX_BLOCK_EVENTS ); - wxPanel *panel = new wxPanel(); - res->LoadPanel( panel, dialog, form->GetPropertyAsString( wxT( "name" ) ) ); - dialog->SetClientSize( panel->GetSize() ); - dialog->SetSize( form->GetPropertyAsSize( wxT( "size" ) ) ); - dialog->CenterOnScreen(); - dialog->Show(); - window = dialog; - } - else if ( className == wxT( "MenuBar" ) ) - { - wxFrame* frame = new wxFrame( NULL, wxID_ANY, form->GetPropertyAsString( wxT( "name" ) ) ); - // Prevent events from propagating up to wxFB's frame - frame->SetExtraStyle( frame->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS ); - frame->SetMenuBar( res->LoadMenuBar( form->GetPropertyAsString( wxT( "name" ) ) ) ); - frame->CenterOnScreen(); - frame->Show(); - window = frame; - } - else if ( className == wxT( "ToolBar" ) ) - { - wxFrame* frame = new wxFrame( NULL, wxID_ANY, form->GetPropertyAsString( wxT( "name" ) ) ); - // Prevent events from propagating up to wxFB's frame - frame->SetExtraStyle( frame->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS ); - frame->SetToolBar( res->LoadToolBar( frame, form->GetPropertyAsString( wxT( "name" ) ) ) ); - frame->CenterOnScreen(); - frame->Show(); - window = frame; - } - - if ( window ) - { - AddEventHandler( window, window ); - } - - ::wxSetWorkingDirectory( workingDir ); - - res->Unload( wxT("memory:xrcpreview.xrc") ); - - wxMemoryFSHandler::RemoveFile( wxT("xrcpreview.xrc") ); + } else if (className == wxT("Panel")) { + wxDialog* dialog = new wxDialog( + wxTheApp->GetTopWindow(), wxID_ANY, wxT("Dialog"), wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); + // Prevent events from propagating up to wxFB's frame + dialog->SetExtraStyle(wxWS_EX_BLOCK_EVENTS); + wxPanel* panel = new wxPanel(); + res->LoadPanel(panel, dialog, form->GetPropertyAsString(wxT("name"))); + dialog->SetClientSize(panel->GetSize()); + dialog->SetSize(form->GetPropertyAsSize(wxT("size"))); + dialog->CenterOnScreen(); + dialog->Show(); + window = dialog; + } else if (className == wxT("MenuBar")) { + wxFrame* frame = new wxFrame(NULL, wxID_ANY, form->GetPropertyAsString(wxT("name"))); + // Prevent events from propagating up to wxFB's frame + frame->SetExtraStyle(frame->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS); + frame->SetMenuBar(res->LoadMenuBar(form->GetPropertyAsString(wxT("name")))); + frame->CenterOnScreen(); + frame->Show(); + window = frame; + } else if (className == wxT("ToolBar")) { + wxFrame* frame = new wxFrame(NULL, wxID_ANY, form->GetPropertyAsString(wxT("name"))); + // Prevent events from propagating up to wxFB's frame + frame->SetExtraStyle(frame->GetExtraStyle() | wxWS_EX_BLOCK_EVENTS); + frame->SetToolBar(res->LoadToolBar(frame, form->GetPropertyAsString(wxT("name")))); + frame->CenterOnScreen(); + frame->Show(); + window = frame; + } + + if (window) { + AddEventHandler(window, window); + } + + ::wxSetWorkingDirectory(workingDir); + + res->Unload(wxT("memory:xrcpreview.xrc")); + + wxMemoryFSHandler::RemoveFile(wxT("xrcpreview.xrc")); } -void XRCPreview::AddEventHandler( wxWindow* window, wxWindow* form ) +void XRCPreview::AddEventHandler(wxWindow* window, wxWindow* form) { - const wxWindowList& children = window->GetChildren(); - for ( size_t i = 0; i < children.GetCount(); ++i ) - { - AddEventHandler( children.Item( i )->GetData(), form ); - } - window->PushEventHandler( ( new XRCPreviewEvtHandler( form ) ) ); + const wxWindowList& children = window->GetChildren(); + for (size_t i = 0; i < children.GetCount(); ++i) { AddEventHandler(children.Item(i)->GetData(), form); } + window->PushEventHandler((new XRCPreviewEvtHandler(form))); } diff --git a/src/rad/xrcpreview/xrcpreview.h b/src/rad/xrcpreview/xrcpreview.h index c6bb2e095..7b77e22d7 100644 --- a/src/rad/xrcpreview/xrcpreview.h +++ b/src/rad/xrcpreview/xrcpreview.h @@ -21,19 +21,23 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef RAD_XRCPREVIEW_XRCPREVIEW_H #define RAD_XRCPREVIEW_XRCPREVIEW_H #include "utils/wxfbdefs.h" + class wxWindow; + class XRCPreview { private: - static void AddEventHandler( wxWindow* window, wxWindow* form ); + static void AddEventHandler(wxWindow* window, wxWindow* form); + public: - static void Show( PObjectBase form, const wxString& projectpath ); + static void Show(PObjectBase form, const wxString& projectpath); }; -#endif // RAD_XRCPREVIEW_XRCPREVIEW_H +#endif // RAD_XRCPREVIEW_XRCPREVIEW_H diff --git a/src/utils/annoyingdialog.cpp b/src/utils/annoyingdialog.cpp index 5e7b27422..113dc2c3c 100644 --- a/src/utils/annoyingdialog.cpp +++ b/src/utils/annoyingdialog.cpp @@ -1,18 +1,19 @@ /* -* This file is part of Code::Blocks Studio, an open-source cross-platform IDE -* Copyright (C) 2003 Yiannis An. Mandravellos -* -* This program is distributed under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 2 of the License, or (at your option) any later version. -* -* Revision: 4204 -* Id: annoyingdialog.cpp 4204 2007-07-02 12:30:47Z mandrav -* HeadURL: http://svn.berlios.de/svnroot/repos/codeblocks/trunk/src/sdk/annoyingdialog.cpp -*/ + * This file is part of Code::Blocks Studio, an open-source cross-platform IDE + * Copyright (C) 2003 Yiannis An. Mandravellos + * + * This program is distributed under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + * + * Revision: 4204 + * Id: annoyingdialog.cpp 4204 2007-07-02 12:30:47Z mandrav + * HeadURL: http://svn.berlios.de/svnroot/repos/codeblocks/trunk/src/sdk/annoyingdialog.cpp + */ #include "annoyingdialog.h" #include + #include #include #include @@ -21,40 +22,41 @@ #include #include + BEGIN_EVENT_TABLE(AnnoyingDialog, wxDialog) - EVT_BUTTON(wxID_ANY, AnnoyingDialog::OnButton) +EVT_BUTTON(wxID_ANY, AnnoyingDialog::OnButton) END_EVENT_TABLE() -AnnoyingDialog::AnnoyingDialog(const wxString& caption, const wxString& message, const wxArtID icon, - dStyle style, int defaultReturn, bool /*separate*/, - const wxString& b1, const wxString& b2, const wxString& b3) - : wxDialog(NULL, wxID_ANY, caption, wxDefaultPosition, wxDefaultSize, wxCAPTION), - m_cb(0), - m_dontAnnoy(false), - m_defRet(defaultReturn) + +AnnoyingDialog::AnnoyingDialog( + const wxString& caption, const wxString& message, const wxArtID icon, dStyle style, int defaultReturn, + bool /*separate*/, const wxString& b1, const wxString& b2, const wxString& b3) : + wxDialog(NULL, wxID_ANY, caption, wxDefaultPosition, wxDefaultSize, wxCAPTION), + m_cb(0), + m_dontAnnoy(false), + m_defRet(defaultReturn) { - wxConfigBase* config = wxConfigBase::Get(); - int defRet; - if ( config->Read( wxT("annoyingdialog/") + caption, &defRet ) ) - { - if ( defRet != wxID_CANCEL ) - { - m_dontAnnoy = true; - m_defRet = defRet; - return; - } + wxConfigBase* config = wxConfigBase::Get(); + int defRet; + if (config->Read(wxT("annoyingdialog/") + caption, &defRet)) { + if (defRet != wxID_CANCEL) { + m_dontAnnoy = true; + m_defRet = defRet; + return; + } } - auto outerSizer = std::make_unique(wxVERTICAL); + auto outerSizer = std::make_unique(wxVERTICAL); - wxFlexGridSizer *mainArea = new wxFlexGridSizer(2, 0, 0); - wxStaticBitmap *bitmap = new wxStaticBitmap(this, wxID_ANY, wxArtProvider::GetBitmap(icon, wxART_MESSAGE_BOX), wxDefaultPosition); + wxFlexGridSizer* mainArea = new wxFlexGridSizer(2, 0, 0); + wxStaticBitmap* bitmap = + new wxStaticBitmap(this, wxID_ANY, wxArtProvider::GetBitmap(icon, wxART_MESSAGE_BOX), wxDefaultPosition); mainArea->Add(bitmap, 0, wxALL, 5); - wxStaticText *txt = new wxStaticText(this, wxID_ANY, message, wxDefaultPosition, wxDefaultSize, 0); - mainArea->Add( txt, 0, wxALIGN_CENTER|wxALL, 5 ); + wxStaticText* txt = new wxStaticText(this, wxID_ANY, message, wxDefaultPosition, wxDefaultSize, 0); + mainArea->Add(txt, 0, wxALIGN_CENTER | wxALL, 5); - mainArea->Add( 1, 1, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT|wxTOP, 5 ); + mainArea->Add(1, 1, 0, wxGROW | wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT | wxTOP, 5); int numButtons = 0; int id1 = wxID_ANY; @@ -64,118 +66,102 @@ AnnoyingDialog::AnnoyingDialog(const wxString& caption, const wxString& message, wxString bTxt2; wxString bTxt3; - if(style == OK || style == ONE_BUTTON) - { + if (style == OK || style == ONE_BUTTON) { numButtons = 1; id1 = (style == OK ? wxID_OK : 1); bTxt1 = b1.IsEmpty() ? wxString(_("&OK")) : b1; - } - else if(style == YES_NO || style == OK_CANCEL || style == TWO_BUTTONS) - { + } else if (style == YES_NO || style == OK_CANCEL || style == TWO_BUTTONS) { numButtons = 2; - id1 = (style == YES_NO ? wxID_YES : (style == OK_CANCEL ? wxID_OK : 1)); - id2 = (style == YES_NO ? wxID_NO : (style == OK_CANCEL ? wxID_CANCEL : 2)); - bTxt1 = b1.IsEmpty() ? (style == YES_NO ? wxString(_("&Yes")) : wxString(_("&OK"))) : b1; - bTxt2 = b2.IsEmpty() ? (style == YES_NO ? wxString(_("&No")) : wxString(_("&Cancel"))) : b2; - } - else if(style == YES_NO_CANCEL || style == THREE_BUTTONS) - { + id1 = (style == YES_NO ? wxID_YES : (style == OK_CANCEL ? wxID_OK : 1)); + id2 = (style == YES_NO ? wxID_NO : (style == OK_CANCEL ? wxID_CANCEL : 2)); + bTxt1 = b1.IsEmpty() ? (style == YES_NO ? wxString(_("&Yes")) : wxString(_("&OK"))) : b1; + bTxt2 = b2.IsEmpty() ? (style == YES_NO ? wxString(_("&No")) : wxString(_("&Cancel"))) : b2; + } else if (style == YES_NO_CANCEL || style == THREE_BUTTONS) { numButtons = 3; - id1 = (style == YES_NO_CANCEL ? wxID_YES : 1); - id2 = (style == YES_NO_CANCEL ? wxID_NO : 2); + id1 = (style == YES_NO_CANCEL ? wxID_YES : 1); + id2 = (style == YES_NO_CANCEL ? wxID_NO : 2); id3 = (style == YES_NO_CANCEL ? wxID_CANCEL : 3); bTxt1 = b1.IsEmpty() ? wxString(_("&Yes")) : b1; bTxt2 = b2.IsEmpty() ? wxString(_("&No")) : b2; bTxt3 = b3.IsEmpty() ? wxString(_("&Cancel")) : b3; + } else { + wxLogError(wxT("Fatal error:\nUndefined style in dialog %s"), caption); + return; } - else + + wxSizer* buttonSizer = 0; + if (style < ONE_BUTTON) // standard buttons? use wxStdDialogButtonSizer { - wxLogError( wxT("Fatal error:\nUndefined style in dialog %s"), caption ); - return; + wxStdDialogButtonSizer* buttonArea = new wxStdDialogButtonSizer(); + + wxButton* but1 = new wxButton(this, id1, bTxt1, wxDefaultPosition, wxDefaultSize, 0); + but1->SetDefault(); + buttonArea->AddButton(but1); + + if (numButtons > 1) { + wxButton* but2 = new wxButton(this, id2, bTxt2, wxDefaultPosition, wxDefaultSize, 0); + but2->SetDefault(); + buttonArea->AddButton(but2); + } + if (numButtons > 2) { + wxButton* but3 = new wxButton(this, id3, bTxt3, wxDefaultPosition, wxDefaultSize, 0); + but3->SetDefault(); + buttonArea->AddButton(but3); + } + buttonArea->Realize(); + buttonSizer = buttonArea; + } else { + // wxStdDialogButtonSizer accepts only standard IDs for its buttons, so we can't use + // it with custom buttons + buttonSizer = new wxBoxSizer(wxHORIZONTAL); + + wxButton* but1 = new wxButton(this, id1, bTxt1, wxDefaultPosition, wxDefaultSize, 0); + but1->SetDefault(); + buttonSizer->Add(but1, 0, wxRIGHT, 5); + + if (numButtons > 1) { + wxButton* but2 = new wxButton(this, id2, bTxt2, wxDefaultPosition, wxDefaultSize, 0); + but2->SetDefault(); + buttonSizer->Add(but2, 0, wxRIGHT, 5); + } + if (numButtons > 2) { + wxButton* but3 = new wxButton(this, id3, bTxt3, wxDefaultPosition, wxDefaultSize, 0); + but3->SetDefault(); + buttonSizer->Add(but3, 0, wxRIGHT, 5); + } } - wxSizer* buttonSizer = 0; - if (style < ONE_BUTTON) // standard buttons? use wxStdDialogButtonSizer - { - wxStdDialogButtonSizer *buttonArea = new wxStdDialogButtonSizer(); - - wxButton *but1 = new wxButton(this, id1, bTxt1, wxDefaultPosition, wxDefaultSize, 0); - but1->SetDefault(); - buttonArea->AddButton(but1); - - if(numButtons > 1) - { - wxButton *but2 = new wxButton(this, id2, bTxt2, wxDefaultPosition, wxDefaultSize, 0); - but2->SetDefault(); - buttonArea->AddButton(but2); - } - if(numButtons > 2) - { - wxButton *but3 = new wxButton(this, id3, bTxt3, wxDefaultPosition, wxDefaultSize, 0); - but3->SetDefault(); - buttonArea->AddButton(but3); - } - buttonArea->Realize(); - buttonSizer = buttonArea; - } - else - { - // wxStdDialogButtonSizer accepts only standard IDs for its buttons, so we can't use - // it with custom buttons - buttonSizer = new wxBoxSizer(wxHORIZONTAL); - - wxButton *but1 = new wxButton(this, id1, bTxt1, wxDefaultPosition, wxDefaultSize, 0); - but1->SetDefault(); - buttonSizer->Add(but1, 0, wxRIGHT, 5); - - if(numButtons > 1) - { - wxButton *but2 = new wxButton(this, id2, bTxt2, wxDefaultPosition, wxDefaultSize, 0); - but2->SetDefault(); - buttonSizer->Add(but2, 0, wxRIGHT, 5); - } - if(numButtons > 2) - { - wxButton *but3 = new wxButton(this, id3, bTxt3, wxDefaultPosition, wxDefaultSize, 0); - but3->SetDefault(); - buttonSizer->Add(but3, 0, wxRIGHT, 5); - } - } - - outerSizer->Add( mainArea, 0, wxALIGN_CENTER|wxALL, 5); - outerSizer->Add( buttonSizer, 0, wxALIGN_CENTER); + outerSizer->Add(mainArea, 0, wxALIGN_CENTER | wxALL, 5); + outerSizer->Add(buttonSizer, 0, wxALIGN_CENTER); m_cb = new wxCheckBox(this, wxID_ANY, _("Don't annoy me again!"), wxDefaultPosition, wxDefaultSize, 0); - outerSizer->Add(m_cb, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxBOTTOM, 5); + outerSizer->Add(m_cb, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxBOTTOM, 5); - SetSizer(outerSizer.release()); - GetSizer()->SetSizeHints(this); + SetSizer(outerSizer.release()); + GetSizer()->SetSizeHints(this); Centre(); } void AnnoyingDialog::OnButton(wxCommandEvent& event) { - if(!m_cb) - { + if (!m_cb) { wxLogError(_T("Ow... null pointer.")); return; } - if ( event.GetId() != wxID_CANCEL ) - { - wxConfigBase* config = wxConfigBase::Get(); - if ( m_cb->IsChecked() ) - { - config->Write( wxT("annoyingdialog/") + GetTitle(), event.GetId() ); - } - } + if (event.GetId() != wxID_CANCEL) { + wxConfigBase* config = wxConfigBase::Get(); + if (m_cb->IsChecked()) { + config->Write(wxT("annoyingdialog/") + GetTitle(), event.GetId()); + } + } EndModal(event.GetId()); } int AnnoyingDialog::ShowModal() { - if(m_dontAnnoy) + if (m_dontAnnoy) return m_defRet; return wxDialog::ShowModal(); } diff --git a/src/utils/annoyingdialog.h b/src/utils/annoyingdialog.h index 55ebbaf8e..f7fcb3160 100644 --- a/src/utils/annoyingdialog.h +++ b/src/utils/annoyingdialog.h @@ -1,22 +1,24 @@ /* -* This file was copied from Code::Blocks Studio, an open-source cross-platform IDE -* Copyright (C) 2003 Yiannis An. Mandravellos -* -* This program is distributed under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 2 of the License, or (at your option) any later version. -* -* Revision: 4204 -* Id: annoyingdialog.cpp 4204 2007-07-02 12:30:47Z mandrav -* HeadURL: http://svn.berlios.de/svnroot/repos/codeblocks/trunk/src/sdk/annoyingdialog.cpp -*/ + * This file was copied from Code::Blocks Studio, an open-source cross-platform IDE + * Copyright (C) 2003 Yiannis An. Mandravellos + * + * This program is distributed under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + * + * Revision: 4204 + * Id: annoyingdialog.cpp 4204 2007-07-02 12:30:47Z mandrav + * HeadURL: http://svn.berlios.de/svnroot/repos/codeblocks/trunk/src/sdk/annoyingdialog.cpp + */ #ifndef UTILS_ANNOYINGDIALOG_H #define UTILS_ANNOYINGDIALOG_H -#include #include +#include + class wxCheckBox; + /** Dialog that contains a "Don't annoy me" checkbox. @@ -25,29 +27,22 @@ The dialog can be then re-enabled in the settings */ class AnnoyingDialog : public wxDialog { - public: - enum dStyle - { - OK, - YES_NO, - YES_NO_CANCEL, - OK_CANCEL, - ONE_BUTTON, - TWO_BUTTONS, - THREE_BUTTONS - }; - - AnnoyingDialog(const wxString& caption, const wxString& message, const wxArtID icon = wxART_INFORMATION, - dStyle style = YES_NO, int defaultReturn = wxID_YES, bool separate = true, - const wxString& b1 = wxEmptyString, const wxString& b2 = wxEmptyString, const wxString& b3 = wxEmptyString); - - int ShowModal() override; - private: - void OnButton( wxCommandEvent& event ); - wxCheckBox* m_cb; - bool m_dontAnnoy; - int m_defRet; - DECLARE_EVENT_TABLE() +public: + enum dStyle { OK, YES_NO, YES_NO_CANCEL, OK_CANCEL, ONE_BUTTON, TWO_BUTTONS, THREE_BUTTONS }; + + AnnoyingDialog( + const wxString& caption, const wxString& message, const wxArtID icon = wxART_INFORMATION, dStyle style = YES_NO, + int defaultReturn = wxID_YES, bool separate = true, const wxString& b1 = wxEmptyString, + const wxString& b2 = wxEmptyString, const wxString& b3 = wxEmptyString); + + int ShowModal() override; + +private: + void OnButton(wxCommandEvent& event); + wxCheckBox* m_cb; + bool m_dontAnnoy; + int m_defRet; + DECLARE_EVENT_TABLE() }; -#endif // UTILS_ANNOYINGDIALOG_H +#endif // UTILS_ANNOYINGDIALOG_H diff --git a/src/utils/debug.h b/src/utils/debug.h index e81a46af1..c35e8822d 100644 --- a/src/utils/debug.h +++ b/src/utils/debug.h @@ -27,29 +27,26 @@ #define UTILS_DEBUG_H #ifdef __WXFB_DEBUG__ -#include -#include - -#define LogDebug(...) \ - { \ - wxString LOG_MSG; \ - LOG_MSG << wxT(__FILE__); \ - LOG_MSG = LOG_MSG.AfterLast('/'); \ - LOG_MSG << wxT("@"); \ - LOG_MSG << __LINE__; \ - LOG_MSG << wxT(" "); \ - LOG_MSG << __FUNCTION__; \ - LOG_MSG << wxT(": "); \ - wxString s; \ - s.Printf(__VA_ARGS__); \ - LOG_MSG << s; \ - wxLogDebug(LOG_MSG); \ - } + #include + #include + #define LogDebug(...) \ + { \ + wxString LOG_MSG; \ + LOG_MSG << wxT(__FILE__); \ + LOG_MSG = LOG_MSG.AfterLast('/'); \ + LOG_MSG << wxT("@"); \ + LOG_MSG << __LINE__; \ + LOG_MSG << wxT(" "); \ + LOG_MSG << __FUNCTION__; \ + LOG_MSG << wxT(": "); \ + wxString s; \ + s.Printf(__VA_ARGS__); \ + LOG_MSG << s; \ + wxLogDebug(LOG_MSG); \ + } #else - -#define LogDebug(...) - + #define LogDebug(...) #endif -#endif // UTILS_DEBUG_H +#endif // UTILS_DEBUG_H diff --git a/src/utils/filetocarray.cpp b/src/utils/filetocarray.cpp index f29241a69..594edc35a 100644 --- a/src/utils/filetocarray.cpp +++ b/src/utils/filetocarray.cpp @@ -1,158 +1,148 @@ #include "filetocarray.h" -#include "rad/appdata.h" -#include "model/objectbase.h" +#include + +#include + #include "codegen/codewriter.h" #include "codegen/cppcg.h" +#include "model/objectbase.h" +#include "rad/appdata.h" #include "utils/typeconv.h" #include "utils/wxfbexception.h" -#include - -#include -#define CASE_BITMAP_TYPE( x ) \ - case x: \ - return wxT(#x); +#define CASE_BITMAP_TYPE(x) \ + case x: \ + return wxT(#x); -wxString GetBitmapTypeName( long type ) +wxString GetBitmapTypeName(long type) { - switch( type ) - { - CASE_BITMAP_TYPE( wxBITMAP_TYPE_BMP ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_ICO ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_CUR ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_XBM ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_XBM_DATA ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_XPM ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_XPM_DATA ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_TIF ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_GIF ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_PNG ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_JPEG ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_PNM ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_PCX ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_PICT ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_ICON ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_ANI ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_IFF ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_TGA ) - CASE_BITMAP_TYPE( wxBITMAP_TYPE_MACCURSOR ) - default: - return wxT("wxBITMAP_TYPE_ANY"); - }; + switch (type) { + CASE_BITMAP_TYPE(wxBITMAP_TYPE_BMP) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_ICO) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_CUR) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_XBM) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_XBM_DATA) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_XPM) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_XPM_DATA) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_TIF) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_GIF) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_PNG) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_JPEG) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_PNM) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_PCX) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_PICT) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_ICON) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_ANI) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_IFF) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_TGA) + CASE_BITMAP_TYPE(wxBITMAP_TYPE_MACCURSOR) + default: + return wxT("wxBITMAP_TYPE_ANY"); + }; } -wxString GetBitmapType( const wxFileName& sourceFileName ) +wxString GetBitmapType(const wxFileName& sourceFileName) { - wxImageHandler* handler = wxImage::FindHandler( sourceFileName.GetExt(), wxBITMAP_TYPE_ANY ); - if ( handler) - { - return GetBitmapTypeName( handler->GetType() ); - } - else - { - return wxT("wxBITMAP_TYPE_ANY"); - } + wxImageHandler* handler = wxImage::FindHandler(sourceFileName.GetExt(), wxBITMAP_TYPE_ANY); + if (handler) { + return GetBitmapTypeName(handler->GetType()); + } else { + return wxT("wxBITMAP_TYPE_ANY"); + } } -wxString FileToCArray::Generate( const wxString& sourcePath ) +wxString FileToCArray::Generate(const wxString& sourcePath) { - wxFileName sourceFileName( sourcePath ); - - const wxString& sourceFullName = sourceFileName.GetFullName(); - const wxString targetFullName = sourceFullName + wxT(".h"); - wxString arrayName = CppCodeGenerator::ConvertEmbeddedBitmapName( sourcePath ); - - if ( !sourceFileName.FileExists() ) - { - wxLogWarning( sourcePath + wxT(" does not exist") ); - return targetFullName; - } - - PObjectBase project = AppData()->GetProjectData(); - - // Get the output path - wxString outputPath; - wxString embeddedFilesOutputPath; - try - { - outputPath = AppData()->GetOutputPath(); - embeddedFilesOutputPath = AppData()->GetEmbeddedFilesOutputPath(); - } - catch ( wxFBException& ex ) - { - wxLogWarning( ex.what() ); - return targetFullName; - } - - // Determine if Microsoft BOM should be used - bool useMicrosoftBOM = false; - PProperty pUseMicrosoftBOM = project->GetProperty( wxT( "use_microsoft_bom" ) ); - if ( pUseMicrosoftBOM ) - { - useMicrosoftBOM = ( pUseMicrosoftBOM->GetValueAsInteger() != 0 ); - } - - // Determine if Utf8 or Ansi is to be created - bool useUtf8 = false; - PProperty pUseUtf8 = project->GetProperty( _("encoding") ); - - if ( pUseUtf8 ) - { - useUtf8 = ( pUseUtf8->GetValueAsString() != wxT("ANSI") ); - } - - // setup output file - PCodeWriter arrayCodeWriter( new FileCodeWriter( embeddedFilesOutputPath + targetFullName, useMicrosoftBOM, useUtf8 ) ); - - const wxString headerGuardName = arrayName.Upper() + wxT("_H"); - arrayCodeWriter->WriteLn( wxT("#ifndef ") + headerGuardName ); - arrayCodeWriter->WriteLn( wxT("#define ") + headerGuardName ); - arrayCodeWriter->WriteLn(); - - arrayCodeWriter->WriteLn( wxT("#include ") ); - arrayCodeWriter->WriteLn( wxT("#include ") ); - arrayCodeWriter->WriteLn( wxT("#include ") ); - arrayCodeWriter->WriteLn(); - - arrayCodeWriter->WriteLn( wxT("static const unsigned char ") + arrayName + wxT("[] = ") ); - arrayCodeWriter->WriteLn( wxT("{") ); - arrayCodeWriter->Indent(); - - unsigned int count = 1; - const unsigned int bytesPerLine = 10; - std::ifstream binFile( static_cast< const char* >( sourcePath.mb_str( wxConvFile ) ), std::ios::binary ); - for ( std::istreambuf_iterator< char > byte( binFile ), end; byte != end; ++byte, ++count ) - { - arrayCodeWriter->Write( wxString::Format( wxT("0x%02X, "), static_cast< unsigned int >( static_cast< unsigned char >( *byte ) ) ) ); - if ( count >= bytesPerLine ) - { - arrayCodeWriter->WriteLn(); - count = 0; - } - } - if ( (count < bytesPerLine) && (count != 1) ) - { - arrayCodeWriter->WriteLn(); - } - arrayCodeWriter->Unindent(); - arrayCodeWriter->WriteLn( wxT("};") ); - arrayCodeWriter->WriteLn(); - - arrayCodeWriter->WriteLn( wxT("wxBitmap& ") + arrayName + wxT("_to_wx_bitmap()") ); - arrayCodeWriter->WriteLn( wxT("{") ); - arrayCodeWriter->Indent(); - arrayCodeWriter->WriteLn( wxT("static wxMemoryInputStream memIStream( ") + arrayName + wxT(", sizeof( ") + arrayName + wxT(" ) );") ); - arrayCodeWriter->WriteLn( wxT("static wxImage image( memIStream, ") + GetBitmapType( sourceFileName ) + wxT(" );") ); - arrayCodeWriter->WriteLn( wxT("static wxBitmap bmp( image );") ); - arrayCodeWriter->WriteLn( wxT("return bmp;") ); - arrayCodeWriter->Unindent(); - arrayCodeWriter->WriteLn( wxT("}") ); - arrayCodeWriter->WriteLn(); - - arrayCodeWriter->WriteLn(); - arrayCodeWriter->WriteLn( wxT("#endif //") + headerGuardName ); - - return TypeConv::MakeRelativePath( embeddedFilesOutputPath + targetFullName, outputPath ); + wxFileName sourceFileName(sourcePath); + + const wxString& sourceFullName = sourceFileName.GetFullName(); + const wxString targetFullName = sourceFullName + wxT(".h"); + wxString arrayName = CppCodeGenerator::ConvertEmbeddedBitmapName(sourcePath); + + if (!sourceFileName.FileExists()) { + wxLogWarning(sourcePath + wxT(" does not exist")); + return targetFullName; + } + + PObjectBase project = AppData()->GetProjectData(); + + // Get the output path + wxString outputPath; + wxString embeddedFilesOutputPath; + try { + outputPath = AppData()->GetOutputPath(); + embeddedFilesOutputPath = AppData()->GetEmbeddedFilesOutputPath(); + } catch (wxFBException& ex) { + wxLogWarning(ex.what()); + return targetFullName; + } + + // Determine if Microsoft BOM should be used + bool useMicrosoftBOM = false; + PProperty pUseMicrosoftBOM = project->GetProperty(wxT("use_microsoft_bom")); + if (pUseMicrosoftBOM) { + useMicrosoftBOM = (pUseMicrosoftBOM->GetValueAsInteger() != 0); + } + + // Determine if Utf8 or Ansi is to be created + bool useUtf8 = false; + PProperty pUseUtf8 = project->GetProperty(_("encoding")); + + if (pUseUtf8) { + useUtf8 = (pUseUtf8->GetValueAsString() != wxT("ANSI")); + } + + // setup output file + PCodeWriter arrayCodeWriter(new FileCodeWriter(embeddedFilesOutputPath + targetFullName, useMicrosoftBOM, useUtf8)); + + const wxString headerGuardName = arrayName.Upper() + wxT("_H"); + arrayCodeWriter->WriteLn(wxT("#ifndef ") + headerGuardName); + arrayCodeWriter->WriteLn(wxT("#define ") + headerGuardName); + arrayCodeWriter->WriteLn(); + + arrayCodeWriter->WriteLn(wxT("#include ")); + arrayCodeWriter->WriteLn(wxT("#include ")); + arrayCodeWriter->WriteLn(wxT("#include ")); + arrayCodeWriter->WriteLn(); + + arrayCodeWriter->WriteLn(wxT("static const unsigned char ") + arrayName + wxT("[] = ")); + arrayCodeWriter->WriteLn(wxT("{")); + arrayCodeWriter->Indent(); + + unsigned int count = 1; + const unsigned int bytesPerLine = 10; + std::ifstream binFile(static_cast(sourcePath.mb_str(wxConvFile)), std::ios::binary); + for (std::istreambuf_iterator byte(binFile), end; byte != end; ++byte, ++count) { + arrayCodeWriter->Write( + wxString::Format(wxT("0x%02X, "), static_cast(static_cast(*byte)))); + if (count >= bytesPerLine) { + arrayCodeWriter->WriteLn(); + count = 0; + } + } + if ((count < bytesPerLine) && (count != 1)) { + arrayCodeWriter->WriteLn(); + } + arrayCodeWriter->Unindent(); + arrayCodeWriter->WriteLn(wxT("};")); + arrayCodeWriter->WriteLn(); + + arrayCodeWriter->WriteLn(wxT("wxBitmap& ") + arrayName + wxT("_to_wx_bitmap()")); + arrayCodeWriter->WriteLn(wxT("{")); + arrayCodeWriter->Indent(); + arrayCodeWriter->WriteLn( + wxT("static wxMemoryInputStream memIStream( ") + arrayName + wxT(", sizeof( ") + arrayName + wxT(" ) );")); + arrayCodeWriter->WriteLn(wxT("static wxImage image( memIStream, ") + GetBitmapType(sourceFileName) + wxT(" );")); + arrayCodeWriter->WriteLn(wxT("static wxBitmap bmp( image );")); + arrayCodeWriter->WriteLn(wxT("return bmp;")); + arrayCodeWriter->Unindent(); + arrayCodeWriter->WriteLn(wxT("}")); + arrayCodeWriter->WriteLn(); + + arrayCodeWriter->WriteLn(); + arrayCodeWriter->WriteLn(wxT("#endif //") + headerGuardName); + + return TypeConv::MakeRelativePath(embeddedFilesOutputPath + targetFullName, outputPath); } diff --git a/src/utils/filetocarray.h b/src/utils/filetocarray.h index 895b84581..fff319dac 100644 --- a/src/utils/filetocarray.h +++ b/src/utils/filetocarray.h @@ -3,10 +3,11 @@ #include + class FileToCArray { public: - static wxString Generate( const wxString& sourcepath ); + static wxString Generate(const wxString& sourcepath); }; -#endif // UTILS_FILETOCARRAY_H +#endif // UTILS_FILETOCARRAY_H diff --git a/src/utils/m_wxfb.cpp b/src/utils/m_wxfb.cpp index d70b84786..fd565c351 100644 --- a/src/utils/m_wxfb.cpp +++ b/src/utils/m_wxfb.cpp @@ -12,11 +12,11 @@ TAG_HANDLER_BEGIN(wxFBVersion, "WXFB-VERSION") TAG_HANDLER_PROC(WXUNUSED(tag)) { - auto* cell = new wxHtmlWordCell(getVersion(), *m_WParser->GetDC()); - m_WParser->ApplyStateToCell(cell); - m_WParser->GetContainer()->InsertCell(cell); + auto* cell = new wxHtmlWordCell(getVersion(), *m_WParser->GetDC()); + m_WParser->ApplyStateToCell(cell); + m_WParser->GetContainer()->InsertCell(cell); - return false; + return false; } TAG_HANDLER_END(wxFBVersion) @@ -26,11 +26,11 @@ TAG_HANDLER_BEGIN(wxFBRevision, "WXFB-REVISION") TAG_HANDLER_PROC(WXUNUSED(tag)) { - auto* cell = new wxHtmlWordCell(getPostfixRevision(getVersion()), *m_WParser->GetDC()); - m_WParser->ApplyStateToCell(cell); - m_WParser->GetContainer()->InsertCell(cell); + auto* cell = new wxHtmlWordCell(getPostfixRevision(getVersion()), *m_WParser->GetDC()); + m_WParser->ApplyStateToCell(cell); + m_WParser->GetContainer()->InsertCell(cell); - return false; + return false; } TAG_HANDLER_END(wxFBRevision) diff --git a/src/utils/stringutils.cpp b/src/utils/stringutils.cpp index 12abd9dc4..0f4cd52b7 100644 --- a/src/utils/stringutils.cpp +++ b/src/utils/stringutils.cpp @@ -25,382 +25,354 @@ #include "stringutils.h" -#include "utils/typeconv.h" -#include "utils/wxfbexception.h" - #include #include #include -wxString StringUtils::IntToStr(const int num) { - wxString result; - result.Printf(wxT("%d"), num); - return result; +#include "utils/typeconv.h" +#include "utils/wxfbexception.h" + + +wxString StringUtils::IntToStr(const int num) +{ + wxString result; + result.Printf(wxT("%d"), num); + return result; } -wxString StringUtils::GetSupportedEncodings( bool columnateWithTab, wxArrayString* array ) +wxString StringUtils::GetSupportedEncodings(bool columnateWithTab, wxArrayString* array) { - wxString result = wxEmptyString; - size_t count = wxFontMapper::GetSupportedEncodingsCount(); - size_t max = 40; - for ( size_t i = 0; i < count; ++i ) - { - wxFontEncoding encoding = wxFontMapper::GetEncoding( i ); - wxString name = wxFontMapper::GetEncodingName( encoding ); - size_t length = name.length(); - if ( length > max ) - { - max = length + 10; - } - if ( columnateWithTab ) - { - name = name.Pad( (size_t)((max - length)/8 + 1), wxT('\t') ); - } - else - { - name = name.Pad( max - length ); - } - name += wxFontMapper::GetEncodingDescription( encoding ); - if ( NULL != array ) - { - array->Add( name ); - } - result += name; - result += wxT("\n"); - } - - return result; + wxString result = wxEmptyString; + size_t count = wxFontMapper::GetSupportedEncodingsCount(); + size_t max = 40; + for (size_t i = 0; i < count; ++i) { + wxFontEncoding encoding = wxFontMapper::GetEncoding(i); + wxString name = wxFontMapper::GetEncodingName(encoding); + size_t length = name.length(); + if (length > max) { + max = length + 10; + } + if (columnateWithTab) { + name = name.Pad((size_t)((max - length) / 8 + 1), wxT('\t')); + } else { + name = name.Pad(max - length); + } + name += wxFontMapper::GetEncodingDescription(encoding); + if (NULL != array) { + array->Add(name); + } + result += name; + result += wxT("\n"); + } + + return result; } -wxFontEncoding StringUtils::GetEncodingFromUser( const wxString& message ) +wxFontEncoding StringUtils::GetEncodingFromUser(const wxString& message) { - wxArrayString array; - GetSupportedEncodings( false, &array ); - int selection = ::wxGetSingleChoiceIndex( message, _("Choose an Encoding"), array, wxTheApp->GetTopWindow() ); - if ( -1 == selection ) - { - return wxFONTENCODING_MAX; - } - return wxFontMapper::GetEncoding( selection ); + wxArrayString array; + GetSupportedEncodings(false, &array); + int selection = ::wxGetSingleChoiceIndex(message, _("Choose an Encoding"), array, wxTheApp->GetTopWindow()); + if (-1 == selection) { + return wxFONTENCODING_MAX; + } + return wxFontMapper::GetEncoding(selection); } namespace XMLUtils { - template < class T, class U > - void LoadXMLFileImp( T& doc, bool condenseWhiteSpace, const wxString& path, U* declaration ) - { - if ( NULL == declaration ) - { - // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration - wxString msg = _("This xml file has no declaration.\n"); - msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); - msg += _("You will be prompted for an encoding.\n\n"); - msg += _("Path: "); - msg += path; - int result = wxMessageBox( msg, _("Missing Declaration"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ); - if ( wxNO == result ) - { - // User declined, give up - THROW_WXFBEX( _("Missing Declaration on XML File: ") << path ); - } - - // User accepted, convert the file - wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser( _("Please choose the original encoding.") ); - if ( wxFONTENCODING_MAX == chosenEncoding ) - { - THROW_WXFBEX( _("Missing Declaration on XML File: ") << path ); - } - - ConvertAndAddDeclaration( path, chosenEncoding ); - - // Reload - LoadXMLFile( doc, condenseWhiteSpace, path ); - return; - } - - // The file will have a declaration at this point - wxString version = _WXSTR( declaration->Version() ); - if ( version.empty() ) - { - version = wxT("1.0"); - } - - wxString standalone = _WXSTR( declaration->Standalone() ); - if ( standalone.empty() ) - { - standalone = wxT("yes"); - } - - wxString encodingName = _WXSTR( declaration->Encoding() ); - if ( encodingName.empty() ) - { - // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration - wxString msg = _("This xml file has no encoding specified.\n"); - msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); - msg += _("You will be prompted for an encoding.\n\n"); - msg += _("Path: "); - msg += path; - if ( wxNO == wxMessageBox( msg, _("Unknown Encoding"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) ) - { - // User declined, give up - THROW_WXFBEX( _("Unknown Encoding for XML File: ") << path ); - } - - // User accepted, convert the file - wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser( _("Please choose the original encoding.") ); - if ( wxFONTENCODING_MAX == chosenEncoding ) - { - THROW_WXFBEX( _("Unknown Encoding for XML File: ") << path ); - } - ConvertAndChangeDeclaration( path, version, standalone, chosenEncoding ); - - // Reload - LoadXMLFile( doc, condenseWhiteSpace, path ); - return; - } - - // The file will have an encoding at this point - wxFontEncoding encoding = wxFontMapperBase::GetEncodingFromName( encodingName.MakeLower() ); - if ( wxFONTENCODING_UTF8 == encoding ) - { - // This is what we want - return; - } - else if ( wxFONTENCODING_MAX == encoding ) - { - wxString msg = wxString::Format( _("The encoding of this xml file is not supported.\n\nFile: %s\nEncoding: %s\nSupported Encodings:\n\n%s"), - path, - encodingName, - StringUtils::GetSupportedEncodings() ); - wxMessageBox( msg, wxString::Format( _("Unsupported Encoding: %s"), encodingName ) ); - THROW_WXFBEX( _("Unsupported encoding for XML File: ") << path ); - } - else - { - // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration - wxString msg = wxString::Format( _("This xml file has specified encoding %s. wxFormBuilder only works with UTF-8.\n"), - wxFontMapper::GetEncodingDescription( encoding ) ); - msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n\n"); - msg += _("Path: "); - msg += path; - if ( wxNO == wxMessageBox( msg, _("Not UTF-8"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) ) - { - // User declined, give up - THROW_WXFBEX( _("Wrong Encoding for XML File: ") << path ); - } - - // User accepted, convert the file - ConvertAndChangeDeclaration( path, version, standalone, encoding ); - - // Reload - LoadXMLFile( doc, condenseWhiteSpace, path ); - return; - } - } +template +void LoadXMLFileImp(T& doc, bool condenseWhiteSpace, const wxString& path, U* declaration) +{ + if (NULL == declaration) { + // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration + wxString msg = _("This xml file has no declaration.\n"); + msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); + msg += _("You will be prompted for an encoding.\n\n"); + msg += _("Path: "); + msg += path; + int result = wxMessageBox( + msg, _("Missing Declaration"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow()); + if (wxNO == result) { + // User declined, give up + THROW_WXFBEX(_("Missing Declaration on XML File: ") << path); + } + + // User accepted, convert the file + wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser(_("Please choose the original encoding.")); + if (wxFONTENCODING_MAX == chosenEncoding) { + THROW_WXFBEX(_("Missing Declaration on XML File: ") << path); + } + + ConvertAndAddDeclaration(path, chosenEncoding); + + // Reload + LoadXMLFile(doc, condenseWhiteSpace, path); + return; + } + + // The file will have a declaration at this point + wxString version = _WXSTR(declaration->Version()); + if (version.empty()) { + version = wxT("1.0"); + } + + wxString standalone = _WXSTR(declaration->Standalone()); + if (standalone.empty()) { + standalone = wxT("yes"); + } + + wxString encodingName = _WXSTR(declaration->Encoding()); + if (encodingName.empty()) { + // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration + wxString msg = _("This xml file has no encoding specified.\n"); + msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); + msg += _("You will be prompted for an encoding.\n\n"); + msg += _("Path: "); + msg += path; + if ( + wxNO == wxMessageBox( + msg, _("Unknown Encoding"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow())) { + // User declined, give up + THROW_WXFBEX(_("Unknown Encoding for XML File: ") << path); + } + + // User accepted, convert the file + wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser(_("Please choose the original encoding.")); + if (wxFONTENCODING_MAX == chosenEncoding) { + THROW_WXFBEX(_("Unknown Encoding for XML File: ") << path); + } + ConvertAndChangeDeclaration(path, version, standalone, chosenEncoding); + + // Reload + LoadXMLFile(doc, condenseWhiteSpace, path); + return; + } + + // The file will have an encoding at this point + wxFontEncoding encoding = wxFontMapperBase::GetEncodingFromName(encodingName.MakeLower()); + if (wxFONTENCODING_UTF8 == encoding) { + // This is what we want + return; + } else if (wxFONTENCODING_MAX == encoding) { + wxString msg = wxString::Format( + _("The encoding of this xml file is not supported.\n\nFile: %s\nEncoding: %s\nSupported Encodings:\n\n%s"), + path, encodingName, StringUtils::GetSupportedEncodings()); + wxMessageBox(msg, wxString::Format(_("Unsupported Encoding: %s"), encodingName)); + THROW_WXFBEX(_("Unsupported encoding for XML File: ") << path); + } else { + // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration + wxString msg = wxString::Format( + _("This xml file has specified encoding %s. wxFormBuilder only works with UTF-8.\n"), + wxFontMapper::GetEncodingDescription(encoding)); + msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n\n"); + msg += _("Path: "); + msg += path; + if ( + wxNO == + wxMessageBox(msg, _("Not UTF-8"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow())) { + // User declined, give up + THROW_WXFBEX(_("Wrong Encoding for XML File: ") << path); + } + + // User accepted, convert the file + ConvertAndChangeDeclaration(path, version, standalone, encoding); + + // Reload + LoadXMLFile(doc, condenseWhiteSpace, path); + return; + } } +} // namespace XMLUtils -void XMLUtils::LoadXMLFile( ticpp::Document& doc, bool condenseWhiteSpace, const wxString& path ) +void XMLUtils::LoadXMLFile(ticpp::Document& doc, bool condenseWhiteSpace, const wxString& path) { - try - { - if ( path.empty() ) - { - THROW_WXFBEX( _("LoadXMLFile needs a path") ) - } - - if ( !::wxFileExists( path ) ) - { - THROW_WXFBEX( _("The file does not exist.\nFile: ") << path ) - } - TiXmlBase::SetCondenseWhiteSpace( condenseWhiteSpace ); - doc.SetValue( std::string( path.mb_str( wxConvFile ) ) ); - doc.LoadFile(); - } - catch ( ticpp::Exception& ) - { - // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration - wxString msg = _("This xml file could not be loaded. This could be the result of an unsupported encoding.\n"); - msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); - msg += _("You will be prompted for the original encoding.\n\n"); - msg += _("Path: "); - msg += path; - if ( wxNO == wxMessageBox( msg, _("Unable to load file"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) ) - { - // User declined, give up - THROW_WXFBEX( _("Unable to load file: ") << path ); - } - - // User accepted, convert the file - wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser( _("Please choose the original encoding.") ); - if ( wxFONTENCODING_MAX == chosenEncoding ) - { - THROW_WXFBEX( _("Unable to load file: ") << path ); - } - - ConvertAndAddDeclaration( path, chosenEncoding ); - - LoadXMLFile( doc, condenseWhiteSpace, path ); - } - - ticpp::Declaration* declaration; - try - { - ticpp::Node* firstChild = doc.FirstChild(); - declaration = firstChild->ToDeclaration(); - } - catch( ticpp::Exception& ) - { - declaration = NULL; - } - - LoadXMLFileImp( doc, condenseWhiteSpace, path, declaration ); + try { + if (path.empty()) { + THROW_WXFBEX(_("LoadXMLFile needs a path")) + } + + if (!::wxFileExists(path)) { + THROW_WXFBEX(_("The file does not exist.\nFile: ") << path) + } + TiXmlBase::SetCondenseWhiteSpace(condenseWhiteSpace); + doc.SetValue(std::string(path.mb_str(wxConvFile))); + doc.LoadFile(); + } catch (ticpp::Exception&) { + // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration + wxString msg = _("This xml file could not be loaded. This could be the result of an unsupported encoding.\n"); + msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); + msg += _("You will be prompted for the original encoding.\n\n"); + msg += _("Path: "); + msg += path; + if ( + wxNO == + wxMessageBox( + msg, _("Unable to load file"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow())) { + // User declined, give up + THROW_WXFBEX(_("Unable to load file: ") << path); + } + + // User accepted, convert the file + wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser(_("Please choose the original encoding.")); + if (wxFONTENCODING_MAX == chosenEncoding) { + THROW_WXFBEX(_("Unable to load file: ") << path); + } + + ConvertAndAddDeclaration(path, chosenEncoding); + + LoadXMLFile(doc, condenseWhiteSpace, path); + } + + ticpp::Declaration* declaration; + try { + ticpp::Node* firstChild = doc.FirstChild(); + declaration = firstChild->ToDeclaration(); + } catch (ticpp::Exception&) { + declaration = NULL; + } + + LoadXMLFileImp(doc, condenseWhiteSpace, path, declaration); } -void XMLUtils::LoadXMLFile( TiXmlDocument& doc, bool condenseWhiteSpace, const wxString& path ) +void XMLUtils::LoadXMLFile(TiXmlDocument& doc, bool condenseWhiteSpace, const wxString& path) { - if ( path.empty() ) - { - THROW_WXFBEX( _("LoadXMLFile needs a path") ) - } - - if ( !::wxFileExists( path ) ) - { - THROW_WXFBEX( _("The file does not exist.\nFile: ") << path ) - } - - TiXmlBase::SetCondenseWhiteSpace( condenseWhiteSpace ); - doc.SetValue( std::string( path.mb_str( wxConvFile ) ) ); - if ( !doc.LoadFile() ) - { - // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration - wxString msg = _("This xml file could not be loaded. This could be the result of an unsupported encoding.\n"); - msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); - msg += _("You will be prompted for the original encoding.\n\n"); - msg += _("Path: "); - msg += path; - if ( wxNO == wxMessageBox( msg, _("Unable to load file"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow() ) ) - { - // User declined, give up - THROW_WXFBEX( _("Unable to load file: ") << path ); - } - - // User accepted, convert the file - wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser( _("Please choose the original encoding.") ); - if ( wxFONTENCODING_MAX == chosenEncoding ) - { - THROW_WXFBEX( _("Unable to load file: ") << path ); - } - - ConvertAndAddDeclaration( path, chosenEncoding ); - - LoadXMLFile( doc, condenseWhiteSpace, path ); - } - - TiXmlDeclaration* declaration = NULL; - TiXmlNode* firstChild = doc.FirstChild(); - if ( firstChild ) - { - declaration = firstChild->ToDeclaration(); - } - - LoadXMLFileImp( doc, condenseWhiteSpace, path, declaration ); + if (path.empty()) { + THROW_WXFBEX(_("LoadXMLFile needs a path")) + } + + if (!::wxFileExists(path)) { + THROW_WXFBEX(_("The file does not exist.\nFile: ") << path) + } + + TiXmlBase::SetCondenseWhiteSpace(condenseWhiteSpace); + doc.SetValue(std::string(path.mb_str(wxConvFile))); + if (!doc.LoadFile()) { + // Ask user to all wxFB to convert the file to UTF-8 and add the XML declaration + wxString msg = _("This xml file could not be loaded. This could be the result of an unsupported encoding.\n"); + msg += _("Would you like wxFormBuilder to backup the file and convert it to UTF-8\?\n"); + msg += _("You will be prompted for the original encoding.\n\n"); + msg += _("Path: "); + msg += path; + if ( + wxNO == + wxMessageBox( + msg, _("Unable to load file"), wxICON_QUESTION | wxYES_NO | wxYES_DEFAULT, wxTheApp->GetTopWindow())) { + // User declined, give up + THROW_WXFBEX(_("Unable to load file: ") << path); + } + + // User accepted, convert the file + wxFontEncoding chosenEncoding = StringUtils::GetEncodingFromUser(_("Please choose the original encoding.")); + if (wxFONTENCODING_MAX == chosenEncoding) { + THROW_WXFBEX(_("Unable to load file: ") << path); + } + + ConvertAndAddDeclaration(path, chosenEncoding); + + LoadXMLFile(doc, condenseWhiteSpace, path); + } + + TiXmlDeclaration* declaration = NULL; + TiXmlNode* firstChild = doc.FirstChild(); + if (firstChild) { + declaration = firstChild->ToDeclaration(); + } + + LoadXMLFileImp(doc, condenseWhiteSpace, path, declaration); } -void XMLUtils::ConvertAndAddDeclaration( const wxString& path, wxFontEncoding encoding, bool backup ) +void XMLUtils::ConvertAndAddDeclaration(const wxString& path, wxFontEncoding encoding, bool backup) { - ConvertAndChangeDeclaration( path, wxT("1.0"), wxT("yes"), encoding, backup ); + ConvertAndChangeDeclaration(path, wxT("1.0"), wxT("yes"), encoding, backup); } -void XMLUtils::ConvertAndChangeDeclaration( const wxString& path, const wxString& version, const wxString& standalone, wxFontEncoding encoding, bool backup ) +void XMLUtils::ConvertAndChangeDeclaration( + const wxString& path, const wxString& version, const wxString& standalone, wxFontEncoding encoding, bool backup) { - // Backup the file - if ( backup ) - { - if ( !::wxCopyFile( path, path + wxT(".bak") ) ) - { - wxString msg = wxString::Format( _("Unable to backup file.\nFile: %s\nBackup: %s.bak"), path, path ); - THROW_WXFBEX( msg ) - } - } - - // Read the entire contents into a string - wxFFile oldEncoding( path, wxT("r") ); - wxString contents; - wxCSConv encodingConv( encoding ); - if ( !oldEncoding.ReadAll( &contents, encodingConv ) ) - { - wxString msg = wxString::Format( _("Unable to read the file in the specified encoding.\nFile: %s\nEncoding: %s"), path, wxFontMapper::GetEncodingDescription( encoding ) ); - THROW_WXFBEX( msg ); - } - - if ( contents.empty() ) - { - wxString msg = wxString::Format( _("The file is either empty or read with the wrong encoding.\nFile: %s\nEncoding: %s"), path, wxFontMapper::GetEncodingDescription( encoding ) ); - THROW_WXFBEX( msg ); - } - - if ( !oldEncoding.Close() ) - { - wxString msg = wxString::Format( _("Unable to close original file.\nFile: %s"), path ); - THROW_WXFBEX( msg ); - } - - // Modify the declaration, so TinyXML correctly determines the new encoding - int declStart = contents.Find( wxT("<\?") ); - int declEnd = contents.Find( wxT("\?>") ); - if ( wxNOT_FOUND == declStart && wxNOT_FOUND == declEnd ) - { - int firstElement = contents.Find( wxT("<") ); - if ( wxNOT_FOUND == firstElement ) - { - firstElement = 0; - } - contents.insert( firstElement, wxString::Format( wxT("<\?xml version=\"%s\" encoding=\"UTF-8\" standalone=\"%s\" \?>\n"), version, standalone ) ); - } - else - { - if ( wxNOT_FOUND == declStart ) - { - wxString msg = wxString::Format( _("Found a declaration end tag \"\?>\" but could not find the start \"<\?\".\nFile: %s"), path ); - THROW_WXFBEX( msg ); - } - - if ( wxNOT_FOUND == declEnd ) - { - wxString msg = wxString::Format( _("Found a declaration start tag \"<\?\" but could not find the end \"\?>\".\nFile: %s"), path ); - THROW_WXFBEX( msg ); - } - - // declStart and declEnd are both valid, replace that section with a new declaration - contents.replace( - declStart, declEnd - declStart + 2, - wxString::Format(wxT("<\?xml version=\"%s\" encoding=\"UTF-8\" standalone=\"%s\" \?>"), - version, standalone)); - } - - // Remove the old file - if ( !::wxRemoveFile( path ) ) - { - wxString msg = wxString::Format( _("Unable to delete original file.\nFile: %s"), path ); - THROW_WXFBEX( msg ); - } - - // Write the new file - wxFFile newEncoding( path, wxT("w") ); - if ( !newEncoding.Write( contents, wxConvUTF8 ) ) - { - wxString msg = wxString::Format( _("Unable to write file in its new encoding.\nFile: %s\nEncoding: %s"), path, wxFontMapper::GetEncodingDescription( wxFONTENCODING_UTF8 ) ); - THROW_WXFBEX( msg ); - } - - if ( !newEncoding.Close() ) - { - wxString msg = wxString::Format( _("Unable to close file after converting the encoding.\nFile: %s\nOld Encoding: %s\nNew Encoding: %s"), - path, - wxFontMapper::GetEncodingDescription( encoding ), - wxFontMapper::GetEncodingDescription( wxFONTENCODING_UTF8 ) ); - THROW_WXFBEX( msg ); - } + // Backup the file + if (backup) { + if (!::wxCopyFile(path, path + wxT(".bak"))) { + wxString msg = wxString::Format(_("Unable to backup file.\nFile: %s\nBackup: %s.bak"), path, path); + THROW_WXFBEX(msg) + } + } + + // Read the entire contents into a string + wxFFile oldEncoding(path, wxT("r")); + wxString contents; + wxCSConv encodingConv(encoding); + if (!oldEncoding.ReadAll(&contents, encodingConv)) { + wxString msg = wxString::Format( + _("Unable to read the file in the specified encoding.\nFile: %s\nEncoding: %s"), path, + wxFontMapper::GetEncodingDescription(encoding)); + THROW_WXFBEX(msg); + } + + if (contents.empty()) { + wxString msg = wxString::Format( + _("The file is either empty or read with the wrong encoding.\nFile: %s\nEncoding: %s"), path, + wxFontMapper::GetEncodingDescription(encoding)); + THROW_WXFBEX(msg); + } + + if (!oldEncoding.Close()) { + wxString msg = wxString::Format(_("Unable to close original file.\nFile: %s"), path); + THROW_WXFBEX(msg); + } + + // Modify the declaration, so TinyXML correctly determines the new encoding + int declStart = contents.Find(wxT("<\?")); + int declEnd = contents.Find(wxT("\?>")); + if (wxNOT_FOUND == declStart && wxNOT_FOUND == declEnd) { + int firstElement = contents.Find(wxT("<")); + if (wxNOT_FOUND == firstElement) { + firstElement = 0; + } + contents.insert( + firstElement, + wxString::Format( + wxT("<\?xml version=\"%s\" encoding=\"UTF-8\" standalone=\"%s\" \?>\n"), version, standalone)); + } else { + if (wxNOT_FOUND == declStart) { + wxString msg = wxString::Format( + _("Found a declaration end tag \"\?>\" but could not find the start \"<\?\".\nFile: %s"), path); + THROW_WXFBEX(msg); + } + + if (wxNOT_FOUND == declEnd) { + wxString msg = wxString::Format( + _("Found a declaration start tag \"<\?\" but could not find the end \"\?>\".\nFile: %s"), path); + THROW_WXFBEX(msg); + } + + // declStart and declEnd are both valid, replace that section with a new declaration + contents.replace( + declStart, declEnd - declStart + 2, + wxString::Format(wxT("<\?xml version=\"%s\" encoding=\"UTF-8\" standalone=\"%s\" \?>"), version, standalone)); + } + + // Remove the old file + if (!::wxRemoveFile(path)) { + wxString msg = wxString::Format(_("Unable to delete original file.\nFile: %s"), path); + THROW_WXFBEX(msg); + } + + // Write the new file + wxFFile newEncoding(path, wxT("w")); + if (!newEncoding.Write(contents, wxConvUTF8)) { + wxString msg = wxString::Format( + _("Unable to write file in its new encoding.\nFile: %s\nEncoding: %s"), path, + wxFontMapper::GetEncodingDescription(wxFONTENCODING_UTF8)); + THROW_WXFBEX(msg); + } + + if (!newEncoding.Close()) { + wxString msg = wxString::Format( + _("Unable to close file after converting the encoding.\nFile: %s\nOld Encoding: %s\nNew Encoding: %s"), path, + wxFontMapper::GetEncodingDescription(encoding), wxFontMapper::GetEncodingDescription(wxFONTENCODING_UTF8)); + THROW_WXFBEX(msg); + } } diff --git a/src/utils/stringutils.h b/src/utils/stringutils.h index 6002386eb..906ce965c 100644 --- a/src/utils/stringutils.h +++ b/src/utils/stringutils.h @@ -22,37 +22,43 @@ // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef UTILS_STRINGUTILS_H #define UTILS_STRINGUTILS_H #include -namespace ticpp { +namespace ticpp +{ class Document; } class TiXmlDocument; class wxArrayString; + namespace StringUtils { - wxString IntToStr(int num); +wxString IntToStr(int num); - wxString GetSupportedEncodings( bool columnateWithTab = true, wxArrayString* array = NULL ); - wxFontEncoding GetEncodingFromUser( const wxString& message ); -} +wxString GetSupportedEncodings(bool columnateWithTab = true, wxArrayString* array = NULL); +wxFontEncoding GetEncodingFromUser(const wxString& message); +} // namespace StringUtils namespace XMLUtils { - // These are only vaguely string related, perhaps they deserve their own files. - // These load xml files and verify the encoding is correct, optionally converting - // the files using wxWidgets. - void LoadXMLFile( ticpp::Document& doc, bool condenseWhiteSpace, const wxString& path = wxEmptyString ); - void LoadXMLFile( TiXmlDocument& doc, bool condenseWhiteSpace, const wxString& path = wxEmptyString ); - - // Converts to UTF-8 and prepends declaration - void ConvertAndAddDeclaration( const wxString& path, wxFontEncoding encoding = wxFONTENCODING_SYSTEM, bool backup = true ); - void ConvertAndChangeDeclaration( const wxString& path, const wxString& version, const wxString& standalone, wxFontEncoding encoding = wxFONTENCODING_SYSTEM, bool backup = true ); -} +// These are only vaguely string related, perhaps they deserve their own files. +// These load xml files and verify the encoding is correct, optionally converting +// the files using wxWidgets. +void LoadXMLFile(ticpp::Document& doc, bool condenseWhiteSpace, const wxString& path = wxEmptyString); +void LoadXMLFile(TiXmlDocument& doc, bool condenseWhiteSpace, const wxString& path = wxEmptyString); + +// Converts to UTF-8 and prepends declaration +void ConvertAndAddDeclaration( + const wxString& path, wxFontEncoding encoding = wxFONTENCODING_SYSTEM, bool backup = true); +void ConvertAndChangeDeclaration( + const wxString& path, const wxString& version, const wxString& standalone, + wxFontEncoding encoding = wxFONTENCODING_SYSTEM, bool backup = true); +} // namespace XMLUtils -#endif // UTILS_STRINGUTILS_H +#endif // UTILS_STRINGUTILS_H diff --git a/src/utils/typeconv.cpp b/src/utils/typeconv.cpp index fd2ba9ac9..781e4a4db 100644 --- a/src/utils/typeconv.cpp +++ b/src/utils/typeconv.cpp @@ -25,14 +25,13 @@ #include "typeconv.h" +#include +#include + #include "rad/appdata.h" #include "rad/bitmaps.h" #include "rad/inspector/objinspect.h" -#include -#include - -//////////////////////////////////// // Assuming that the locale is constant throughout one execution, // store the locale so that numbers can be stored in the "C" locale, @@ -40,27 +39,21 @@ class LocaleFinder { private: - char* m_locale; + char* m_locale; public: - LocaleFinder() - { - // get current locale - char* localePtr = ::setlocale( LC_NUMERIC, 0 ); - size_t size = ::strlen( localePtr ) + 1; - m_locale = new char[ size ]; - ::strncpy( m_locale, localePtr, size ); - } - - ~LocaleFinder() - { - delete [] m_locale; - } - - const char* GetString() - { - return m_locale; - } + LocaleFinder() + { + // get current locale + char* localePtr = ::setlocale(LC_NUMERIC, 0); + size_t size = ::strlen(localePtr) + 1; + m_locale = new char[size]; + ::strncpy(m_locale, localePtr, size); + } + + ~LocaleFinder() { delete[] m_locale; } + + const char* GetString() { return m_locale; } }; // Unfortunately, the locale is "C" at the start of execution, and is changed to the correct locale @@ -71,29 +64,21 @@ class LocaleFinder class LocaleHolder { private: - LocaleFinder* m_finder; + LocaleFinder* m_finder; public: - LocaleHolder() - : - m_finder( 0 ) - { - } - - ~LocaleHolder() - { - delete m_finder; - } - - const char* GetString() - { - if ( 0 == m_finder ) - { - m_finder = new LocaleFinder; - } - - return m_finder->GetString(); - } + LocaleHolder() : m_finder(0) {} + + ~LocaleHolder() { delete m_finder; } + + const char* GetString() + { + if (0 == m_finder) { + m_finder = new LocaleFinder; + } + + return m_finder->GetString(); + } }; // Creating this object will determine the current locale (when needed) and store it for the duration of the program @@ -103,997 +88,915 @@ static LocaleHolder s_locale; class LocaleSwitcher { private: - const char* m_locale; + const char* m_locale; public: - LocaleSwitcher() - { - m_locale = s_locale.GetString(); // Get the locale first, or it will be lost! - ::setlocale( LC_NUMERIC, "C" ); - } - - ~LocaleSwitcher() - { - ::setlocale( LC_NUMERIC, m_locale ); - } + LocaleSwitcher() + { + m_locale = s_locale.GetString(); // Get the locale first, or it will be lost! + ::setlocale(LC_NUMERIC, "C"); + } + + ~LocaleSwitcher() { ::setlocale(LC_NUMERIC, m_locale); } }; //////////////////////////////////// using namespace TypeConv; -wxString TypeConv::_StringToWxString(const std::string &str) +wxString TypeConv::_StringToWxString(const std::string& str) { - return _StringToWxString(str.c_str()); + return _StringToWxString(str.c_str()); } -wxString TypeConv::_StringToWxString(const char *str) +wxString TypeConv::_StringToWxString(const char* str) { - wxString newstr( str, wxConvUTF8 ); - return newstr; + wxString newstr(str, wxConvUTF8); + return newstr; } -std::string TypeConv::_WxStringToString(const wxString &str) +std::string TypeConv::_WxStringToString(const wxString& str) { - std::string newstr( str.mb_str(wxConvUTF8) ); - return newstr; + std::string newstr(str.mb_str(wxConvUTF8)); + return newstr; } -std::string TypeConv::_WxStringToAnsiString(const wxString &str) +std::string TypeConv::_WxStringToAnsiString(const wxString& str) { - std::string newstr( str.mb_str(wxConvISO8859_1) ); - return newstr; -// setlocale(LC_ALL, ""); -// size_t len = wcstombs(NULL, str.char_str(), 0); -// std::vector buf(len + 1); -// wcstombs(&buf[0], str.char_str(), len); -// return std::string(&buf[0]); + std::string newstr(str.mb_str(wxConvISO8859_1)); + return newstr; + // setlocale(LC_ALL, ""); + // size_t len = wcstombs(NULL, str.char_str(), 0); + // std::vector buf(len + 1); + // wcstombs(&buf[0], str.char_str(), len); + // return std::string(&buf[0]); } -bool TypeConv::StringToPoint(const wxString &val, wxPoint *point) +bool TypeConv::StringToPoint(const wxString& val, wxPoint* point) { - wxPoint result; - - bool error = false; - wxString str_x,str_y; - long val_x = -1, val_y = -1; - - if (val != wxT("")) - { - wxStringTokenizer tkz(val, wxT(",")); - if (tkz.HasMoreTokens()) - { - str_x = tkz.GetNextToken(); - str_x.Trim(true); - str_x.Trim(false); - if (tkz.HasMoreTokens()) - { - str_y = tkz.GetNextToken(); - str_y.Trim(true); - str_y.Trim(false); - } - else - error = true; - } - else - error = true; - - if (!error) - error = !str_x.ToLong(&val_x); - - if (!error) - error = !str_y.ToLong(&val_y); - - if (!error) - result = wxPoint(val_x,val_y); - } - else - result = wxDefaultPosition; - - if (error) - result = wxDefaultPosition; - - point->x = result.x; - point->y = result.y; - - return !error; + wxPoint result; + + bool error = false; + wxString str_x, str_y; + long val_x = -1, val_y = -1; + + if (val != wxT("")) { + wxStringTokenizer tkz(val, wxT(",")); + if (tkz.HasMoreTokens()) { + str_x = tkz.GetNextToken(); + str_x.Trim(true); + str_x.Trim(false); + if (tkz.HasMoreTokens()) { + str_y = tkz.GetNextToken(); + str_y.Trim(true); + str_y.Trim(false); + } else + error = true; + } else + error = true; + + if (!error) + error = !str_x.ToLong(&val_x); + + if (!error) + error = !str_y.ToLong(&val_y); + + if (!error) + result = wxPoint(val_x, val_y); + } else + result = wxDefaultPosition; + + if (error) + result = wxDefaultPosition; + + point->x = result.x; + point->y = result.y; + + return !error; } -wxPoint TypeConv::StringToPoint (const wxString &val) +wxPoint TypeConv::StringToPoint(const wxString& val) { - wxPoint result; - StringToPoint (val,&result); - return result; + wxPoint result; + StringToPoint(val, &result); + return result; } -wxSize TypeConv::StringToSize (const wxString &val) +wxSize TypeConv::StringToSize(const wxString& val) { - wxPoint point = StringToPoint(val); - return wxSize(point.x, point.y); + wxPoint point = StringToPoint(val); + return wxSize(point.x, point.y); } -int TypeConv::BitlistToInt (const wxString &str) +int TypeConv::BitlistToInt(const wxString& str) { - int result = 0; - wxStringTokenizer tkz(str, wxT("|")); - while (tkz.HasMoreTokens()) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim(true); - token.Trim(false); - - result |= GetMacroValue(token); - } - - return result; + int result = 0; + wxStringTokenizer tkz(str, wxT("|")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + result |= GetMacroValue(token); + } + + return result; } -wxString TypeConv::PointToString(const wxPoint &point) +wxString TypeConv::PointToString(const wxPoint& point) { - wxString value = wxString::Format(wxT("%d,%d"),point.x,point.y); - return value; + wxString value = wxString::Format(wxT("%d,%d"), point.x, point.y); + return value; } -wxString TypeConv::SizeToString(const wxSize &size) +wxString TypeConv::SizeToString(const wxSize& size) { - wxString value = wxString::Format(wxT("%d,%d"),size.GetWidth(), size.GetHeight()); - return value; + wxString value = wxString::Format(wxT("%d,%d"), size.GetWidth(), size.GetHeight()); + return value; } -int TypeConv::GetMacroValue(const wxString &str) +int TypeConv::GetMacroValue(const wxString& str) { - int value = 0; + int value = 0; - PMacroDictionary dic = MacroDictionary::GetInstance(); - if (!dic->SearchMacro(str, &value)) - { - value = StringToInt(str); - } + PMacroDictionary dic = MacroDictionary::GetInstance(); + if (!dic->SearchMacro(str, &value)) { + value = StringToInt(str); + } - return value; + return value; } -int TypeConv::StringToInt(const wxString &str) +int TypeConv::StringToInt(const wxString& str) { - long l = 0; - str.ToLong(&l); + long l = 0; + str.ToLong(&l); - return (int)l; + return (int)l; } -wxFontContainer TypeConv::StringToFont (const wxString &str) +wxFontContainer TypeConv::StringToFont(const wxString& str) { - wxFontContainer font; - - // face name, style, weight, point size, family, underlined - wxStringTokenizer tkz( str, wxT(",") ); - - if ( tkz.HasMoreTokens() ) - { - wxString faceName = tkz.GetNextToken(); - faceName.Trim( true ); - faceName.Trim( false ); - font.SetFaceName( faceName ); - } - - if (tkz.HasMoreTokens()) { - long l_style; - wxString s_style = tkz.GetNextToken(); - if (s_style.ToLong(&l_style)) { - if (l_style >= wxFONTSTYLE_NORMAL && l_style < wxFONTSTYLE_MAX) { - font.SetStyle(static_cast(l_style)); - } else { - font.SetStyle(wxFONTSTYLE_NORMAL); - } - } - } - - if (tkz.HasMoreTokens()) { - long l_weight; - wxString s_weight = tkz.GetNextToken(); - if (s_weight.ToLong(&l_weight)) { - // Due to an ABI break in wxWidgets 3.1.2 the values of the symbols changed, the previous - // values are distinct from the new values but are in their range, so they need to be tested first. - #if wxCHECK_VERSION(3, 1, 2) - if (l_weight >= wxNORMAL && l_weight <= wxBOLD) { - switch (l_weight) { - case wxNORMAL: - font.SetWeight(wxFONTWEIGHT_NORMAL); - break; - case wxLIGHT: - font.SetWeight(wxFONTWEIGHT_LIGHT); - break; - case wxBOLD: - font.SetWeight(wxFONTWEIGHT_BOLD); - break; - default: - font.SetWeight(wxFONTWEIGHT_NORMAL); - break; - } - } else if (l_weight > wxFONTWEIGHT_INVALID && l_weight < wxFONTWEIGHT_MAX) { - font.SetWeight(static_cast(l_weight)); - } else { - font.SetWeight(wxFONTWEIGHT_NORMAL); - } - #else - if (l_weight >= wxFONTWEIGHT_NORMAL && l_weight < wxFONTWEIGHT_MAX) { - font.SetWeight(static_cast(l_weight)); - } else { - // Either an invalid value or a value of a wxWidgets 3.1.2 symbol, - // since these symbols are not available here, test for their values directly - switch (l_weight) { - case 300: - font.SetWeight(wxFONTWEIGHT_LIGHT); - break; - case 400: - font.SetWeight(wxFONTWEIGHT_NORMAL); - break; - case 700: - font.SetWeight(wxFONTWEIGHT_BOLD); - break; - default: - font.SetWeight(wxFONTWEIGHT_NORMAL); - break; - } - } - #endif - } - } - - if ( tkz.HasMoreTokens() ) - { - long l_size; - wxString s_size = tkz.GetNextToken(); - if ( s_size.ToLong( &l_size ) ) - { - font.SetPointSize( (int)l_size ); - } - } - - if (tkz.HasMoreTokens()) { - long l_family; - wxString s_family = tkz.GetNextToken(); - if (s_family.ToLong(&l_family)) { - if (l_family >= wxFONTFAMILY_DEFAULT && l_family < wxFONTFAMILY_MAX) { - font.SetFamily(static_cast(l_family)); - } else { - font.SetFamily(wxFONTFAMILY_DEFAULT); - } - } - } - - if ( tkz.HasMoreTokens() ) - { - long l_underlined; - wxString s_underlined = tkz.GetNextToken(); - if ( s_underlined.ToLong( &l_underlined ) ) - { - font.SetUnderlined( l_underlined != 0 ); - } - } - - return font; + wxFontContainer font; + + // face name, style, weight, point size, family, underlined + wxStringTokenizer tkz(str, wxT(",")); + + if (tkz.HasMoreTokens()) { + wxString faceName = tkz.GetNextToken(); + faceName.Trim(true); + faceName.Trim(false); + font.SetFaceName(faceName); + } + + if (tkz.HasMoreTokens()) { + long l_style; + wxString s_style = tkz.GetNextToken(); + if (s_style.ToLong(&l_style)) { + if (l_style >= wxFONTSTYLE_NORMAL && l_style < wxFONTSTYLE_MAX) { + font.SetStyle(static_cast(l_style)); + } else { + font.SetStyle(wxFONTSTYLE_NORMAL); + } + } + } + + if (tkz.HasMoreTokens()) { + long l_weight; + wxString s_weight = tkz.GetNextToken(); + if (s_weight.ToLong(&l_weight)) { +// Due to an ABI break in wxWidgets 3.1.2 the values of the symbols changed, the previous +// values are distinct from the new values but are in their range, so they need to be tested first. +#if wxCHECK_VERSION(3, 1, 2) + if (l_weight >= wxNORMAL && l_weight <= wxBOLD) { + switch (l_weight) { + case wxNORMAL: + font.SetWeight(wxFONTWEIGHT_NORMAL); + break; + case wxLIGHT: + font.SetWeight(wxFONTWEIGHT_LIGHT); + break; + case wxBOLD: + font.SetWeight(wxFONTWEIGHT_BOLD); + break; + default: + font.SetWeight(wxFONTWEIGHT_NORMAL); + break; + } + } else if (l_weight > wxFONTWEIGHT_INVALID && l_weight < wxFONTWEIGHT_MAX) { + font.SetWeight(static_cast(l_weight)); + } else { + font.SetWeight(wxFONTWEIGHT_NORMAL); + } +#else + if (l_weight >= wxFONTWEIGHT_NORMAL && l_weight < wxFONTWEIGHT_MAX) { + font.SetWeight(static_cast(l_weight)); + } else { + // Either an invalid value or a value of a wxWidgets 3.1.2 symbol, + // since these symbols are not available here, test for their values directly + switch (l_weight) { + case 300: + font.SetWeight(wxFONTWEIGHT_LIGHT); + break; + case 400: + font.SetWeight(wxFONTWEIGHT_NORMAL); + break; + case 700: + font.SetWeight(wxFONTWEIGHT_BOLD); + break; + default: + font.SetWeight(wxFONTWEIGHT_NORMAL); + break; + } + } +#endif + } + } + + if (tkz.HasMoreTokens()) { + long l_size; + wxString s_size = tkz.GetNextToken(); + if (s_size.ToLong(&l_size)) { + font.SetPointSize((int)l_size); + } + } + + if (tkz.HasMoreTokens()) { + long l_family; + wxString s_family = tkz.GetNextToken(); + if (s_family.ToLong(&l_family)) { + if (l_family >= wxFONTFAMILY_DEFAULT && l_family < wxFONTFAMILY_MAX) { + font.SetFamily(static_cast(l_family)); + } else { + font.SetFamily(wxFONTFAMILY_DEFAULT); + } + } + } + + if (tkz.HasMoreTokens()) { + long l_underlined; + wxString s_underlined = tkz.GetNextToken(); + if (s_underlined.ToLong(&l_underlined)) { + font.SetUnderlined(l_underlined != 0); + } + } + + return font; } -wxString TypeConv::FontToString (const wxFontContainer &font) +wxString TypeConv::FontToString(const wxFontContainer& font) { - // face name, style, weight, point size, family, underlined - return wxString::Format( wxT("%s,%d,%d,%d,%d,%d"), font.GetFaceName(), font.GetStyle(), font.GetWeight(), font.GetPointSize(), font.GetFamily(), font.GetUnderlined() ? 1 : 0 ); + // face name, style, weight, point size, family, underlined + return wxString::Format( + wxT("%s,%d,%d,%d,%d,%d"), font.GetFaceName(), font.GetStyle(), font.GetWeight(), font.GetPointSize(), + font.GetFamily(), font.GetUnderlined() ? 1 : 0); } -wxString TypeConv::FontFamilyToString(wxFontFamily family) { - wxString result; - - switch (family) { - case wxFONTFAMILY_DECORATIVE: - result = wxT("wxFONTFAMILY_DECORATIVE"); - break; - case wxFONTFAMILY_ROMAN: - result = wxT("wxFONTFAMILY_ROMAN"); - break; - case wxFONTFAMILY_SCRIPT: - result = wxT("wxFONTFAMILY_SCRIPT"); - break; - case wxFONTFAMILY_SWISS: - result = wxT("wxFONTFAMILY_SWISS"); - break; - case wxFONTFAMILY_MODERN: - result = wxT("wxFONTFAMILY_MODERN"); - break; - case wxFONTFAMILY_TELETYPE: - result = wxT("wxFONTFAMILY_TELETYPE"); - break; - default: - result = wxT("wxFONTFAMILY_DEFAULT"); - break; - } - - return result; +wxString TypeConv::FontFamilyToString(wxFontFamily family) +{ + wxString result; + + switch (family) { + case wxFONTFAMILY_DECORATIVE: + result = wxT("wxFONTFAMILY_DECORATIVE"); + break; + case wxFONTFAMILY_ROMAN: + result = wxT("wxFONTFAMILY_ROMAN"); + break; + case wxFONTFAMILY_SCRIPT: + result = wxT("wxFONTFAMILY_SCRIPT"); + break; + case wxFONTFAMILY_SWISS: + result = wxT("wxFONTFAMILY_SWISS"); + break; + case wxFONTFAMILY_MODERN: + result = wxT("wxFONTFAMILY_MODERN"); + break; + case wxFONTFAMILY_TELETYPE: + result = wxT("wxFONTFAMILY_TELETYPE"); + break; + default: + result = wxT("wxFONTFAMILY_DEFAULT"); + break; + } + + return result; } -wxString TypeConv::FontStyleToString(wxFontStyle style) { - wxString result; - - switch (style) { - case wxFONTSTYLE_ITALIC: - result = wxT("wxFONTSTYLE_ITALIC"); - break; - case wxFONTSTYLE_SLANT: - result = wxT("wxFONTSTYLE_SLANT"); - break; - default: - result = wxT("wxFONTSTYLE_NORMAL"); - break; - } - - return result; +wxString TypeConv::FontStyleToString(wxFontStyle style) +{ + wxString result; + + switch (style) { + case wxFONTSTYLE_ITALIC: + result = wxT("wxFONTSTYLE_ITALIC"); + break; + case wxFONTSTYLE_SLANT: + result = wxT("wxFONTSTYLE_SLANT"); + break; + default: + result = wxT("wxFONTSTYLE_NORMAL"); + break; + } + + return result; } -wxString TypeConv::FontWeightToString(wxFontWeight weight) { - wxString result; - - switch (weight) { - case wxFONTWEIGHT_LIGHT: - result = wxT("wxFONTWEIGHT_LIGHT"); - break; - case wxFONTWEIGHT_BOLD: - result = wxT("wxFONTWEIGHT_BOLD"); - break; - default: - result = wxT("wxFONTWEIGHT_NORMAL"); - break; - } - - return result; +wxString TypeConv::FontWeightToString(wxFontWeight weight) +{ + wxString result; + + switch (weight) { + case wxFONTWEIGHT_LIGHT: + result = wxT("wxFONTWEIGHT_LIGHT"); + break; + case wxFONTWEIGHT_BOLD: + result = wxT("wxFONTWEIGHT_BOLD"); + break; + default: + result = wxT("wxFONTWEIGHT_NORMAL"); + break; + } + + return result; } -wxBitmap TypeConv::StringToBitmap( const wxString& filename ) +wxBitmap TypeConv::StringToBitmap(const wxString& filename) { - #ifndef __WXFB_DEBUG__ - wxLogNull stopLogging; - #endif - - // Get bitmap from art provider - if( filename.Contains( _("Load From Art Provider") ) ) - { - wxString image = filename.AfterFirst( wxT(';') ).Trim( false ); - wxString rid = image.BeforeFirst( wxT(';') ).Trim( false ); - wxString cid = image.AfterFirst( wxT(';') ).Trim( false ); - - if( rid.IsEmpty() || cid.IsEmpty() ) - { - return AppBitmaps::GetBitmap( wxT("unknown") ); - } - else - { - //return wxArtProvider::GetBitmap( rid, cid + wxT("_C") ){ - wxBitmap bmp = wxArtProvider::GetBitmap( rid, cid + wxT("_C") ); - - if (!bmp.IsOk()) - { - return AppBitmaps::GetBitmap( wxT("unknown") ); - - /* // Create another bitmap of the appropriate size to show it's invalid. - // We can get here if the user entered a custom wxArtID which, presumably, - // they will have already installed in their app. - bmp = wxArtProvider::GetBitmap( wxT("wxART_MISSING_IMAGE"), cid + wxT("_C") ); - - if (bmp.IsOk()) - { - wxMemoryDC dc; - dc.SelectObject(bmp); - dc.SetPen(wxPen(*wxRED, 3)); - dc.DrawLine(wxPoint(0, 0), wxPoint(bmp.GetWidth(), bmp.GetHeight())); - dc.SelectObject(wxNullBitmap); - } */ - } - else - return bmp; - } - } - - // Get path from bitmap property - wxString path = filename.AfterFirst( wxT(';') ).Trim( false ); - - // No value - default bitmap - if ( !wxFileName( path ).IsOk() ) - { - return AppBitmaps::GetBitmap( wxT("unknown") ); - } - - // Setup the working directory to the project path - paths should be saved in the .fbp file relative to the location - // of the .fbp file - wxFileSystem system; - system.ChangePathTo( AppData()->GetProjectPath(), true ); - - // The loader can get goofy on linux if it starts with file:, not sure why (wxGTK 2.8.7) - wxFSFile *fsfile = NULL; - wxString remainder; - if ( path.StartsWith( wxT("file:"), &remainder ) ) - { - fsfile = system.OpenFile( remainder, wxFS_READ | wxFS_SEEKABLE ); - } - else - { - fsfile = system.OpenFile( path, wxFS_READ | wxFS_SEEKABLE ); - } - - // Unable to open the file - if ( fsfile == NULL ) - { - return AppBitmaps::GetBitmap( wxT("unknown") ); - } - - // Create a wxImage from the file stream - wxImage img( *(fsfile->GetStream()) ); - delete fsfile; - - // The stream is not an image - if ( !img.Ok() ) - { - return AppBitmaps::GetBitmap( wxT("unknown") ); - } - - // Create a wxBitmap from the image - return wxBitmap( img ); +#ifndef __WXFB_DEBUG__ + wxLogNull stopLogging; +#endif + + // Get bitmap from art provider + if (filename.Contains(_("Load From Art Provider"))) { + wxString image = filename.AfterFirst(wxT(';')).Trim(false); + wxString rid = image.BeforeFirst(wxT(';')).Trim(false); + wxString cid = image.AfterFirst(wxT(';')).Trim(false); + + if (rid.IsEmpty() || cid.IsEmpty()) { + return AppBitmaps::GetBitmap(wxT("unknown")); + } else { + // return wxArtProvider::GetBitmap( rid, cid + wxT("_C") ){ + wxBitmap bmp = wxArtProvider::GetBitmap(rid, cid + wxT("_C")); + + if (!bmp.IsOk()) { + return AppBitmaps::GetBitmap(wxT("unknown")); + + /* // Create another bitmap of the appropriate size to show it's invalid. + // We can get here if the user entered a custom wxArtID which, presumably, + // they will have already installed in their app. + bmp = wxArtProvider::GetBitmap( wxT("wxART_MISSING_IMAGE"), cid + wxT("_C") ); + + if (bmp.IsOk()) + { + wxMemoryDC dc; + dc.SelectObject(bmp); + dc.SetPen(wxPen(*wxRED, 3)); + dc.DrawLine(wxPoint(0, 0), wxPoint(bmp.GetWidth(), bmp.GetHeight())); + dc.SelectObject(wxNullBitmap); + } */ + } else + return bmp; + } + } + + // Get path from bitmap property + wxString path = filename.AfterFirst(wxT(';')).Trim(false); + + // No value - default bitmap + if (!wxFileName(path).IsOk()) { + return AppBitmaps::GetBitmap(wxT("unknown")); + } + + // Setup the working directory to the project path - paths should be saved in the .fbp file relative to the location + // of the .fbp file + wxFileSystem system; + system.ChangePathTo(AppData()->GetProjectPath(), true); + + // The loader can get goofy on linux if it starts with file:, not sure why (wxGTK 2.8.7) + wxFSFile* fsfile = NULL; + wxString remainder; + if (path.StartsWith(wxT("file:"), &remainder)) { + fsfile = system.OpenFile(remainder, wxFS_READ | wxFS_SEEKABLE); + } else { + fsfile = system.OpenFile(path, wxFS_READ | wxFS_SEEKABLE); + } + + // Unable to open the file + if (fsfile == NULL) { + return AppBitmaps::GetBitmap(wxT("unknown")); + } + + // Create a wxImage from the file stream + wxImage img(*(fsfile->GetStream())); + delete fsfile; + + // The stream is not an image + if (!img.Ok()) { + return AppBitmaps::GetBitmap(wxT("unknown")); + } + + // Create a wxBitmap from the image + return wxBitmap(img); } -void TypeConv::ParseBitmapWithResource( const wxString& value, wxString* image, wxString* source, wxSize* icoSize ) +void TypeConv::ParseBitmapWithResource(const wxString& value, wxString* image, wxString* source, wxSize* icoSize) { - // Splitting bitmap resource property value - it is of the form "path; source [width; height]" - - *image = value; - *source = _("Load From File"); - *icoSize = wxDefaultSize; - - wxArrayString children; - wxStringTokenizer tkz( value, wxT("[];"), wxTOKEN_RET_EMPTY ); - while ( tkz.HasMoreTokens() ) - { - wxString child = tkz.GetNextToken(); - child.Trim( false ); - child.Trim( true ); - children.Add( child ); - } - - if( children.Index( _("Load From Art Provider") ) == wxNOT_FOUND ) - { - long temp; - switch ( children.size() ) - { - case 5: - case 4: - if( children.size() > 4 ) - { - children[4].ToLong( &temp ); - icoSize->SetHeight( temp ); - } - wxFALLTHROUGH; - case 3: - if( children.size() > 3 ) - { - children[3].ToLong( &temp ); - icoSize->SetWidth( temp ); - } - wxFALLTHROUGH; - case 2: - if( children.size() > 1 ) *image = children[1]; - wxFALLTHROUGH; - case 1: - if( children.size() > 0 ) *source = children[0]; - break; - default: - break; - } - } - else - { - if( children.size() == 3 ) - { - *image = children[1] + wxT(":") + children[2]; - *source = children[0]; - } - else - { - *image = wxT(""); - *source = children[0]; - } - } - wxLogDebug( wxT("TypeConv:ParseBitmap: source:%s image:%s "), source->c_str(), image->c_str() ); + // Splitting bitmap resource property value - it is of the form "path; source [width; height]" + + *image = value; + *source = _("Load From File"); + *icoSize = wxDefaultSize; + + wxArrayString children; + wxStringTokenizer tkz(value, wxT("[];"), wxTOKEN_RET_EMPTY); + while (tkz.HasMoreTokens()) { + wxString child = tkz.GetNextToken(); + child.Trim(false); + child.Trim(true); + children.Add(child); + } + + if (children.Index(_("Load From Art Provider")) == wxNOT_FOUND) { + long temp; + switch (children.size()) { + case 5: + case 4: + if (children.size() > 4) { + children[4].ToLong(&temp); + icoSize->SetHeight(temp); + } + wxFALLTHROUGH; + case 3: + if (children.size() > 3) { + children[3].ToLong(&temp); + icoSize->SetWidth(temp); + } + wxFALLTHROUGH; + case 2: + if (children.size() > 1) + *image = children[1]; + wxFALLTHROUGH; + case 1: + if (children.size() > 0) + *source = children[0]; + break; + default: + break; + } + } else { + if (children.size() == 3) { + *image = children[1] + wxT(":") + children[2]; + *source = children[0]; + } else { + *image = wxT(""); + *source = children[0]; + } + } + wxLogDebug(wxT("TypeConv:ParseBitmap: source:%s image:%s "), source->c_str(), image->c_str()); } -wxString TypeConv::MakeAbsolutePath ( const wxString& filename, const wxString& basePath ) +wxString TypeConv::MakeAbsolutePath(const wxString& filename, const wxString& basePath) { - wxFileName fnFile( filename ); - wxFileName noChanges = fnFile; - if ( fnFile.IsRelative() ) - { - // Es una ruta relativa, por tanto hemos de obtener la ruta completa - // a partir de basePath - wxFileName fnBasePath( basePath ); - if ( fnBasePath.IsAbsolute() ) - { - if ( fnFile.MakeAbsolute(basePath) ) - { - wxString path = fnFile.GetFullPath(); - return path; - } - } - } - - // Either it is already absolute, or it could not be made absolute, so give it back - but change to '/' for separators - wxString path = noChanges.GetFullPath(); - return path; + wxFileName fnFile(filename); + wxFileName noChanges = fnFile; + if (fnFile.IsRelative()) { + // Es una ruta relativa, por tanto hemos de obtener la ruta completa + // a partir de basePath + wxFileName fnBasePath(basePath); + if (fnBasePath.IsAbsolute()) { + if (fnFile.MakeAbsolute(basePath)) { + wxString path = fnFile.GetFullPath(); + return path; + } + } + } + + // Either it is already absolute, or it could not be made absolute, so give it back - but change to '/' for + // separators + wxString path = noChanges.GetFullPath(); + return path; } -wxString TypeConv::MakeRelativePath( const wxString& filename, const wxString& basePath ) +wxString TypeConv::MakeRelativePath(const wxString& filename, const wxString& basePath) { - wxFileName fnFile( filename ); - wxFileName noChanges = fnFile; - if ( fnFile.IsAbsolute() ) - { - wxFileName fnBasePath( basePath) ; - if ( fnBasePath.IsAbsolute() ) - { - if ( fnFile.MakeRelativeTo( basePath ) ) - { - return fnFile.GetFullPath( wxPATH_UNIX ); - } - } - } - - // Either it is already relative, or it could not be made relative, so give it back - but change to '/' for separators - if ( noChanges.IsAbsolute() ) - { - wxString path = noChanges.GetFullPath(); - return path; - } - else - { - return noChanges.GetFullPath( wxPATH_UNIX ); - } + wxFileName fnFile(filename); + wxFileName noChanges = fnFile; + if (fnFile.IsAbsolute()) { + wxFileName fnBasePath(basePath); + if (fnBasePath.IsAbsolute()) { + if (fnFile.MakeRelativeTo(basePath)) { + return fnFile.GetFullPath(wxPATH_UNIX); + } + } + } + + // Either it is already relative, or it could not be made relative, so give it back - but change to '/' for + // separators + if (noChanges.IsAbsolute()) { + wxString path = noChanges.GetFullPath(); + return path; + } else { + return noChanges.GetFullPath(wxPATH_UNIX); + } } -void TypeConv::SplitFileSystemURL( const wxString& url, wxString* protocol, wxString* path, wxString* anchor ) +void TypeConv::SplitFileSystemURL(const wxString& url, wxString* protocol, wxString* path, wxString* anchor) { - wxString remainder; - if ( url.StartsWith( wxT("file:"), &remainder ) ) - { - *protocol = wxT("file:"); - } - else - { - protocol->clear(); - remainder = url; - } - - *path = remainder.BeforeFirst( wxT('#') ); - if ( remainder.size() > path->size() ) - { - *anchor = remainder.substr( path->size() ); - } - else - { - anchor->clear(); - } + wxString remainder; + if (url.StartsWith(wxT("file:"), &remainder)) { + *protocol = wxT("file:"); + } else { + protocol->clear(); + remainder = url; + } + + *path = remainder.BeforeFirst(wxT('#')); + if (remainder.size() > path->size()) { + *anchor = remainder.substr(path->size()); + } else { + anchor->clear(); + } } -wxString TypeConv::MakeAbsoluteURL( const wxString& url, const wxString& basePath ) +wxString TypeConv::MakeAbsoluteURL(const wxString& url, const wxString& basePath) { - wxString protocol, path, anchor; - SplitFileSystemURL( url, &protocol, &path, &anchor ); - return protocol + MakeAbsolutePath( path, basePath ) + anchor; + wxString protocol, path, anchor; + SplitFileSystemURL(url, &protocol, &path, &anchor); + return protocol + MakeAbsolutePath(path, basePath) + anchor; } -wxString TypeConv::MakeRelativeURL( const wxString& url, const wxString& basePath ) +wxString TypeConv::MakeRelativeURL(const wxString& url, const wxString& basePath) { - wxString protocol, path, anchor; - SplitFileSystemURL( url, &protocol, &path, &anchor ); - return protocol + MakeRelativePath( path, basePath ) + anchor; + wxString protocol, path, anchor; + SplitFileSystemURL(url, &protocol, &path, &anchor); + return protocol + MakeRelativePath(path, basePath) + anchor; } -#define ElseIfSystemColourConvert( NAME, value ) \ - else if ( value == wxT(#NAME) ) \ - { \ - systemVal = NAME; \ - } +#define ElseIfSystemColourConvert(NAME, value) \ + else if (value == wxT(#NAME)) { systemVal = NAME; } -wxSystemColour TypeConv::StringToSystemColour( const wxString& str ) +wxSystemColour TypeConv::StringToSystemColour(const wxString& str) { - wxSystemColour systemVal = wxSYS_COLOUR_BTNFACE; - - if( false ) - {} - ElseIfSystemColourConvert( wxSYS_COLOUR_SCROLLBAR, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_BACKGROUND, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_ACTIVECAPTION, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_INACTIVECAPTION, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_MENU, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_WINDOW, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_WINDOWFRAME, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_MENUTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_WINDOWTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_CAPTIONTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_ACTIVEBORDER, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_INACTIVEBORDER, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_APPWORKSPACE, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_HIGHLIGHT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_HIGHLIGHTTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_BTNFACE, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_BTNSHADOW, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_GRAYTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_BTNTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_INACTIVECAPTIONTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_BTNHIGHLIGHT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_3DDKSHADOW, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_3DLIGHT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_INFOTEXT, str ) - ElseIfSystemColourConvert( wxSYS_COLOUR_INFOBK, str ) - - return systemVal; + wxSystemColour systemVal = wxSYS_COLOUR_BTNFACE; + + if (false) {} + ElseIfSystemColourConvert(wxSYS_COLOUR_SCROLLBAR, str) ElseIfSystemColourConvert(wxSYS_COLOUR_BACKGROUND, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_ACTIVECAPTION, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_INACTIVECAPTION, str) ElseIfSystemColourConvert(wxSYS_COLOUR_MENU, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_WINDOW, str) ElseIfSystemColourConvert(wxSYS_COLOUR_WINDOWFRAME, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_MENUTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_WINDOWTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_CAPTIONTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_ACTIVEBORDER, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_INACTIVEBORDER, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_APPWORKSPACE, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_HIGHLIGHT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_HIGHLIGHTTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_BTNFACE, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_BTNSHADOW, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_GRAYTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_BTNTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_INACTIVECAPTIONTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_BTNHIGHLIGHT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_3DDKSHADOW, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_3DLIGHT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_INFOTEXT, str) + ElseIfSystemColourConvert(wxSYS_COLOUR_INFOBK, str) + + return systemVal; } -wxColour TypeConv::StringToColour( const wxString& str ) +wxColour TypeConv::StringToColour(const wxString& str) { - // check for system colour - if ( str.find_first_of( wxT("wx") ) == 0 ) - { - return wxSystemSettings::GetColour( StringToSystemColour( str ) ); - } - else - { - wxStringTokenizer tkz(str,wxT(",")); - unsigned int red,green,blue; - - red = green = blue = 0; - - // bool set_red, set_green, set_blue; - - // set_red = set_green = set_blue = false; - - if (tkz.HasMoreTokens()) - { - wxString s_red = tkz.GetNextToken(); - long l_red; - - if (s_red.ToLong(&l_red) && (l_red >= 0 && l_red <= 255)) - { - red = (int)l_red; - // set_size = true; - } - } - - if (tkz.HasMoreTokens()) - { - wxString s_green = tkz.GetNextToken(); - long l_green; - - if (s_green.ToLong(&l_green) && (l_green >= 0 && l_green <= 255)) - { - green = (int)l_green; - // set_size = true; - } - } - - if (tkz.HasMoreTokens()) - { - wxString s_blue = tkz.GetNextToken(); - long l_blue; - - if (s_blue.ToLong(&l_blue) && (l_blue >= 0 && l_blue <= 255)) - { - blue = (int)l_blue; - // set_size = true; - } - } - - - return wxColour(red,green,blue); - } + // check for system colour + if (str.find_first_of(wxT("wx")) == 0) { + return wxSystemSettings::GetColour(StringToSystemColour(str)); + } else { + wxStringTokenizer tkz(str, wxT(",")); + unsigned int red, green, blue; + + red = green = blue = 0; + + // bool set_red, set_green, set_blue; + + // set_red = set_green = set_blue = false; + + if (tkz.HasMoreTokens()) { + wxString s_red = tkz.GetNextToken(); + long l_red; + + if (s_red.ToLong(&l_red) && (l_red >= 0 && l_red <= 255)) { + red = (int)l_red; + // set_size = true; + } + } + + if (tkz.HasMoreTokens()) { + wxString s_green = tkz.GetNextToken(); + long l_green; + + if (s_green.ToLong(&l_green) && (l_green >= 0 && l_green <= 255)) { + green = (int)l_green; + // set_size = true; + } + } + + if (tkz.HasMoreTokens()) { + wxString s_blue = tkz.GetNextToken(); + long l_blue; + + if (s_blue.ToLong(&l_blue) && (l_blue >= 0 && l_blue <= 255)) { + blue = (int)l_blue; + // set_size = true; + } + } + + + return wxColour(red, green, blue); + } } -wxString TypeConv::ColourToString( const wxColour& colour ) +wxString TypeConv::ColourToString(const wxColour& colour) { - return wxString::Format(wxT("%d,%d,%d"),colour.Red(),colour.Green(),colour.Blue()); + return wxString::Format(wxT("%d,%d,%d"), colour.Red(), colour.Green(), colour.Blue()); } -#define SystemColourConvertCase( NAME ) \ - case NAME: \ - s = wxT(#NAME); \ - break; +#define SystemColourConvertCase(NAME) \ + case NAME: \ + s = wxT(#NAME); \ + break; -wxString TypeConv::SystemColourToString( long colour ) +wxString TypeConv::SystemColourToString(long colour) { - wxString s; - - switch ( colour ) - { - SystemColourConvertCase( wxSYS_COLOUR_SCROLLBAR ) - SystemColourConvertCase( wxSYS_COLOUR_BACKGROUND ) - SystemColourConvertCase( wxSYS_COLOUR_ACTIVECAPTION ) - SystemColourConvertCase( wxSYS_COLOUR_INACTIVECAPTION ) - SystemColourConvertCase( wxSYS_COLOUR_MENU ) - SystemColourConvertCase( wxSYS_COLOUR_WINDOW ) - SystemColourConvertCase( wxSYS_COLOUR_WINDOWFRAME ) - SystemColourConvertCase( wxSYS_COLOUR_MENUTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_WINDOWTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_CAPTIONTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_ACTIVEBORDER ) - SystemColourConvertCase( wxSYS_COLOUR_INACTIVEBORDER ) - SystemColourConvertCase( wxSYS_COLOUR_APPWORKSPACE ) - SystemColourConvertCase( wxSYS_COLOUR_HIGHLIGHT ) - SystemColourConvertCase( wxSYS_COLOUR_HIGHLIGHTTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_BTNFACE ) - SystemColourConvertCase( wxSYS_COLOUR_BTNSHADOW ) - SystemColourConvertCase( wxSYS_COLOUR_GRAYTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_BTNTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_INACTIVECAPTIONTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_BTNHIGHLIGHT ) - SystemColourConvertCase( wxSYS_COLOUR_3DDKSHADOW ) - SystemColourConvertCase( wxSYS_COLOUR_3DLIGHT ) - SystemColourConvertCase( wxSYS_COLOUR_INFOTEXT ) - SystemColourConvertCase( wxSYS_COLOUR_INFOBK ) - } - - return s; + wxString s; + + switch (colour) { + SystemColourConvertCase(wxSYS_COLOUR_SCROLLBAR) SystemColourConvertCase(wxSYS_COLOUR_BACKGROUND) + SystemColourConvertCase(wxSYS_COLOUR_ACTIVECAPTION) SystemColourConvertCase(wxSYS_COLOUR_INACTIVECAPTION) + SystemColourConvertCase(wxSYS_COLOUR_MENU) SystemColourConvertCase(wxSYS_COLOUR_WINDOW) + SystemColourConvertCase(wxSYS_COLOUR_WINDOWFRAME) SystemColourConvertCase(wxSYS_COLOUR_MENUTEXT) + SystemColourConvertCase(wxSYS_COLOUR_WINDOWTEXT) SystemColourConvertCase(wxSYS_COLOUR_CAPTIONTEXT) + SystemColourConvertCase(wxSYS_COLOUR_ACTIVEBORDER) + SystemColourConvertCase(wxSYS_COLOUR_INACTIVEBORDER) + SystemColourConvertCase(wxSYS_COLOUR_APPWORKSPACE) SystemColourConvertCase(wxSYS_COLOUR_HIGHLIGHT) + SystemColourConvertCase(wxSYS_COLOUR_HIGHLIGHTTEXT) + SystemColourConvertCase(wxSYS_COLOUR_BTNFACE) SystemColourConvertCase(wxSYS_COLOUR_BTNSHADOW) + SystemColourConvertCase(wxSYS_COLOUR_GRAYTEXT) SystemColourConvertCase(wxSYS_COLOUR_BTNTEXT) + SystemColourConvertCase(wxSYS_COLOUR_INACTIVECAPTIONTEXT) + SystemColourConvertCase(wxSYS_COLOUR_BTNHIGHLIGHT) + SystemColourConvertCase(wxSYS_COLOUR_3DDKSHADOW) + SystemColourConvertCase(wxSYS_COLOUR_3DLIGHT) + SystemColourConvertCase(wxSYS_COLOUR_INFOTEXT) + SystemColourConvertCase(wxSYS_COLOUR_INFOBK) + } + + return s; } -bool TypeConv::FlagSet (const wxString &flag, const wxString ¤tValue) +bool TypeConv::FlagSet(const wxString& flag, const wxString& currentValue) { - bool set = false; - wxStringTokenizer tkz(currentValue, wxT("|")); - while (!set && tkz.HasMoreTokens()) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim(true); - token.Trim(false); - - if (token == flag) - set = true; - } - - return set; + bool set = false; + wxStringTokenizer tkz(currentValue, wxT("|")); + while (!set && tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + if (token == flag) + set = true; + } + + return set; } -wxString TypeConv::ClearFlag(const wxString &flag, const wxString ¤tValue) +wxString TypeConv::ClearFlag(const wxString& flag, const wxString& currentValue) { - if (flag == wxT("")) - return currentValue; - - wxString result; - wxStringTokenizer tkz(currentValue, wxT("|")); - while (tkz.HasMoreTokens()) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim(true); - token.Trim(false); - - if (token != flag) - { - if (result != wxT("")) - result = result + wxT('|'); - - result = result + token; - } - } - - return result; + if (flag == wxT("")) + return currentValue; + + wxString result; + wxStringTokenizer tkz(currentValue, wxT("|")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + if (token != flag) { + if (result != wxT("")) + result = result + wxT('|'); + + result = result + token; + } + } + + return result; } -wxString TypeConv::SetFlag (const wxString &flag, const wxString ¤tValue) +wxString TypeConv::SetFlag(const wxString& flag, const wxString& currentValue) { - if (flag == wxT("")) - return currentValue; - - bool found = false; - wxString result = currentValue; - wxStringTokenizer tkz(currentValue, wxT("|")); - while (tkz.HasMoreTokens()) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim(true); - token.Trim(false); - - if (token == flag) - found = true; - } - - if (!found) - { - if (result != wxT("")) - result = result + wxT('|'); - - result = result + flag; - } - return result; + if (flag == wxT("")) + return currentValue; + + bool found = false; + wxString result = currentValue; + wxStringTokenizer tkz(currentValue, wxT("|")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + if (token == flag) + found = true; + } + + if (!found) { + if (result != wxT("")) + result = result + wxT('|'); + + result = result + flag; + } + return result; } // la representación de un array de cadenas será: // 'string1' 'string2' 'string3' // el caracter (') se representa dentro de una cadena como ('') // 'wxString''1''' -wxArrayString TypeConv::OldStringToArrayString( const wxString& str ) +wxArrayString TypeConv::OldStringToArrayString(const wxString& str) { - int i=0, size = (int)str.Length(), state = 0; - wxArrayString result; - wxString substr; - while (i < size) - { - wxChar c = str[i]; - switch (state) - { - case 0: // esperando (') de comienzo de cadena - if (c == wxT('\'')) - state = 1; - break; - case 1: // guardando cadena - if (c == wxT('\'')) - { - if (i+1 < size && str[i+1] == wxT('\'')) - { - substr = substr + wxT('\''); // sustitución ('') por (') y seguimos - i++; - } - else - { - result.Add(substr); // fin de cadena - substr.Clear(); - state = 0; - } - } - else - substr = substr + c; // seguimos guardado la cadena - - break; - } - i++; - } - return result; + int i = 0, size = (int)str.Length(), state = 0; + wxArrayString result; + wxString substr; + while (i < size) { + wxChar c = str[i]; + switch (state) { + case 0: // esperando (') de comienzo de cadena + if (c == wxT('\'')) + state = 1; + break; + case 1: // guardando cadena + if (c == wxT('\'')) { + if (i + 1 < size && str[i + 1] == wxT('\'')) { + substr = substr + wxT('\''); // sustitución ('') por (') y seguimos + i++; + } else { + result.Add(substr); // fin de cadena + substr.Clear(); + state = 0; + } + } else + substr = substr + c; // seguimos guardado la cadena + + break; + } + i++; + } + return result; } -wxArrayString TypeConv::StringToArrayString( const wxString& str ) +wxArrayString TypeConv::StringToArrayString(const wxString& str) { - //wxArrayString result = wxStringTokenize( str, wxT(";") ); - wxArrayString result; + // wxArrayString result = wxStringTokenize( str, wxT(";") ); + wxArrayString result; - WX_PG_TOKENIZER2_BEGIN( str, wxT('"') ) + WX_PG_TOKENIZER2_BEGIN(str, wxT('"')) - result.Add ( token ); + result.Add(token); - WX_PG_TOKENIZER2_END() + WX_PG_TOKENIZER2_END() - return result; + return result; } -wxString TypeConv::ArrayStringToString(const wxArrayString &arrayStr) +wxString TypeConv::ArrayStringToString(const wxArrayString& arrayStr) { - wxString result; + wxString result; - wxArrayStringProperty::ArrayStringToString( result, arrayStr, '"', 1 ); + wxArrayStringProperty::ArrayStringToString(result, arrayStr, '"', 1); - return result; + return result; } -wxString TypeConv::ReplaceSynonymous(const wxString &bitlist) +wxString TypeConv::ReplaceSynonymous(const wxString& bitlist) { - wxMessageBox(wxT("Antes: ")+bitlist); - wxString result; - wxString translation; - wxStringTokenizer tkz(bitlist, wxT("|")); - while (tkz.HasMoreTokens()) - { - wxString token; - token = tkz.GetNextToken(); - token.Trim(true); - token.Trim(false); - - if (result != wxT("")) - result = result + wxChar('|'); - - if (MacroDictionary::GetInstance()->SearchSynonymous( token, translation)) - result += translation; - else - result += token; - - } - wxMessageBox(wxT("Despues: ")+result); - return result; + wxMessageBox(wxT("Antes: ") + bitlist); + wxString result; + wxString translation; + wxStringTokenizer tkz(bitlist, wxT("|")); + while (tkz.HasMoreTokens()) { + wxString token; + token = tkz.GetNextToken(); + token.Trim(true); + token.Trim(false); + + if (result != wxT("")) + result = result + wxChar('|'); + + if (MacroDictionary::GetInstance()->SearchSynonymous(token, translation)) + result += translation; + else + result += token; + } + wxMessageBox(wxT("Despues: ") + result); + return result; } -wxString TypeConv::TextToString(const wxString &str) +wxString TypeConv::TextToString(const wxString& str) { - wxString result; - - for (unsigned int i=0 ; i < str.length() ; i++) - { - wxChar c = str[i]; - if ( c == wxT('\\') ) - { - if (i < str.length() - 1) - { - wxChar next = str[i+1]; - - switch (next) - { - case wxT('n'): result += wxT('\n'); - i++; - break; - - case wxT('t'): result += wxT('\t'); - i++; - break; - - case wxT('r'): result += wxT('\r'); - i++; - break; - - case wxT('\\'): result += wxT('\\'); - i++; - break; - } - } - } - else - result += c; - } - - return result; + wxString result; + + for (unsigned int i = 0; i < str.length(); i++) { + wxChar c = str[i]; + if (c == wxT('\\')) { + if (i < str.length() - 1) { + wxChar next = str[i + 1]; + + switch (next) { + case wxT('n'): + result += wxT('\n'); + i++; + break; + + case wxT('t'): + result += wxT('\t'); + i++; + break; + + case wxT('r'): + result += wxT('\r'); + i++; + break; + + case wxT('\\'): + result += wxT('\\'); + i++; + break; + } + } + } else + result += c; + } + + return result; } -wxString TypeConv::StringToText(const wxString &str) +wxString TypeConv::StringToText(const wxString& str) { - wxString result; - - for (unsigned int i=0 ; i < str.length() ; i++) - { - wxChar c = str[i]; - - switch (c) - { - case wxT('\n'): result += wxT("\\n"); - break; - - case wxT('\t'): result += wxT("\\t"); - break; - - case wxT('\r'): result += wxT("\\r"); - break; - - case wxT('\\'): result += wxT("\\\\"); - break; - - default: - result += c; - break; - } - } - return result; + wxString result; + + for (unsigned int i = 0; i < str.length(); i++) { + wxChar c = str[i]; + + switch (c) { + case wxT('\n'): + result += wxT("\\n"); + break; + + case wxT('\t'): + result += wxT("\\t"); + break; + + case wxT('\r'): + result += wxT("\\r"); + break; + + case wxT('\\'): + result += wxT("\\\\"); + break; + + default: + result += c; + break; + } + } + return result; } -double TypeConv::StringToFloat( const wxString& str ) +double TypeConv::StringToFloat(const wxString& str) { - // Numbers are stored in "C" locale - LocaleSwitcher switcher; + // Numbers are stored in "C" locale + LocaleSwitcher switcher; - double out; - str.ToDouble( &out ); - return out; + double out; + str.ToDouble(&out); + return out; } -wxString TypeConv::FloatToString( const double& val ) +wxString TypeConv::FloatToString(const double& val) { - // Numbers are stored in "C" locale - LocaleSwitcher switcher; + // Numbers are stored in "C" locale + LocaleSwitcher switcher; - wxString convert; - convert << val; - return convert; + wxString convert; + convert << val; + return convert; } /////////////////////////////////////////////////////////////////////////////// @@ -1102,44 +1005,41 @@ PMacroDictionary MacroDictionary::s_instance = 0; PMacroDictionary MacroDictionary::GetInstance() { - if ( 0 == s_instance ) - { - s_instance = new MacroDictionary(); - } + if (0 == s_instance) { + s_instance = new MacroDictionary(); + } - return s_instance; + return s_instance; } void MacroDictionary::Destroy() { - delete s_instance; - s_instance = 0; + delete s_instance; + s_instance = 0; } -bool MacroDictionary::SearchMacro(wxString name, int *result) +bool MacroDictionary::SearchMacro(wxString name, int* result) { - bool found = false; - MacroMap::iterator it = m_map.find(name); - if (it != m_map.end()) - { - found = true; - *result = it->second; - } - - return found; + bool found = false; + MacroMap::iterator it = m_map.find(name); + if (it != m_map.end()) { + found = true; + *result = it->second; + } + + return found; } bool MacroDictionary::SearchSynonymous(wxString synName, wxString& result) { - bool found = false; - SynMap::iterator it = m_synMap.find(synName); - if (it != m_synMap.end()) - { - found = true; - result = it->second; - } - - return found; + bool found = false; + SynMap::iterator it = m_synMap.find(synName); + if (it != m_synMap.end()) { + found = true; + result = it->second; + } + + return found; } /* #define MACRO(x) m_map.insert(MacroMap::value_type(#x,x)) @@ -1147,16 +1047,16 @@ bool MacroDictionary::SearchSynonymous(wxString synName, wxString& result) void MacroDictionary::AddMacro(wxString name, int value) { - m_map.insert(MacroMap::value_type(name,value)); + m_map.insert(MacroMap::value_type(name, value)); } void MacroDictionary::AddSynonymous(wxString synName, wxString name) { - m_synMap.insert(SynMap::value_type(synName, name)); + m_synMap.insert(SynMap::value_type(synName, name)); } MacroDictionary::MacroDictionary() { - // Las macros serán incluidas en las bibliotecas de componentes... - // Sizers macros + // Las macros serán incluidas en las bibliotecas de componentes... + // Sizers macros } diff --git a/src/utils/typeconv.h b/src/utils/typeconv.h index 8c036c6bf..d2dae444f 100644 --- a/src/utils/typeconv.h +++ b/src/utils/typeconv.h @@ -26,83 +26,86 @@ #ifndef UTILS_TYPECONV_H #define UTILS_TYPECONV_H -#include "model/types.h" #include +#include "model/types.h" + + // macros para la conversión entre wxString <-> wxString -#define _WXSTR(x) TypeConv::_StringToWxString(x) +#define _WXSTR(x) TypeConv::_StringToWxString(x) #define _STDSTR(x) TypeConv::_WxStringToString(x) #define _ANSISTR(x) TypeConv::_WxStringToAnsiString(x) + namespace TypeConv { - wxString _StringToWxString( const std::string &str ); - wxString _StringToWxString( const char *str ); - std::string _WxStringToString( const wxString &str ); - std::string _WxStringToAnsiString( const wxString & str ); +wxString _StringToWxString(const std::string& str); +wxString _StringToWxString(const char* str); +std::string _WxStringToString(const wxString& str); +std::string _WxStringToAnsiString(const wxString& str); - wxPoint StringToPoint( const wxString &str ); - bool StringToPoint( const wxString &str, wxPoint *point ); - wxSize StringToSize( const wxString &str ); +wxPoint StringToPoint(const wxString& str); +bool StringToPoint(const wxString& str, wxPoint* point); +wxSize StringToSize(const wxString& str); - wxString PointToString( const wxPoint &point ); - wxString SizeToString( const wxSize &size ); +wxString PointToString(const wxPoint& point); +wxString SizeToString(const wxSize& size); - int BitlistToInt( const wxString &str ); - int GetMacroValue( const wxString &str ); - int StringToInt( const wxString &str ); +int BitlistToInt(const wxString& str); +int GetMacroValue(const wxString& str); +int StringToInt(const wxString& str); - bool FlagSet( const wxString &flag, const wxString ¤tValue ); - wxString ClearFlag( const wxString &flag, const wxString ¤tValue ); - wxString SetFlag( const wxString &flag, const wxString ¤tValue ); +bool FlagSet(const wxString& flag, const wxString& currentValue); +wxString ClearFlag(const wxString& flag, const wxString& currentValue); +wxString SetFlag(const wxString& flag, const wxString& currentValue); - wxBitmap StringToBitmap( const wxString& filename ); +wxBitmap StringToBitmap(const wxString& filename); - wxFontContainer StringToFont( const wxString &str ); - wxString FontToString( const wxFontContainer &font ); - wxString FontFamilyToString(wxFontFamily family); - wxString FontStyleToString(wxFontStyle style); - wxString FontWeightToString(wxFontWeight weight); +wxFontContainer StringToFont(const wxString& str); +wxString FontToString(const wxFontContainer& font); +wxString FontFamilyToString(wxFontFamily family); +wxString FontStyleToString(wxFontStyle style); +wxString FontWeightToString(wxFontWeight weight); - wxColour StringToColour( const wxString &str ); - wxSystemColour StringToSystemColour( const wxString& str ); - wxString ColourToString( const wxColour &colour ); - wxString SystemColourToString( long colour ); +wxColour StringToColour(const wxString& str); +wxSystemColour StringToSystemColour(const wxString& str); +wxString ColourToString(const wxColour& colour); +wxString SystemColourToString(long colour); - bool StringToBool( const wxString &str ); - wxString BoolToString( bool val ); +bool StringToBool(const wxString& str); +wxString BoolToString(bool val); - wxArrayString StringToArrayString( const wxString &str ); - wxString ArrayStringToString( const wxArrayString &arrayStr ); +wxArrayString StringToArrayString(const wxString& str); +wxString ArrayStringToString(const wxArrayString& arrayStr); - void ParseBitmapWithResource( const wxString& value, wxString* image, wxString* source, wxSize* icoSize ); +void ParseBitmapWithResource(const wxString& value, wxString* image, wxString* source, wxSize* icoSize); - /** - @internal - Used to import old projects. - */ - wxArrayString OldStringToArrayString( const wxString& str ); +/** +@internal +Used to import old projects. +*/ +wxArrayString OldStringToArrayString(const wxString& str); - wxString ReplaceSynonymous( const wxString &bitlist ); +wxString ReplaceSynonymous(const wxString& bitlist); - void SplitFileSystemURL( const wxString& url, wxString* protocol, wxString* path, wxString* anchor ); +void SplitFileSystemURL(const wxString& url, wxString* protocol, wxString* path, wxString* anchor); - // Obtiene la ruta absoluta de un archivo - wxString MakeAbsolutePath( const wxString& filename, const wxString& basePath ); - wxString MakeAbsoluteURL( const wxString& url, const wxString& basePath ); +// Obtiene la ruta absoluta de un archivo +wxString MakeAbsolutePath(const wxString& filename, const wxString& basePath); +wxString MakeAbsoluteURL(const wxString& url, const wxString& basePath); - // Obtiene la ruta relativa de un archivo - wxString MakeRelativePath( const wxString& filename, const wxString& basePath ); - wxString MakeRelativeURL( const wxString& url, const wxString& basePath ); +// Obtiene la ruta relativa de un archivo +wxString MakeRelativePath(const wxString& filename, const wxString& basePath); +wxString MakeRelativeURL(const wxString& url, const wxString& basePath); - // dada una cadena de caracteres obtiene otra transformando los caracteres - // especiales denotados al estilo C ('\n' '\\' '\t') - wxString StringToText( const wxString &str ); - wxString TextToString( const wxString &str ); +// dada una cadena de caracteres obtiene otra transformando los caracteres +// especiales denotados al estilo C ('\n' '\\' '\t') +wxString StringToText(const wxString& str); +wxString TextToString(const wxString& str); - double StringToFloat( const wxString& str ); - wxString FloatToString( const double& val ); -} +double StringToFloat(const wxString& str); +wxString FloatToString(const double& val); +} // namespace TypeConv // No me gusta nada tener que usar variables globales o singletons @@ -114,23 +117,23 @@ typedef MacroDictionary* PMacroDictionary; class MacroDictionary { private: - typedef std::map MacroMap; - static PMacroDictionary s_instance; + typedef std::map MacroMap; + static PMacroDictionary s_instance; - typedef std::map SynMap; + typedef std::map SynMap; - MacroMap m_map; - SynMap m_synMap; + MacroMap m_map; + SynMap m_synMap; - MacroDictionary(); + MacroDictionary(); public: - static PMacroDictionary GetInstance(); - static void Destroy(); - bool SearchMacro( wxString name, int *result ); - void AddMacro( wxString name, int value ); - void AddSynonymous( wxString synName, wxString name ); - bool SearchSynonymous( wxString synName, wxString& result ); + static PMacroDictionary GetInstance(); + static void Destroy(); + bool SearchMacro(wxString name, int* result); + void AddMacro(wxString name, int value); + void AddSynonymous(wxString synName, wxString name); + bool SearchSynonymous(wxString synName, wxString& result); }; -#endif // UTILS_TYPECONV_H +#endif // UTILS_TYPECONV_H diff --git a/src/utils/wxfbdefs.h b/src/utils/wxfbdefs.h index e9afc3139..e8660458e 100644 --- a/src/utils/wxfbdefs.h +++ b/src/utils/wxfbdefs.h @@ -27,8 +27,10 @@ #include #include #include + #include + class ObjectBase; class ObjectInfo; class ObjectPackage; @@ -50,27 +52,27 @@ class StringCodeWriter; typedef std::shared_ptr POptionList; typedef std::shared_ptr PObjectBase; -typedef std::weak_ptr WPObjectBase; -typedef std::shared_ptr PObjectPackage; -typedef std::weak_ptr WPObjectPackage; +typedef std::weak_ptr WPObjectBase; +typedef std::shared_ptr PObjectPackage; +typedef std::weak_ptr WPObjectPackage; -typedef std::shared_ptr PCodeInfo; -typedef std::shared_ptr PObjectInfo; -typedef std::shared_ptr PProperty; +typedef std::shared_ptr PCodeInfo; +typedef std::shared_ptr PObjectInfo; +typedef std::shared_ptr PProperty; typedef std::shared_ptr PPropertyInfo; -typedef std::shared_ptr PEventInfo; -typedef std::shared_ptr PEvent; +typedef std::shared_ptr PEventInfo; +typedef std::shared_ptr PEvent; typedef std::shared_ptr PPropertyCategory; typedef std::map PropertyInfoMap; -typedef std::map ObjectInfoMap; -typedef std::map EventInfoMap; -typedef std::map PropertyMap; -typedef std::map EventMap; +typedef std::map ObjectInfoMap; +typedef std::map EventInfoMap; +typedef std::map PropertyMap; +typedef std::map EventMap; typedef std::vector ObjectBaseVector; -typedef std::vector EventVector; +typedef std::vector EventVector; typedef std::shared_ptr PwxFBManager; typedef std::shared_ptr PCodeWriter; @@ -78,7 +80,10 @@ typedef std::shared_ptr PTemplateParser; typedef std::shared_ptr PTCCodeWriter; typedef std::shared_ptr PStringCodeWriter; -// Flatnotebook styles are stored in config, if style #defines change, or config is manually modified, these style overrides still apply -#define FNB_STYLE_OVERRIDES( x ) ( x | wxFNB_CUSTOM_DLG | wxFNB_NO_X_BUTTON ) & ( ~wxFNB_X_ON_TAB & ~wxFNB_MOUSE_MIDDLE_CLOSES_TABS & ~wxFNB_DCLICK_CLOSES_TABS & ~wxFNB_ALLOW_FOREIGN_DND ) +// Flatnotebook styles are stored in config, if style #defines change, or config is manually modified, these style +// overrides still apply +#define FNB_STYLE_OVERRIDES(x) \ + (x | wxFNB_CUSTOM_DLG | wxFNB_NO_X_BUTTON) & \ + (~wxFNB_X_ON_TAB & ~wxFNB_MOUSE_MIDDLE_CLOSES_TABS & ~wxFNB_DCLICK_CLOSES_TABS & ~wxFNB_ALLOW_FOREIGN_DND) -#endif // UTILS_WXFBDEFS_H +#endif // UTILS_WXFBDEFS_H diff --git a/src/utils/wxfbexception.h b/src/utils/wxfbexception.h index d2401fe63..56ab0a23d 100644 --- a/src/utils/wxfbexception.h +++ b/src/utils/wxfbexception.h @@ -21,6 +21,7 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef UITILS_WXFBEXCEPTION_H #define UITILS_WXFBEXCEPTION_H @@ -32,34 +33,28 @@ Exception class for wxFormBuilder class wxFBException { public: - explicit wxFBException( const wxString& what ) - : - m_what(what) - {} + explicit wxFBException(const wxString& what) : m_what(what) {} - virtual ~wxFBException() = default; + virtual ~wxFBException() = default; - virtual const wxChar* what() const throw() - { - return m_what.c_str(); - } + virtual const wxChar* what() const throw() { return m_what.c_str(); } private: - wxString m_what; + wxString m_what; }; /** This allows you to stream your exceptions in. It will take care of the conversion and throwing the exception. */ -#define THROW_WXFBEX( message ) \ - { \ - wxString hopefullyThisNameWontConflictWithOtherVariables; \ - wxString hopefullyUniqueFile(__FILE__, wxConvUTF8); \ - hopefullyUniqueFile = hopefullyUniqueFile.substr(hopefullyUniqueFile.find_last_of(wxT("\\/")) + 1); \ - hopefullyThisNameWontConflictWithOtherVariables << message << wxT(" <") << hopefullyUniqueFile << wxT("@"); \ - hopefullyThisNameWontConflictWithOtherVariables << wxString::Format( wxT("%i"), __LINE__ ) << wxT(">"); \ - throw wxFBException( hopefullyThisNameWontConflictWithOtherVariables ); \ - } +#define THROW_WXFBEX(message) \ + { \ + wxString hopefullyThisNameWontConflictWithOtherVariables; \ + wxString hopefullyUniqueFile(__FILE__, wxConvUTF8); \ + hopefullyUniqueFile = hopefullyUniqueFile.substr(hopefullyUniqueFile.find_last_of(wxT("\\/")) + 1); \ + hopefullyThisNameWontConflictWithOtherVariables << message << wxT(" <") << hopefullyUniqueFile << wxT("@"); \ + hopefullyThisNameWontConflictWithOtherVariables << wxString::Format(wxT("%i"), __LINE__) << wxT(">"); \ + throw wxFBException(hopefullyThisNameWontConflictWithOtherVariables); \ + } -#endif // UITILS_WXFBEXCEPTION_H +#endif // UITILS_WXFBEXCEPTION_H diff --git a/src/utils/wxfbipc.cpp b/src/utils/wxfbipc.cpp index 8021ddeec..b22cf32b0 100644 --- a/src/utils/wxfbipc.cpp +++ b/src/utils/wxfbipc.cpp @@ -24,218 +24,196 @@ #include "wxfbipc.h" +#include +#include + #include "utils/debug.h" -#include -#include -bool wxFBIPC::VerifySingleInstance( const wxString& file, bool switchTo ) +bool wxFBIPC::VerifySingleInstance(const wxString& file, bool switchTo) { - // Possible send a message to the running instance through this string later, for now it is left empty - wxString expression = wxEmptyString; - - // Make path absolute - wxFileName path( file ); - if ( !path.IsOk() ) - { - wxLogError( wxT("This path is invalid: %s"), file ); - return false; - } - - if ( !path.IsAbsolute() ) - { - if ( !path.MakeAbsolute() ) - { - wxLogError( wxT("Could not make path absolute: %s"), file ); - return false; - } - } - - // Check for single instance - - // Create lockfile/mutex name - wxString name = wxString::Format( wxT("wxFormBuilder-%s-%s"), wxGetUserId(), path.GetFullPath() ); - - // Get forbidden characters - wxString forbidden = wxFileName::GetForbiddenChars(); - - // Replace forbidded characters - for ( size_t c = 0; c < forbidden.Length(); ++c ) - { - wxString bad( forbidden.GetChar( c ) ); - name.Replace( bad, wxT("_") ); - } - - // Paths are not case sensitive in windows - #ifdef __WXMSW__ - name = name.MakeLower(); - #endif - - // GetForbiddenChars is missing "/" in unix. Prepend '.' to make lockfiles hidden - #ifndef __WXMSW__ - name.Replace( wxT("/"), wxT("_") ); - name.Prepend( wxT(".") ); - #endif - - // Check to see if I already have a server with this name - if so, no need to make another! - if (m_server) { - if ( m_server->m_name == name ) - { - return true; - } - } - - std::unique_ptr checker; + // Possible send a message to the running instance through this string later, for now it is left empty + wxString expression = wxEmptyString; + + // Make path absolute + wxFileName path(file); + if (!path.IsOk()) { + wxLogError(wxT("This path is invalid: %s"), file); + return false; + } + + if (!path.IsAbsolute()) { + if (!path.MakeAbsolute()) { + wxLogError(wxT("Could not make path absolute: %s"), file); + return false; + } + } + + // Check for single instance + + // Create lockfile/mutex name + wxString name = wxString::Format(wxT("wxFormBuilder-%s-%s"), wxGetUserId(), path.GetFullPath()); + + // Get forbidden characters + wxString forbidden = wxFileName::GetForbiddenChars(); + + // Replace forbidded characters + for (size_t c = 0; c < forbidden.Length(); ++c) { + wxString bad(forbidden.GetChar(c)); + name.Replace(bad, wxT("_")); + } + +// Paths are not case sensitive in windows +#ifdef __WXMSW__ + name = name.MakeLower(); +#endif + +// GetForbiddenChars is missing "/" in unix. Prepend '.' to make lockfiles hidden +#ifndef __WXMSW__ + name.Replace(wxT("/"), wxT("_")); + name.Prepend(wxT(".")); +#endif + + // Check to see if I already have a server with this name - if so, no need to make another! + if (m_server) { + if (m_server->m_name == name) { + return true; + } + } + + std::unique_ptr checker; { - // Suspend logging, because error messages here are not useful - #ifndef __WXFB_DEBUG__ +// Suspend logging, because error messages here are not useful +#ifndef __WXFB_DEBUG__ wxLogNull stopLogging; - #endif - checker.reset( new wxSingleInstanceChecker( name ) ); +#endif + checker.reset(new wxSingleInstanceChecker(name)); } - if ( !checker->IsAnotherRunning() ) - { - // This is the first instance of this project, so setup a server and save the single instance checker - if ( CreateServer( name ) ) - { - m_checker = std::move(checker); - return true; - } - else - { - return false; - } - } - else if ( switchTo ) - { - // Suspend logging, because error messages here are not useful - #ifndef __WXFB_DEBUG__ - wxLogNull stopLogging; - #endif - - // There is another app, so connect and send the expression - - // Cannot have a client and a server at the same time, due to the implementation of wxTCPServer and wxTCPClient, - // so temporarily drop the server if there is one - bool hadServer = false; - wxString oldName; - if (m_server) { - oldName = m_server->m_name; - m_server.reset(); - hadServer = true; - } - - // Create the client - std::unique_ptr client(new AppClient); - - // Create the connection - std::unique_ptr connection; - #ifdef __WXMSW__ - connection.reset( client->MakeConnection( wxT("localhost"), name, name ) ); - #else - bool connected = false; - for ( int i = m_port; i < m_port + 20; ++i ) - { - wxString sPort = wxString::Format( "%i", i ); - connection.reset( client->MakeConnection( "localhost", sPort, name ) ); - if (connection) { - connected = true; - wxChar* pid = (wxChar*)connection->Request( wxT("PID"), NULL ); - if ( NULL != pid ) - { - wxLogStatus( wxT("%s already open in process %s"), file, pid ); - } - break; - } - } - if ( !connected ) - { - wxLogError( wxT("There is a lockfile named '%s', but unable to make a connection to that instance."), name ); - } - #endif - - // Drop the connection and client - connection.reset(); - client.reset(); - - // Create the server again, if necessary - if ( hadServer ) - { - CreateServer( oldName ); - } + if (!checker->IsAnotherRunning()) { + // This is the first instance of this project, so setup a server and save the single instance checker + if (CreateServer(name)) { + m_checker = std::move(checker); + return true; + } else { + return false; + } + } else if (switchTo) { +// Suspend logging, because error messages here are not useful +#ifndef __WXFB_DEBUG__ + wxLogNull stopLogging; +#endif + + // There is another app, so connect and send the expression + + // Cannot have a client and a server at the same time, due to the implementation of wxTCPServer and wxTCPClient, + // so temporarily drop the server if there is one + bool hadServer = false; + wxString oldName; + if (m_server) { + oldName = m_server->m_name; + m_server.reset(); + hadServer = true; + } + + // Create the client + std::unique_ptr client(new AppClient); + + // Create the connection + std::unique_ptr connection; +#ifdef __WXMSW__ + connection.reset(client->MakeConnection(wxT("localhost"), name, name)); +#else + bool connected = false; + for (int i = m_port; i < m_port + 20; ++i) { + wxString sPort = wxString::Format("%i", i); + connection.reset(client->MakeConnection("localhost", sPort, name)); + if (connection) { + connected = true; + wxChar* pid = (wxChar*)connection->Request(wxT("PID"), NULL); + if (NULL != pid) { + wxLogStatus(wxT("%s already open in process %s"), file, pid); + } + break; + } + } + if (!connected) { + wxLogError(wxT("There is a lockfile named '%s', but unable to make a connection to that instance."), name); + } +#endif + + // Drop the connection and client + connection.reset(); + client.reset(); + + // Create the server again, if necessary + if (hadServer) { + CreateServer(oldName); + } } return false; } -bool wxFBIPC::CreateServer( const wxString& name ) +bool wxFBIPC::CreateServer(const wxString& name) { - // Suspend logging, because error messages here are not useful - #ifndef __WXFB_DEBUG__ - wxLogNull stopLogging; - #endif - - auto server = std::make_unique(name); - - #ifdef __WXMSW__ - if ( server->Create( name ) ) - { - m_server = std::move(server); - return true; - } - #else - { - for ( int i = m_port; i < m_port + 20; ++i ) - { - wxString nameWithPort = wxString::Format( wxT("%i%s"), i, name ); - if( server->Create( nameWithPort ) ) - { - m_server = std::move(server); - return true; - } - else - { - LogDebug( "Server Creation Failed. " + nameWithPort ); - } - } - } - #endif - - wxLogError( wxT("Failed to create an IPC service with name %s"), name ); - return false; +// Suspend logging, because error messages here are not useful +#ifndef __WXFB_DEBUG__ + wxLogNull stopLogging; +#endif + + auto server = std::make_unique(name); + +#ifdef __WXMSW__ + if (server->Create(name)) { + m_server = std::move(server); + return true; + } +#else + { + for (int i = m_port; i < m_port + 20; ++i) { + wxString nameWithPort = wxString::Format(wxT("%i%s"), i, name); + if (server->Create(nameWithPort)) { + m_server = std::move(server); + return true; + } else { + LogDebug("Server Creation Failed. " + nameWithPort); + } + } + } +#endif + + wxLogError(wxT("Failed to create an IPC service with name %s"), name); + return false; } void wxFBIPC::Reset() { - m_server.reset(); - m_checker.reset(); + m_server.reset(); + m_checker.reset(); } -wxConnectionBase* AppServer::OnAcceptConnection( const wxString& topic ) +wxConnectionBase* AppServer::OnAcceptConnection(const wxString& topic) { - if ( topic == m_name ) - { - wxFrame* frame = wxDynamicCast( wxTheApp->GetTopWindow(), wxFrame ); - if ( !frame ) - { - return NULL; - } - frame->Enable(); - - if ( frame->IsIconized() ) - { - frame->Iconize( false ); - } - - frame->Raise(); - - return new AppConnection; - } - - return NULL; + if (topic == m_name) { + wxFrame* frame = wxDynamicCast(wxTheApp->GetTopWindow(), wxFrame); + if (!frame) { + return NULL; + } + frame->Enable(); + + if (frame->IsIconized()) { + frame->Iconize(false); + } + + frame->Raise(); + + return new AppConnection; + } + + return NULL; } wxConnectionBase* AppClient::OnMakeConnection() { - return new AppConnection; + return new AppConnection; } diff --git a/src/utils/wxfbipc.h b/src/utils/wxfbipc.h index a01889039..35bcc6b85 100644 --- a/src/utils/wxfbipc.h +++ b/src/utils/wxfbipc.h @@ -21,63 +21,62 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef UTILS_WXFBIPC_H #define UTILS_WXFBIPC_H -#include #include + +#include #include + /* Only allow one instance of a project to be loaded at a time */ class AppServer; class wxFBIPC { - private: - std::unique_ptr m_checker; - std::unique_ptr m_server; - const int m_port; - - bool CreateServer( const wxString& name ); - - public: - wxFBIPC() - : - m_port( 4242 ) - { - } - - bool VerifySingleInstance( const wxString& file, bool switchTo = true ); - void Reset(); +private: + std::unique_ptr m_checker; + std::unique_ptr m_server; + const int m_port; + + bool CreateServer(const wxString& name); + +public: + wxFBIPC() : m_port(4242) {} + + bool VerifySingleInstance(const wxString& file, bool switchTo = true); + void Reset(); }; // Connection class, for use by both communicationg instances -class AppConnection: public wxConnection +class AppConnection : public wxConnection { private: - wxString m_data; + wxString m_data; public: - AppConnection(){} + AppConnection() {} }; // Server class, for listening to connection requests -class AppServer: public wxServer +class AppServer : public wxServer { public: - const wxString m_name; + const wxString m_name; - AppServer( const wxString& name ) : m_name( name ){} - wxConnectionBase* OnAcceptConnection(const wxString& topic) override; + AppServer(const wxString& name) : m_name(name) {} + wxConnectionBase* OnAcceptConnection(const wxString& topic) override; }; // Client class, to be used by subsequent instances in OnInit -class AppClient: public wxClient +class AppClient : public wxClient { public: - AppClient(){} - wxConnectionBase* OnMakeConnection() override; + AppClient() {} + wxConnectionBase* OnMakeConnection() override; }; -#endif // UTILS_WXFBIPC_H +#endif // UTILS_WXFBIPC_H diff --git a/src/utils/wxlogstring.h b/src/utils/wxlogstring.h index f8e3197fc..ae906207a 100644 --- a/src/utils/wxlogstring.h +++ b/src/utils/wxlogstring.h @@ -21,32 +21,34 @@ // Ryan Mulder - rjmyst3@gmail.com // /////////////////////////////////////////////////////////////////////////////// + #ifndef UTILS_WXLOGSTRING_H #define UTILS_WXLOGSTRING_H #include -class wxLogString : public wxLog { + +class wxLogString : public wxLog +{ public: - wxLogString() { - } + wxLogString() {} - void DoLogString(const wxChar* str, time_t t) { - m_str += str; - m_str += wxT("\n"); - } + void DoLogString(const wxChar* str, time_t t) + { + m_str += str; + m_str += wxT("\n"); + } - void FlushStr(wxString& str) { - str = m_str; - m_str.clear(); - } + void FlushStr(wxString& str) + { + str = m_str; + m_str.clear(); + } - wxString GetStr() const { - return m_str; - } + wxString GetStr() const { return m_str; } private: - wxString m_str; + wxString m_str; }; -#endif // UTILS_WXLOGSTRING_H +#endif // UTILS_WXLOGSTRING_H