From 57375ce7c2374893a25957c688fe4c83a81c5f48 Mon Sep 17 00:00:00 2001 From: wmayer Date: Sun, 3 Oct 2021 16:45:45 +0200 Subject: [PATCH] Gui: [skip ci] add Gui::cmdAppDocumentArgs and support further string types with FormatString::str --- src/Gui/CommandT.h | 49 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/src/Gui/CommandT.h b/src/Gui/CommandT.h index ee29102d9f..64154d8cca 100644 --- a/src/Gui/CommandT.h +++ b/src/Gui/CommandT.h @@ -30,6 +30,7 @@ #include #include #include +#include #include namespace Gui { @@ -40,11 +41,24 @@ public: static std::string str(const std::string& s) { return s; } + static std::string str(const char* s) { + return s; + } + static std::string str(const QString& s) { + return s.toStdString(); + } static std::string str(const std::stringstream& s) { return s.str(); } + static std::string str(const std::ostringstream& s) { + return s.str(); + } static std::string str(const std::ostream& s) { - return dynamic_cast(s).str(); + if (typeid(s) == typeid(std::ostringstream)) + return dynamic_cast(s).str(); + else if (typeid(s) == typeid(std::stringstream)) + return dynamic_cast(s).str(); + throw Base::TypeError("Not a std::stringstream or std::ostringstream"); } static std::string toStr(boost::format& f) { return f.str(); @@ -152,6 +166,39 @@ inline void cmdAppDocument(const App::DocumentObject* obj, T&& cmd) { _cmdDocument(Gui::Command::Doc, obj, "App", std::forward(cmd)); } +/** Runs a command for accessing a document's attribute or method + * @param doc: pointer to a Document + * @param cmd: command string, supporting printf like formatter + * + * Example: + * @code{.cpp} + * cmdAppDocumentArgs(obj, "addObject('%s')", "Part::Feature"); + * @endcode + * + * Translates to command (assuming obj's document name is 'DocName': + * @code{.py} + * App.getDocument('DocName').addObject('Part::Feature') + * @endcode + */ +template +void cmdAppDocumentArgs(const App::Document* doc, const std::string& cmd, Args&&... args) { + std::string _cmd; + try { + boost::format fmt(cmd); + _cmd = FormatString::toStr(fmt, std::forward(args)...); + Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument('%s').%s", + doc->getName(), _cmd.c_str()); + } + catch (const std::exception& e) { + Base::Console().Error("%s: %s\n", e.what(), cmd.c_str()); + } + catch (const Base::Exception&) { + Base::Console().Error("App.getDocument('%s').%s\n", + doc->getName(), _cmd.c_str()); + throw; + } +} + /** Runs a command for accessing an object's Gui::Document attribute or method * This function is an alternative to FCMD_VOBJ_DOC_CMD * @param obj: pointer to a DocumentObject