diff --git a/src/Gui/Application.cpp b/src/Gui/Application.cpp index 89793a71cc..d4f5b34ce0 100644 --- a/src/Gui/Application.cpp +++ b/src/Gui/Application.cpp @@ -23,22 +23,22 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# 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 #endif #include @@ -140,35 +140,42 @@ namespace sp = std::placeholders; Application* Application::Instance = nullptr; -namespace Gui { +namespace Gui +{ -class ViewProviderMap { - std::unordered_map map; +class ViewProviderMap +{ + std::unordered_map map; public: void newObject(const ViewProvider& vp) { auto vpd = Base::freecad_dynamic_cast(const_cast(&vp)); - if (vpd && vpd->getObject()) + if (vpd && vpd->getObject()) { map[vpd->getObject()] = vpd; + } } void deleteObject(const ViewProvider& vp) { auto vpd = Base::freecad_dynamic_cast(const_cast(&vp)); - if (vpd && vpd->getObject()) + if (vpd && vpd->getObject()) { map.erase(vpd->getObject()); + } } - void deleteDocument(const App::Document& doc) { - for (auto obj : doc.getObjects()) + void deleteDocument(const App::Document& doc) + { + for (auto obj : doc.getObjects()) { map.erase(obj); + } } Gui::ViewProvider* getViewProvider(const App::DocumentObject* obj) const { auto it = map.find(obj); - if (it == map.end()) + if (it == map.end()) { return nullptr; + } return it->second; } }; @@ -179,10 +186,12 @@ struct ApplicationP explicit ApplicationP(bool GUIenabled) { // create the macro manager - if (GUIenabled) + if (GUIenabled) { macroMngr = new MacroManager(); - else + } + else { macroMngr = nullptr; + } // Create the Theme Manager prefPackManager = new PreferencePackManager(); @@ -197,34 +206,33 @@ struct ApplicationP /// list of all handled documents std::map documents; /// Active document - Gui::Document* activeDocument{nullptr}; - Gui::Document* editDocument{nullptr}; - MacroManager* macroMngr; + Gui::Document* activeDocument {nullptr}; + Gui::Document* editDocument {nullptr}; + MacroManager* macroMngr; PreferencePackManager* prefPackManager; /// List of all registered views std::list passive; - bool isClosing{false}; - bool startingUp{true}; + bool isClosing {false}; + bool startingUp {true}; /// Handles all commands CommandManager commandManager; ViewProviderMap viewproviderMap; std::bitset<32> StatusBits; }; -static PyObject * -FreeCADGui_subgraphFromObject(PyObject * /*self*/, PyObject *args) +static PyObject* FreeCADGui_subgraphFromObject(PyObject* /*self*/, PyObject* args) { - PyObject *o; - if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type), &o)) + PyObject* o; + if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &o)) { return nullptr; + } App::DocumentObject* obj = static_cast(o)->getDocumentObjectPtr(); std::string vp = obj->getViewProviderName(); SoNode* node = nullptr; try { auto base = static_cast(Base::Type::createInstanceByName(vp.c_str(), true)); - if (base - && base->isDerivedFrom()) { + if (base && base->isDerivedFrom()) { std::unique_ptr vp( static_cast(base)); std::map Map; @@ -242,8 +250,9 @@ FreeCADGui_subgraphFromObject(PyObject * /*self*/, PyObject *args) } std::vector modes = vp->getDisplayModes(); - if (!modes.empty()) + if (!modes.empty()) { vp->setDisplayMode(modes.front().c_str()); + } node = vp->getRoot()->copy(); node->ref(); std::string prefix = "So"; @@ -258,13 +267,17 @@ FreeCADGui_subgraphFromObject(PyObject * /*self*/, PyObject *args) type += " *"; PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj( - "pivy.coin", type.c_str(), static_cast(node), 1); + proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", + type.c_str(), + static_cast(node), + 1); return Py::new_reference_to(Py::Object(proxy, true)); } } catch (const Base::Exception& e) { - if (node) node->unref(); + if (node) { + node->unref(); + } PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr; } @@ -273,14 +286,14 @@ FreeCADGui_subgraphFromObject(PyObject * /*self*/, PyObject *args) return Py_None; } -static PyObject * -FreeCADGui_exportSubgraph(PyObject * /*self*/, PyObject *args) +static PyObject* FreeCADGui_exportSubgraph(PyObject* /*self*/, PyObject* args) { const char* format = "VRML"; PyObject* proxy; PyObject* output; - if (!PyArg_ParseTuple(args, "OO|s", &proxy, &output, &format)) + if (!PyArg_ParseTuple(args, "OO|s", &proxy, &output, &format)) { return nullptr; + } void* ptr = nullptr; try { @@ -315,36 +328,42 @@ FreeCADGui_exportSubgraph(PyObject * /*self*/, PyObject *args) } } -static PyObject * -FreeCADGui_getSoDBVersion(PyObject * /*self*/, PyObject *args) +static PyObject* FreeCADGui_getSoDBVersion(PyObject* /*self*/, PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return PyUnicode_FromString(SoDB::getVersion()); } struct PyMethodDef FreeCADGui_methods[] = { - {"subgraphFromObject",FreeCADGui_subgraphFromObject,METH_VARARGS, + {"subgraphFromObject", + FreeCADGui_subgraphFromObject, + METH_VARARGS, "subgraphFromObject(object) -> Node\n\n" "Return the Inventor subgraph to an object"}, - {"exportSubgraph",FreeCADGui_exportSubgraph,METH_VARARGS, + {"exportSubgraph", + FreeCADGui_exportSubgraph, + METH_VARARGS, "exportSubgraph(Node, File or Buffer, [Format='VRML']) -> None\n\n" "Exports the sub-graph in the requested format" "The format string can be VRML or IV"}, - {"getSoDBVersion",FreeCADGui_getSoDBVersion,METH_VARARGS, + {"getSoDBVersion", + FreeCADGui_getSoDBVersion, + METH_VARARGS, "getSoDBVersion() -> String\n\n" "Return a text string containing the name\n" "of the Coin library and version information"}, - {nullptr, nullptr, 0, nullptr} /* sentinel */ + {nullptr, nullptr, 0, nullptr} /* sentinel */ }; -} // namespace Gui +} // namespace Gui Application::Application(bool GUIenabled) { - //App::GetApplication().Attach(this); + // App::GetApplication().Attach(this); if (GUIenabled) { - //NOLINTBEGIN + // NOLINTBEGIN App::GetApplication().signalNewDocument.connect( std::bind(&Gui::Application::slotNewDocument, this, sp::_1, sp::_2)); App::GetApplication().signalDeleteDocument.connect( @@ -357,11 +376,10 @@ Application::Application(bool GUIenabled) std::bind(&Gui::Application::slotRelabelDocument, this, sp::_1)); App::GetApplication().signalShowHidden.connect( std::bind(&Gui::Application::slotShowHidden, this, sp::_1)); - //NOLINTEND + // NOLINTEND // install the last active language - ParameterGrp::handle hPGrp = - App::GetApplication().GetUserParameter().GetGroup("BaseApp"); + ParameterGrp::handle hPGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp"); hPGrp = hPGrp->GetGroup("Preferences")->GetGroup("General"); QString lang = QLocale::languageToString(QLocale().language()); Translator::instance()->activateLanguage( @@ -411,12 +429,15 @@ Application::Application(bool GUIenabled) PyObject* modules = PyImport_GetModuleDict(); PyObject* module = PyDict_GetItemString(modules, "FreeCADGui"); if (!module) { - static struct PyModuleDef FreeCADGuiModuleDef = { - PyModuleDef_HEAD_INIT, - "FreeCADGui", FreeCADGui_doc, -1, - Application::Methods, - nullptr, nullptr, nullptr, nullptr - }; + static struct PyModuleDef FreeCADGuiModuleDef = {PyModuleDef_HEAD_INIT, + "FreeCADGui", + FreeCADGui_doc, + -1, + Application::Methods, + nullptr, + nullptr, + nullptr, + nullptr}; module = PyModule_Create(&FreeCADGuiModuleDef); PyDict_SetItemString(modules, "FreeCADGui", module); @@ -425,11 +446,10 @@ Application::Application(bool GUIenabled) // extend the method list PyModule_AddFunctions(module, Application::Methods); } - Py::Module(module).setAttr(std::string("ActiveDocument"),Py::None()); + Py::Module(module).setAttr(std::string("ActiveDocument"), Py::None()); UiLoaderPy::init_type(); - Base::Interpreter().addType(UiLoaderPy::type_object(), - module,"UiLoader"); + Base::Interpreter().addType(UiLoaderPy::type_object(), module, "UiLoader"); PyResource::init_type(); // PySide additions @@ -437,64 +457,72 @@ Application::Application(bool GUIenabled) ExpressionBindingPy::init_type(); Base::Interpreter().addType(ExpressionBindingPy::type_object(), - module,"ExpressionBinding"); + module, + "ExpressionBinding"); - //insert Selection module - static struct PyModuleDef SelectionModuleDef = { - PyModuleDef_HEAD_INIT, - "Selection", "Selection module", -1, - SelectionSingleton::Methods, - nullptr, nullptr, nullptr, nullptr - }; + // insert Selection module + static struct PyModuleDef SelectionModuleDef = {PyModuleDef_HEAD_INIT, + "Selection", + "Selection module", + -1, + SelectionSingleton::Methods, + nullptr, + nullptr, + nullptr, + nullptr}; PyObject* pSelectionModule = PyModule_Create(&SelectionModuleDef); Py_INCREF(pSelectionModule); PyModule_AddObject(module, "Selection", pSelectionModule); SelectionFilterPy::init_type(); - Base::Interpreter().addType(SelectionFilterPy::type_object(), - pSelectionModule,"Filter"); + Base::Interpreter().addType(SelectionFilterPy::type_object(), pSelectionModule, "Filter"); Gui::TaskView::ControlPy::init_type(); Py::Module(module).setAttr(std::string("Control"), - Py::Object(Gui::TaskView::ControlPy::getInstance(), true)); + Py::Object(Gui::TaskView::ControlPy::getInstance(), true)); Gui::TaskView::TaskDialogPy::init_type(); CommandActionPy::init_type(); - Base::Interpreter().addType(CommandActionPy::type_object(), - module, "CommandAction"); + Base::Interpreter().addType(CommandActionPy::type_object(), module, "CommandAction"); Base::Interpreter().addType(&LinkViewPy::Type, module, "LinkView"); Base::Interpreter().addType(&AxisOriginPy::Type, module, "AxisOrigin"); Base::Interpreter().addType(&CommandPy::Type, module, "Command"); Base::Interpreter().addType(&DocumentPy::Type, module, "Document"); Base::Interpreter().addType(&ViewProviderPy::Type, module, "ViewProvider"); - Base::Interpreter().addType( - &ViewProviderDocumentObjectPy::Type, module, "ViewProviderDocumentObject"); - Base::Interpreter().addType( - &ViewProviderGeometryObjectPy::Type, module, "ViewProviderGeometryObject"); + Base::Interpreter().addType(&ViewProviderDocumentObjectPy::Type, + module, + "ViewProviderDocumentObject"); + Base::Interpreter().addType(&ViewProviderGeometryObjectPy::Type, + module, + "ViewProviderGeometryObject"); Base::Interpreter().addType(&ViewProviderLinkPy::Type, module, "ViewProviderLink"); } Base::PyGILStateLocker lock; - PyObject *module = PyImport_AddModule("FreeCADGui"); - PyMethodDef *meth = FreeCADGui_methods; - PyObject *dict = PyModule_GetDict(module); + PyObject* module = PyImport_AddModule("FreeCADGui"); + PyMethodDef* meth = FreeCADGui_methods; + PyObject* dict = PyModule_GetDict(module); for (; meth->ml_name != nullptr; meth++) { - PyObject *descr; - descr = PyCFunction_NewEx(meth,nullptr,nullptr); - if (!descr) + PyObject* descr; + descr = PyCFunction_NewEx(meth, nullptr, nullptr); + if (!descr) { break; - if (PyDict_SetItemString(dict, meth->ml_name, descr) != 0) + } + if (PyDict_SetItemString(dict, meth->ml_name, descr) != 0) { break; + } Py_DECREF(descr); } SoQtOffscreenRendererPy::init_type(); Base::Interpreter().addType(SoQtOffscreenRendererPy::type_object(), - module,"SoQtOffscreenRenderer"); + module, + "SoQtOffscreenRenderer"); App::Application::Config()["COIN_VERSION"] = COIN_VERSION; + // clang-format off // Python console binding PythonDebugModule ::init_module(); PythonStdout ::init_type(); @@ -507,6 +535,7 @@ Application::Application(bool GUIenabled) View3DInventorPy ::init_type(); View3DInventorViewerPy ::init_type(); AbstractSplitViewPy ::init_type(); + // clang-format on d = new ApplicationP(GUIenabled); @@ -573,9 +602,9 @@ void Application::open(const char* FileName, const char* Module) // in case of an automatically created empty document at startup App::Document* act = App::GetApplication().getActiveDocument(); Gui::Document* gui = this->getDocument(act); - if (act && act->countObjects() == 0 && gui && !gui->isModified()){ + if (act && act->countObjects() == 0 && gui && !gui->isModified()) { Command::doCommand(Command::App, "App.closeDocument('%s')", act->getName()); - qApp->processEvents(); // an update is needed otherwise the new view isn't shown + qApp->processEvents(); // an update is needed otherwise the new view isn't shown } if (Module) { @@ -583,7 +612,7 @@ void Application::open(const char* FileName, const char* Module) if (File.hasExtension("FCStd")) { bool handled = false; std::string filepath = File.filePath(); - for (auto &v : d->documents) { + for (auto& v : d->documents) { auto doc = v.second->getDocument(); std::string fi = Base::FileInfo(doc->FileName.getValue()).filePath(); if (filepath == fi) { @@ -593,9 +622,11 @@ void Application::open(const char* FileName, const char* Module) } } - if (!handled) - Command::doCommand( - Command::App, "FreeCAD.openDocument('%s')", unicodepath.c_str()); + if (!handled) { + Command::doCommand(Command::App, + "FreeCAD.openDocument('%s')", + unicodepath.c_str()); + } } else { // issue module loading @@ -614,10 +645,11 @@ void Application::open(const char* FileName, const char* Module) // ViewFit if (sendHasMsgToActiveView("ViewFit")) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); - if (hGrp->GetBool("AutoFitToView", true)) + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); + if (hGrp->GetBool("AutoFitToView", true)) { Command::doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")"); + } } } @@ -626,14 +658,16 @@ void Application::open(const char* FileName, const char* Module) getMainWindow()->appendRecentFile(filename); FileDialog::setWorkingDirectory(filename); } - catch (const Base::PyException& e){ + catch (const Base::PyException& e) { // Usually thrown if the file is invalid somehow e.ReportException(); } } else { wc.restoreCursor(); - QMessageBox::warning(getMainWindow(), QObject::tr("Unknown filetype"), + QMessageBox::warning( + getMainWindow(), + QObject::tr("Unknown filetype"), QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str()))); wc.setWaitCursor(); return; @@ -656,10 +690,10 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch // load the file with the module if (File.hasExtension("FCStd")) { - Command::doCommand(Command::App, "%s.open(u\"%s\")" - , Module, unicodepath.c_str()); - if (activeDocument()) + Command::doCommand(Command::App, "%s.open(u\"%s\")", Module, unicodepath.c_str()); + if (activeDocument()) { activeDocument()->setModified(false); + } } else { // Open transaction when importing a file @@ -667,23 +701,29 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch bool pendingCommand = false; if (doc) { pendingCommand = doc->hasPendingCommand(); - if (!pendingCommand) + if (!pendingCommand) { doc->openCommand(QT_TRANSLATE_NOOP("Command", "Import")); + } } // check for additional import options std::stringstream str; if (DocName) { str << "if hasattr(" << Module << ", \"importOptions\"):\n" - << " options = " << Module << ".importOptions(u\"" << unicodepath << "\")\n" - << " " << Module << ".insert(u\"" << unicodepath << "\", \"" << DocName << "\", options = options)\n" + << " options = " << Module << ".importOptions(u\"" << unicodepath + << "\")\n" + << " " << Module << ".insert(u\"" << unicodepath << "\", \"" << DocName + << "\", options = options)\n" << "else:\n" - << " " << Module << ".insert(u\"" << unicodepath << "\", \"" << DocName << "\")\n"; + << " " << Module << ".insert(u\"" << unicodepath << "\", \"" << DocName + << "\")\n"; } else { str << "if hasattr(" << Module << ", \"importOptions\"):\n" - << " options = " << Module << ".importOptions(u\"" << unicodepath << "\")\n" - << " " << Module << ".insert(u\"" << unicodepath << "\", options = options)\n" + << " options = " << Module << ".importOptions(u\"" << unicodepath + << "\")\n" + << " " << Module << ".insert(u\"" << unicodepath + << "\", options = options)\n" << "else:\n" << " " << Module << ".insert(u\"" << unicodepath << "\")\n"; } @@ -706,14 +746,15 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch if (doc) { doc->setModified(true); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); if (hGrp->GetBool("AutoFitToView", true)) { MDIView* view = doc->getActiveView(); if (view) { const char* ret = nullptr; - if (view->onMsg("ViewFit", &ret)) + if (view->onMsg("ViewFit", &ret)) { updateActions(true); + } } } } @@ -725,20 +766,22 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch "User parameter:BaseApp/Preferences/General"); bool addToRecent = parameterGroup->GetBool("RecentIncludesImported", true); parameterGroup->SetBool("RecentIncludesImported", - addToRecent);// Make sure it gets added to the parameter list + addToRecent); // Make sure it gets added to the parameter list if (addToRecent) { getMainWindow()->appendRecentFile(filename); } FileDialog::setWorkingDirectory(filename); } - catch (const Base::PyException& e){ + catch (const Base::PyException& e) { // Usually thrown if the file is invalid somehow e.ReportException(); } } else { wc.restoreCursor(); - QMessageBox::warning(getMainWindow(), QObject::tr("Unknown filetype"), + QMessageBox::warning( + getMainWindow(), + QObject::tr("Unknown filetype"), QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str()))); wc.setWaitCursor(); } @@ -755,8 +798,8 @@ void Application::exportTo(const char* FileName, const char* DocName, const char if (Module) { try { - std::vector sel = Gui::Selection().getObjectsOfType - (App::DocumentObject::getClassTypeId(),DocName); + std::vector sel = + Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId(), DocName); if (sel.empty()) { App::Document* doc = App::GetApplication().getDocument(DocName); sel = doc->getObjectsOfType(App::DocumentObject::getClassTypeId()); @@ -788,30 +831,34 @@ void Application::exportTo(const char* FileName, const char* DocName, const char "User parameter:BaseApp/Preferences/General"); bool addToRecent = parameterGroup->GetBool("RecentIncludesExported", false); parameterGroup->SetBool("RecentIncludesExported", - addToRecent);// Make sure it gets added to the parameter list + addToRecent); // Make sure it gets added to the parameter list if (addToRecent) { // search for a module that is able to open the exported file because otherwise // it doesn't need to be added to the recent files list (#0002047) std::map importMap = App::GetApplication().getImportFilters(te.c_str()); - if (!importMap.empty()) + if (!importMap.empty()) { getMainWindow()->appendRecentFile(QString::fromUtf8(File.filePath().c_str())); + } } // allow exporters to pass _objs__ to submodules before deleting it Gui::Command::runCommand(Gui::Command::App, "del __objs__"); } - catch (const Base::PyException& e){ + catch (const Base::PyException& e) { // Usually thrown if the file is invalid somehow e.ReportException(); wc.restoreCursor(); - QMessageBox::critical(getMainWindow(), QObject::tr("Export failed"), - QString::fromUtf8(e.what())); + QMessageBox::critical(getMainWindow(), + QObject::tr("Export failed"), + QString::fromUtf8(e.what())); wc.setWaitCursor(); } } else { wc.restoreCursor(); - QMessageBox::warning(getMainWindow(), QObject::tr("Unknown filetype"), + QMessageBox::warning( + getMainWindow(), + QObject::tr("Unknown filetype"), QObject::tr("Cannot save to unknown filetype: %1").arg(QLatin1String(te.c_str()))); wc.setWaitCursor(); } @@ -836,27 +883,28 @@ void Application::slotNewDocument(const App::Document& Doc, bool isMainDoc) #ifdef FC_DEBUG assert(d->documents.find(&Doc) == d->documents.end()); #endif - auto pDoc = new Gui::Document(const_cast(&Doc),this); + auto pDoc = new Gui::Document(const_cast(&Doc), this); d->documents[&Doc] = pDoc; - //NOLINTBEGIN - // connect the signals to the application for the new document + // NOLINTBEGIN + // connect the signals to the application for the new document pDoc->signalNewObject.connect(std::bind(&Gui::Application::slotNewObject, this, sp::_1)); - pDoc->signalDeletedObject.connect(std::bind(&Gui::Application::slotDeletedObject, - this, sp::_1)); - pDoc->signalChangedObject.connect(std::bind(&Gui::Application::slotChangedObject, - this, sp::_1, sp::_2)); - pDoc->signalRelabelObject.connect(std::bind(&Gui::Application::slotRelabelObject, - this, sp::_1)); - pDoc->signalActivatedObject.connect(std::bind(&Gui::Application::slotActivatedObject, - this, sp::_1)); + pDoc->signalDeletedObject.connect( + std::bind(&Gui::Application::slotDeletedObject, this, sp::_1)); + pDoc->signalChangedObject.connect( + std::bind(&Gui::Application::slotChangedObject, this, sp::_1, sp::_2)); + pDoc->signalRelabelObject.connect( + std::bind(&Gui::Application::slotRelabelObject, this, sp::_1)); + pDoc->signalActivatedObject.connect( + std::bind(&Gui::Application::slotActivatedObject, this, sp::_1)); pDoc->signalInEdit.connect(std::bind(&Gui::Application::slotInEdit, this, sp::_1)); pDoc->signalResetEdit.connect(std::bind(&Gui::Application::slotResetEdit, this, sp::_1)); - //NOLINTEND + // NOLINTEND signalNewDocument(*pDoc, isMainDoc); - if (isMainDoc) + if (isMainDoc) { pDoc->createView(View3DInventor::getClassTypeId()); + } } void Application::slotDeleteDocument(const App::Document& Doc) @@ -881,13 +929,14 @@ void Application::slotDeleteDocument(const App::Document& Doc) // If the active document gets destructed we must set it to 0. If there are further existing // documents then the view that becomes active sets the active document again. So, we needn't // worry about this. - if (d->activeDocument == doc->second) + if (d->activeDocument == doc->second) { setActiveDocument(nullptr); + } d->viewproviderMap.deleteDocument(Doc); // For exception-safety use a smart pointer - unique_ptr delDoc (doc->second); + unique_ptr delDoc(doc->second); d->documents.erase(doc); } @@ -895,7 +944,7 @@ void Application::slotRelabelDocument(const App::Document& Doc) { std::map::iterator doc = d->documents.find(&Doc); #ifdef FC_DEBUG - assert(doc!=d->documents.end()); + assert(doc != d->documents.end()); #endif signalRelabelDocument(*doc->second); @@ -906,7 +955,7 @@ void Application::slotRenameDocument(const App::Document& Doc) { std::map::iterator doc = d->documents.find(&Doc); #ifdef FC_DEBUG - assert(doc!=d->documents.end()); + assert(doc != d->documents.end()); #endif signalRenameDocument(*doc->second); @@ -916,7 +965,7 @@ void Application::slotShowHidden(const App::Document& Doc) { std::map::iterator doc = d->documents.find(&Doc); #ifdef FC_DEBUG - assert(doc!=d->documents.end()); + assert(doc != d->documents.end()); #endif signalShowHidden(*doc->second); @@ -934,31 +983,32 @@ void Application::slotActiveDocument(const App::Document& Doc) if (d->activeDocument) { Base::PyGILStateLocker lock; Py::Object active(d->activeDocument->getPyObject(), true); - Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"),active); + Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"), active); auto view = getMainWindow()->activeWindow(); - if(!view || view->getAppDocument()!=&Doc) { + if (!view || view->getAppDocument() != &Doc) { Gui::MDIView* view = d->activeDocument->getActiveView(); getMainWindow()->setActiveWindow(view); } } else { Base::PyGILStateLocker lock; - Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"),Py::None()); + Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"), Py::None()); } } // Update the application to show the unit change - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Units"); - if( Doc.FileName.getValue()[0] != '\0' && ! hGrp->GetBool("IgnoreProjectSchema")) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Units"); + if (Doc.FileName.getValue()[0] != '\0' && !hGrp->GetBool("IgnoreProjectSchema")) { int userSchema = Doc.UnitSystem.getValue(); Base::UnitsApi::setSchema(static_cast(userSchema)); getMainWindow()->setUserSchema(userSchema); Application::Instance->onUpdate(); - }else{// set up Unit system default - Base::UnitsApi::setSchema((Base::UnitSystem)hGrp->GetInt("UserSchema",0)); - Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals())); + } + else { // set up Unit system default + Base::UnitsApi::setSchema((Base::UnitSystem)hGrp->GetInt("UserSchema", 0)); + Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals())); } signalActiveDocument(*doc->second); updateActions(); @@ -979,7 +1029,7 @@ void Application::slotDeletedObject(const ViewProvider& vp) void Application::slotChangedObject(const ViewProvider& vp, const App::Property& prop) { - this->signalChangedObject(vp,prop); + this->signalChangedObject(vp, prop); updateActions(true); } @@ -1010,15 +1060,18 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) if (!d->isClosing && pcDoc) { // Call the closing mechanism from Python. This also checks whether pcDoc is the last // open document. - Command::doCommand( - Command::Doc, "App.closeDocument(\"%s\")", pcDoc->getDocument()->getName()); + Command::doCommand(Command::Doc, + "App.closeDocument(\"%s\")", + pcDoc->getDocument()->getName()); if (!d->activeDocument && !d->documents.empty()) { - Document *gdoc = nullptr; - for(auto &v : d->documents) { - if (v.second->getDocument()->testStatus(App::Document::TempDoc)) + Document* gdoc = nullptr; + for (auto& v : d->documents) { + if (v.second->getDocument()->testStatus(App::Document::TempDoc)) { continue; - else if (!gdoc) + } + else if (!gdoc) { gdoc = v.second; + } Gui::MDIView* view = v.second->getActiveView(); if (view) { @@ -1030,7 +1083,7 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) if (gdoc) { setActiveDocument(gdoc); - activateView(View3DInventor::getClassTypeId(),true); + activateView(View3DInventor::getClassTypeId(), true); } } } @@ -1058,7 +1111,7 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) bool Application::sendMsgToActiveView(const char* pMsg, const char** ppReturn) { MDIView* pView = getMainWindow()->activeWindow(); - bool res = pView ? pView->onMsg(pMsg,ppReturn) : false; + bool res = pView ? pView->onMsg(pMsg, ppReturn) : false; updateActions(true); return res; } @@ -1073,11 +1126,12 @@ bool Application::sendHasMsgToActiveView(const char* pMsg) bool Application::sendMsgToFocusView(const char* pMsg, const char** ppReturn) { MDIView* pView = getMainWindow()->activeWindow(); - if(!pView) + if (!pView) { return false; - for(auto focus=qApp->focusWidget();focus;focus=focus->parentWidget()) { - if(focus == pView) { - bool res = pView->onMsg(pMsg,ppReturn); + } + for (auto focus = qApp->focusWidget(); focus; focus = focus->parentWidget()) { + if (focus == pView) { + bool res = pView->onMsg(pMsg, ppReturn); updateActions(true); return res; } @@ -1088,21 +1142,25 @@ bool Application::sendMsgToFocusView(const char* pMsg, const char** ppReturn) bool Application::sendHasMsgToFocusView(const char* pMsg) { MDIView* pView = getMainWindow()->activeWindow(); - if(!pView) + if (!pView) { return false; - for(auto focus=qApp->focusWidget();focus;focus=focus->parentWidget()) { - if(focus == pView) + } + for (auto focus = qApp->focusWidget(); focus; focus = focus->parentWidget()) { + if (focus == pView) { return pView->onHasMsg(pMsg); + } } return false; } Gui::MDIView* Application::activeView() const { - if (activeDocument()) + if (activeDocument()) { return activeDocument()->getActiveView(); - else + } + else { return nullptr; + } } /** @@ -1118,13 +1176,16 @@ void Application::activateView(const Base::Type& type, bool create) Document* doc = activeDocument(); if (doc) { MDIView* mdiView = doc->getActiveView(); - if (mdiView && mdiView->isDerivedFrom(type)) + if (mdiView && mdiView->isDerivedFrom(type)) { return; + } std::list mdiViews = doc->getMDIViewsOfType(type); - if (!mdiViews.empty()) + if (!mdiViews.empty()) { doc->setActiveWindow(mdiViews.back()); - else if (create) + } + else if (create) { doc->createView(type); + } } } @@ -1139,26 +1200,31 @@ Gui::Document* Application::editDocument() const return d->editDocument; } -Gui::MDIView* Application::editViewOfNode(SoNode *node) const +Gui::MDIView* Application::editViewOfNode(SoNode* node) const { - return d->editDocument?d->editDocument->getViewOfNode(node):nullptr; + return d->editDocument ? d->editDocument->getViewOfNode(node) : nullptr; } -void Application::setEditDocument(Gui::Document *doc) { - if(doc == d->editDocument) +void Application::setEditDocument(Gui::Document* doc) +{ + if (doc == d->editDocument) { return; - if(!doc) + } + if (!doc) { d->editDocument = nullptr; - for(auto &v : d->documents) + } + for (auto& v : d->documents) { v.second->_resetEdit(); + } d->editDocument = doc; updateActions(); } void Application::setActiveDocument(Gui::Document* pcDocument) { - if (d->activeDocument == pcDocument) - return; // nothing needs to be done + if (d->activeDocument == pcDocument) { + return; // nothing needs to be done + } updateActions(); @@ -1167,33 +1233,34 @@ void Application::setActiveDocument(Gui::Document* pcDocument) // closed and a second view is activated. The document is still not // removed from the map. App::Document* doc = pcDocument->getDocument(); - if (d->documents.find(doc) == d->documents.end()) + if (d->documents.find(doc) == d->documents.end()) { return; + } } d->activeDocument = pcDocument; std::string nameApp, nameGui; // This adds just a line to the macro file but does not set the active document // Macro recording of this is problematic, thus it's written out as comment. - if (pcDocument){ + if (pcDocument) { nameApp += "App.setActiveDocument(\""; nameApp += pcDocument->getDocument()->getName(); - nameApp += "\")\n"; + nameApp += "\")\n"; nameApp += "App.ActiveDocument=App.getDocument(\""; nameApp += pcDocument->getDocument()->getName(); - nameApp += "\")"; - macroManager()->addLine(MacroManager::Cmt,nameApp.c_str()); + nameApp += "\")"; + macroManager()->addLine(MacroManager::Cmt, nameApp.c_str()); nameGui += "Gui.ActiveDocument=Gui.getDocument(\""; nameGui += pcDocument->getDocument()->getName(); - nameGui += "\")"; - macroManager()->addLine(MacroManager::Cmt,nameGui.c_str()); + nameGui += "\")"; + macroManager()->addLine(MacroManager::Cmt, nameGui.c_str()); } else { nameApp += "App.setActiveDocument(\"\")\n"; nameApp += "App.ActiveDocument=None"; - macroManager()->addLine(MacroManager::Cmt,nameApp.c_str()); + macroManager()->addLine(MacroManager::Cmt, nameApp.c_str()); nameGui += "Gui.ActiveDocument=None"; - macroManager()->addLine(MacroManager::Cmt,nameGui.c_str()); + macroManager()->addLine(MacroManager::Cmt, nameGui.c_str()); } // Sets the currently active document @@ -1210,8 +1277,9 @@ void Application::setActiveDocument(Gui::Document* pcDocument) // May be useful for error detection if (d->activeDocument) { App::Document* doc = d->activeDocument->getDocument(); - Base::Console().Log( - "Active document is %s (at %p)\n", doc->getName(), static_cast(doc)); + Base::Console().Log("Active document is %s (at %p)\n", + doc->getName(), + static_cast(doc)); } else { Base::Console().Log("No active document\n"); @@ -1219,39 +1287,48 @@ void Application::setActiveDocument(Gui::Document* pcDocument) #endif // notify all views attached to the application (not views belong to a special document) - for(list::iterator It=d->passive.begin();It!=d->passive.end();++It) + for (list::iterator It = d->passive.begin(); It != d->passive.end(); ++It) { (*It)->setDocument(pcDocument); + } } Gui::Document* Application::getDocument(const char* name) const { - App::Document* pDoc = App::GetApplication().getDocument( name ); + App::Document* pDoc = App::GetApplication().getDocument(name); std::map::const_iterator it = d->documents.find(pDoc); - if ( it!=d->documents.end() ) + if (it != d->documents.end()) { return it->second; - else + } + else { return nullptr; + } } Gui::Document* Application::getDocument(const App::Document* pDoc) const { std::map::const_iterator it = d->documents.find(pDoc); - if ( it!=d->documents.end() ) + if (it != d->documents.end()) { return it->second; - else + } + else { return nullptr; + } } void Application::showViewProvider(const App::DocumentObject* obj) { ViewProvider* vp = getViewProvider(obj); - if (vp) vp->show(); + if (vp) { + vp->show(); + } } void Application::hideViewProvider(const App::DocumentObject* obj) { ViewProvider* vp = getViewProvider(obj); - if (vp) vp->hide(); + if (vp) { + vp->hide(); + } } Gui::ViewProvider* Application::getViewProvider(const App::DocumentObject* obj) const @@ -1273,11 +1350,14 @@ void Application::onUpdate() { // update all documents std::map::iterator It; - for (It = d->documents.begin();It != d->documents.end();++It) + for (It = d->documents.begin(); It != d->documents.end(); ++It) { It->second->onUpdate(); + } // update all the independent views - for (std::list::iterator It2 = d->passive.begin();It2 != d->passive.end();++It2) + for (std::list::iterator It2 = d->passive.begin(); It2 != d->passive.end(); + ++It2) { (*It2)->onUpdate(); + } } /// Gets called if a view gets activated, this manages the whole activation scheme @@ -1286,7 +1366,8 @@ void Application::viewActivated(MDIView* pcView) #ifdef FC_DEBUG // May be useful for error detection Base::Console().Log("Active view is %s (at %p)\n", - (const char*)pcView->windowTitle().toUtf8(),static_cast(pcView)); + (const char*)pcView->windowTitle().toUtf8(), + static_cast(pcView)); #endif signalActivateView(pcView); @@ -1298,8 +1379,9 @@ void Application::viewActivated(MDIView* pcView) // Set the new active document which is taken of the activated view. If, however, // this view is passive we let the currently active document unchanged as we would // have no document active which is causing a lot of trouble. - if (!pcView->isPassive()) + if (!pcView->isPassive()) { setActiveDocument(pcView->getGuiDocument()); + } } @@ -1313,17 +1395,20 @@ void Application::updateActions(bool delay) getMainWindow()->updateActions(delay); } -void Application::tryClose(QCloseEvent * e) +void Application::tryClose(QCloseEvent* e) { e->setAccepted(getMainWindow()->closeAllDocuments(false)); - if(!e->isAccepted()) + if (!e->isAccepted()) { return; + } // ask all passive views if closable - for (std::list::iterator It = d->passive.begin();It!=d->passive.end();++It) { + for (std::list::iterator It = d->passive.begin(); It != d->passive.end(); + ++It) { e->setAccepted((*It)->canClose()); - if (!e->isAccepted()) + if (!e->isAccepted()) { return; + } } if (e->isAccepted()) { @@ -1331,8 +1416,8 @@ void Application::tryClose(QCloseEvent * e) std::map::iterator It; - //detach the passive views - //SetActiveDocument(0); + // detach the passive views + // SetActiveDocument(0); std::list::iterator itp = d->passive.begin(); while (itp != d->passive.end()) { (*itp)->onClose(); @@ -1343,12 +1428,12 @@ void Application::tryClose(QCloseEvent * e) } } -int Application::getUserEditMode(const std::string &mode) const +int Application::getUserEditMode(const std::string& mode) const { if (mode.empty()) { return userEditMode; } - for (auto const &uem : userEditModes) { + for (auto const& uem : userEditModes) { if (uem.second.first == mode) { return uem.first; } @@ -1356,7 +1441,7 @@ int Application::getUserEditMode(const std::string &mode) const return -1; } -std::pair Application::getUserEditModeUIStrings(int mode) const +std::pair Application::getUserEditModeUIStrings(int mode) const { if (mode == -1) { return userEditModes.at(userEditMode); @@ -1377,9 +1462,9 @@ bool Application::setUserEditMode(int mode) return false; } -bool Application::setUserEditMode(const std::string &mode) +bool Application::setUserEditMode(const std::string& mode) { - for (auto const &uem : userEditModes) { + for (auto const& uem : userEditModes) { if (uem.second.first == mode) { return setUserEditMode(uem.first); } @@ -1401,8 +1486,9 @@ bool Application::activateWorkbench(const char* name) bool ok = false; WaitCursor wc; Workbench* oldWb = WorkbenchManager::instance()->active(); - if (oldWb && oldWb->name() == name) - return false; // already active + if (oldWb && oldWb->name() == name) { + return false; // already active + } Base::PyGILStateLocker lock; // we check for the currently active workbench and call its 'Deactivated' @@ -1416,8 +1502,9 @@ bool Application::activateWorkbench(const char* name) PyObject* pcWorkbench = nullptr; pcWorkbench = PyDict_GetItemString(_pcWorkbenchDictionary, name); // test if the workbench exists - if (!pcWorkbench) + if (!pcWorkbench) { return false; + } try { std::string type; @@ -1431,8 +1518,9 @@ bool Application::activateWorkbench(const char* name) if (Base::Type::fromName(type.c_str()) .isDerivedFrom(Gui::PythonBaseWorkbench::getClassTypeId())) { Workbench* wb = WorkbenchManager::instance()->createWorkbench(name, type); - if (!wb) + if (!wb) { throw Py::RuntimeError("Failed to instantiate workbench of type " + type); + } handler.setAttr(std::string("__Workbench__"), Py::Object(wb->getPyObject(), true)); } @@ -1450,8 +1538,9 @@ bool Application::activateWorkbench(const char* name) // does the Python workbench handler have changed the workbench? Workbench* curWb = WorkbenchManager::instance()->active(); - if (curWb && curWb->name() == name) - ok = true; // already active + if (curWb && curWb->name() == name) { + ok = true; // already active + } // now try to create and activate the matching workbench object else if (WorkbenchManager::instance()->activate(name, type)) { getMainWindow()->activateWorkbench(QString::fromLatin1(name)); @@ -1463,8 +1552,9 @@ bool Application::activateWorkbench(const char* name) // which could be created after loading the appropriate module if (!handler.hasAttr(std::string("__Workbench__"))) { Workbench* wb = WorkbenchManager::instance()->getWorkbench(name); - if (wb) + if (wb) { handler.setAttr(std::string("__Workbench__"), Py::Object(wb->getPyObject(), true)); + } } // If the method Deactivate is available we call it @@ -1480,8 +1570,9 @@ bool Application::activateWorkbench(const char* name) } } - if (oldWb) + if (oldWb) { oldWb->deactivated(); + } // If the method Activate is available we call it if (handler.hasAttr(std::string("Activated"))) { @@ -1506,7 +1597,7 @@ bool Application::activateWorkbench(const char* name) } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text QString msg = QString::fromUtf8(e.what()); QRegularExpression rx; // ignore '' prefixes @@ -1518,15 +1609,18 @@ bool Application::activateWorkbench(const char* name) } Base::Console().Error("%s\n", (const char*)msg.toUtf8()); - if (!d->startingUp) + if (!d->startingUp) { Base::Console().Error("%s\n", e.getStackTrace().c_str()); - else + } + else { Base::Console().Log("%s\n", e.getStackTrace().c_str()); + } if (!d->startingUp) { wc.restoreCursor(); - QMessageBox::critical(getMainWindow(), QObject::tr("Workbench failure"), - QObject::tr("%1").arg(msg)); + QMessageBox::critical(getMainWindow(), + QObject::tr("Workbench failure"), + QObject::tr("%1").arg(msg)); wc.setWaitCursor(); } } @@ -1543,11 +1637,12 @@ QPixmap Application::workbenchIcon(const QString& wb) const if (pcWorkbench) { // make a unique icon name std::stringstream str; - str << static_cast(pcWorkbench) << std::ends; + str << static_cast(pcWorkbench) << std::ends; std::string iconName = str.str(); QPixmap icon; - if (BitmapFactory().findPixmapInCache(iconName.c_str(), icon)) + if (BitmapFactory().findPixmapInCache(iconName.c_str(), icon)) { return icon; + } // get its Icon member if possible try { @@ -1561,13 +1656,14 @@ QPixmap Application::workbenchIcon(const QString& wb) const QByteArray ary; int strlen = (int)content.size(); ary.resize(strlen); - for (int j=0; j 0) { // Make sure to remove crap around the XPM data QList lines = ary.split('\n'); QByteArray buffer; - buffer.reserve(ary.size()+lines.size()); + buffer.reserve(ary.size() + lines.size()); for (QList::iterator it = lines.begin(); it != lines.end(); ++it) { QByteArray trim = it->trimmed(); if (!trim.isEmpty()) { @@ -1602,8 +1698,9 @@ QPixmap Application::workbenchIcon(const QString& wb) const QIcon icon = QApplication::windowIcon(); if (!icon.isNull()) { QList s = icon.availableSizes(); - if (!s.isEmpty()) + if (!s.isEmpty()) { return icon.pixmap(s[0]); + } } return {}; } @@ -1660,7 +1757,7 @@ QString Application::workbenchMenuText(const QString& wb) const QStringList Application::workbenches() const { // If neither 'HiddenWorkbench' nor 'ExtraWorkbench' is set then all workbenches are returned. - const std::map& config = App::Application::Config(); + const std::map& config = App::Application::Config(); auto ht = config.find("HiddenWorkbench"); auto et = config.find("ExtraWorkbench"); auto st = config.find("StartWorkbench"); @@ -1668,23 +1765,25 @@ QStringList Application::workbenches() const QStringList hidden, extra; if (ht != config.end()) { QString items = QString::fromLatin1(ht->second.c_str()); -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) hidden = items.split(QLatin1Char(';'), Qt::SkipEmptyParts); #else hidden = items.split(QLatin1Char(';'), QString::SkipEmptyParts); #endif - if (hidden.isEmpty()) + if (hidden.isEmpty()) { hidden.push_back(QLatin1String("")); + } } if (et != config.end()) { QString items = QString::fromLatin1(et->second.c_str()); -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) extra = items.split(QLatin1Char(';'), Qt::SkipEmptyParts); #else extra = items.split(QLatin1Char(';'), QString::SkipEmptyParts); #endif - if (extra.isEmpty()) + if (extra.isEmpty()) { extra.push_back(QLatin1String("")); + } } PyObject *key, *value; @@ -1696,19 +1795,21 @@ QStringList Application::workbenches() const const char* wbName = PyUnicode_AsUTF8(key); // add only allowed workbenches bool ok = true; - if (!extra.isEmpty()&&ok) { + if (!extra.isEmpty() && ok) { ok = (extra.indexOf(QString::fromLatin1(wbName)) != -1); } - if (!hidden.isEmpty()&&ok) { + if (!hidden.isEmpty() && ok) { ok = (hidden.indexOf(QString::fromLatin1(wbName)) == -1); } // okay the item is visible - if (ok) + if (ok) { wb.push_back(QString::fromLatin1(wbName)); + } // also allow start workbench in case it is hidden - else if (strcmp(wbName, start) == 0) + else if (strcmp(wbName, start) == 0) { wb.push_back(QString::fromLatin1(wbName)); + } } return wb; @@ -1753,12 +1854,12 @@ bool Application::isClosing() return d->isClosing; } -MacroManager *Application::macroManager() +MacroManager* Application::macroManager() { return d->macroMngr; } -CommandManager &Application::commandManager() +CommandManager& Application::commandManager() { return d->commandManager; } @@ -1772,7 +1873,8 @@ Gui::PreferencePackManager* Application::prefPackManager() //************************************************************************** // Init, Destruct and singleton -namespace { +namespace +{ void setCategoryFilterRules() { QString filter; @@ -1784,12 +1886,12 @@ void setCategoryFilterRules() stream.flush(); QLoggingCategory::setFilterRules(filter); } -} +} // namespace -using _qt_msg_handler_old = void (*)(QtMsgType, const QMessageLogContext &, const QString &); +using _qt_msg_handler_old = void (*)(QtMsgType, const QMessageLogContext&, const QString&); _qt_msg_handler_old old_qtmsg_handler = nullptr; -void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) +void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { QByteArray output; if (context.category && strcmp(context.category, "default") != 0) { @@ -1801,26 +1903,25 @@ void messageHandler(QtMsgType type, const QMessageLogContext &context, const QSt output.append(msg.toUtf8()); - switch (type) - { - case QtInfoMsg: - case QtDebugMsg: + switch (type) { + case QtInfoMsg: + case QtDebugMsg: #ifdef FC_DEBUG - Base::Console().Message("%s\n", output.constData()); + Base::Console().Message("%s\n", output.constData()); #else - // do not stress user with Qt internals but write to log file if enabled - Base::Console().Log("%s\n", output.constData()); + // do not stress user with Qt internals but write to log file if enabled + Base::Console().Log("%s\n", output.constData()); #endif - break; - case QtWarningMsg: - Base::Console().Warning("%s\n", output.constData()); - break; - case QtCriticalMsg: - Base::Console().Error("%s\n", output.constData()); - break; - case QtFatalMsg: - Base::Console().Error("%s\n", output.constData()); - abort(); // deliberately core dump + break; + case QtWarningMsg: + Base::Console().Warning("%s\n", output.constData()); + break; + case QtCriticalMsg: + Base::Console().Error("%s\n", output.constData()); + break; + case QtFatalMsg: + Base::Console().Error("%s\n", output.constData()); + abort(); // deliberately core dump } #ifdef FC_OS_WIN32 if (old_qtmsg_handler) { @@ -1829,32 +1930,32 @@ void messageHandler(QtMsgType type, const QMessageLogContext &context, const QSt #endif } -#ifdef FC_DEBUG // redirect Coin messages to FreeCAD -void messageHandlerCoin(const SoError * error, void * /*userdata*/) +#ifdef FC_DEBUG // redirect Coin messages to FreeCAD +void messageHandlerCoin(const SoError* error, void* /*userdata*/) { if (error && error->getTypeId() == SoDebugError::getClassTypeId()) { const SoDebugError* dbg = static_cast(error); const char* msg = error->getDebugString().getString(); - switch (dbg->getSeverity()) - { - case SoDebugError::INFO: - Base::Console().Message("%s\n", msg); - break; - case SoDebugError::WARNING: - Base::Console().Warning("%s\n", msg); - break; - default: // error - Base::Console().Error("%s\n", msg); - break; + switch (dbg->getSeverity()) { + case SoDebugError::INFO: + Base::Console().Message("%s\n", msg); + break; + case SoDebugError::WARNING: + Base::Console().Warning("%s\n", msg); + break; + default: // error + Base::Console().Error("%s\n", msg); + break; } #ifdef FC_OS_WIN32 - if (old_qtmsg_handler) - (*old_qtmsg_handler)(QtDebugMsg, QMessageLogContext(), QString::fromLatin1(msg)); + if (old_qtmsg_handler) { + (*old_qtmsg_handler)(QtDebugMsg, QMessageLogContext(), QString::fromLatin1(msg)); + } #endif } else if (error) { const char* msg = error->getDebugString().getString(); - Base::Console().Log( msg ); + Base::Console().Log(msg); } } @@ -1879,7 +1980,7 @@ void Application::initApplication() try { initTypes(); - new Base::ScriptProducer( "FreeCADGuiInit", FreeCADGuiInit ); + new Base::ScriptProducer("FreeCADGuiInit", FreeCADGuiInit); init_resources(); setCategoryFilterRules(); old_qtmsg_handler = qInstallMessageHandler(messageHandler); @@ -1981,17 +2082,18 @@ void Application::runInitGuiScript() Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADGuiInit")); } -namespace { +namespace +{ bool onlySingleInstance(GUISingleApplication& mainApp) { - const std::map& cfg = App::Application::Config(); + const std::map& cfg = App::Application::Config(); auto it = cfg.find("SingleInstance"); if (it != cfg.end() && mainApp.isRunning()) { // send the file names to be opened to the server application so that this // opens them QDir cwd = QDir::current(); std::list files = App::Application::getCmdLineFiles(); - for (const auto & file : files) { + for (const auto& file : files) { QString fn = QString::fromUtf8(file.c_str(), static_cast(file.size())); QFileInfo fi(fn); // if path name is relative make it absolute because the running instance @@ -2016,7 +2118,7 @@ bool onlySingleInstance(GUISingleApplication& mainApp) void setAppNameAndIcon() { - const std::map& cfg = App::Application::Config(); + const std::map& cfg = App::Application::Config(); // set application icon and window title auto it = cfg.find("Application"); @@ -2024,7 +2126,8 @@ void setAppNameAndIcon() QApplication::setApplicationName(QString::fromUtf8(it->second.c_str())); } else { - QApplication::setApplicationName(QString::fromStdString(App::Application::getExecutableName())); + QApplication::setApplicationName( + QString::fromStdString(App::Application::getExecutableName())); } #ifndef Q_OS_MACOS QApplication::setWindowIcon( @@ -2035,8 +2138,8 @@ void setAppNameAndIcon() void tryRunEventLoop(GUISingleApplication& mainApp) { std::stringstream s; - s << App::Application::getUserCachePath() << App::Application::getExecutableName() - << "_" << QCoreApplication::applicationPid() << ".lock"; + s << App::Application::getUserCachePath() << App::Application::getExecutableName() << "_" + << QCoreApplication::applicationPid() << ".lock"; // open a lock file with the PID Base::FileInfo fi(s.str()); Base::ofstream lock(fi); @@ -2098,7 +2201,7 @@ void runEventLoop(GUISingleApplication& mainApp) throw; } } -} +} // namespace void Application::runApplication() { @@ -2133,8 +2236,8 @@ void Application::runApplication() MainWindow mw; mw.setProperty("QuitOnClosed", true); -#ifdef FC_DEBUG // redirect Coin messages to FreeCAD - SoDebugError::setHandlerCallback( messageHandlerCoin, 0 ); +#ifdef FC_DEBUG // redirect Coin messages to FreeCAD + SoDebugError::setHandlerCallback(messageHandlerCoin, 0); #endif StartupPostProcess postProcess(&mw, app, &mainApp); @@ -2194,7 +2297,8 @@ void Application::setStyleSheet(const QString& qssFile, bool tiledBackground) // color: #rrggbb; // } // - // See https://stackoverflow.com/questions/5497799/how-do-i-customise-the-appearance-of-links-in-qlabels-using-style-sheets + // See + // https://stackoverflow.com/questions/5497799/how-do-i-customise-the-appearance-of-links-in-qlabels-using-style-sheets // and https://forum.freecad.org/viewtopic.php?f=34&t=50744 static bool init = true; if (init) { @@ -2266,7 +2370,7 @@ void Application::setStyleSheet(const QString& qssFile, bool tiledBackground) qApp->setStyleSheet(QString()); ActionStyleEvent e(ActionStyleEvent::Restore); qApp->sendEvent(getMainWindow(), &e); - mdi->setBackground(QBrush(QColor(160,160,160))); + mdi->setBackground(QBrush(QColor(160, 160, 160))); } } @@ -2275,30 +2379,41 @@ void Application::setStyleSheet(const QString& qssFile, bool tiledBackground) // See https://doc.qt.io/qt-5/qstyle.html#unpolish-1 // See https://forum.freecad.org/viewtopic.php?f=17&t=50783 if (!d->startingUp) { - if (mdi->style()) + if (mdi->style()) { mdi->style()->unpolish(qApp); + } } } QString Application::replaceVariablesInQss(QString qssText) { - //First we fetch the colors from preferences, - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Themes"); + // First we fetch the colors from preferences, + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Themes"); unsigned long longAccentColor1 = hGrp->GetUnsigned("ThemeAccentColor1", 0); unsigned long longAccentColor2 = hGrp->GetUnsigned("ThemeAccentColor2", 0); unsigned long longAccentColor3 = hGrp->GetUnsigned("ThemeAccentColor3", 0); - //convert them to hex. - //Note: the ulong contains alpha channels so 8 hex characters when we need 6 here. - QString accentColor1 = QString::fromLatin1("#%1").arg(longAccentColor1, 8, 16, QLatin1Char('0')).toUpper().mid(0, 7); - QString accentColor2 = QString::fromLatin1("#%1").arg(longAccentColor2, 8, 16, QLatin1Char('0')).toUpper().mid(0, 7); - QString accentColor3 = QString::fromLatin1("#%1").arg(longAccentColor3, 8, 16, QLatin1Char('0')).toUpper().mid(0, 7); + // convert them to hex. + // Note: the ulong contains alpha channels so 8 hex characters when we need 6 here. + QString accentColor1 = QString::fromLatin1("#%1") + .arg(longAccentColor1, 8, 16, QLatin1Char('0')) + .toUpper() + .mid(0, 7); + QString accentColor2 = QString::fromLatin1("#%1") + .arg(longAccentColor2, 8, 16, QLatin1Char('0')) + .toUpper() + .mid(0, 7); + QString accentColor3 = QString::fromLatin1("#%1") + .arg(longAccentColor3, 8, 16, QLatin1Char('0')) + .toUpper() + .mid(0, 7); qssText = qssText.replace(QString::fromLatin1("@ThemeAccentColor1"), accentColor1); qssText = qssText.replace(QString::fromLatin1("@ThemeAccentColor2"), accentColor2); qssText = qssText.replace(QString::fromLatin1("@ThemeAccentColor3"), accentColor3); - //Base::Console().Warning("%s\n", qssText.toStdString()); + // Base::Console().Warning("%s\n", qssText.toStdString()); return qssText; } @@ -2345,68 +2460,79 @@ void Application::checkForPreviousCrashes() } } -App::Document *Application::reopen(App::Document *doc) { - if(!doc) +App::Document* Application::reopen(App::Document* doc) +{ + if (!doc) { return nullptr; + } std::string name = doc->FileName.getValue(); std::set untouchedDocs; - for(auto &v : d->documents) { - if(!v.second->isModified() && !v.second->getDocument()->isTouched()) + for (auto& v : d->documents) { + if (!v.second->isModified() && !v.second->getDocument()->isTouched()) { untouchedDocs.insert(v.second); + } } WaitCursor wc; wc.setIgnoreEvents(WaitCursor::NoEvents); - if(doc->testStatus(App::Document::PartialDoc) - || doc->testStatus(App::Document::PartialRestore)) - { + if (doc->testStatus(App::Document::PartialDoc) + || doc->testStatus(App::Document::PartialRestore)) { App::GetApplication().openDocument(name.c_str()); - } else { + } + else { std::vector docs; - for(auto d : doc->getDependentDocuments(true)) { - if(d->testStatus(App::Document::PartialDoc) - || d->testStatus(App::Document::PartialRestore) ) + for (auto d : doc->getDependentDocuments(true)) { + if (d->testStatus(App::Document::PartialDoc) + || d->testStatus(App::Document::PartialRestore)) { docs.emplace_back(d->FileName.getValue()); + } } - if(docs.empty()) { - Document *gdoc = getDocument(doc); - if(gdoc) { + if (docs.empty()) { + Document* gdoc = getDocument(doc); + if (gdoc) { setActiveDocument(gdoc); - if(!gdoc->setActiveView()) - gdoc->setActiveView(nullptr,View3DInventor::getClassTypeId()); + if (!gdoc->setActiveView()) { + gdoc->setActiveView(nullptr, View3DInventor::getClassTypeId()); + } } return doc; } - for(auto &file : docs) - App::GetApplication().openDocument(file.c_str(),false); + for (auto& file : docs) { + App::GetApplication().openDocument(file.c_str(), false); + } } doc = nullptr; - for(auto &v : d->documents) { - if(name == v.first->FileName.getValue()) + for (auto& v : d->documents) { + if (name == v.first->FileName.getValue()) { doc = const_cast(v.first); - if(untouchedDocs.count(v.second)) { - if(!v.second->isModified()) continue; + } + if (untouchedDocs.count(v.second)) { + if (!v.second->isModified()) { + continue; + } bool reset = true; - for(auto obj : v.second->getDocument()->getObjects()) { - if(!obj->isTouched()) + for (auto obj : v.second->getDocument()->getObjects()) { + if (!obj->isTouched()) { continue; + } std::vector props; obj->getPropertyList(props); - for(auto prop : props){ + for (auto prop : props) { auto link = dynamic_cast(prop); - if(link && link->checkRestore()) { + if (link && link->checkRestore()) { reset = false; break; } } - if(!reset) + if (!reset) { break; + } } - if(reset) { + if (reset) { v.second->getDocument()->purgeTouched(); v.second->setModified(false); } diff --git a/src/Gui/Clipping.cpp b/src/Gui/Clipping.cpp index 8238a04f67..e56eb2997b 100644 --- a/src/Gui/Clipping.cpp +++ b/src/Gui/Clipping.cpp @@ -23,12 +23,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #endif #include "Clipping.h" @@ -39,7 +39,8 @@ using namespace Gui::Dialog; -class Clipping::Private { +class Clipping::Private +{ public: Ui_Clipping ui; QPointer view; @@ -48,30 +49,30 @@ public: SoClipPlane* clipY; SoClipPlane* clipZ; SoClipPlane* clipView; - bool flipX{false}; - bool flipY{false}; - bool flipZ{false}; + bool flipX {false}; + bool flipY {false}; + bool flipZ {false}; SoTimerSensor* sensor; Private() { clipX = new SoClipPlane(); clipX->on.setValue(false); - clipX->plane.setValue(SbPlane(SbVec3f(1,0,0),0)); + clipX->plane.setValue(SbPlane(SbVec3f(1, 0, 0), 0)); clipX->ref(); clipY = new SoClipPlane(); clipY->on.setValue(false); - clipY->plane.setValue(SbPlane(SbVec3f(0,1,0),0)); + clipY->plane.setValue(SbPlane(SbVec3f(0, 1, 0), 0)); clipY->ref(); clipZ = new SoClipPlane(); clipZ->on.setValue(false); - clipZ->plane.setValue(SbPlane(SbVec3f(0,0,1),0)); + clipZ->plane.setValue(SbPlane(SbVec3f(0, 0, 1), 0)); clipZ->ref(); clipView = new SoClipPlane(); clipView->on.setValue(false); - clipView->plane.setValue(SbPlane(SbVec3f(0,0,1),0)); + clipView->plane.setValue(SbPlane(SbVec3f(0, 0, 1), 0)); clipView->ref(); node = nullptr; @@ -85,7 +86,7 @@ public: clipView->unref(); delete sensor; } - static void moveCallback(void * data, SoSensor * sensor) + static void moveCallback(void* data, SoSensor* sensor) { Q_UNUSED(sensor); auto self = static_cast(data); @@ -93,7 +94,7 @@ public: Gui::View3DInventorViewer* view = self->view->getViewer(); SoClipPlane* clip = self->clipView; SbPlane pln = clip->plane.getValue(); - clip->plane.setValue(SbPlane(view->getViewDirection(),pln.getDistanceFromOrigin())); + clip->plane.setValue(SbPlane(view->getViewDirection(), pln.getDistanceFromOrigin())); } } }; @@ -101,27 +102,27 @@ public: /* TRANSLATOR Gui::Dialog::Clipping */ Clipping::Clipping(Gui::View3DInventor* view, QWidget* parent) - : QDialog(parent) - , d(new Private) + : QDialog(parent) + , d(new Private) { // create widgets d->ui.setupUi(this); setupConnections(); - d->ui.clipView->setRange(-INT_MAX,INT_MAX); + d->ui.clipView->setRange(-INT_MAX, INT_MAX); d->ui.clipView->setSingleStep(0.1f); - d->ui.clipX->setRange(-INT_MAX,INT_MAX); + d->ui.clipX->setRange(-INT_MAX, INT_MAX); d->ui.clipX->setSingleStep(0.1f); - d->ui.clipY->setRange(-INT_MAX,INT_MAX); + d->ui.clipY->setRange(-INT_MAX, INT_MAX); d->ui.clipY->setSingleStep(0.1f); - d->ui.clipZ->setRange(-INT_MAX,INT_MAX); + d->ui.clipZ->setRange(-INT_MAX, INT_MAX); d->ui.clipZ->setSingleStep(0.1f); - d->ui.dirX->setRange(-INT_MAX,INT_MAX); + d->ui.dirX->setRange(-INT_MAX, INT_MAX); d->ui.dirX->setSingleStep(0.1f); - d->ui.dirY->setRange(-INT_MAX,INT_MAX); + d->ui.dirY->setRange(-INT_MAX, INT_MAX); d->ui.dirY->setSingleStep(0.1f); - d->ui.dirZ->setRange(-INT_MAX,INT_MAX); + d->ui.dirZ->setRange(-INT_MAX, INT_MAX); d->ui.dirZ->setSingleStep(0.1f); d->ui.dirZ->setValue(1.0f); @@ -146,7 +147,7 @@ Clipping::Clipping(Gui::View3DInventor* view, QWidget* parent) d->ui.clipZ->setValue(cnt[2]); int minDecimals = 2; - float lenx, leny,lenz; + float lenx, leny, lenz; box.getSize(lenx, leny, lenz); int steps = 100; float minlen = std::min(lenx, std::min(leny, lenz)); @@ -192,7 +193,7 @@ Clipping* Clipping::makeDockWidget(Gui::View3DInventor* view) auto clipping = new Clipping(view); Gui::DockWindowManager* pDockMgr = Gui::DockWindowManager::instance(); QDockWidget* dw = pDockMgr->addDockWindow("Clipping", clipping, Qt::LeftDockWidgetArea); - dw->setFeatures(QDockWidget::DockWidgetMovable|QDockWidget::DockWidgetFloatable); + dw->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); dw->show(); return clipping; @@ -211,6 +212,7 @@ Clipping::~Clipping() void Clipping::setupConnections() { + // clang-format off connect(d->ui.groupBoxX, &QGroupBox::toggled, this, &Clipping::onGroupBoxXToggled); connect(d->ui.groupBoxY, &QGroupBox::toggled, @@ -243,6 +245,7 @@ void Clipping::setupConnections() this, &Clipping::onDirYValueChanged); connect(d->ui.dirZ, qOverload(&QDoubleSpinBox::valueChanged), this, &Clipping::onDirZValueChanged); + // clang-format on } void Clipping::reject() @@ -284,40 +287,40 @@ void Clipping::onGroupBoxZToggled(bool on) void Clipping::onClipXValueChanged(double val) { SbPlane pln = d->clipX->plane.getValue(); - d->clipX->plane.setValue(SbPlane(pln.getNormal(),d->flipX ? -val : val)); + d->clipX->plane.setValue(SbPlane(pln.getNormal(), d->flipX ? -val : val)); } void Clipping::onClipYValueChanged(double val) { SbPlane pln = d->clipY->plane.getValue(); - d->clipY->plane.setValue(SbPlane(pln.getNormal(),d->flipY ? -val : val)); + d->clipY->plane.setValue(SbPlane(pln.getNormal(), d->flipY ? -val : val)); } void Clipping::onClipZValueChanged(double val) { SbPlane pln = d->clipZ->plane.getValue(); - d->clipZ->plane.setValue(SbPlane(pln.getNormal(),d->flipZ ? -val : val)); + d->clipZ->plane.setValue(SbPlane(pln.getNormal(), d->flipZ ? -val : val)); } void Clipping::onFlipClipXClicked() { d->flipX = !d->flipX; SbPlane pln = d->clipX->plane.getValue(); - d->clipX->plane.setValue(SbPlane(-pln.getNormal(),-pln.getDistanceFromOrigin())); + d->clipX->plane.setValue(SbPlane(-pln.getNormal(), -pln.getDistanceFromOrigin())); } void Clipping::onFlipClipYClicked() { d->flipY = !d->flipY; SbPlane pln = d->clipY->plane.getValue(); - d->clipY->plane.setValue(SbPlane(-pln.getNormal(),-pln.getDistanceFromOrigin())); + d->clipY->plane.setValue(SbPlane(-pln.getNormal(), -pln.getDistanceFromOrigin())); } void Clipping::onFlipClipZClicked() { d->flipZ = !d->flipZ; SbPlane pln = d->clipZ->plane.getValue(); - d->clipZ->plane.setValue(SbPlane(-pln.getNormal(),-pln.getDistanceFromOrigin())); + d->clipZ->plane.setValue(SbPlane(-pln.getNormal(), -pln.getDistanceFromOrigin())); } void Clipping::onGroupBoxViewToggled(bool on) @@ -334,7 +337,7 @@ void Clipping::onGroupBoxViewToggled(bool on) void Clipping::onClipViewValueChanged(double val) { SbPlane pln = d->clipView->plane.getValue(); - d->clipView->plane.setValue(SbPlane(pln.getNormal(),val)); + d->clipView->plane.setValue(SbPlane(pln.getNormal(), val)); } void Clipping::onFromViewClicked() @@ -343,7 +346,7 @@ void Clipping::onFromViewClicked() Gui::View3DInventorViewer* view = d->view->getViewer(); SbVec3f dir = view->getViewDirection(); SbPlane pln = d->clipView->plane.getValue(); - d->clipView->plane.setValue(SbPlane(dir,pln.getDistanceFromOrigin())); + d->clipView->plane.setValue(SbPlane(dir, pln.getDistanceFromOrigin())); } } @@ -354,10 +357,12 @@ void Clipping::onAdjustViewdirectionToggled(bool on) d->ui.dirZ->setDisabled(on); d->ui.fromView->setDisabled(on); - if (on) + if (on) { d->sensor->schedule(); - else + } + else { d->sensor->unschedule(); + } } void Clipping::onDirXValueChanged(double) @@ -367,9 +372,10 @@ void Clipping::onDirXValueChanged(double) double z = d->ui.dirZ->value(); SbPlane pln = d->clipView->plane.getValue(); - SbVec3f normal(x,y,z); - if (normal.sqrLength() > 0.0f) - d->clipView->plane.setValue(SbPlane(normal,pln.getDistanceFromOrigin())); + SbVec3f normal(x, y, z); + if (normal.sqrLength() > 0.0f) { + d->clipView->plane.setValue(SbPlane(normal, pln.getDistanceFromOrigin())); + } } void Clipping::onDirYValueChanged(double) @@ -379,9 +385,10 @@ void Clipping::onDirYValueChanged(double) double z = d->ui.dirZ->value(); SbPlane pln = d->clipView->plane.getValue(); - SbVec3f normal(x,y,z); - if (normal.sqrLength() > 0.0f) - d->clipView->plane.setValue(SbPlane(normal,pln.getDistanceFromOrigin())); + SbVec3f normal(x, y, z); + if (normal.sqrLength() > 0.0f) { + d->clipView->plane.setValue(SbPlane(normal, pln.getDistanceFromOrigin())); + } } void Clipping::onDirZValueChanged(double) @@ -391,9 +398,10 @@ void Clipping::onDirZValueChanged(double) double z = d->ui.dirZ->value(); SbPlane pln = d->clipView->plane.getValue(); - SbVec3f normal(x,y,z); - if (normal.sqrLength() > 0.0f) - d->clipView->plane.setValue(SbPlane(normal,pln.getDistanceFromOrigin())); + SbVec3f normal(x, y, z); + if (normal.sqrLength() > 0.0f) { + d->clipView->plane.setValue(SbPlane(normal, pln.getDistanceFromOrigin())); + } } #include "moc_Clipping.cpp" diff --git a/src/Gui/DemoMode.cpp b/src/Gui/DemoMode.cpp index e1185b1d21..861e1bf86f 100644 --- a/src/Gui/DemoMode.cpp +++ b/src/Gui/DemoMode.cpp @@ -22,9 +22,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include @@ -43,7 +43,9 @@ using namespace Gui::Dialog; /* TRANSLATOR Gui::Dialog::DemoMode */ DemoMode::DemoMode(QWidget* /*parent*/, Qt::WindowFlags fl) - : QDialog(nullptr, fl | Qt::WindowStaysOnTopHint), viewAxis(0, 0, -1), ui(new Ui_DemoMode) + : QDialog(nullptr, fl | Qt::WindowStaysOnTopHint) + , viewAxis(0, 0, -1) + , ui(new Ui_DemoMode) { // create widgets ui->setupUi(this); @@ -69,6 +71,7 @@ DemoMode::~DemoMode() void DemoMode::setupConnections() { + // clang-format off connect(ui->playButton, &QPushButton::clicked, this, &DemoMode::onPlayButtonToggled); connect(ui->fullscreen, &QCheckBox::toggled, @@ -81,16 +84,18 @@ void DemoMode::setupConnections() this, &DemoMode::onAngleSliderValueChanged); connect(ui->timeout, qOverload(&QSpinBox::valueChanged), this, &DemoMode::onTimeoutValueChanged); + // clang-format on } void DemoMode::reset() { onFullscreenToggled(false); Gui::View3DInventor* view = activeView(); - if (view) + if (view) { view->getViewer()->stopAnimating(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); + } + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); hGrp->Notify("UseNavigationAnimations"); } @@ -106,7 +111,7 @@ void DemoMode::reject() QDialog::reject(); } -bool DemoMode::eventFilter(QObject *obj, QEvent *event) +bool DemoMode::eventFilter(QObject* obj, QEvent* event) { if (event->type() == QEvent::MouseMove) { if (ui->fullscreen->isChecked()) { @@ -120,14 +125,15 @@ bool DemoMode::eventFilter(QObject *obj, QEvent *event) return QDialog::eventFilter(obj, event); } -void DemoMode::showEvent(QShowEvent *) +void DemoMode::showEvent(QShowEvent*) { - if (this->wasHidden) + if (this->wasHidden) { this->move(this->pnt); + } this->wasHidden = false; } -void DemoMode::hideEvent(QHideEvent *) +void DemoMode::hideEvent(QHideEvent*) { this->pnt = this->pos(); this->wasHidden = true; @@ -150,21 +156,23 @@ Gui::View3DInventor* DemoMode::activeView() const float DemoMode::getSpeed(int v) const { - float speed = (static_cast(v)) / 10.0f; // let 10.0 be the maximum speed + float speed = (static_cast(v)) / 10.0f; // let 10.0 be the maximum speed return speed; } SbVec3f DemoMode::getDirection(Gui::View3DInventor* view) const { SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); - if (!cam) + if (!cam) { return this->viewAxis; + } SbRotation rot = cam->orientation.getValue(); SbRotation inv = rot.inverse(); SbVec3f vec(this->viewAxis); inv.multVec(vec, vec); - if (vec.length() < FLT_EPSILON) + if (vec.length() < FLT_EPSILON) { vec = this->viewAxis; + } vec.normalize(); return vec; } @@ -174,11 +182,12 @@ void DemoMode::onAngleSliderValueChanged(int v) Gui::View3DInventor* view = activeView(); if (view) { SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); - if (!cam) + if (!cam) { return; - auto angle = Base::toRadians(/*90-v*/v - this->oldvalue); + } + auto angle = Base::toRadians(/*90-v*/ v - this->oldvalue); SbRotation rot(SbVec3f(-1, 0, 0), angle); - reorientCamera(cam ,rot); + reorientCamera(cam, rot); this->oldvalue = v; if (view->getViewer()->isSpinning()) { startAnimation(view); @@ -186,13 +195,12 @@ void DemoMode::onAngleSliderValueChanged(int v) } } -void DemoMode::reorientCamera(SoCamera * cam, const SbRotation & rot) +void DemoMode::reorientCamera(SoCamera* cam, const SbRotation& rot) { // Find global coordinates of focal point. SbVec3f direction; cam->orientation.getValue().multVec(SbVec3f(0, 0, -1), direction); - SbVec3f focalpoint = cam->position.getValue() + - cam->focalDistance.getValue() * direction; + SbVec3f focalpoint = cam->position.getValue() + cam->focalDistance.getValue() * direction; // Set new orientation value by accumulating the new rotation. cam->orientation = rot * cam->orientation.getValue(); @@ -220,7 +228,7 @@ void DemoMode::onPlayButtonToggled(bool pressed) SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); if (cam) { SbRotation rot = cam->orientation.getValue(); - SbVec3f vec(0,-1,0); + SbVec3f vec(0, -1, 0); rot.multVec(vec, this->viewAxis); } } @@ -239,9 +247,11 @@ void DemoMode::onFullscreenToggled(bool on) { Gui::View3DInventor* view = activeView(); if (view) { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); Command* cmd = rcCmdMgr.getCommandByName("Std_ViewDockUndockFullscreen"); - if (cmd) cmd->invoke(on ? MDIView::FullScreen : MDIView::Child); + if (cmd) { + cmd->invoke(on ? MDIView::FullScreen : MDIView::Child); + } this->activateWindow(); ui->playButton->setChecked(false); } @@ -277,16 +287,19 @@ void DemoMode::startAnimation(Gui::View3DInventor* view) void DemoMode::onTimerCheckToggled(bool on) { - if (on) + if (on) { timer->start(); - else + } + else { timer->stop(); + } } -void DemoMode::changeEvent(QEvent *e) +void DemoMode::changeEvent(QEvent* e) { - if (e->type() == QEvent::LanguageChange) + if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); + } QDialog::changeEvent(e); } diff --git a/src/Gui/DlgActionsImp.cpp b/src/Gui/DlgActionsImp.cpp index 9aef912ce4..a1c72702e5 100644 --- a/src/Gui/DlgActionsImp.cpp +++ b/src/Gui/DlgActionsImp.cpp @@ -22,15 +22,15 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include "DlgActionsImp.h" @@ -54,31 +54,35 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgCustomActionsImp::DlgCustomActionsImp( QWidget* parent ) - : CustomizeActionPage(parent) - , ui(new Ui_DlgCustomActions) +DlgCustomActionsImp::DlgCustomActionsImp(QWidget* parent) + : CustomizeActionPage(parent) + , ui(new Ui_DlgCustomActions) { ui->setupUi(this); setupConnections(); // search for all macros - std::string cMacroPath = App::GetApplication(). - GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") - ->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str()); + std::string cMacroPath = + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); QDir d(QString::fromUtf8(cMacroPath.c_str()), QLatin1String("*.FCMacro *.py")); - for (unsigned int i=0; iactionMacros->insertItem(0,d[i],QVariant(false)); + for (unsigned int i = 0; i < d.count(); i++) { + ui->actionMacros->insertItem(0, d[i], QVariant(false)); + } - QString systemMacroDirStr = QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro"); + QString systemMacroDirStr = + QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro"); d = QDir(systemMacroDirStr, QLatin1String("*.FCMacro *.py")); if (d.exists()) { - for (unsigned int i=0; iactionMacros->insertItem(0,d[i],QVariant(true)); + for (unsigned int i = 0; i < d.count(); i++) { + ui->actionMacros->insertItem(0, d[i], QVariant(true)); } } - QStringList labels; labels << tr("Icons") << tr("Macros"); + QStringList labels; + labels << tr("Icons") << tr("Macros"); ui->actionListWidget->setHeaderLabels(labels); ui->actionListWidget->header()->hide(); ui->actionListWidget->setIconSize(QSize(32, 32)); @@ -90,12 +94,14 @@ DlgCustomActionsImp::DlgCustomActionsImp( QWidget* parent ) /** Destroys the object and frees any allocated resources */ DlgCustomActionsImp::~DlgCustomActionsImp() { - if (bChanged) + if (bChanged) { MacroCommand::save(); + } } void DlgCustomActionsImp::setupConnections() { + // clang-format off connect(ui->actionListWidget, &QTreeWidget::itemActivated, this, &DlgCustomActionsImp::onActionListWidgetItemActivated); connect(ui->buttonChoosePixmap, &QToolButton::clicked, @@ -106,10 +112,12 @@ void DlgCustomActionsImp::setupConnections() this, &DlgCustomActionsImp::onButtonRemoveActionClicked); connect(ui->buttonReplaceAction, &QPushButton::clicked, this, &DlgCustomActionsImp::onButtonReplaceActionClicked); + // clang-format on } bool DlgCustomActionsImp::event(QEvent* e) { + // clang-format off bool ok = QWidget::event(e); if (e->type() == QEvent::ParentChange || e->type() == QEvent::ParentAboutToChange) @@ -139,6 +147,7 @@ bool DlgCustomActionsImp::event(QEvent* e) } } } + // clang-format on return ok; } @@ -148,7 +157,7 @@ void DlgCustomActionsImp::onAddMacroAction(const QByteArray&) bChanged = true; } -void DlgCustomActionsImp::onRemoveMacroAction(const QByteArray &name) +void DlgCustomActionsImp::onRemoveMacroAction(const QByteArray& name) { bChanged = true; ShortcutManager::instance()->reset(name.constData()); @@ -163,22 +172,23 @@ void DlgCustomActionsImp::showActions() { CommandManager& rclMan = Application::Instance->commandManager(); std::vector aclCurMacros = rclMan.getGroupCommands("Macros"); - for (const auto & aclCurMacro : aclCurMacros) - { + for (const auto& aclCurMacro : aclCurMacros) { auto item = new QTreeWidgetItem(ui->actionListWidget); QByteArray actionName = aclCurMacro->getName(); item->setData(1, Qt::UserRole, actionName); item->setText(1, QString::fromUtf8(aclCurMacro->getMenuText())); item->setSizeHint(0, QSize(32, 32)); - if ( aclCurMacro->getPixmap() ) + if (aclCurMacro->getPixmap()) { item->setIcon(0, BitmapFactory().pixmap(aclCurMacro->getPixmap())); + } } } -void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem *item) +void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem* item) { - if (!item) - return; // no valid item + if (!item) { + return; // no valid item + } // search for the command in the manager and if necessary in the temporary created ones QByteArray actionName = item->data(1, Qt::UserRole).toByteArray(); @@ -187,105 +197,108 @@ void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem *item) auto pScript = dynamic_cast(pCmd); // if valid command - if ( pScript ) - { + if (pScript) { bool bFound = false; QString scriptName = QString::fromUtf8(pScript->getScriptName()); - for (int i = 0; iactionMacros->count(); i++) - { - if (ui->actionMacros->itemText(i).startsWith(scriptName, Qt::CaseSensitive)) - { + for (int i = 0; i < ui->actionMacros->count(); i++) { + if (ui->actionMacros->itemText(i).startsWith(scriptName, Qt::CaseSensitive)) { bFound = true; ui->actionMacros->setCurrentIndex(i); break; } } - if (!bFound) - { - QMessageBox::critical(this, tr("Macro not found"), - tr("Sorry, couldn't find macro file '%1'.").arg(scriptName)); + if (!bFound) { + QMessageBox::critical(this, + tr("Macro not found"), + tr("Sorry, couldn't find macro file '%1'.").arg(scriptName)); } // fill up labels with the command's data - ui->actionWhatsThis -> setText(QString::fromUtf8(pScript->getWhatsThis())); - ui->actionMenu -> setText(QString::fromUtf8(pScript->getMenuText())); - ui->actionToolTip -> setText(QString::fromUtf8(pScript->getToolTipText())); - ui->actionStatus -> setText(QString::fromUtf8(pScript->getStatusTip())); - ui->actionAccel -> setText(ShortcutManager::instance()->getShortcut( - actionName.constData(), pScript->getAccel())); + ui->actionWhatsThis->setText(QString::fromUtf8(pScript->getWhatsThis())); + ui->actionMenu->setText(QString::fromUtf8(pScript->getMenuText())); + ui->actionToolTip->setText(QString::fromUtf8(pScript->getToolTipText())); + ui->actionStatus->setText(QString::fromUtf8(pScript->getStatusTip())); + ui->actionAccel->setText( + ShortcutManager::instance()->getShortcut(actionName.constData(), pScript->getAccel())); ui->pixmapLabel->clear(); m_sPixmap.clear(); const char* name = pScript->getPixmap(); - if (name && std::strlen(name) > 2) - { + if (name && std::strlen(name) > 2) { QPixmap p = Gui::BitmapFactory().pixmap(pScript->getPixmap()); ui->pixmapLabel->setPixmap(p); - m_sPixmap = QString::fromUtf8(name); // can also be a path + m_sPixmap = QString::fromUtf8(name); // can also be a path } } } void DlgCustomActionsImp::onButtonAddActionClicked() { - if (ui->actionMacros-> currentText().isEmpty()) - { - QMessageBox::warning(this, tr("Empty macro"),tr("Please specify the macro first.")); + if (ui->actionMacros->currentText().isEmpty()) { + QMessageBox::warning(this, tr("Empty macro"), tr("Please specify the macro first.")); return; } - if (ui->actionMenu->text().isEmpty()) - { - QMessageBox::warning(this, tr("Empty text"),tr("Please specify the menu text first.")); + if (ui->actionMenu->text().isEmpty()) { + QMessageBox::warning(this, tr("Empty text"), tr("Please specify the menu text first.")); return; } // search for the command in the manager CommandManager& rclMan = Application::Instance->commandManager(); QByteArray actionName = QString::fromStdString(rclMan.newMacroName()).toLatin1(); - auto macro = new MacroCommand(actionName, ui->actionMacros->itemData(ui->actionMacros->currentIndex()).toBool()); - rclMan.addCommand( macro ); + auto macro = + new MacroCommand(actionName, + ui->actionMacros->itemData(ui->actionMacros->currentIndex()).toBool()); + rclMan.addCommand(macro); // add new action auto item = new QTreeWidgetItem(ui->actionListWidget); item->setData(1, Qt::UserRole, actionName); item->setText(1, ui->actionMenu->text()); item->setSizeHint(0, QSize(32, 32)); -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) item->setIcon(0, ui->pixmapLabel->pixmap(Qt::ReturnByValue)); #else - if (ui->pixmapLabel->pixmap()) + if (ui->pixmapLabel->pixmap()) { item->setIcon(0, *ui->pixmapLabel->pixmap()); + } #endif // Convert input text into utf8 - if (!ui->actionWhatsThis->text().isEmpty()) + if (!ui->actionWhatsThis->text().isEmpty()) { macro->setWhatsThis(ui->actionWhatsThis->text().toUtf8()); + } ui->actionWhatsThis->clear(); - if (!ui->actionMacros-> currentText().isEmpty()) + if (!ui->actionMacros->currentText().isEmpty()) { macro->setScriptName(ui->actionMacros->currentText().toUtf8()); + } - if (!ui->actionMenu->text().isEmpty()) + if (!ui->actionMenu->text().isEmpty()) { macro->setMenuText(ui->actionMenu->text().toUtf8()); + } ui->actionMenu->clear(); - if (!ui->actionToolTip->text().isEmpty()) + if (!ui->actionToolTip->text().isEmpty()) { macro->setToolTipText(ui->actionToolTip->text().toUtf8()); + } ui->actionToolTip->clear(); - if (!ui->actionStatus->text().isEmpty()) + if (!ui->actionStatus->text().isEmpty()) { macro->setStatusTip(ui->actionStatus->text().toUtf8()); + } ui->actionStatus->clear(); - if (!m_sPixmap.isEmpty()) + if (!m_sPixmap.isEmpty()) { macro->setPixmap(m_sPixmap.toLatin1()); + } ui->pixmapLabel->clear(); m_sPixmap.clear(); if (!ui->actionAccel->text().isEmpty()) { - ShortcutManager::instance()->setShortcut( - actionName.constData(), ui->actionAccel->text().toLatin1().constData()); + ShortcutManager::instance()->setShortcut(actionName.constData(), + ui->actionAccel->text().toLatin1().constData()); } ui->actionAccel->clear(); @@ -296,15 +309,13 @@ void DlgCustomActionsImp::onButtonAddActionClicked() void DlgCustomActionsImp::onButtonReplaceActionClicked() { QTreeWidgetItem* item = ui->actionListWidget->currentItem(); - if (!item) - { - QMessageBox::warning(this, tr("No item selected"),tr("Please select a macro item first.")); + if (!item) { + QMessageBox::warning(this, tr("No item selected"), tr("Please select a macro item first.")); return; } - if (ui->actionMenu->text().isEmpty()) - { - QMessageBox::warning(this, tr("Empty text"),tr("Please specify the menu text first.")); + if (ui->actionMenu->text().isEmpty()) { + QMessageBox::warning(this, tr("Empty text"), tr("Please specify the menu text first.")); return; } @@ -314,30 +325,37 @@ void DlgCustomActionsImp::onButtonReplaceActionClicked() CommandManager& rclMan = Application::Instance->commandManager(); Command* pCmd = rclMan.getCommandByName(actionName.constData()); auto macro = dynamic_cast(pCmd); - if (!macro) + if (!macro) { return; + } - if (!ui->actionWhatsThis->text().isEmpty()) + if (!ui->actionWhatsThis->text().isEmpty()) { macro->setWhatsThis(ui->actionWhatsThis->text().toUtf8()); + } ui->actionWhatsThis->clear(); - if (!ui->actionMacros-> currentText().isEmpty()) + if (!ui->actionMacros->currentText().isEmpty()) { macro->setScriptName(ui->actionMacros->currentText().toUtf8()); + } - if (!ui->actionMenu->text().isEmpty()) + if (!ui->actionMenu->text().isEmpty()) { macro->setMenuText(ui->actionMenu->text().toUtf8()); + } ui->actionMenu->clear(); - if (!ui->actionToolTip->text().isEmpty()) + if (!ui->actionToolTip->text().isEmpty()) { macro->setToolTipText(ui->actionToolTip->text().toUtf8()); + } ui->actionToolTip->clear(); - if (!ui->actionStatus->text().isEmpty()) + if (!ui->actionStatus->text().isEmpty()) { macro->setStatusTip(ui->actionStatus->text().toUtf8()); + } ui->actionStatus->clear(); - if (!m_sPixmap.isEmpty()) + if (!m_sPixmap.isEmpty()) { macro->setPixmap(m_sPixmap.toLatin1()); + } ui->pixmapLabel->clear(); m_sPixmap.clear(); @@ -348,33 +366,35 @@ void DlgCustomActionsImp::onButtonReplaceActionClicked() // check whether the macro is already in use Action* action = macro->getAction(); - if (action) - { + if (action) { // does all the text related stuff action->setText(QString::fromUtf8(macro->getMenuText())); action->setToolTip(QString::fromUtf8(macro->getToolTipText())); action->setWhatsThis(QString::fromUtf8(macro->getWhatsThis())); action->setStatusTip(QString::fromUtf8(macro->getStatusTip())); - if (macro->getPixmap()) + if (macro->getPixmap()) { action->setIcon(Gui::BitmapFactory().pixmap(macro->getPixmap())); - action->setShortcut(ShortcutManager::instance()->getShortcut( - actionName.constData(), macro->getAccel())); + } + action->setShortcut( + ShortcutManager::instance()->getShortcut(actionName.constData(), macro->getAccel())); } // emit signal to notify the container widget Q_EMIT modifyMacroAction(actionName); // call this at the end because it internally invokes the highlight method - if (macro->getPixmap()) + if (macro->getPixmap()) { item->setIcon(0, Gui::BitmapFactory().pixmap(macro->getPixmap())); + } } void DlgCustomActionsImp::onButtonRemoveActionClicked() { // remove item from list view QTreeWidgetItem* item = ui->actionListWidget->currentItem(); - if (!item) + if (!item) { return; + } int current = ui->actionListWidget->indexOfTopLevelItem(item); ui->actionListWidget->takeTopLevelItem(current); QByteArray actionName = item->data(1, Qt::UserRole).toByteArray(); @@ -383,10 +403,8 @@ void DlgCustomActionsImp::onButtonRemoveActionClicked() // if the command is registered in the manager just remove it CommandManager& rclMan = Application::Instance->commandManager(); std::vector aclCurMacros = rclMan.getGroupCommands("Macros"); - for (auto & aclCurMacro : aclCurMacros) - { - if (actionName == aclCurMacro->getName()) - { + for (auto& aclCurMacro : aclCurMacros) { + if (actionName == aclCurMacro->getName()) { // emit signal to notify the container widget Q_EMIT removeMacroAction(actionName); // remove from manager and delete it immediately @@ -397,7 +415,8 @@ void DlgCustomActionsImp::onButtonRemoveActionClicked() } IconDialog::IconDialog(QWidget* parent) - : QDialog(parent), ui(new Ui_DlgChooseIcon) + : QDialog(parent) + , ui(new Ui_DlgChooseIcon) { ui->setupUi(this); ui->listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -407,7 +426,7 @@ IconDialog::IconDialog(QWidget* parent) QListWidgetItem* item; QStringList names = BitmapFactory().findIconFiles(); - for (const auto & name : names) { + for (const auto& name : names) { item = new QListWidgetItem(ui->listWidget); item->setIcon(QIcon(BitmapFactory().pixmap((const char*)name.toUtf8()))); item->setText(QFileInfo(name).baseName()); @@ -433,12 +452,13 @@ void IconDialog::resizeEvent(QResizeEvent*) void IconDialog::onAddIconPath() { // Add the user defined paths - Base::Reference group = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Bitmaps"); + Base::Reference group = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Bitmaps"); std::vector paths = group->GetASCIIs("CustomPath"); QStringList pathList; - for (const auto & path : paths) + for (const auto& path : paths) { pathList << QString::fromUtf8(path.c_str()); + } IconFolders dlg(pathList, this); dlg.setWindowTitle(tr("Icon folders")); @@ -447,7 +467,7 @@ void IconDialog::onAddIconPath() // Write to user config group->Clear(); - int index=0; + int index = 0; for (QStringList::iterator it = paths.begin(); it != paths.end(); ++it, ++index) { std::stringstream str; str << "CustomPath" << index; @@ -455,19 +475,21 @@ void IconDialog::onAddIconPath() } QStringList search = BitmapFactory().getPaths(); - for (auto & it : search) { + for (auto& it : search) { it = QDir::toNativeSeparators(it); } - for (const auto & path : paths) { + for (const auto& path : paths) { if (search.indexOf(path) < 0) { QStringList filters; QList formats = QImageReader::supportedImageFormats(); - for (const auto & format : formats) - filters << QString::fromLatin1("*.%1").arg(QString::fromLatin1(format).toLower()); + for (const auto& format : formats) { + filters << QString::fromLatin1("*.%1").arg( + QString::fromLatin1(format).toLower()); + } QDir d(path); d.setNameFilters(filters); QFileInfoList fi = d.entryInfoList(); - for (const auto & jt : fi) { + for (const auto& jt : fi) { QString file = jt.absoluteFilePath(); auto item = new QListWidgetItem(ui->listWidget); item->setIcon(QIcon(file)); @@ -494,12 +516,12 @@ void DlgCustomActionsImp::onButtonChoosePixmapClicked() QListWidgetItem* item = dlg.currentItem(); if (item) { m_sPixmap = item->text(); - ui->pixmapLabel->setPixmap(item->icon().pixmap(QSize(32,32))); + ui->pixmapLabel->setPixmap(item->icon().pixmap(QSize(32, 32))); } } } -void DlgCustomActionsImp::changeEvent(QEvent *e) +void DlgCustomActionsImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -511,9 +533,11 @@ void DlgCustomActionsImp::changeEvent(QEvent *e) } IconFolders::IconFolders(const QStringList& paths, QWidget* parent) - : QDialog(parent), restart(false), maxLines(10) + : QDialog(parent) + , restart(false) + , maxLines(10) { - resize(600,400); + resize(600, 400); auto buttonBox = new QDialogButtonBox(this); buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, &QDialogButtonBox::accepted, this, &IconFolders::accept); @@ -530,7 +554,7 @@ IconFolders::IconFolders(const QStringList& paths, QWidget* parent) // Add the user defined paths int numPaths = static_cast(paths.size()); int maxRow = this->maxLines; - for (int row=0; rowsetReadOnly(true); gridLayout->addWidget(edit, row, 0, 1, 1); @@ -559,8 +583,9 @@ IconFolders::IconFolders(const QStringList& paths, QWidget* parent) gridLayout->addWidget(addButton, maxRow, 1, 1, 1); connect(addButton, &QPushButton::clicked, this, &IconFolders::addFolder); - if (numPaths >= this->maxLines) + if (numPaths >= this->maxLines) { addButton->setDisabled(true); + } } IconFolders::~IconFolders() = default; @@ -569,11 +594,13 @@ void IconFolders::addFolder() { int countHidden = -1; QStringList paths; - for (const auto & it : buttonMap) { + for (const auto& it : buttonMap) { if (it.first->isHidden()) { countHidden++; if (countHidden == 0) { - QString dir = QFileDialog::getExistingDirectory(this, IconDialog::tr("Add icon folder"), QString()); + QString dir = QFileDialog::getExistingDirectory(this, + IconDialog::tr("Add icon folder"), + QString()); if (!dir.isEmpty() && paths.indexOf(dir) < 0) { QLineEdit* edit = it.first; edit->setVisible(true); @@ -597,14 +624,16 @@ void IconFolders::removeFolder() { if (!restart) { restart = true; - QMessageBox::information(this, tr("Remove folder"), + QMessageBox::information( + this, + tr("Remove folder"), tr("Removing a folder only takes effect after an application restart.")); } addButton->setEnabled(true); auto remove = static_cast(sender()); QLineEdit* edit = nullptr; - for (const auto & it : buttonMap) { + for (const auto& it : buttonMap) { if (it.second == remove) { edit = it.first; } @@ -628,7 +657,7 @@ void IconFolders::removeFolder() QStringList IconFolders::getPaths() const { QStringList paths; - for (const auto & it : buttonMap) { + for (const auto& it : buttonMap) { if (!it.first->isHidden()) { paths << QDir::toNativeSeparators(it.first->text()); } diff --git a/src/Gui/DlgCustomizeSpNavSettings.cpp b/src/Gui/DlgCustomizeSpNavSettings.cpp index 441ef48ea6..3840d0b20e 100644 --- a/src/Gui/DlgCustomizeSpNavSettings.cpp +++ b/src/Gui/DlgCustomizeSpNavSettings.cpp @@ -30,17 +30,17 @@ using namespace Gui::Dialog; -DlgCustomizeSpNavSettings::DlgCustomizeSpNavSettings(QWidget *parent) : - CustomizeActionPage(parent) - , ui(new Ui_DlgCustomizeSpNavSettings) - , init(false) +DlgCustomizeSpNavSettings::DlgCustomizeSpNavSettings(QWidget* parent) + : CustomizeActionPage(parent) + , ui(new Ui_DlgCustomizeSpNavSettings) + , init(false) { - auto app = qobject_cast(QApplication::instance()); + auto app = qobject_cast(QApplication::instance()); - if (!app) + if (!app) { return; - if (!app->isSpaceballPresent()) - { + } + if (!app->isSpaceballPresent()) { this->setWindowTitle(tr("Spaceball Motion")); this->setMessage(tr("No Spaceball Present")); return; @@ -55,6 +55,7 @@ DlgCustomizeSpNavSettings::~DlgCustomizeSpNavSettings() = default; void DlgCustomizeSpNavSettings::setupConnections() { + // clang-format off connect(ui->CBDominant, &QCheckBox::clicked, this, &DlgCustomizeSpNavSettings::on_CBDominant_clicked); connect(ui->CBFlipYZ, &QCheckBox::clicked, @@ -105,11 +106,12 @@ void DlgCustomizeSpNavSettings::setupConnections() this, &DlgCustomizeSpNavSettings::on_ButtonDefaultSpNavMotions_clicked); connect(ui->ButtonCalibrate, &QPushButton::clicked, this, &DlgCustomizeSpNavSettings::on_ButtonCalibrate_clicked); + // clang-format on } void DlgCustomizeSpNavSettings::setMessage(const QString& message) { - auto messageLabel = new QLabel(message,this); + auto messageLabel = new QLabel(message, this); auto layout = new QVBoxLayout(); auto layout2 = new QHBoxLayout(); layout2->addStretch(); @@ -119,7 +121,7 @@ void DlgCustomizeSpNavSettings::setMessage(const QString& message) this->setLayout(layout); } -void DlgCustomizeSpNavSettings::changeEvent(QEvent *e) +void DlgCustomizeSpNavSettings::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { if (this->init) { @@ -127,8 +129,10 @@ void DlgCustomizeSpNavSettings::changeEvent(QEvent *e) } else { this->setWindowTitle(tr("Spaceball Motion")); - QLabel *messageLabel = this->findChild(); - if (messageLabel) messageLabel->setText(tr("No Spaceball Present")); + QLabel* messageLabel = this->findChild(); + if (messageLabel) { + messageLabel->setText(tr("No Spaceball Present")); + } } } QWidget::changeEvent(e); @@ -136,7 +140,11 @@ void DlgCustomizeSpNavSettings::changeEvent(QEvent *e) ParameterGrp::handle DlgCustomizeSpNavSettings::spaceballMotionGroup() const { - static ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Spaceball")->GetGroup("Motion"); + static ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Spaceball") + ->GetGroup("Motion"); return group; } @@ -153,49 +161,51 @@ void DlgCustomizeSpNavSettings::initialize() ui->CBTranslations->setChecked(spaceballMotionGroup()->GetBool("Translations", true)); ui->SliderGlobal->setValue(spaceballMotionGroup()->GetInt("GlobalSensitivity", 0)); - ui->CBEnablePanLR ->setChecked(spaceballMotionGroup()->GetBool("PanLREnable", true)); + ui->CBEnablePanLR->setChecked(spaceballMotionGroup()->GetBool("PanLREnable", true)); ui->CBReversePanLR->setChecked(spaceballMotionGroup()->GetBool("PanLRReverse", false)); - ui->SliderPanLR ->setValue(spaceballMotionGroup()->GetInt("PanLRSensitivity", 0)); + ui->SliderPanLR->setValue(spaceballMotionGroup()->GetInt("PanLRSensitivity", 0)); - ui->CBEnablePanUD ->setChecked(spaceballMotionGroup()->GetBool("PanUDEnable", true)); + ui->CBEnablePanUD->setChecked(spaceballMotionGroup()->GetBool("PanUDEnable", true)); ui->CBReversePanUD->setChecked(spaceballMotionGroup()->GetBool("PanUDReverse", false)); - ui->SliderPanUD ->setValue(spaceballMotionGroup()->GetInt("PanUDSensitivity", 0)); + ui->SliderPanUD->setValue(spaceballMotionGroup()->GetInt("PanUDSensitivity", 0)); - ui->CBEnableZoom ->setChecked(spaceballMotionGroup()->GetBool("ZoomEnable", true)); + ui->CBEnableZoom->setChecked(spaceballMotionGroup()->GetBool("ZoomEnable", true)); ui->CBReverseZoom->setChecked(spaceballMotionGroup()->GetBool("ZoomReverse", false)); - ui->SliderZoom ->setValue(spaceballMotionGroup()->GetInt("ZoomSensitivity", 0)); + ui->SliderZoom->setValue(spaceballMotionGroup()->GetInt("ZoomSensitivity", 0)); - ui->CBEnableTilt ->setChecked(spaceballMotionGroup()->GetBool("TiltEnable", true)); + ui->CBEnableTilt->setChecked(spaceballMotionGroup()->GetBool("TiltEnable", true)); ui->CBReverseTilt->setChecked(spaceballMotionGroup()->GetBool("TiltReverse", false)); - ui->SliderTilt ->setValue(spaceballMotionGroup()->GetInt("TiltSensitivity", 0)); + ui->SliderTilt->setValue(spaceballMotionGroup()->GetInt("TiltSensitivity", 0)); - ui->CBEnableRoll ->setChecked(spaceballMotionGroup()->GetBool("RollEnable", true)); + ui->CBEnableRoll->setChecked(spaceballMotionGroup()->GetBool("RollEnable", true)); ui->CBReverseRoll->setChecked(spaceballMotionGroup()->GetBool("RollReverse", false)); - ui->SliderRoll ->setValue(spaceballMotionGroup()->GetInt("RollSensitivity", 0)); + ui->SliderRoll->setValue(spaceballMotionGroup()->GetInt("RollSensitivity", 0)); - ui->CBEnableSpin ->setChecked(spaceballMotionGroup()->GetBool("SpinEnable", true)); + ui->CBEnableSpin->setChecked(spaceballMotionGroup()->GetBool("SpinEnable", true)); ui->CBReverseSpin->setChecked(spaceballMotionGroup()->GetBool("SpinReverse", false)); - ui->SliderSpin ->setValue(spaceballMotionGroup()->GetInt("SpinSensitivity", 0)); + ui->SliderSpin->setValue(spaceballMotionGroup()->GetInt("SpinSensitivity", 0)); - ui->CBEnableTilt ->setEnabled(ui->CBRotations->isChecked()); + ui->CBEnableTilt->setEnabled(ui->CBRotations->isChecked()); ui->CBReverseTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked()); - ui->SliderTilt ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked()); - ui->CBEnableRoll ->setEnabled(ui->CBRotations->isChecked()); + ui->SliderTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked()); + ui->CBEnableRoll->setEnabled(ui->CBRotations->isChecked()); ui->CBReverseRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked()); - ui->SliderRoll ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked()); - ui->CBEnableSpin ->setEnabled(ui->CBRotations->isChecked()); + ui->SliderRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked()); + ui->CBEnableSpin->setEnabled(ui->CBRotations->isChecked()); ui->CBReverseSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); - ui->SliderSpin ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); + ui->SliderSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); - ui->CBEnablePanLR ->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); - ui->SliderPanLR ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); - ui->CBEnablePanUD ->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); - ui->SliderPanUD ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); - ui->CBEnableZoom ->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReverseZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); - ui->SliderZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); + ui->CBEnablePanLR->setEnabled(ui->CBTranslations->isChecked()); + ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() + && ui->CBEnablePanLR->isChecked()); + ui->SliderPanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); + ui->CBEnablePanUD->setEnabled(ui->CBTranslations->isChecked()); + ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() + && ui->CBEnablePanUD->isChecked()); + ui->SliderPanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); + ui->CBEnableZoom->setEnabled(ui->CBTranslations->isChecked()); + ui->CBReverseZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); + ui->SliderZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); } void DlgCustomizeSpNavSettings::on_ButtonDefaultSpNavMotions_clicked() @@ -218,30 +228,32 @@ void DlgCustomizeSpNavSettings::on_CBRotations_clicked() { spaceballMotionGroup()->SetBool("Rotations", ui->CBRotations->isChecked()); - ui->CBEnableTilt ->setEnabled(ui->CBRotations->isChecked()); + ui->CBEnableTilt->setEnabled(ui->CBRotations->isChecked()); ui->CBReverseTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked()); - ui->SliderTilt ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked()); - ui->CBEnableRoll ->setEnabled(ui->CBRotations->isChecked()); + ui->SliderTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked()); + ui->CBEnableRoll->setEnabled(ui->CBRotations->isChecked()); ui->CBReverseRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked()); - ui->SliderRoll ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked()); - ui->CBEnableSpin ->setEnabled(ui->CBRotations->isChecked()); + ui->SliderRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked()); + ui->CBEnableSpin->setEnabled(ui->CBRotations->isChecked()); ui->CBReverseSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); - ui->SliderSpin ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); + ui->SliderSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); } void DlgCustomizeSpNavSettings::on_CBTranslations_clicked() { spaceballMotionGroup()->SetBool("Translations", ui->CBTranslations->isChecked()); - ui->CBEnablePanLR ->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); - ui->SliderPanLR ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); - ui->CBEnablePanUD ->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); - ui->SliderPanUD ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); - ui->CBEnableZoom ->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReverseZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); - ui->SliderZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); + ui->CBEnablePanLR->setEnabled(ui->CBTranslations->isChecked()); + ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() + && ui->CBEnablePanLR->isChecked()); + ui->SliderPanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); + ui->CBEnablePanUD->setEnabled(ui->CBTranslations->isChecked()); + ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() + && ui->CBEnablePanUD->isChecked()); + ui->SliderPanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); + ui->CBEnableZoom->setEnabled(ui->CBTranslations->isChecked()); + ui->CBReverseZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); + ui->SliderZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); } void DlgCustomizeSpNavSettings::on_SliderGlobal_sliderReleased() @@ -254,7 +266,7 @@ void DlgCustomizeSpNavSettings::on_CBEnablePanLR_clicked() spaceballMotionGroup()->SetBool("PanLREnable", ui->CBEnablePanLR->isChecked()); ui->CBReversePanLR->setEnabled(ui->CBEnablePanLR->isChecked()); - ui->SliderPanLR ->setEnabled(ui->CBEnablePanLR->isChecked()); + ui->SliderPanLR->setEnabled(ui->CBEnablePanLR->isChecked()); } void DlgCustomizeSpNavSettings::on_CBReversePanLR_clicked() @@ -272,7 +284,7 @@ void DlgCustomizeSpNavSettings::on_CBEnablePanUD_clicked() spaceballMotionGroup()->SetBool("PanUDEnable", ui->CBEnablePanUD->isChecked()); ui->CBReversePanUD->setEnabled(ui->CBEnablePanUD->isChecked()); - ui->SliderPanUD ->setEnabled(ui->CBEnablePanUD->isChecked()); + ui->SliderPanUD->setEnabled(ui->CBEnablePanUD->isChecked()); } void DlgCustomizeSpNavSettings::on_CBReversePanUD_clicked() @@ -289,8 +301,8 @@ void DlgCustomizeSpNavSettings::on_CBEnableZoom_clicked() { spaceballMotionGroup()->SetBool("ZoomEnable", ui->CBEnableZoom->isChecked()); - ui->CBReverseZoom ->setEnabled(ui->CBEnableZoom->isChecked()); - ui->SliderZoom ->setEnabled(ui->CBEnableZoom->isChecked()); + ui->CBReverseZoom->setEnabled(ui->CBEnableZoom->isChecked()); + ui->SliderZoom->setEnabled(ui->CBEnableZoom->isChecked()); } void DlgCustomizeSpNavSettings::on_CBReverseZoom_clicked() @@ -308,7 +320,7 @@ void DlgCustomizeSpNavSettings::on_CBEnableTilt_clicked() spaceballMotionGroup()->SetBool("TiltEnable", ui->CBEnableTilt->isChecked()); ui->CBReverseTilt->setEnabled(ui->CBEnableTilt->isChecked()); - ui->SliderTilt ->setEnabled(ui->CBEnableTilt->isChecked()); + ui->SliderTilt->setEnabled(ui->CBEnableTilt->isChecked()); } void DlgCustomizeSpNavSettings::on_CBReverseTilt_clicked() @@ -326,7 +338,7 @@ void DlgCustomizeSpNavSettings::on_CBEnableRoll_clicked() spaceballMotionGroup()->SetBool("RollEnable", ui->CBEnableRoll->isChecked()); ui->CBReverseRoll->setEnabled(ui->CBEnableRoll->isChecked()); - ui->SliderRoll ->setEnabled(ui->CBEnableRoll->isChecked()); + ui->SliderRoll->setEnabled(ui->CBEnableRoll->isChecked()); } void DlgCustomizeSpNavSettings::on_CBReverseRoll_clicked() @@ -344,7 +356,7 @@ void DlgCustomizeSpNavSettings::on_CBEnableSpin_clicked() spaceballMotionGroup()->SetBool("SpinEnable", ui->CBEnableSpin->isChecked()); ui->CBReverseSpin->setEnabled(ui->CBEnableSpin->isChecked()); - ui->SliderSpin ->setEnabled(ui->CBEnableSpin->isChecked()); + ui->SliderSpin->setEnabled(ui->CBEnableSpin->isChecked()); } void DlgCustomizeSpNavSettings::on_CBReverseSpin_clicked() @@ -357,21 +369,21 @@ void DlgCustomizeSpNavSettings::on_SliderSpin_sliderReleased() spaceballMotionGroup()->SetInt("SpinSensitivity", ui->SliderSpin->value()); } -void DlgCustomizeSpNavSettings::onAddMacroAction(const QByteArray ¯oName) +void DlgCustomizeSpNavSettings::onAddMacroAction(const QByteArray& macroName) { - //don't need to do anything here. + // don't need to do anything here. Q_UNUSED(macroName); } -void DlgCustomizeSpNavSettings::onRemoveMacroAction(const QByteArray ¯oName) +void DlgCustomizeSpNavSettings::onRemoveMacroAction(const QByteArray& macroName) { - //don't need to do anything here. + // don't need to do anything here. Q_UNUSED(macroName); } -void DlgCustomizeSpNavSettings::onModifyMacroAction(const QByteArray ¯oName) +void DlgCustomizeSpNavSettings::onModifyMacroAction(const QByteArray& macroName) { - //don't need to do anything here. + // don't need to do anything here. Q_UNUSED(macroName); } diff --git a/src/Gui/DlgKeyboardImp.cpp b/src/Gui/DlgKeyboardImp.cpp index 2263814e3f..fe703f5a44 100644 --- a/src/Gui/DlgKeyboardImp.cpp +++ b/src/Gui/DlgKeyboardImp.cpp @@ -24,10 +24,10 @@ #include "PreCompiled.h" #include #ifndef _PreComp_ -# include -# include -# include -# include +#include +#include +#include +#include #endif #include @@ -48,19 +48,25 @@ using namespace Gui::Dialog; -namespace Gui { namespace Dialog { -using GroupMap = std::vector< std::pair >; +namespace Gui +{ +namespace Dialog +{ +using GroupMap = std::vector>; -struct GroupMap_find { +struct GroupMap_find +{ const QLatin1String& item; - explicit GroupMap_find(const QLatin1String& item) : item(item) {} - bool operator () (const std::pair& elem) const + explicit GroupMap_find(const QLatin1String& item) + : item(item) + {} + bool operator()(const std::pair& elem) const { return elem.first == item; } }; -} -} +} // namespace Dialog +} // namespace Gui /* TRANSLATOR Gui::Dialog::DlgCustomKeyboardImp */ @@ -71,23 +77,28 @@ struct GroupMap_find { * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgCustomKeyboardImp::DlgCustomKeyboardImp( QWidget* parent ) - : CustomizeActionPage(parent) - , ui(new Ui_DlgCustomKeyboard) - , firstShow(true) +DlgCustomKeyboardImp::DlgCustomKeyboardImp(QWidget* parent) + : CustomizeActionPage(parent) + , ui(new Ui_DlgCustomKeyboard) + , firstShow(true) { ui->setupUi(this); setupConnections(); // Force create actions for all commands with shortcut to register with ShortcutManager for (auto cmd : Application::Instance->commandManager().getAllCommands()) { - if (cmd->getShortcut().size()) + if (cmd->getShortcut().size()) { cmd->initAction(); + } } - QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, this, - [](const char *cmdName) { - if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) + QObject::connect( + ShortcutManager::instance(), + &ShortcutManager::shortcutChanged, + this, + [](const char* cmdName) { + if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) { cmd->initAction(); + } }); conn = initCommandWidgets(ui->commandTreeWidget, @@ -101,7 +112,7 @@ DlgCustomKeyboardImp::DlgCustomKeyboardImp( QWidget* parent ) ui->accelLineEditShortcut); ui->shortcutTimeout->onRestore(); - QTimer *timer = new QTimer(this); + QTimer* timer = new QTimer(this); QObject::connect(ui->shortcutTimeout, qOverload(&QSpinBox::valueChanged), timer, [=](int) { timer->start(100); }); @@ -115,6 +126,7 @@ DlgCustomKeyboardImp::~DlgCustomKeyboardImp() = default; void DlgCustomKeyboardImp::setupConnections() { + // clang-format off connect(ui->categoryBox, qOverload(&QComboBox::activated), this, &DlgCustomKeyboardImp::onCategoryBoxActivated); connect(ui->commandTreeWidget, &QTreeWidget::currentItemChanged, @@ -129,49 +141,52 @@ void DlgCustomKeyboardImp::setupConnections() this, &DlgCustomKeyboardImp::onButtonResetAllClicked); connect(ui->editShortcut, &AccelLineEdit::textChanged, this, &DlgCustomKeyboardImp::onEditShortcutTextChanged); + // clang-format on } -void DlgCustomKeyboardImp::initCommandCompleter(QLineEdit *edit, - QComboBox *combo, - QTreeWidget *commandTreeWidget, - QTreeWidgetItem *separatorItem) +void DlgCustomKeyboardImp::initCommandCompleter(QLineEdit* edit, + QComboBox* combo, + QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem) { edit->setPlaceholderText(tr("Type to search...")); auto completer = new CommandCompleter(edit, edit); - QObject::connect(completer, &CommandCompleter::commandActivated, - [=](const QByteArray &name) { - CommandManager & cCmdMgr = Application::Instance->commandManager(); - Command *cmd = cCmdMgr.getCommandByName(name.constData()); - if (!cmd) - return; + QObject::connect(completer, &CommandCompleter::commandActivated, [=](const QByteArray& name) { + CommandManager& cCmdMgr = Application::Instance->commandManager(); + Command* cmd = cCmdMgr.getCommandByName(name.constData()); + if (!cmd) { + return; + } - QString group = QString::fromLatin1(cmd->getGroupName()); - int index = combo->findData(group); - if (index < 0) + QString group = QString::fromLatin1(cmd->getGroupName()); + int index = combo->findData(group); + if (index < 0) { + return; + } + if (index != combo->currentIndex()) { + QSignalBlocker blocker(combo); + combo->setCurrentIndex(index); + populateCommandList(commandTreeWidget, separatorItem, combo); + } + for (int i = 0; i < commandTreeWidget->topLevelItemCount(); ++i) { + QTreeWidgetItem* item = commandTreeWidget->topLevelItem(i); + if (item->data(1, Qt::UserRole).toByteArray() == name) { + commandTreeWidget->setCurrentItem(item); return; - if (index != combo->currentIndex()) { - QSignalBlocker blocker(combo); - combo->setCurrentIndex(index); - populateCommandList(commandTreeWidget, separatorItem, combo); } - for (int i=0 ; itopLevelItemCount(); ++i) { - QTreeWidgetItem *item = commandTreeWidget->topLevelItem(i); - if (item->data(1, Qt::UserRole).toByteArray() == name) { - commandTreeWidget->setCurrentItem(item); - return; - } - } - }); + } + }); } -void DlgCustomKeyboardImp::populateCommandList(QTreeWidget *commandTreeWidget, - QTreeWidgetItem *separatorItem, - QComboBox *combo) +void DlgCustomKeyboardImp::populateCommandList(QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* combo) { QByteArray current; - if (auto item = commandTreeWidget->currentItem()) + if (auto item = commandTreeWidget->currentItem()) { current = item->data(1, Qt::UserRole).toByteArray(); + } if (separatorItem) { commandTreeWidget->takeTopLevelItem(commandTreeWidget->indexOfTopLevelItem(separatorItem)); @@ -181,36 +196,39 @@ void DlgCustomKeyboardImp::populateCommandList(QTreeWidget *commandTreeWidget, commandTreeWidget->addTopLevelItem(separatorItem); } - CommandManager & cCmdMgr = Application::Instance->commandManager(); + CommandManager& cCmdMgr = Application::Instance->commandManager(); auto group = combo->itemData(combo->currentIndex(), Qt::UserRole).toByteArray(); - auto cmds = group == "All" ? cCmdMgr.getAllCommands() - : cCmdMgr.getGroupCommands(group.constData()); - QTreeWidgetItem *currentItem = nullptr; - for (const Command *cmd : cmds) { + auto cmds = + group == "All" ? cCmdMgr.getAllCommands() : cCmdMgr.getGroupCommands(group.constData()); + QTreeWidgetItem* currentItem = nullptr; + for (const Command* cmd : cmds) { QTreeWidgetItem* item = new QTreeWidgetItem(commandTreeWidget); item->setText(1, Action::commandMenuText(cmd)); item->setToolTip(1, Action::commandToolTip(cmd)); item->setData(1, Qt::UserRole, QByteArray(cmd->getName())); item->setSizeHint(0, QSize(32, 32)); - if (auto pixmap = cmd->getPixmap()) + if (auto pixmap = cmd->getPixmap()) { item->setIcon(0, BitmapFactory().iconFromTheme(pixmap)); + } item->setText(2, cmd->getShortcut()); - if (auto accel = cmd->getAccel()) + if (auto accel = cmd->getAccel()) { item->setText(3, QKeySequence(QString::fromLatin1(accel)).toString()); + } - if (current == cmd->getName()) + if (current == cmd->getName()) { currentItem = item; + } } - if (currentItem) + if (currentItem) { commandTreeWidget->setCurrentItem(currentItem); + } commandTreeWidget->resizeColumnToContents(2); commandTreeWidget->resizeColumnToContents(3); } -boost::signals2::connection -DlgCustomKeyboardImp::initCommandList(QTreeWidget *commandTreeWidget, - QTreeWidgetItem *separatorItem, - QComboBox *combo) +boost::signals2::connection DlgCustomKeyboardImp::initCommandList(QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* combo) { QStringList labels; labels << tr("Icon") << tr("Command") << tr("Shortcut") << tr("Default"); @@ -225,30 +243,33 @@ DlgCustomKeyboardImp::initCommandList(QTreeWidget *commandTreeWidget, // Using a timer to respond to command change for performance, and also // because macro command may be added before proper initialization (null // menu text, etc.) - QTimer *timer = new QTimer(combo); + QTimer* timer = new QTimer(combo); timer->setSingleShot(true); - QObject::connect(timer, &QTimer::timeout, [=](){ + QObject::connect(timer, &QTimer::timeout, [=]() { populateCommandGroups(combo); populateCommandList(commandTreeWidget, separatorItem, combo); }); - QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, timer, [timer]() { - timer->start(100); - }); + QObject::connect(ShortcutManager::instance(), + &ShortcutManager::shortcutChanged, + timer, + [timer]() { + timer->start(100); + }); QObject::connect(combo, qOverload(&QComboBox::activated), timer, [timer]() { timer->start(100); }); - return Application::Instance->commandManager().signalChanged.connect([timer](){ + return Application::Instance->commandManager().signalChanged.connect([timer]() { timer->start(100); }); } -void DlgCustomKeyboardImp::initPriorityList(QTreeWidget *priorityList, - QAbstractButton *buttonUp, - QAbstractButton *buttonDown) +void DlgCustomKeyboardImp::initPriorityList(QTreeWidget* priorityList, + QAbstractButton* buttonUp, + QAbstractButton* buttonDown) { QStringList labels; labels << tr("Name") << tr("Title"); @@ -259,18 +280,20 @@ void DlgCustomKeyboardImp::initPriorityList(QTreeWidget *priorityList, auto updatePriorityList = [priorityList](bool up) { auto item = priorityList->currentItem(); - if (!item) + if (!item) { return; + } int index = priorityList->indexOfTopLevelItem(item); - if (index < 0) + if (index < 0) { return; - if ((index == 0 && up) - || (index == priorityList->topLevelItemCount()-1 && !up)) + } + if ((index == 0 && up) || (index == priorityList->topLevelItemCount() - 1 && !up)) { return; + } std::vector actions; - for (int i=0; itopLevelItemCount(); ++i) { + for (int i = 0; i < priorityList->topLevelItemCount(); ++i) { auto item = priorityList->topLevelItem(i); actions.push_back(item->data(0, Qt::UserRole).toByteArray()); } @@ -281,26 +304,28 @@ void DlgCustomKeyboardImp::initPriorityList(QTreeWidget *priorityList, ShortcutManager::instance()->setPriorities(actions); }; - QObject::connect(buttonUp, &QAbstractButton::clicked, [=](){updatePriorityList(true);}); - QObject::connect(buttonDown, &QAbstractButton::clicked, [=](){updatePriorityList(false);}); - QObject::connect(priorityList, &QTreeWidget::currentItemChanged, - [=](QTreeWidgetItem *item){ - buttonUp->setEnabled(item!=nullptr); - buttonDown->setEnabled(item!=nullptr); - } - ); + QObject::connect(buttonUp, &QAbstractButton::clicked, [=]() { + updatePriorityList(true); + }); + QObject::connect(buttonDown, &QAbstractButton::clicked, [=]() { + updatePriorityList(false); + }); + QObject::connect(priorityList, &QTreeWidget::currentItemChanged, [=](QTreeWidgetItem* item) { + buttonUp->setEnabled(item != nullptr); + buttonDown->setEnabled(item != nullptr); + }); } boost::signals2::connection -DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget *commandTreeWidget, - QTreeWidgetItem *separatorItem, - QComboBox *comboGroups, - QLineEdit *editCommand, - QTreeWidget *priorityList, - QAbstractButton *buttonUp, - QAbstractButton *buttonDown, - Gui::AccelLineEdit *editShortcut, - Gui::AccelLineEdit *currentShortcut) +DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* comboGroups, + QLineEdit* editCommand, + QTreeWidget* priorityList, + QAbstractButton* buttonUp, + QAbstractButton* buttonDown, + Gui::AccelLineEdit* editShortcut, + Gui::AccelLineEdit* currentShortcut) { initCommandCompleter(editCommand, comboGroups, commandTreeWidget, separatorItem); auto conn = initCommandList(commandTreeWidget, separatorItem, comboGroups); @@ -318,9 +343,12 @@ DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget *commandTreeWidget, QObject::connect(editShortcut, &QLineEdit::textChanged, timer, [timer]() { timer->start(200); }); - QObject::connect(ShortcutManager::instance(), &ShortcutManager::priorityChanged, timer, [timer](){ - timer->start(200); - }); + QObject::connect(ShortcutManager::instance(), + &ShortcutManager::priorityChanged, + timer, + [timer]() { + timer->start(200); + }); QObject::connect(timer, &QTimer::timeout, [=]() { populatePriorityList(priorityList, editShortcut, currentShortcut); }); @@ -329,45 +357,51 @@ DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget *commandTreeWidget, return conn; } -void DlgCustomKeyboardImp::populatePriorityList(QTreeWidget *priorityList, - Gui::AccelLineEdit *editor, - Gui::AccelLineEdit *curShortcut) +void DlgCustomKeyboardImp::populatePriorityList(QTreeWidget* priorityList, + Gui::AccelLineEdit* editor, + Gui::AccelLineEdit* curShortcut) { QByteArray current; - if (auto currentItem = priorityList->currentItem()) + if (auto currentItem = priorityList->currentItem()) { current = currentItem->data(0, Qt::UserRole).toByteArray(); + } priorityList->clear(); QString sc; - if (!editor->isNone() && editor->text().size()) + if (!editor->isNone() && editor->text().size()) { sc = editor->text(); - else if (curShortcut && !curShortcut->isNone()) + } + else if (curShortcut && !curShortcut->isNone()) { sc = curShortcut->text(); + } auto actionList = ShortcutManager::instance()->getActionsByShortcut(sc); - QTreeWidgetItem *currentItem = nullptr; - for (const auto &info : actionList) { - if (!info.second) + QTreeWidgetItem* currentItem = nullptr; + for (const auto& info : actionList) { + if (!info.second) { continue; + } QTreeWidgetItem* item = new QTreeWidgetItem(priorityList); item->setText(0, QString::fromUtf8(info.first)); item->setText(1, Action::cleanTitle(info.second->text())); item->setToolTip(0, info.second->toolTip()); item->setIcon(0, info.second->icon()); item->setData(0, Qt::UserRole, info.first); - if (current == info.first) + if (current == info.first) { currentItem = item; + } } priorityList->resizeColumnToContents(0); priorityList->resizeColumnToContents(1); - if (currentItem) + if (currentItem) { priorityList->setCurrentItem(currentItem); + } } -void DlgCustomKeyboardImp::populateCommandGroups(QComboBox *combo) +void DlgCustomKeyboardImp::populateCommandGroups(QComboBox* combo) { - CommandManager & cCmdMgr = Application::Instance->commandManager(); - std::map sCommands = cCmdMgr.getCommands(); + CommandManager& cCmdMgr = Application::Instance->commandManager(); + std::map sCommands = cCmdMgr.getCommands(); GroupMap groupMap; groupMap.push_back(std::make_pair(QLatin1String("File"), QString())); @@ -377,16 +411,18 @@ void DlgCustomKeyboardImp::populateCommandGroups(QComboBox *combo) groupMap.push_back(std::make_pair(QLatin1String("Tools"), QString())); groupMap.push_back(std::make_pair(QLatin1String("Window"), QString())); groupMap.push_back(std::make_pair(QLatin1String("Help"), QString())); - groupMap.push_back(std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros"))); + groupMap.push_back( + std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros"))); - for (const auto & sCommand : sCommands) { + for (const auto& sCommand : sCommands) { QLatin1String group(sCommand.second->getGroupName()); QString text = sCommand.second->translatedGroupName(); GroupMap::iterator jt; jt = std::find_if(groupMap.begin(), groupMap.end(), GroupMap_find(group)); if (jt != groupMap.end()) { - if (jt->second.isEmpty()) + if (jt->second.isEmpty()) { jt->second = text; + } } else { groupMap.push_back(std::make_pair(group, text)); @@ -394,10 +430,10 @@ void DlgCustomKeyboardImp::populateCommandGroups(QComboBox *combo) } groupMap.push_back(std::make_pair(QLatin1String("All"), tr("All"))); - for (const auto & it : groupMap) { + for (const auto& it : groupMap) { if (combo->findData(it.first) < 0) { combo->addItem(it.second); - combo->setItemData(combo->count()-1, QVariant(it.first), Qt::UserRole); + combo->setItemData(combo->count() - 1, QVariant(it.first), Qt::UserRole); } } } @@ -416,23 +452,25 @@ void DlgCustomKeyboardImp::showEvent(QShowEvent* e) /** Shows the description for the corresponding command */ void DlgCustomKeyboardImp::onCommandTreeWidgetCurrentItemChanged(QTreeWidgetItem* item) { - if (!item) + if (!item) { return; + } QVariant data = item->data(1, Qt::UserRole); - QByteArray name = data.toByteArray(); // command name + QByteArray name = data.toByteArray(); // command name - CommandManager & cCmdMgr = Application::Instance->commandManager(); + CommandManager& cCmdMgr = Application::Instance->commandManager(); Command* cmd = cCmdMgr.getCommandByName(name.constData()); if (cmd) { - QKeySequence ks = ShortcutManager::instance()->getShortcut( - cmd->getName(), cmd->getAccel()); + QKeySequence ks = ShortcutManager::instance()->getShortcut(cmd->getName(), cmd->getAccel()); QKeySequence ks2 = QString::fromLatin1(cmd->getAccel()); QKeySequence ks3 = ui->editShortcut->text(); - if (ks.isEmpty()) - ui->accelLineEditShortcut->setText( tr("none") ); - else + if (ks.isEmpty()) { + ui->accelLineEditShortcut->setText(tr("none")); + } + else { ui->accelLineEditShortcut->setText(ks.toString(QKeySequence::NativeText)); + } ui->buttonAssign->setEnabled(!ui->editShortcut->text().isEmpty() && (ks != ks3)); ui->buttonReset->setEnabled((ks != ks2)); @@ -451,11 +489,12 @@ void DlgCustomKeyboardImp::onCategoryBoxActivated(int) void DlgCustomKeyboardImp::setShortcutOfCurrentAction(const QString& accelText) { QTreeWidgetItem* item = ui->commandTreeWidget->currentItem(); - if (!item) + if (!item) { return; + } QVariant data = item->data(1, Qt::UserRole); - QByteArray name = data.toByteArray(); // command name + QByteArray name = data.toByteArray(); // command name QString portableText; if (!accelText.isEmpty()) { @@ -490,16 +529,17 @@ void DlgCustomKeyboardImp::onButtonClearClicked() void DlgCustomKeyboardImp::onButtonResetClicked() { QTreeWidgetItem* item = ui->commandTreeWidget->currentItem(); - if (!item) + if (!item) { return; + } QVariant data = item->data(1, Qt::UserRole); - QByteArray name = data.toByteArray(); // command name + QByteArray name = data.toByteArray(); // command name ShortcutManager::instance()->reset(name); QString txt = ShortcutManager::instance()->getShortcut(name); ui->accelLineEditShortcut->setText((txt.isEmpty() ? tr("none") : txt)); - ui->buttonReset->setEnabled( false ); + ui->buttonReset->setEnabled(false); } /** Resets the accelerator of all commands to the default. */ @@ -510,32 +550,32 @@ void DlgCustomKeyboardImp::onButtonResetAllClicked() } /** Checks for an already occupied shortcut. */ -void DlgCustomKeyboardImp::onEditShortcutTextChanged(const QString& ) +void DlgCustomKeyboardImp::onEditShortcutTextChanged(const QString&) { QTreeWidgetItem* item = ui->commandTreeWidget->currentItem(); if (item) { QVariant data = item->data(1, Qt::UserRole); - QByteArray name = data.toByteArray(); // command name + QByteArray name = data.toByteArray(); // command name - CommandManager & cCmdMgr = Application::Instance->commandManager(); + CommandManager& cCmdMgr = Application::Instance->commandManager(); Command* cmd = cCmdMgr.getCommandByName(name.constData()); - if (!ui->editShortcut->isNone()) + if (!ui->editShortcut->isNone()) { ui->buttonAssign->setEnabled(true); + } else { - if (cmd && cmd->getAction() && cmd->getAction()->shortcut().isEmpty()) - ui->buttonAssign->setEnabled(false); // both key sequences are empty + if (cmd && cmd->getAction() && cmd->getAction()->shortcut().isEmpty()) { + ui->buttonAssign->setEnabled(false); // both key sequences are empty + } } } } void DlgCustomKeyboardImp::onAddMacroAction(const QByteArray&) -{ -} +{} void DlgCustomKeyboardImp::onRemoveMacroAction(const QByteArray&) -{ -} +{} void DlgCustomKeyboardImp::onModifyMacroAction(const QByteArray&) { @@ -546,14 +586,14 @@ void DlgCustomKeyboardImp::onModifyMacroAction(const QByteArray&) } } -void DlgCustomKeyboardImp::changeEvent(QEvent *e) +void DlgCustomKeyboardImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); int count = ui->categoryBox->count(); - CommandManager & cCmdMgr = Application::Instance->commandManager(); - for (int i=0; icommandManager(); + for (int i = 0; i < count; i++) { QVariant data = ui->categoryBox->itemData(i, Qt::UserRole); std::vector aCmds = cCmdMgr.getGroupCommands(data.toByteArray()); if (!aCmds.empty()) { diff --git a/src/Gui/DlgMacroExecuteImp.cpp b/src/Gui/DlgMacroExecuteImp.cpp index 11781d4ef8..b361c20b41 100644 --- a/src/Gui/DlgMacroExecuteImp.cpp +++ b/src/Gui/DlgMacroExecuteImp.cpp @@ -22,12 +22,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #endif #include @@ -50,21 +50,24 @@ using namespace Gui; using namespace Gui::Dialog; -namespace Gui { - namespace Dialog { - class MacroItem : public QTreeWidgetItem - { - public: - MacroItem(QTreeWidget * widget, bool systemwide) - : QTreeWidgetItem(widget), - systemWide(systemwide){} +namespace Gui +{ +namespace Dialog +{ +class MacroItem: public QTreeWidgetItem +{ +public: + MacroItem(QTreeWidget* widget, bool systemwide) + : QTreeWidgetItem(widget) + , systemWide(systemwide) + {} - ~MacroItem() override = default; + ~MacroItem() override = default; - bool systemWide; - }; - } -} + bool systemWide; +}; +} // namespace Dialog +} // namespace Gui /* TRANSLATOR Gui::Dialog::DlgMacroExecuteImp */ @@ -76,9 +79,9 @@ namespace Gui { * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgMacroExecuteImp::DlgMacroExecuteImp( QWidget* parent, Qt::WindowFlags fl ) - : QDialog( parent, fl ) - , WindowParameter( "Macro" ) +DlgMacroExecuteImp::DlgMacroExecuteImp(QWidget* parent, Qt::WindowFlags fl) + : QDialog(parent, fl) + , WindowParameter("Macro") , ui(new Ui_DlgMacroExecute) { watcher = std::make_unique(this); @@ -88,14 +91,16 @@ DlgMacroExecuteImp::DlgMacroExecuteImp( QWidget* parent, Qt::WindowFlags fl ) // retrieve the macro path from parameter or use the user data as default { QSignalBlocker blocker(ui->fileChooser); - std::string path = getWindowParameter()->GetASCII("MacroPath", - App::Application::getUserMacroDir().c_str()); + std::string path = + getWindowParameter()->GetASCII("MacroPath", + App::Application::getUserMacroDir().c_str()); this->macroPath = QString::fromUtf8(path.c_str()); ui->fileChooser->setFileName(this->macroPath); } // Fill the List box - QStringList labels; labels << tr("Macros"); + QStringList labels; + labels << tr("Macros"); ui->userMacroListBox->setHeaderLabels(labels); ui->userMacroListBox->header()->hide(); ui->systemMacroListBox->setHeaderLabels(labels); @@ -111,6 +116,7 @@ DlgMacroExecuteImp::~DlgMacroExecuteImp() = default; void DlgMacroExecuteImp::setupConnections() { + // clang-format off connect(ui->fileChooser, &FileChooser::fileNameChanged, this, &DlgMacroExecuteImp::onFileChooserFileNameChanged); connect(ui->createButton, &QPushButton::clicked, @@ -137,6 +143,7 @@ void DlgMacroExecuteImp::setupConnections() this, &DlgMacroExecuteImp::onLineEditFindTextChanged); connect(ui->LineEditFindInFiles, &QLineEdit::textChanged, this, &DlgMacroExecuteImp::onLineEditFindInFilesTextChanged); + // clang-format on } /** Take a folder and return a StringList of the filenames in it @@ -154,27 +161,30 @@ void DlgMacroExecuteImp::setupConnections() * doing both the User and System macro list boxes in the fillUpList() function. */ -QStringList DlgMacroExecuteImp::filterFiles(const QString& folder){ +QStringList DlgMacroExecuteImp::filterFiles(const QString& folder) +{ QDir dir(folder, QLatin1String("*.FCMacro *.py")); - QStringList unfiltered = dir.entryList(); //all .fcmacro and .py files - QString fileFilter = ui->LineEditFind->text(); //used to search by filename - QString searchText = ui->LineEditFindInFiles->text(); //used to search in file content + QStringList unfiltered = dir.entryList(); // all .fcmacro and .py files + QString fileFilter = ui->LineEditFind->text(); // used to search by filename + QString searchText = ui->LineEditFindInFiles->text(); // used to search in file content - if (fileFilter.isEmpty() && searchText.isEmpty()){ //skip filtering if no filters + if (fileFilter.isEmpty() && searchText.isEmpty()) { // skip filtering if no filters return unfiltered; } QStringList filteredByFileName; - if (fileFilter.isEmpty()){ - filteredByFileName = unfiltered; //skip the loop if no file filter - } else { + if (fileFilter.isEmpty()) { + filteredByFileName = unfiltered; // skip the loop if no file filter + } + else { QRegularExpression regexFileName(fileFilter, QRegularExpression::CaseInsensitiveOption); - bool isValidFileFilter = regexFileName.isValid(); //check here instead of inside the loop - for (auto uf : unfiltered){ - if (isValidFileFilter){ + bool isValidFileFilter = regexFileName.isValid(); // check here instead of inside the loop + for (auto uf : unfiltered) { + if (isValidFileFilter) { if (regexFileName.match(uf).hasMatch()) { filteredByFileName.append(uf); } - } else { //not valid, so do a simple text search + } + else { // not valid, so do a simple text search if (uf.contains(fileFilter, Qt::CaseInsensitive)) { filteredByFileName.append(uf); } @@ -182,7 +192,7 @@ QStringList DlgMacroExecuteImp::filterFiles(const QString& folder){ } } - if (searchText.isEmpty()){ //skip reading file contents if no find in file filter + if (searchText.isEmpty()) { // skip reading file contents if no find in file filter return filteredByFileName; } @@ -190,18 +200,19 @@ QStringList DlgMacroExecuteImp::filterFiles(const QString& folder){ bool isValidContentFilter = regexContent.isValid(); QStringList filteredByContent; for (auto fn : filteredByFileName) { - const QString &fileName = fn; + const QString& fileName = fn; QString filePath = dir.filePath(fileName); QFile file(filePath); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&file); QString fileContent = in.readAll(); - if (isValidContentFilter){ + if (isValidContentFilter) { if (regexContent.match(fileContent).hasMatch()) { filteredByContent.append(fileName); } - } else { - if (fileContent.contains(searchText, Qt::CaseInsensitive)){ + } + else { + if (fileContent.contains(searchText, Qt::CaseInsensitive)) { filteredByContent.append(fileName); } } @@ -219,17 +230,18 @@ void DlgMacroExecuteImp::fillUpList() { QStringList filteredByContent = this->filterFiles(this->macroPath); ui->userMacroListBox->clear(); - for (auto fn : filteredByContent){ - auto item = new MacroItem(ui->userMacroListBox,false); + for (auto fn : filteredByContent) { + auto item = new MacroItem(ui->userMacroListBox, false); item->setText(0, fn); } - QString dirstr = QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro"); + QString dirstr = + QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro"); filteredByContent = this->filterFiles(dirstr); ui->systemMacroListBox->clear(); for (auto fn : filteredByContent) { - auto item = new MacroItem(ui->systemMacroListBox,true); + auto item = new MacroItem(ui->systemMacroListBox, true); item->setText(0, fn); } } @@ -262,12 +274,14 @@ void DlgMacroExecuteImp::onUserMacroListBoxCurrentItemChanged(QTreeWidgetItem* i } } -void DlgMacroExecuteImp::onLineEditFindTextChanged(const QString &text){ +void DlgMacroExecuteImp::onLineEditFindTextChanged(const QString& text) +{ Q_UNUSED(text); this->fillUpList(); } -void DlgMacroExecuteImp::onLineEditFindInFilesTextChanged(const QString &text){ +void DlgMacroExecuteImp::onLineEditFindInFilesTextChanged(const QString& text) +{ Q_UNUSED(text); this->fillUpList(); } @@ -281,7 +295,7 @@ void DlgMacroExecuteImp::onSystemMacroListBoxCurrentItemChanged(QTreeWidgetItem* ui->deleteButton->setEnabled(false); ui->toolbarButton->setEnabled(false); ui->createButton->setEnabled(false); - ui->editButton->setEnabled(true); //look but don't touch + ui->editButton->setEnabled(true); // look but don't touch ui->renameButton->setEnabled(false); ui->duplicateButton->setEnabled(false); } @@ -300,7 +314,7 @@ void DlgMacroExecuteImp::onTabMacroWidgetCurrentChanged(int index) { QTreeWidgetItem* item; - if (index == 0) { //user-specific + if (index == 0) { // user-specific item = ui->userMacroListBox->currentItem(); if (item) { ui->executeButton->setEnabled(true); @@ -321,7 +335,7 @@ void DlgMacroExecuteImp::onTabMacroWidgetCurrentChanged(int index) ui->duplicateButton->setEnabled(false); } } - else { //index==1 system-wide + else { // index==1 system-wide item = ui->systemMacroListBox->currentItem(); if (item) { @@ -329,7 +343,7 @@ void DlgMacroExecuteImp::onTabMacroWidgetCurrentChanged(int index) ui->deleteButton->setEnabled(false); ui->toolbarButton->setEnabled(false); ui->createButton->setEnabled(false); - ui->editButton->setEnabled(true); //but you can't save it + ui->editButton->setEnabled(true); // but you can't save it ui->renameButton->setEnabled(false); ui->duplicateButton->setEnabled(false); } @@ -360,27 +374,29 @@ void DlgMacroExecuteImp::accept() QTreeWidgetItem* item; int index = ui->tabMacroWidget->currentIndex(); - if (index == 0) { //user-specific + if (index == 0) { // user-specific item = ui->userMacroListBox->currentItem(); } else { - //index == 1 system-wide + // index == 1 system-wide item = ui->systemMacroListBox->currentItem(); } - if (!item) + if (!item) { return; + } QDialog::accept(); - auto mitem = static_cast(item); + auto mitem = static_cast(item); QDir dir; - if (!mitem->systemWide){ - dir =QDir(this->macroPath); + if (!mitem->systemWide) { + dir = QDir(this->macroPath); } else { - QString dirstr = QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro"); + QString dirstr = + QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro"); dir = QDir(dirstr); } @@ -392,8 +408,9 @@ void DlgMacroExecuteImp::accept() getMainWindow()->appendRecentMacro(fi.filePath()); Application::Instance->macroManager()->run(Gui::MacroManager::File, fi.filePath().toUtf8()); // after macro run recalculate the document - if (Application::Instance->activeDocument()) + if (Application::Instance->activeDocument()) { Application::Instance->activeDocument()->getDocument()->recompute(); + } getMainWindow()->unsetCursor(); } catch (const Base::SystemExitException&) { @@ -410,11 +427,10 @@ void DlgMacroExecuteImp::accept() */ void DlgMacroExecuteImp::onFileChooserFileNameChanged(const QString& fn) { - if (!fn.isEmpty()) - { + if (!fn.isEmpty()) { // save the path in the parameters this->macroPath = fn; - getWindowParameter()->SetASCII("MacroPath",fn.toUtf8()); + getWindowParameter()->SetASCII("MacroPath", fn.toUtf8()); // fill the list box fillUpList(); } @@ -429,20 +445,22 @@ void DlgMacroExecuteImp::onEditButtonClicked() QTreeWidgetItem* item = nullptr; int index = ui->tabMacroWidget->currentIndex(); - if (index == 0) { //user-specific + if (index == 0) { // user-specific item = ui->userMacroListBox->currentItem(); dir.setPath(this->macroPath); } else { - //index == 1 system-wide + // index == 1 system-wide item = ui->systemMacroListBox->currentItem(); - dir.setPath(QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro")); + dir.setPath(QString::fromStdString(App::Application::getHomePath()) + + QString::fromLatin1("Macro")); } - if (!item) + if (!item) { return; + } - auto mitem = static_cast(item); + auto mitem = static_cast(item); QString file = QString::fromLatin1("%1/%2").arg(dir.absolutePath(), item->text(0)); auto editor = new PythonEditor(); @@ -467,37 +485,47 @@ void DlgMacroExecuteImp::onEditButtonClicked() void DlgMacroExecuteImp::onCreateButtonClicked() { // query file name - bool replaceSpaces = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->GetBool("ReplaceSpaces", true); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->SetBool("ReplaceSpaces", replaceSpaces); //create parameter + bool replaceSpaces = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetBool("ReplaceSpaces", true); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter - QString fn = QInputDialog::getText(this, tr("Macro file"), tr("Enter a file name, please:"), - QLineEdit::Normal, QString(), nullptr, Qt::MSWindowsFixedSizeDialogHint); + QString fn = QInputDialog::getText(this, + tr("Macro file"), + tr("Enter a file name, please:"), + QLineEdit::Normal, + QString(), + nullptr, + Qt::MSWindowsFixedSizeDialogHint); - if(replaceSpaces){ - fn = fn.replace(QString::fromStdString(" "),QString::fromStdString("_")); + if (replaceSpaces) { + fn = fn.replace(QString::fromStdString(" "), QString::fromStdString("_")); } - if (!fn.isEmpty()) - { + if (!fn.isEmpty()) { QString suffix = QFileInfo(fn).suffix().toLower(); - if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) + if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) { fn += QLatin1String(".FCMacro"); + } QDir dir(this->macroPath); // create the macroPath if nonexistent if (!dir.exists()) { dir.mkpath(this->macroPath); } QFileInfo fi(dir, fn); - if (fi.exists() && fi.isFile()) - { - QMessageBox::warning(this, tr("Existing file"), - tr("'%1'.\nThis file already exists.").arg(fi.fileName())); + if (fi.exists() && fi.isFile()) { + QMessageBox::warning(this, + tr("Existing file"), + tr("'%1'.\nThis file already exists.").arg(fi.fileName())); } - else - { + else { QFile file(fi.absoluteFilePath()); if (!file.open(QFile::WriteOnly)) { - QMessageBox::warning(this, tr("Cannot create file"), + QMessageBox::warning( + this, + tr("Cannot create file"), tr("Creation of file '%1' failed.").arg(fi.absoluteFilePath())); return; } @@ -519,21 +547,25 @@ void DlgMacroExecuteImp::onCreateButtonClicked() void DlgMacroExecuteImp::onDeleteButtonClicked() { QTreeWidgetItem* item = ui->userMacroListBox->currentItem(); - if (!item) + if (!item) { return; + } - auto mitem = static_cast(item); + auto mitem = static_cast(item); if (mitem->systemWide) { - QMessageBox::critical(Gui::getMainWindow(), QObject::tr("Delete macro"), - QObject::tr("Not allowed to delete system-wide macros")); + QMessageBox::critical(Gui::getMainWindow(), + QObject::tr("Delete macro"), + QObject::tr("Not allowed to delete system-wide macros")); return; } QString fn = item->text(0); - auto ret = QMessageBox::question(this, tr("Delete macro"), - tr("Do you really want to delete the macro '%1'?").arg( fn ), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + auto ret = QMessageBox::question(this, + tr("Delete macro"), + tr("Do you really want to delete the macro '%1'?").arg(fn), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No); if (ret == QMessageBox::Yes) { QDir dir(this->macroPath); dir.remove(fn); @@ -556,12 +588,15 @@ void DlgMacroExecuteImp::onToolbarButtonClicked() /** * advise user of what we are doing, offer chance to cancel * unless user already said not to show this messagebox again - **/ + **/ - bool showAgain = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->GetBool("ShowWalkthroughMessage", true); - if (showAgain){ + bool showAgain = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetBool("ShowWalkthroughMessage", true); + if (showAgain) { QMessageBox msgBox; - QAbstractButton* doNotShowAgainButton = msgBox.addButton(tr("Do not show again"), QMessageBox::YesRole); + QAbstractButton* doNotShowAgainButton = + msgBox.addButton(tr("Do not show again"), QMessageBox::YesRole); msgBox.setText(tr("Guided Walkthrough")); msgBox.setInformativeText(tr("This will guide you in setting up this macro in a custom \ global toolbar. Instructions will be in red text inside the dialog.\n\ @@ -570,33 +605,40 @@ Note: your changes will be applied when you next switch workbenches\n")); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Ok); int result = msgBox.exec(); - if (result == QMessageBox::Cancel){ + if (result == QMessageBox::Cancel) { return; } - if (msgBox.clickedButton() == doNotShowAgainButton){ - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->SetBool("ShowWalkthroughMessage",false); + if (msgBox.clickedButton() == doNotShowAgainButton) { + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->SetBool("ShowWalkthroughMessage", false); } } QTreeWidgetItem* item = ui->userMacroListBox->currentItem(); - if (!item) + if (!item) { return; + } QString fn = item->text(0); - QString bareFileName = QFileInfo(fn).baseName(); //for use as default menu text (filename without extension) + QString bareFileName = + QFileInfo(fn).baseName(); // for use as default menu text (filename without extension) /** check if user already has custom toolbar, so we can tailor instructions accordingly **/ bool hasCustomToolbar = true; - if (App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Workbench/Global/Toolbar")->GetGroups().empty()) { - hasCustomToolbar=false; + if (App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Workbench/Global/Toolbar") + ->GetGroups() + .empty()) { + hasCustomToolbar = false; } /** check if user already has this macro command created, if so skip dialog 1 **/ bool hasMacroCommand = false; QString macroMenuText; - CommandManager & cCmdMgr = Application::Instance->commandManager(); + CommandManager& cCmdMgr = Application::Instance->commandManager(); std::vector aCmds = cCmdMgr.getGroupCommands("Macros"); - for (const auto & aCmd : aCmds) { + for (const auto& aCmd : aCmds) { auto mc = dynamic_cast(aCmd); if (mc && fn.compare(QLatin1String(mc->getScriptName())) == 0) { hasMacroCommand = true; @@ -606,7 +648,7 @@ Note: your changes will be applied when you next switch workbenches\n")); QTabWidget* tabWidget = nullptr; - if (!hasMacroCommand){ + if (!hasMacroCommand) { /** first the custom macros page dialog **/ Gui::Dialog::DlgCustomizeImp dlg(this); @@ -619,43 +661,55 @@ Note: your changes will be applied when you next switch workbenches\n")); return; } - auto setupCustomMacrosPage = tabWidget->findChild(QString::fromLatin1("Gui__Dialog__DlgCustomActions")); + auto setupCustomMacrosPage = + tabWidget->findChild(QString::fromLatin1("Gui__Dialog__DlgCustomActions")); if (!setupCustomMacrosPage) { - std::cerr << "Toolbar walkthrough error: Unable to find setupCustomMacrosPage" << std::endl; + std::cerr << "Toolbar walkthrough error: Unable to find setupCustomMacrosPage" + << std::endl; return; } tabWidget->setCurrentWidget(setupCustomMacrosPage); - auto groupBox7 = setupCustomMacrosPage->findChild(QString::fromLatin1("GroupBox7")); + auto groupBox7 = + setupCustomMacrosPage->findChild(QString::fromLatin1("GroupBox7")); if (!groupBox7) { Base::Console().Warning("Toolbar walkthrough: Unable to find groupBox7\n"); - //just warn when not a fatal error - } else { + // just warn when not a fatal error + } + else { /** normally the groupbox title is "Setup Custom Macros", but we change it here **/ - groupBox7->setTitle(tr("Walkthrough instructions: Fill in missing fields (optional) then click Add, then Close")); + groupBox7->setTitle(tr("Walkthrough instructions: Fill in missing fields (optional) " + "then click Add, then Close")); groupBox7->setStyleSheet(QString::fromLatin1("QGroupBox::title {color:red}")); } - auto buttonAddAction = setupCustomMacrosPage->findChild(QString::fromLatin1("buttonAddAction")); + auto buttonAddAction = + setupCustomMacrosPage->findChild(QString::fromLatin1("buttonAddAction")); if (!buttonAddAction) { Base::Console().Warning("Toolbar walkthrough: Unable to find buttonAddAction\n"); - } else { + } + else { buttonAddAction->setStyleSheet(QString::fromLatin1("color:red")); } - auto macroListBox = setupCustomMacrosPage->findChild(QString::fromLatin1("actionMacros")); + auto macroListBox = + setupCustomMacrosPage->findChild(QString::fromLatin1("actionMacros")); if (!macroListBox) { Base::Console().Warning("Toolbar walkthrough: Unable to find actionMacros combo box\n"); - } else { - int macroIndex = macroListBox->findText(fn); //fn is the macro filename - macroListBox->setCurrentIndex(macroIndex); //select it for the user so they don't have to + } + else { + int macroIndex = macroListBox->findText(fn); // fn is the macro filename + macroListBox->setCurrentIndex( + macroIndex); // select it for the user so they don't have to } - auto menuText = setupCustomMacrosPage->findChild(QString::fromLatin1("actionMenu")); + auto menuText = + setupCustomMacrosPage->findChild(QString::fromLatin1("actionMenu")); if (!menuText) { Base::Console().Warning("Toolbar walkthrough: Unable to find actionMenu menuText\n"); - } else { - menuText->setText(bareFileName); //user can fill in other fields, e.g. tooltip + } + else { + menuText->setText(bareFileName); // user can fill in other fields, e.g. tooltip } dlg.exec(); @@ -665,38 +719,47 @@ Note: your changes will be applied when you next switch workbenches\n")); Gui::Dialog::DlgCustomizeImp dlg(this); - if (hasMacroCommand){ + if (hasMacroCommand) { dlg.setWindowTitle(tr("Walkthrough, dialog 1 of 1")); - } else { + } + else { dlg.setWindowTitle(tr("Walkthrough, dialog 2 of 2")); } tabWidget = nullptr; tabWidget = dlg.findChild(QString::fromLatin1("Gui__Dialog__TabWidget")); if (!tabWidget) { - std::cerr << "Toolbar walkthrough: Unable to find tabWidget Gui__Dialog__TabWidget" << std::endl; + std::cerr << "Toolbar walkthrough: Unable to find tabWidget Gui__Dialog__TabWidget" + << std::endl; return; } - auto setupToolbarPage = tabWidget->findChild(QString::fromLatin1("Gui__Dialog__DlgCustomToolbars")); - if (!setupToolbarPage){ - std::cerr << "Toolbar walkthrough: Unable to find setupToolbarPage Gui__Dialog__DlgCustomToolbars" << std::endl; + auto setupToolbarPage = tabWidget->findChild( + QString::fromLatin1("Gui__Dialog__DlgCustomToolbars")); + if (!setupToolbarPage) { + std::cerr + << "Toolbar walkthrough: Unable to find setupToolbarPage Gui__Dialog__DlgCustomToolbars" + << std::endl; return; } tabWidget->setCurrentWidget(setupToolbarPage); - auto moveActionRightButton = setupToolbarPage->findChild(QString::fromLatin1("moveActionRightButton")); - if (!moveActionRightButton){ + auto moveActionRightButton = + setupToolbarPage->findChild(QString::fromLatin1("moveActionRightButton")); + if (!moveActionRightButton) { Base::Console().Warning("Toolbar walkthrough: Unable to find moveActionRightButton\n"); - } else { + } + else { moveActionRightButton->setStyleSheet(QString::fromLatin1("background-color: red")); } /** tailor instructions depending on whether user already has custom toolbar created * if not, they need to click New button to create one first - **/ + **/ - QString instructions2 = tr("Walkthrough instructions: Click right arrow button (->), then Close."); - auto workbenchBox = setupToolbarPage->findChild(QString::fromLatin1("workbenchBox")); + QString instructions2 = + tr("Walkthrough instructions: Click right arrow button (->), then Close."); + auto workbenchBox = + setupToolbarPage->findChild(QString::fromLatin1("workbenchBox")); if (!workbenchBox) { Base::Console().Warning("Toolbar walkthrough: Unable to find workbenchBox\n"); } @@ -704,70 +767,89 @@ Note: your changes will be applied when you next switch workbenches\n")); /** find the Global workbench and select it for the user **/ int globalIdx = workbenchBox->findData(QString::fromLatin1("Global")); - if (globalIdx != -1){ + if (globalIdx != -1) { workbenchBox->setCurrentIndex(globalIdx); - QMetaObject::invokeMethod(setupToolbarPage, "on_workbenchBox_activated", - Qt::DirectConnection, - Q_ARG(int, globalIdx)); - } else { + QMetaObject::invokeMethod(setupToolbarPage, + "on_workbenchBox_activated", + Qt::DirectConnection, + Q_ARG(int, globalIdx)); + } + else { Base::Console().Warning("Toolbar walkthrough: Unable to find Global workbench\n"); } - if (!hasCustomToolbar){ - auto newButton = setupToolbarPage->findChild(QString::fromLatin1("newButton")); - if (!newButton){ + if (!hasCustomToolbar) { + auto newButton = + setupToolbarPage->findChild(QString::fromLatin1("newButton")); + if (!newButton) { Base::Console().Warning("Toolbar walkthrough: Unable to find newButton\n"); - } else { + } + else { newButton->setStyleSheet(QString::fromLatin1("color:red")); - instructions2 = tr("Walkthrough instructions: Click New, then right arrow (->) button, then Close."); + instructions2 = tr("Walkthrough instructions: Click New, then right arrow (->) " + "button, then Close."); } } } - /** "label" normally says "Note: the changes become active the next time you load the appropriate workbench" **/ + /** "label" normally says "Note: the changes become active the next time you load the + * appropriate workbench" **/ auto label = setupToolbarPage->findChild(QString::fromLatin1("label")); - if (!label){ + if (!label) { Base::Console().Warning("Toolbar walkthrough: Unable to find label\n"); - } else { + } + else { label->setText(instructions2); label->setStyleSheet(QString::fromLatin1("color:red")); } /** find Macros category and select it for the user **/ auto categoryBox = setupToolbarPage->findChild(QString::fromLatin1("categoryBox")); - if (!categoryBox){ + if (!categoryBox) { Base::Console().Warning("Toolbar walkthrough: Unable to find categoryBox\n"); - } else { + } + else { int macrosIdx = categoryBox->findText(tr("Macros")); - if (macrosIdx != -1){ + if (macrosIdx != -1) { categoryBox->setCurrentIndex(macrosIdx); - QMetaObject::invokeMethod(setupToolbarPage, "on_categoryBox_activated", - Qt::DirectConnection, - Q_ARG(int, macrosIdx)); - } else { + QMetaObject::invokeMethod(setupToolbarPage, + "on_categoryBox_activated", + Qt::DirectConnection, + Q_ARG(int, macrosIdx)); + } + else { Base::Console().Warning("Toolbar walkthrough: Unable to find Macros in categoryBox\n"); } } /** expand custom toolbar items **/ - auto toolbarTreeWidget = setupToolbarPage->findChild(QString::fromLatin1("toolbarTreeWidget")); + auto toolbarTreeWidget = + setupToolbarPage->findChild(QString::fromLatin1("toolbarTreeWidget")); if (!toolbarTreeWidget) { Base::Console().Warning("Toolbar walkthrough: Unable to find toolbarTreeWidget\n"); - } else { + } + else { toolbarTreeWidget->expandAll(); } /** preselect macro command for user **/ - auto commandTreeWidget = setupToolbarPage->findChild(QString::fromLatin1("commandTreeWidget")); + auto commandTreeWidget = + setupToolbarPage->findChild(QString::fromLatin1("commandTreeWidget")); if (!commandTreeWidget) { Base::Console().Warning("Toolbar walkthrough: Unable to find commandTreeWidget\n"); - } else { - if (!hasMacroCommand){ //will be the last in the list, the one just created - commandTreeWidget->setCurrentItem(commandTreeWidget->topLevelItem(commandTreeWidget->topLevelItemCount()-1)); + } + else { + if (!hasMacroCommand) { // will be the last in the list, the one just created + commandTreeWidget->setCurrentItem( + commandTreeWidget->topLevelItem(commandTreeWidget->topLevelItemCount() - 1)); commandTreeWidget->scrollToItem(commandTreeWidget->currentItem()); - } else { //pre-select it for the user (will be the macro menu text) - QList items = commandTreeWidget->findItems(macroMenuText, Qt::MatchFixedString | Qt::MatchWrap,1); + } + else { // pre-select it for the user (will be the macro menu text) + QList items = + commandTreeWidget->findItems(macroMenuText, + Qt::MatchFixedString | Qt::MatchWrap, + 1); if (!items.empty()) { commandTreeWidget->setCurrentItem(items[0]); commandTreeWidget->scrollToItem(commandTreeWidget->currentItem()); @@ -778,7 +860,6 @@ Note: your changes will be applied when you next switch workbenches\n")); } - /** * renames the selected macro */ @@ -788,42 +869,56 @@ void DlgMacroExecuteImp::onRenameButtonClicked() QTreeWidgetItem* item = nullptr; int index = ui->tabMacroWidget->currentIndex(); - if (index == 0) { //user-specific + if (index == 0) { // user-specific item = ui->userMacroListBox->currentItem(); dir.setPath(this->macroPath); } - if (!item) + if (!item) { return; + } - bool replaceSpaces = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->GetBool("ReplaceSpaces", true); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->SetBool("ReplaceSpaces", replaceSpaces); //create parameter + bool replaceSpaces = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetBool("ReplaceSpaces", true); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter QString oldName = item->text(0); QFileInfo oldfi(dir, oldName); QFile oldfile(oldfi.absoluteFilePath()); // query new name - QString fn = QInputDialog::getText(this, tr("Renaming Macro File"), - tr("Enter new name:"), QLineEdit::Normal, oldName, nullptr, Qt::MSWindowsFixedSizeDialogHint); + QString fn = QInputDialog::getText(this, + tr("Renaming Macro File"), + tr("Enter new name:"), + QLineEdit::Normal, + oldName, + nullptr, + Qt::MSWindowsFixedSizeDialogHint); - if(replaceSpaces){ - fn = fn.replace(QString::fromStdString(" "),QString::fromStdString("_")); + if (replaceSpaces) { + fn = fn.replace(QString::fromStdString(" "), QString::fromStdString("_")); } if (!fn.isEmpty() && fn != oldName) { QString suffix = QFileInfo(fn).suffix().toLower(); - if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) + if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) { fn += QLatin1String(".FCMacro"); + } QFileInfo fi(dir, fn); // check if new name exists if (fi.exists()) { - QMessageBox::warning(this, tr("Existing file"), - tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); + QMessageBox::warning(this, + tr("Existing file"), + tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); } else if (!oldfile.rename(fi.absoluteFilePath())) { - QMessageBox::warning(this, tr("Rename Failed"), - tr("Failed to rename to '%1'.\nPerhaps a file permission error?").arg(fi.absoluteFilePath())); + QMessageBox::warning(this, + tr("Rename Failed"), + tr("Failed to rename to '%1'.\nPerhaps a file permission error?") + .arg(fi.absoluteFilePath())); } else { // keep the item selected although it's not necessarily in alphabetic order @@ -845,75 +940,92 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() QDir dir; QTreeWidgetItem* item = nullptr; - //When duplicating a macro we can either begin trying to find a unique name with @001 or begin with the current @NNN if applicable + // When duplicating a macro we can either begin trying to find a unique name with @001 or begin + // with the current @NNN if applicable - bool from001 = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->GetBool("DuplicateFrom001", false); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->SetBool("DuplicateFrom001", from001); //create parameter + bool from001 = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetBool("DuplicateFrom001", false); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->SetBool("DuplicateFrom001", from001); // create parameter - //A user may wish to add a note to end of the filename when duplicating - //example: mymacro@005.fix_bug_in_dialog.FCMacro - //and then when duplicating to have the extra note removed so the suggested new name is: - //mymacro@006.FCMacro instead of mymacro@006.fix_bug_in_dialog.FCMacro since the new duplicate will be given a new note + // A user may wish to add a note to end of the filename when duplicating + // example: mymacro@005.fix_bug_in_dialog.FCMacro + // and then when duplicating to have the extra note removed so the suggested new name is: + // mymacro@006.FCMacro instead of mymacro@006.fix_bug_in_dialog.FCMacro since the new duplicate + // will be given a new note - bool ignoreExtra = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->GetBool("DuplicateIgnoreExtraNote", false); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->SetBool("DuplicateIgnoreExtraNote", ignoreExtra); //create parameter + bool ignoreExtra = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetBool("DuplicateIgnoreExtraNote", false); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->SetBool("DuplicateIgnoreExtraNote", ignoreExtra); // create parameter - //when creating a note it will be convenient to convert spaces to underscores if the user desires this behavior + // when creating a note it will be convenient to convert spaces to underscores if the user + // desires this behavior - bool replaceSpaces = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->GetBool("ReplaceSpaces", true); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")->SetBool("ReplaceSpaces", replaceSpaces); //create parameter + bool replaceSpaces = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetBool("ReplaceSpaces", true); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter int index = ui->tabMacroWidget->currentIndex(); - if (index == 0) { //user-specific + if (index == 0) { // user-specific item = ui->userMacroListBox->currentItem(); dir.setPath(this->macroPath); } - if (!item){ + if (!item) { return; } QString oldName = item->text(0); QFileInfo oldfi(dir, oldName); QFile oldfile(oldfi.absoluteFilePath()); - QString completeSuffix = oldfi.completeSuffix(); //everything after the first "." - QString extraNote = completeSuffix.left(completeSuffix.size()-oldfi.suffix().size()); - QString baseName = oldfi.baseName(); //everything before first "." + QString completeSuffix = oldfi.completeSuffix(); // everything after the first "." + QString extraNote = completeSuffix.left(completeSuffix.size() - oldfi.suffix().size()); + QString baseName = oldfi.baseName(); // everything before first "." QString neutralSymbol = QString::fromStdString("@"); QString last3 = baseName.right(3); - bool ok = true; //was conversion to int successful? + bool ok = true; // was conversion to int successful? int nLast3 = last3.toInt(&ok); - last3 = QString::fromStdString("001"); //increment beginning with 001 unless from001 = false - if (ok ){ - //last3 were all digits, so we strip them from the base name - if (baseName.size()>3){ //if <= 3 leave be (e.g. 2.py becomes 2@001.py) - if(!from001){ - last3 = baseName.right(3); //use these instead of 001 + last3 = QString::fromStdString("001"); // increment beginning with 001 unless from001 = false + if (ok) { + // last3 were all digits, so we strip them from the base name + if (baseName.size() > 3) { // if <= 3 leave be (e.g. 2.py becomes 2@001.py) + if (!from001) { + last3 = baseName.right(3); // use these instead of 001 } - baseName = baseName.left(baseName.size()-3); //strip digits - if (baseName.endsWith(neutralSymbol)){ - baseName = baseName.left(baseName.size()-1); //trim the "@", will be added back later + baseName = baseName.left(baseName.size() - 3); // strip digits + if (baseName.endsWith(neutralSymbol)) { + baseName = + baseName.left(baseName.size() - 1); // trim the "@", will be added back later } } } - //at this point baseName = the base name without any digits, e.g. "MyMacro" - //neutralSymbol = "@" - //last3 is a string representing 3 digits, always "001" - //unless from001 = false, in which case we begin with previous numbers - //completeSuffix = FCMacro or py or FCMacro.py or else suffix will become FCMacro below - //if ignoreExtra any extra notes added between @NN. and .FCMacro will be ignored - //when suggesting a new filename + // at this point baseName = the base name without any digits, e.g. "MyMacro" + // neutralSymbol = "@" + // last3 is a string representing 3 digits, always "001" + // unless from001 = false, in which case we begin with previous numbers + // completeSuffix = FCMacro or py or FCMacro.py or else suffix will become FCMacro below + // if ignoreExtra any extra notes added between @NN. and .FCMacro will be ignored + // when suggesting a new filename - if(ignoreExtra && !extraNote.isEmpty()){ + if (ignoreExtra && !extraNote.isEmpty()) { nLast3++; last3 = QString::number(nLast3); - while (last3.size()<3){ - last3.prepend(QString::fromStdString("0")); //pad 0's if needed + while (last3.size() < 3) { + last3.prepend(QString::fromStdString("0")); // pad 0's if needed } } - QString oldNameDigitized = baseName+neutralSymbol+last3+QString::fromStdString(".")+completeSuffix; + QString oldNameDigitized = + baseName + neutralSymbol + last3 + QString::fromStdString(".") + completeSuffix; QFileInfo fi(dir, oldNameDigitized); @@ -921,48 +1033,56 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() // test from "001" through "999", then give up and let user enter name of choice while (fi.exists()) { - nLast3 = last3.toInt()+1; - if (nLast3 >=1000){ //avoid infinite loop, 999 files will have to be enough + nLast3 = last3.toInt() + 1; + if (nLast3 >= 1000) { // avoid infinite loop, 999 files will have to be enough break; } last3 = QString::number(nLast3); - while (last3.size()<3){ - last3.prepend(QString::fromStdString("0")); //pad 0's if needed + while (last3.size() < 3) { + last3.prepend(QString::fromStdString("0")); // pad 0's if needed } - oldNameDigitized = baseName+neutralSymbol+last3+QString::fromStdString(".")+completeSuffix; - fi = QFileInfo(dir,oldNameDigitized); + oldNameDigitized = + baseName + neutralSymbol + last3 + QString::fromStdString(".") + completeSuffix; + fi = QFileInfo(dir, oldNameDigitized); } - if(ignoreExtra && !extraNote.isEmpty()){ + if (ignoreExtra && !extraNote.isEmpty()) { oldNameDigitized = oldNameDigitized.remove(extraNote); } // give user a chance to pick a different name from digitized name suggested - QString fn = QInputDialog::getText(this, tr("Duplicate Macro"), - tr("Enter new name:"), QLineEdit::Normal, oldNameDigitized, - nullptr, Qt::MSWindowsFixedSizeDialogHint); - if (replaceSpaces){ - fn = fn.replace(QString::fromStdString(" "),QString::fromStdString("_")); + QString fn = QInputDialog::getText(this, + tr("Duplicate Macro"), + tr("Enter new name:"), + QLineEdit::Normal, + oldNameDigitized, + nullptr, + Qt::MSWindowsFixedSizeDialogHint); + if (replaceSpaces) { + fn = fn.replace(QString::fromStdString(" "), QString::fromStdString("_")); } if (!fn.isEmpty() && fn != oldName) { QString suffix = QFileInfo(fn).suffix().toLower(); - if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")){ + if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) { fn += QLatin1String(".FCMacro"); } QFileInfo fi(dir, fn); // check again if new name exists in case user changed it if (fi.exists()) { - QMessageBox::warning(this, tr("Existing file"), - tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); + QMessageBox::warning(this, + tr("Existing file"), + tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); } else if (!oldfile.copy(fi.absoluteFilePath())) { - QMessageBox::warning(this, tr("Duplicate Failed"), - tr("Failed to duplicate to '%1'.\nPerhaps a file permission error?").arg(fi.absoluteFilePath())); + QMessageBox::warning( + this, + tr("Duplicate Failed"), + tr("Failed to duplicate to '%1'.\nPerhaps a file permission error?") + .arg(fi.absoluteFilePath())); } - this->fillUpList(); //repopulate list to show new file + this->fillUpList(); // repopulate list to show new file } - } /** @@ -971,7 +1091,7 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() */ void DlgMacroExecuteImp::onAddonsButtonClicked() { - CommandManager& rMgr=Application::Instance->commandManager(); + CommandManager& rMgr = Application::Instance->commandManager(); rMgr.runCommandByName("Std_AddonMgr"); this->fillUpList(); } diff --git a/src/Gui/DlgMacroRecordImp.cpp b/src/Gui/DlgMacroRecordImp.cpp index 0796749b16..9e0f6b3d1b 100644 --- a/src/Gui/DlgMacroRecordImp.cpp +++ b/src/Gui/DlgMacroRecordImp.cpp @@ -22,10 +22,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include +#include +#include +#include +#include #endif #include "DlgMacroRecordImp.h" @@ -47,7 +47,7 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgMacroRecordImp::DlgMacroRecordImp( QWidget* parent, Qt::WindowFlags fl ) +DlgMacroRecordImp::DlgMacroRecordImp(QWidget* parent, Qt::WindowFlags fl) : QDialog(parent, fl) , WindowParameter("Macro") , ui(new Ui_DlgMacroRecord) @@ -56,8 +56,10 @@ DlgMacroRecordImp::DlgMacroRecordImp( QWidget* parent, Qt::WindowFlags fl ) setupConnections(); // get the macro home path - this->macroPath = QString::fromUtf8(getWindowParameter()->GetASCII("MacroPath", - App::Application::getUserMacroDir().c_str()).c_str()); + this->macroPath = + QString::fromUtf8(getWindowParameter() + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()) + .c_str()); this->macroPath = QDir::toNativeSeparators(QDir(this->macroPath).path() + QDir::separator()); // set the edit fields @@ -67,7 +69,8 @@ DlgMacroRecordImp::DlgMacroRecordImp( QWidget* parent, Qt::WindowFlags fl ) this->macroManager = Application::Instance->macroManager(); // check if a macro recording is in progress - this->macroManager->isOpen() ? ui->buttonStart->setEnabled(false) : ui->buttonStop->setEnabled(false); + this->macroManager->isOpen() ? ui->buttonStart->setEnabled(false) + : ui->buttonStop->setEnabled(false); } /** @@ -77,6 +80,7 @@ DlgMacroRecordImp::~DlgMacroRecordImp() = default; void DlgMacroRecordImp::setupConnections() { + // clang-format off connect(ui->buttonStart, &QPushButton::clicked, this, &DlgMacroRecordImp::onButtonStartClicked); connect(ui->buttonStop, &QPushButton::clicked, @@ -87,6 +91,7 @@ void DlgMacroRecordImp::setupConnections() this, &DlgMacroRecordImp::onButtonChooseDirClicked); connect(ui->lineEditMacroPath, &QLineEdit::textChanged, this, &DlgMacroRecordImp::onMacroPathTextChanged); + // clang-format on } /** @@ -96,14 +101,17 @@ void DlgMacroRecordImp::onButtonStartClicked() { // test if the path already set if (ui->lineEditPath->text().isEmpty()) { - QMessageBox::information(getMainWindow(), tr("Macro recorder"), - tr("Specify first a place to save.")); + QMessageBox::information(getMainWindow(), + tr("Macro recorder"), + tr("Specify first a place to save.")); return; } QDir dir(macroPath); if (!dir.exists()) { - QMessageBox::information(getMainWindow(), tr("Macro recorder"), + QMessageBox::information( + getMainWindow(), + tr("Macro recorder"), tr("The macro directory doesn't exist. Please, choose another one.")); return; } @@ -116,16 +124,22 @@ void DlgMacroRecordImp::onButtonStartClicked() QFileInfo fi(fn); if (fi.isFile() && fi.exists()) { - if (QMessageBox::question(this, tr("Existing macro"), + if (QMessageBox::question( + this, + tr("Existing macro"), tr("The macro '%1' already exists. Do you want to overwrite?").arg(fn), QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) == QMessageBox::No) - return; + QMessageBox::No) + == QMessageBox::No) { + return; + } } QFile file(fn); if (!file.open(QFile::WriteOnly)) { - QMessageBox::information(getMainWindow(), tr("Macro recorder"), + QMessageBox::information( + getMainWindow(), + tr("Macro recorder"), tr("You have no write permission for the directory. Please, choose another one.")); return; } @@ -170,19 +184,19 @@ void DlgMacroRecordImp::onButtonStopClicked() void DlgMacroRecordImp::onButtonChooseDirClicked() { - QString newDir = QFileDialog::getExistingDirectory(nullptr,tr("Choose macro directory"),macroPath); + QString newDir = + QFileDialog::getExistingDirectory(nullptr, tr("Choose macro directory"), macroPath); if (!newDir.isEmpty()) { macroPath = QDir::toNativeSeparators(newDir + QDir::separator()); ui->lineEditMacroPath->setText(macroPath); - getWindowParameter()->SetASCII("MacroPath",macroPath.toUtf8()); + getWindowParameter()->SetASCII("MacroPath", macroPath.toUtf8()); } } -void DlgMacroRecordImp::onMacroPathTextChanged (const QString & newDir) +void DlgMacroRecordImp::onMacroPathTextChanged(const QString& newDir) { macroPath = newDir; } #include "moc_DlgMacroRecordImp.cpp" - diff --git a/src/Gui/DlgMaterialPropertiesImp.cpp b/src/Gui/DlgMaterialPropertiesImp.cpp index 4c76a481de..a8451d940c 100644 --- a/src/Gui/DlgMaterialPropertiesImp.cpp +++ b/src/Gui/DlgMaterialPropertiesImp.cpp @@ -35,8 +35,8 @@ using namespace Gui::Dialog; /* TRANSLATOR Gui::Dialog::DlgMaterialPropertiesImp */ DlgMaterialPropertiesImp::DlgMaterialPropertiesImp(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) - , ui(new Ui_DlgMaterialProperties) + : QDialog(parent, fl) + , ui(new Ui_DlgMaterialProperties) { ui->setupUi(this); setupConnections(); @@ -51,6 +51,7 @@ DlgMaterialPropertiesImp::~DlgMaterialPropertiesImp() = default; void DlgMaterialPropertiesImp::setupConnections() { + // clang-format off connect(ui->ambientColor, &ColorButton::changed, this, &DlgMaterialPropertiesImp::onAmbientColorChanged); connect(ui->diffuseColor, &ColorButton::changed, @@ -65,6 +66,7 @@ void DlgMaterialPropertiesImp::setupConnections() this, &DlgMaterialPropertiesImp::onButtonReset); connect(ui->buttonDefault, &QPushButton::clicked, this, &DlgMaterialPropertiesImp::onButtonDefault); + // clang-format on } void DlgMaterialPropertiesImp::setCustomMaterial(const App::Material& mat) diff --git a/src/Gui/DlgParameterFind.cpp b/src/Gui/DlgParameterFind.cpp index cf7aaf7bb4..9ec5c46dbf 100644 --- a/src/Gui/DlgParameterFind.cpp +++ b/src/Gui/DlgParameterFind.cpp @@ -22,8 +22,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "DlgParameterFind.h" @@ -36,9 +36,9 @@ using namespace Gui::Dialog; /* TRANSLATOR Gui::Dialog::DlgParameterFind */ DlgParameterFind::DlgParameterFind(DlgParameterImp* parent) - : QDialog(parent) - , ui(new Ui_DlgParameterFind) - , dialog(parent) + : QDialog(parent) + , ui(new Ui_DlgParameterFind) + , dialog(parent) { ui->setupUi(this); setupConnections(); @@ -61,6 +61,7 @@ DlgParameterFind::~DlgParameterFind() void DlgParameterFind::setupConnections() { + // clang-format off connect(ui->lineEdit, &QLineEdit::textChanged, this, &DlgParameterFind::onLineEditTextChanged); connect(ui->checkGroups, &QCheckBox::toggled, @@ -69,15 +70,15 @@ void DlgParameterFind::setupConnections() this, &DlgParameterFind::onCheckNamesToggled); connect(ui->checkValues, &QCheckBox::toggled, this, &DlgParameterFind::onCheckValuesToggled); + // clang-format on } void DlgParameterFind::onLineEditTextChanged(const QString& text) { QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok); if (btn) { - bool ok = ui->checkGroups->isChecked() || - ui->checkNames->isChecked() || - ui->checkValues->isChecked(); + bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked() + || ui->checkValues->isChecked(); btn->setDisabled(!ok || text.isEmpty()); } } @@ -86,9 +87,8 @@ void DlgParameterFind::onCheckGroupsToggled(bool) { QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok); if (btn) { - bool ok = ui->checkGroups->isChecked() || - ui->checkNames->isChecked() || - ui->checkValues->isChecked(); + bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked() + || ui->checkValues->isChecked(); QString text = ui->lineEdit->text(); btn->setDisabled(!ok || text.isEmpty()); } @@ -98,9 +98,8 @@ void DlgParameterFind::onCheckNamesToggled(bool) { QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok); if (btn) { - bool ok = ui->checkGroups->isChecked() || - ui->checkNames->isChecked() || - ui->checkValues->isChecked(); + bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked() + || ui->checkValues->isChecked(); QString text = ui->lineEdit->text(); btn->setDisabled(!ok || text.isEmpty()); } @@ -110,9 +109,8 @@ void DlgParameterFind::onCheckValuesToggled(bool) { QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok); if (btn) { - bool ok = ui->checkGroups->isChecked() || - ui->checkNames->isChecked() || - ui->checkValues->isChecked(); + bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked() + || ui->checkValues->isChecked(); QString text = ui->lineEdit->text(); btn->setDisabled(!ok || text.isEmpty()); } @@ -124,12 +122,14 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const if (opt.group) { // whole word matches if (opt.match) { - if (item->text(0).compare(opt.text, Qt::CaseInsensitive) == 0) + if (item->text(0).compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } else { - if (item->text(0).indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (item->text(0).indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } } @@ -148,55 +148,65 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const if (opt.match) { for (const auto& it : boolMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.compare(opt.text, Qt::CaseInsensitive) == 0) + if (text.compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } for (const auto& it : intMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.compare(opt.text, Qt::CaseInsensitive) == 0) + if (text.compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } for (const auto& it : uintMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.compare(opt.text, Qt::CaseInsensitive) == 0) + if (text.compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } for (const auto& it : floatMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.compare(opt.text, Qt::CaseInsensitive) == 0) + if (text.compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } for (const auto& it : asciiMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.compare(opt.text, Qt::CaseInsensitive) == 0) + if (text.compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } } else { for (const auto& it : boolMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } for (const auto& it : intMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } for (const auto& it : uintMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } for (const auto& it : floatMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } for (const auto& it : asciiMap) { QString text = QString::fromUtf8(it.first.c_str()); - if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } } } @@ -206,15 +216,17 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const if (opt.match) { for (const auto& it : asciiMap) { QString text = QString::fromUtf8(it.second.c_str()); - if (text.compare(opt.text, Qt::CaseInsensitive) == 0) + if (text.compare(opt.text, Qt::CaseInsensitive) == 0) { return true; + } } } else { for (const auto& it : asciiMap) { QString text = QString::fromUtf8(it.second.c_str()); - if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) + if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) { return true; + } } } } @@ -225,23 +237,27 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const QTreeWidgetItem* DlgParameterFind::findItem(QTreeWidgetItem* root, const Options& opt) const { - if (!root) + if (!root) { return nullptr; + } if (matches(root, opt)) { // if the root matches then only return if it's not the current element // as otherwise it would never move forward - if (root->treeWidget()->currentItem() != root) + if (root->treeWidget()->currentItem() != root) { return root; + } } - for (int i=0; ichildCount(); i++) { + for (int i = 0; i < root->childCount(); i++) { QTreeWidgetItem* item = root->child(i); - if (matches(item, opt)) + if (matches(item, opt)) { return item; + } item = findItem(item, opt); - if (item) + if (item) { return item; + } } return nullptr; @@ -272,10 +288,11 @@ void DlgParameterFind::accept() } if (parent) { int index = parent->indexOfChild(current); - for (int i=index+1; ichildCount(); i++) { + for (int i = index + 1; i < parent->childCount(); i++) { next = findItem(parent->child(i), opt); - if (next) + if (next) { break; + } } } @@ -285,10 +302,14 @@ void DlgParameterFind::accept() } // if search was successful then make it the current item - if (next) + if (next) { groupTree->setCurrentItem(next); - else - QMessageBox::warning(this, tr("Not found"), tr("Can't find the text: %1").arg(opt.text)); + } + else { + QMessageBox::warning(this, + tr("Not found"), + tr("Can't find the text: %1").arg(opt.text)); + } } } diff --git a/src/Gui/DlgParameterImp.cpp b/src/Gui/DlgParameterImp.cpp index c444e8c04e..28c41b7c17 100644 --- a/src/Gui/DlgParameterImp.cpp +++ b/src/Gui/DlgParameterImp.cpp @@ -22,14 +22,14 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include @@ -56,17 +56,17 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgParameterImp::DlgParameterImp( QWidget* parent, Qt::WindowFlags fl ) - : QDialog(parent, fl|Qt::WindowMinMaxButtonsHint) - , ui(new Ui_DlgParameter) +DlgParameterImp::DlgParameterImp(QWidget* parent, Qt::WindowFlags fl) + : QDialog(parent, fl | Qt::WindowMinMaxButtonsHint) + , ui(new Ui_DlgParameter) { ui->setupUi(this); setupConnections(); - ui->checkSort->setVisible(false); // for testing + ui->checkSort->setVisible(false); // for testing QStringList groupLabels; - groupLabels << tr( "Group" ); + groupLabels << tr("Group"); paramGroup = new ParameterGroup(ui->splitter3); paramGroup->setHeaderLabels(groupLabels); paramGroup->setRootIsDecorated(false); @@ -75,7 +75,7 @@ DlgParameterImp::DlgParameterImp( QWidget* parent, Qt::WindowFlags fl ) paramGroup->header()->setProperty("showSortIndicator", QVariant(true)); QStringList valueLabels; - valueLabels << tr( "Name" ) << tr( "Type" ) << tr( "Value" ); + valueLabels << tr("Name") << tr("Type") << tr("Value"); paramValue = new ParameterValue(ui->splitter3); paramValue->setHeaderLabels(valueLabels); paramValue->setRootIsDecorated(false); @@ -88,26 +88,30 @@ DlgParameterImp::DlgParameterImp( QWidget* parent, Qt::WindowFlags fl ) policy.setHorizontalStretch(3); paramValue->setSizePolicy(policy); -#if 0 // This is needed for Qt's lupdate +#if 0 // This is needed for Qt's lupdate qApp->translate( "Gui::Dialog::DlgParameterImp", "System parameter" ); qApp->translate( "Gui::Dialog::DlgParameterImp", "User parameter" ); #endif ParameterManager* sys = App::GetApplication().GetParameterSet("System parameter"); const auto& rcList = App::GetApplication().GetParameterSetList(); - for (const auto & it : rcList) { - if (it.second != sys) // for now ignore system parameters because they are nowhere used + for (const auto& it : rcList) { + if (it.second != sys) { // for now ignore system parameters because they are nowhere used ui->parameterSet->addItem(tr(it.first.c_str()), QVariant(QByteArray(it.first.c_str()))); + } } QByteArray cStr("User parameter"); ui->parameterSet->setCurrentIndex(ui->parameterSet->findData(cStr)); onChangeParameterSet(ui->parameterSet->currentIndex()); - if (ui->parameterSet->count() < 2) + if (ui->parameterSet->count() < 2) { ui->parameterSet->hide(); + } - connect(ui->parameterSet, qOverload(&QComboBox::activated), - this, &DlgParameterImp::onChangeParameterSet); + connect(ui->parameterSet, + qOverload(&QComboBox::activated), + this, + &DlgParameterImp::onChangeParameterSet); connect(paramGroup, &QTreeWidget::currentItemChanged, this, &DlgParameterImp::onGroupSelected); onGroupSelected(paramGroup->currentItem()); @@ -133,6 +137,7 @@ DlgParameterImp::~DlgParameterImp() void DlgParameterImp::setupConnections() { + // clang-format off connect(ui->buttonFind, &QPushButton::clicked, this, &DlgParameterImp::onButtonFindClicked); connect(ui->findGroupLE, &QLineEdit::textChanged, @@ -143,16 +148,18 @@ void DlgParameterImp::setupConnections() this, &DlgParameterImp::onCloseButtonClicked); connect(ui->checkSort, &QCheckBox::toggled, this, &DlgParameterImp::onCheckSortToggled); + // clang-format on } void DlgParameterImp::onButtonFindClicked() { - if (finder.isNull()) + if (finder.isNull()) { finder = new DlgParameterFind(this); + } finder->show(); } -void DlgParameterImp::onFindGroupTtextChanged(const QString &SearchStr) +void DlgParameterImp::onFindGroupTtextChanged(const QString& SearchStr) { // search for group tree items and highlight found results @@ -167,8 +174,9 @@ void DlgParameterImp::onFindGroupTtextChanged(const QString &SearchStr) // a group can be nested down to several levels // do not collapse if the search string is empty while (!SearchStr.isEmpty()) { - if (!ExpandItem->parent()) + if (!ExpandItem->parent()) { break; + } else { ExpandItem->setExpanded(false); ExpandItem = ExpandItem->parent(); @@ -182,15 +190,17 @@ void DlgParameterImp::onFindGroupTtextChanged(const QString &SearchStr) } // don't perform a search if the string is empty - if (SearchStr.isEmpty()) + if (SearchStr.isEmpty()) { return; + } // search the tree widget foundList = paramGroup->findItems(SearchStr, Qt::MatchContains | Qt::MatchRecursive); if (!foundList.empty()) { // reset background style sheet - if (!ui->findGroupLE->styleSheet().isEmpty()) + if (!ui->findGroupLE->styleSheet().isEmpty()) { ui->findGroupLE->setStyleSheet(QString()); + } for (QTreeWidgetItem* item : std::as_const(foundList)) { item->setFont(0, boldFont); item->setForeground(0, Qt::red); @@ -198,8 +208,9 @@ void DlgParameterImp::onFindGroupTtextChanged(const QString &SearchStr) // a group can be nested down to several levels ExpandItem = item; while (true) { - if (!ExpandItem->parent()) + if (!ExpandItem->parent()) { break; + } else { ExpandItem->setExpanded(true); ExpandItem = ExpandItem->parent(); @@ -213,11 +224,9 @@ void DlgParameterImp::onFindGroupTtextChanged(const QString &SearchStr) } else { // Set red background to indicate no matching - QString styleSheet = QString::fromLatin1( - " QLineEdit {\n" - " background-color: rgb(221,144,161);\n" - " }\n" - ); + QString styleSheet = QString::fromLatin1(" QLineEdit {\n" + " background-color: rgb(221,144,161);\n" + " }\n"); ui->findGroupLE->setStyleSheet(styleSheet); } } @@ -226,15 +235,16 @@ void DlgParameterImp::onFindGroupTtextChanged(const QString &SearchStr) * Sets the strings of the subwidgets using the current * language. */ -void DlgParameterImp::changeEvent(QEvent *e) +void DlgParameterImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); - paramGroup->headerItem()->setText( 0, tr( "Group" ) ); - paramValue->headerItem()->setText( 0, tr( "Name" ) ); - paramValue->headerItem()->setText( 1, tr( "Type" ) ); - paramValue->headerItem()->setText( 2, tr( "Value" ) ); - } else { + paramGroup->headerItem()->setText(0, tr("Group")); + paramValue->headerItem()->setText(0, tr("Name")); + paramValue->headerItem()->setText(1, tr("Type")); + paramValue->headerItem()->setText(2, tr("Value")); + } + else { QDialog::changeEvent(e); } } @@ -265,30 +275,27 @@ void DlgParameterImp::reject() close(); } -void DlgParameterImp::showEvent(QShowEvent* ) +void DlgParameterImp::showEvent(QShowEvent*) { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences"); + ParameterGrp::handle hGrp = + App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); hGrp = hGrp->GetGroup("ParameterEditor"); std::string buf = hGrp->GetASCII("Geometry", ""); if (!buf.empty()) { int x1, y1, x2, y2; char sep; std::stringstream str(buf); - str >> sep >> x1 - >> sep >> y1 - >> sep >> x2 - >> sep >> y2; + str >> sep >> x1 >> sep >> y1 >> sep >> x2 >> sep >> y2; QRect rect; rect.setCoords(x1, y1, x2, y2); this->setGeometry(rect); } } -void DlgParameterImp::closeEvent(QCloseEvent* ) +void DlgParameterImp::closeEvent(QCloseEvent*) { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences"); + ParameterGrp::handle hGrp = + App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); hGrp = hGrp->GetGroup("ParameterEditor"); QTreeWidgetItem* current = paramGroup->currentItem(); if (current) { @@ -305,55 +312,62 @@ void DlgParameterImp::closeEvent(QCloseEvent* ) // save geometry of window const QRect& r = this->geometry(); std::stringstream str; - str << "(" << r.left() << "," << r.top() << "," - << r.right() << "," << r.bottom() << ")"; + str << "(" << r.left() << "," << r.top() << "," << r.right() << "," << r.bottom() << ")"; hGrp->SetASCII("Geometry", str.str().c_str()); } } -void DlgParameterImp::onGroupSelected( QTreeWidgetItem * item ) +void DlgParameterImp::onGroupSelected(QTreeWidgetItem* item) { - if ( item && item->type() == QTreeWidgetItem::UserType + 1 ) - { + if (item && item->type() == QTreeWidgetItem::UserType + 1) { bool sortingEnabled = paramValue->isSortingEnabled(); paramValue->clear(); Base::Reference _hcGrp = static_cast(item)->_hcGrp; - static_cast(paramValue)->setCurrentGroup( _hcGrp ); + static_cast(paramValue)->setCurrentGroup(_hcGrp); // filling up Text nodes - std::vector > mcTextMap = _hcGrp->GetASCIIMap(); - for(const auto & It2 : mcTextMap) - { - (void)new ParameterText(paramValue,QString::fromUtf8(It2.first.c_str()), - It2.second.c_str(), _hcGrp); + std::vector> mcTextMap = _hcGrp->GetASCIIMap(); + for (const auto& It2 : mcTextMap) { + (void)new ParameterText(paramValue, + QString::fromUtf8(It2.first.c_str()), + It2.second.c_str(), + _hcGrp); } // filling up Int nodes - std::vector > mcIntMap = _hcGrp->GetIntMap(); - for(const auto & It3 : mcIntMap) - { - (void)new ParameterInt(paramValue,QString::fromUtf8(It3.first.c_str()),It3.second, _hcGrp); + std::vector> mcIntMap = _hcGrp->GetIntMap(); + for (const auto& It3 : mcIntMap) { + (void)new ParameterInt(paramValue, + QString::fromUtf8(It3.first.c_str()), + It3.second, + _hcGrp); } // filling up Float nodes - std::vector > mcFloatMap = _hcGrp->GetFloatMap(); - for(const auto & It4 : mcFloatMap) - { - (void)new ParameterFloat(paramValue,QString::fromUtf8(It4.first.c_str()),It4.second, _hcGrp); + std::vector> mcFloatMap = _hcGrp->GetFloatMap(); + for (const auto& It4 : mcFloatMap) { + (void)new ParameterFloat(paramValue, + QString::fromUtf8(It4.first.c_str()), + It4.second, + _hcGrp); } // filling up bool nodes - std::vector > mcBoolMap = _hcGrp->GetBoolMap(); - for(const auto & It5 : mcBoolMap) - { - (void)new ParameterBool(paramValue,QString::fromUtf8(It5.first.c_str()),It5.second, _hcGrp); + std::vector> mcBoolMap = _hcGrp->GetBoolMap(); + for (const auto& It5 : mcBoolMap) { + (void)new ParameterBool(paramValue, + QString::fromUtf8(It5.first.c_str()), + It5.second, + _hcGrp); } // filling up UInt nodes - std::vector > mcUIntMap = _hcGrp->GetUnsignedMap(); - for(const auto & It6 : mcUIntMap) - { - (void)new ParameterUInt(paramValue,QString::fromUtf8(It6.first.c_str()),It6.second, _hcGrp); + std::vector> mcUIntMap = _hcGrp->GetUnsignedMap(); + for (const auto& It6 : mcUIntMap) { + (void)new ParameterUInt(paramValue, + QString::fromUtf8(It6.first.c_str()), + It6.second, + _hcGrp); } paramValue->setSortingEnabled(sortingEnabled); } @@ -372,9 +386,11 @@ void DlgParameterImp::activateParameterSet(const char* config) /** Switches the type of parameters either to user or system parameters. */ void DlgParameterImp::onChangeParameterSet(int itemPos) { - ParameterManager* rcParMngr = App::GetApplication().GetParameterSet(ui->parameterSet->itemData(itemPos).toByteArray()); - if (!rcParMngr) + ParameterManager* rcParMngr = + App::GetApplication().GetParameterSet(ui->parameterSet->itemData(itemPos).toByteArray()); + if (!rcParMngr) { return; + } rcParMngr->CheckDocument(); ui->buttonSaveToDisk->setEnabled(rcParMngr->HasSerializer()); @@ -384,25 +400,26 @@ void DlgParameterImp::onChangeParameterSet(int itemPos) paramValue->clear(); // root labels - std::vector > grps = rcParMngr->GetGroups(); - for (const auto & grp : grps) { + std::vector> grps = rcParMngr->GetGroups(); + for (const auto& grp : grps) { auto item = new ParameterGroupItem(paramGroup, grp); paramGroup->expandItem(item); item->setIcon(0, QApplication::style()->standardPixmap(QStyle::SP_ComputerIcon)); } // get the path of the last selected group in the editor - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); + ParameterGrp::handle hGrp = + App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); hGrp = hGrp->GetGroup("ParameterEditor"); QString path = QString::fromUtf8(hGrp->GetASCII("LastParameterGroup").c_str()); -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) QStringList paths = path.split(QLatin1String("."), Qt::SkipEmptyParts); #else QStringList paths = path.split(QLatin1String("."), QString::SkipEmptyParts); #endif QTreeWidgetItem* parent = nullptr; - for (int index=0; index < paramGroup->topLevelItemCount() && !paths.empty(); index++) { + for (int index = 0; index < paramGroup->topLevelItemCount() && !paths.empty(); index++) { QTreeWidgetItem* child = paramGroup->topLevelItem(index); if (child->text(0) == paths.front()) { paths.pop_front(); @@ -414,7 +431,7 @@ void DlgParameterImp::onChangeParameterSet(int itemPos) parent->setExpanded(true); QTreeWidgetItem* item = parent; parent = nullptr; - for (int index=0; index < item->childCount(); index++) { + for (int index = 0; index < item->childCount(); index++) { QTreeWidgetItem* child = item->child(index); if (child->text(0) == paths.front()) { paths.pop_front(); @@ -424,81 +441,92 @@ void DlgParameterImp::onChangeParameterSet(int itemPos) } } - if (parent) + if (parent) { paramGroup->setCurrentItem(parent); - else if (paramGroup->topLevelItemCount() > 0) + } + else if (paramGroup->topLevelItemCount() > 0) { paramGroup->setCurrentItem(paramGroup->topLevelItem(0)); + } } void DlgParameterImp::onButtonSaveToDiskClicked() { int index = ui->parameterSet->currentIndex(); - ParameterManager* parmgr = App::GetApplication().GetParameterSet(ui->parameterSet->itemData(index).toByteArray()); - if (!parmgr) + ParameterManager* parmgr = + App::GetApplication().GetParameterSet(ui->parameterSet->itemData(index).toByteArray()); + if (!parmgr) { return; + } parmgr->SaveDocument(); } -namespace Gui { +namespace Gui +{ bool validateInput(QWidget* parent, const QString& input) { - if (input.isEmpty()) + if (input.isEmpty()) { return false; - for (int i=0; i '9') && // Numbers (c < 'A' || c > 'Z') && // Uppercase letters (c < 'a' || c > 'z') && // Lowercase letters (c != ' ')) { // Space - QMessageBox::warning(parent, DlgParameterImp::tr("Invalid input"), - DlgParameterImp::tr("Invalid key name '%1'").arg(input)); + QMessageBox::warning(parent, + DlgParameterImp::tr("Invalid input"), + DlgParameterImp::tr("Invalid key name '%1'").arg(input)); return false; } } return true; } -} +} // namespace Gui // -------------------------------------------------------------------- /* TRANSLATOR Gui::Dialog::ParameterGroup */ -ParameterGroup::ParameterGroup( QWidget * parent ) - : QTreeWidget(parent) +ParameterGroup::ParameterGroup(QWidget* parent) + : QTreeWidget(parent) { menuEdit = new QMenu(this); expandAct = menuEdit->addAction(tr("Expand"), this, &ParameterGroup::onToggleSelectedItem); menuEdit->addSeparator(); subGrpAct = menuEdit->addAction(tr("Add sub-group"), this, &ParameterGroup::onCreateSubgroup); - removeAct = menuEdit->addAction(tr("Remove group"), this, &ParameterGroup::onDeleteSelectedItem); - renameAct = menuEdit->addAction(tr("Rename group"), this, &ParameterGroup::onRenameSelectedItem); + removeAct = + menuEdit->addAction(tr("Remove group"), this, &ParameterGroup::onDeleteSelectedItem); + renameAct = + menuEdit->addAction(tr("Rename group"), this, &ParameterGroup::onRenameSelectedItem); menuEdit->addSeparator(); exportAct = menuEdit->addAction(tr("Export parameter"), this, &ParameterGroup::onExportToFile); - importAct = menuEdit->addAction(tr("Import parameter"), this, &ParameterGroup::onImportFromFile); + importAct = + menuEdit->addAction(tr("Import parameter"), this, &ParameterGroup::onImportFromFile); menuEdit->setDefaultAction(expandAct); } ParameterGroup::~ParameterGroup() = default; -void ParameterGroup::contextMenuEvent ( QContextMenuEvent* event ) +void ParameterGroup::contextMenuEvent(QContextMenuEvent* event) { QTreeWidgetItem* item = currentItem(); - if (item && item->isSelected()) - { + if (item && item->isSelected()) { expandAct->setEnabled(item->childCount() > 0); // do not allow to import parameters from a non-empty parameter group importAct->setEnabled(item->childCount() == 0); - if (item->isExpanded()) - expandAct->setText( tr("Collapse") ); - else - expandAct->setText( tr("Expand") ); + if (item->isExpanded()) { + expandAct->setText(tr("Collapse")); + } + else { + expandAct->setText(tr("Expand")); + } menuEdit->popup(event->globalPos()); } } -void ParameterGroup::keyPressEvent (QKeyEvent* event) +void ParameterGroup::keyPressEvent(QKeyEvent* event) { if (event->matches(QKeySequence::Delete)) { onDeleteSelectedItem(); @@ -511,12 +539,13 @@ void ParameterGroup::keyPressEvent (QKeyEvent* event) void ParameterGroup::onDeleteSelectedItem() { QTreeWidgetItem* sel = currentItem(); - if (sel && sel->isSelected() && sel->parent()) - { - if ( QMessageBox::question(this, tr("Remove group"), tr("Do you really want to remove this parameter group?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == - QMessageBox::Yes ) - { + if (sel && sel->isSelected() && sel->parent()) { + if (QMessageBox::question(this, + tr("Remove group"), + tr("Do you really want to remove this parameter group?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) + == QMessageBox::Yes) { QTreeWidgetItem* parent = sel->parent(); int index = parent->indexOfChild(sel); parent->takeChild(index); @@ -535,38 +564,42 @@ void ParameterGroup::onDeleteSelectedItem() void ParameterGroup::onToggleSelectedItem() { QTreeWidgetItem* sel = currentItem(); - if (sel && sel->isSelected()) - { - if (sel->isExpanded()) + if (sel && sel->isSelected()) { + if (sel->isExpanded()) { sel->setExpanded(false); - else if (sel->childCount() > 0) + } + else if (sel->childCount() > 0) { sel->setExpanded(true); + } } } void ParameterGroup::onCreateSubgroup() { bool ok; - QString name = QInputDialog::getText(this, QObject::tr("New sub-group"), QObject::tr("Enter the name:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText(this, + QObject::tr("New sub-group"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if (ok && Gui::validateInput(this, name)) - { + if (ok && Gui::validateInput(this, name)) { QTreeWidgetItem* item = currentItem(); - if (item && item->isSelected()) - { + if (item && item->isSelected()) { auto para = static_cast(item); Base::Reference hGrp = para->_hcGrp; - if ( hGrp->HasGroup( name.toLatin1() ) ) - { - QMessageBox::critical( this, tr("Existing sub-group"), - tr("The sub-group '%1' already exists.").arg( name ) ); + if (hGrp->HasGroup(name.toLatin1())) { + QMessageBox::critical(this, + tr("Existing sub-group"), + tr("The sub-group '%1' already exists.").arg(name)); return; } - hGrp = hGrp->GetGroup( name.toLatin1() ); - (void)new ParameterGroupItem(para,hGrp); + hGrp = hGrp->GetGroup(name.toLatin1()); + (void)new ParameterGroupItem(para, hGrp); expandItem(para); } } @@ -574,53 +607,51 @@ void ParameterGroup::onCreateSubgroup() void ParameterGroup::onExportToFile() { - QString file = FileDialog::getSaveFileName( this, tr("Export parameter to file"), - QString(), QString::fromLatin1("XML (*.FCParam)")); - if ( !file.isEmpty() ) - { + QString file = FileDialog::getSaveFileName(this, + tr("Export parameter to file"), + QString(), + QString::fromLatin1("XML (*.FCParam)")); + if (!file.isEmpty()) { QTreeWidgetItem* item = currentItem(); - if (item && item->isSelected()) - { + if (item && item->isSelected()) { auto para = static_cast(item); Base::Reference hGrp = para->_hcGrp; - hGrp->exportTo( file.toUtf8() ); + hGrp->exportTo(file.toUtf8()); } } } void ParameterGroup::onImportFromFile() { - QString file = FileDialog::getOpenFileName( this, tr("Import parameter from file"), - QString(), QString::fromLatin1("XML (*.FCParam)")); - if ( !file.isEmpty() ) - { + QString file = FileDialog::getOpenFileName(this, + tr("Import parameter from file"), + QString(), + QString::fromLatin1("XML (*.FCParam)")); + if (!file.isEmpty()) { QTreeWidgetItem* item = currentItem(); - if (item && item->isSelected()) - { + if (item && item->isSelected()) { auto para = static_cast(item); Base::Reference hGrp = para->_hcGrp; // remove the items and internal parameter values QList childs = para->takeChildren(); - for (auto & child : childs) - { + for (auto& child : childs) { delete child; } - try - { - hGrp->importFrom( file.toUtf8() ); - std::vector > cSubGrps = hGrp->GetGroups(); - for (const auto & cSubGrp : cSubGrps) - { - new ParameterGroupItem(para,cSubGrp); + try { + hGrp->importFrom(file.toUtf8()); + std::vector> cSubGrps = hGrp->GetGroups(); + for (const auto& cSubGrp : cSubGrps) { + new ParameterGroupItem(para, cSubGrp); } para->setExpanded(para->childCount()); } - catch( const Base::Exception& ) - { - QMessageBox::critical(this, tr("Import Error"),tr("Reading from '%1' failed.").arg( file )); + catch (const Base::Exception&) { + QMessageBox::critical(this, + tr("Import Error"), + tr("Reading from '%1' failed.").arg(file)); } } } @@ -629,13 +660,12 @@ void ParameterGroup::onImportFromFile() void ParameterGroup::onRenameSelectedItem() { QTreeWidgetItem* sel = currentItem(); - if (sel && sel->isSelected()) - { + if (sel && sel->isSelected()) { editItem(sel, 0); } } -void ParameterGroup::changeEvent(QEvent *e) +void ParameterGroup::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { expandAct->setText(tr("Expand")); @@ -644,7 +674,8 @@ void ParameterGroup::changeEvent(QEvent *e) renameAct->setText(tr("Rename group")); exportAct->setText(tr("Export parameter")); importAct->setText(tr("Import parameter")); - } else { + } + else { QTreeWidget::changeEvent(e); } } @@ -653,11 +684,13 @@ void ParameterGroup::changeEvent(QEvent *e) /* TRANSLATOR Gui::Dialog::ParameterValue */ -ParameterValue::ParameterValue( QWidget * parent ) - : QTreeWidget(parent) +ParameterValue::ParameterValue(QWidget* parent) + : QTreeWidget(parent) { menuEdit = new QMenu(this); - changeAct = menuEdit->addAction(tr("Change value"), this, qOverload<>(&ParameterValue::onChangeSelectedItem)); + changeAct = menuEdit->addAction(tr("Change value"), + this, + qOverload<>(&ParameterValue::onChangeSelectedItem)); menuEdit->addSeparator(); removeAct = menuEdit->addAction(tr("Remove key"), this, &ParameterValue::onDeleteSelectedItem); renameAct = menuEdit->addAction(tr("Rename key"), this, &ParameterValue::onRenameSelectedItem); @@ -668,16 +701,19 @@ ParameterValue::ParameterValue( QWidget * parent ) newStrAct = menuNew->addAction(tr("New string item"), this, &ParameterValue::onCreateTextItem); newFltAct = menuNew->addAction(tr("New float item"), this, &ParameterValue::onCreateFloatItem); newIntAct = menuNew->addAction(tr("New integer item"), this, &ParameterValue::onCreateIntItem); - newUlgAct = menuNew->addAction(tr("New unsigned item"), this, &ParameterValue::onCreateUIntItem); + newUlgAct = + menuNew->addAction(tr("New unsigned item"), this, &ParameterValue::onCreateUIntItem); newBlnAct = menuNew->addAction(tr("New Boolean item"), this, &ParameterValue::onCreateBoolItem); - connect(this, &ParameterValue::itemDoubleClicked, - this, qOverload(&ParameterValue::onChangeSelectedItem)); + connect(this, + &ParameterValue::itemDoubleClicked, + this, + qOverload(&ParameterValue::onChangeSelectedItem)); } ParameterValue::~ParameterValue() = default; -void ParameterValue::setCurrentGroup( const Base::Reference& hGrp ) +void ParameterValue::setCurrentGroup(const Base::Reference& hGrp) { _hcGrp = hGrp; } @@ -687,14 +723,15 @@ Base::Reference ParameterValue::currentGroup() const return _hcGrp; } -bool ParameterValue::edit ( const QModelIndex & index, EditTrigger trigger, QEvent * event ) +bool ParameterValue::edit(const QModelIndex& index, EditTrigger trigger, QEvent* event) { - if (index.column() > 0) + if (index.column() > 0) { return false; + } return QTreeWidget::edit(index, trigger, event); } -void ParameterValue::contextMenuEvent ( QContextMenuEvent* event ) +void ParameterValue::contextMenuEvent(QContextMenuEvent* event) { QTreeWidgetItem* item = currentItem(); if (item && item->isSelected()) { @@ -705,12 +742,12 @@ void ParameterValue::contextMenuEvent ( QContextMenuEvent* event ) // can be popped up without its parent menu (menuEdit) and thus causes a crash. // A workaround is to simply call exec() instead. // - //menuNew->popup(event->globalPos()); + // menuNew->popup(event->globalPos()); menuNew->exec(event->globalPos()); } } -void ParameterValue::keyPressEvent (QKeyEvent* event) +void ParameterValue::keyPressEvent(QKeyEvent* event) { if (event->matches(QKeySequence::Delete)) { onDeleteSelectedItem(); @@ -732,8 +769,7 @@ void ParameterValue::resizeEvent(QResizeEvent* event) void ParameterValue::onChangeSelectedItem(QTreeWidgetItem* item, int col) { - if (item->isSelected() && col > 0) - { + if (item->isSelected() && col > 0) { static_cast(item)->changeValue(); } } @@ -746,8 +782,7 @@ void ParameterValue::onChangeSelectedItem() void ParameterValue::onDeleteSelectedItem() { QTreeWidgetItem* sel = currentItem(); - if (sel && sel->isSelected()) - { + if (sel && sel->isSelected()) { takeTopLevelItem(indexOfTopLevelItem(sel)); static_cast(sel)->removeFromGroup(); delete sel; @@ -757,8 +792,7 @@ void ParameterValue::onDeleteSelectedItem() void ParameterValue::onRenameSelectedItem() { QTreeWidgetItem* sel = currentItem(); - if (sel && sel->isSelected()) - { + if (sel && sel->isSelected()) { editItem(sel, 0); } } @@ -766,27 +800,37 @@ void ParameterValue::onRenameSelectedItem() void ParameterValue::onCreateTextItem() { bool ok; - QString name = QInputDialog::getText(this, QObject::tr("New text item"), QObject::tr("Enter the name:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText(this, + QObject::tr("New text item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if (!ok || !Gui::validateInput(this, name)) + if (!ok || !Gui::validateInput(this, name)) { return; + } - std::vector > smap = _hcGrp->GetASCIIMap(); - for (const auto & it : smap) { - if (name == QLatin1String(it.first.c_str())) - { - QMessageBox::critical( this, tr("Existing item"), - tr("The item '%1' already exists.").arg( name ) ); + std::vector> smap = _hcGrp->GetASCIIMap(); + for (const auto& it : smap) { + if (name == QLatin1String(it.first.c_str())) { + QMessageBox::critical(this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name)); return; } } - QString val = QInputDialog::getText(this, QObject::tr("New text item"), QObject::tr("Enter your text:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok && !val.isEmpty() ) - { - ParameterValueItem *pcItem; + QString val = QInputDialog::getText(this, + QObject::tr("New text item"), + QObject::tr("Enter your text:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok && !val.isEmpty()) { + ParameterValueItem* pcItem; pcItem = new ParameterText(this, name, val.toUtf8(), _hcGrp); pcItem->appendToGroup(); } @@ -795,29 +839,41 @@ void ParameterValue::onCreateTextItem() void ParameterValue::onCreateIntItem() { bool ok; - QString name = QInputDialog::getText(this, QObject::tr("New integer item"), QObject::tr("Enter the name:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText(this, + QObject::tr("New integer item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if (!ok || !Gui::validateInput(this, name)) + if (!ok || !Gui::validateInput(this, name)) { return; + } - std::vector > lmap = _hcGrp->GetIntMap(); - for (const auto & it : lmap) { - if (name == QLatin1String(it.first.c_str())) - { - QMessageBox::critical( this, tr("Existing item"), - tr("The item '%1' already exists.").arg( name ) ); + std::vector> lmap = _hcGrp->GetIntMap(); + for (const auto& it : lmap) { + if (name == QLatin1String(it.first.c_str())) { + QMessageBox::critical(this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name)); return; } } - int val = QInputDialog::getInt(this, QObject::tr("New integer item"), QObject::tr("Enter your number:"), - 0, -2147483647, 2147483647, 1, &ok, Qt::MSWindowsFixedSizeDialogHint); + int val = QInputDialog::getInt(this, + QObject::tr("New integer item"), + QObject::tr("Enter your number:"), + 0, + -2147483647, + 2147483647, + 1, + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { - ParameterValueItem *pcItem; - pcItem = new ParameterInt(this,name,(long)val, _hcGrp); + if (ok) { + ParameterValueItem* pcItem; + pcItem = new ParameterInt(this, name, (long)val, _hcGrp); pcItem->appendToGroup(); } } @@ -825,34 +881,42 @@ void ParameterValue::onCreateIntItem() void ParameterValue::onCreateUIntItem() { bool ok; - QString name = QInputDialog::getText(this, QObject::tr("New unsigned item"), QObject::tr("Enter the name:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText(this, + QObject::tr("New unsigned item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if (!ok || !Gui::validateInput(this, name)) + if (!ok || !Gui::validateInput(this, name)) { return; + } - std::vector > lmap = _hcGrp->GetUnsignedMap(); - for (const auto & it : lmap) { - if (name == QLatin1String(it.first.c_str())) - { - QMessageBox::critical( this, tr("Existing item"), - tr("The item '%1' already exists.").arg( name ) ); + std::vector> lmap = _hcGrp->GetUnsignedMap(); + for (const auto& it : lmap) { + if (name == QLatin1String(it.first.c_str())) { + QMessageBox::critical(this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name)); return; } } - DlgInputDialogImp dlg(QObject::tr("Enter your number:"),this, true, DlgInputDialogImp::UIntBox); + DlgInputDialogImp dlg(QObject::tr("Enter your number:"), + this, + true, + DlgInputDialogImp::UIntBox); dlg.setWindowTitle(QObject::tr("New unsigned item")); UIntSpinBox* edit = dlg.getUIntBox(); - edit->setRange(0,UINT_MAX); - if (dlg.exec() == QDialog::Accepted ) { + edit->setRange(0, UINT_MAX); + if (dlg.exec() == QDialog::Accepted) { QString value = edit->text(); unsigned long val = value.toULong(&ok); - if ( ok ) - { - ParameterValueItem *pcItem; - pcItem = new ParameterUInt(this,name, val, _hcGrp); + if (ok) { + ParameterValueItem* pcItem; + pcItem = new ParameterUInt(this, name, val, _hcGrp); pcItem->appendToGroup(); } } @@ -861,28 +925,40 @@ void ParameterValue::onCreateUIntItem() void ParameterValue::onCreateFloatItem() { bool ok; - QString name = QInputDialog::getText(this, QObject::tr("New float item"), QObject::tr("Enter the name:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText(this, + QObject::tr("New float item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if (!ok || !Gui::validateInput(this, name)) + if (!ok || !Gui::validateInput(this, name)) { return; + } - std::vector > fmap = _hcGrp->GetFloatMap(); - for (const auto & it : fmap) { - if (name == QLatin1String(it.first.c_str())) - { - QMessageBox::critical( this, tr("Existing item"), - tr("The item '%1' already exists.").arg( name ) ); + std::vector> fmap = _hcGrp->GetFloatMap(); + for (const auto& it : fmap) { + if (name == QLatin1String(it.first.c_str())) { + QMessageBox::critical(this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name)); return; } } - double val = QInputDialog::getDouble(this, QObject::tr("New float item"), QObject::tr("Enter your number:"), - 0, -2147483647, 2147483647, 12, &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { - ParameterValueItem *pcItem; - pcItem = new ParameterFloat(this,name,val, _hcGrp); + double val = QInputDialog::getDouble(this, + QObject::tr("New float item"), + QObject::tr("Enter your number:"), + 0, + -2147483647, + 2147483647, + 12, + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok) { + ParameterValueItem* pcItem; + pcItem = new ParameterFloat(this, name, val, _hcGrp); pcItem->appendToGroup(); } } @@ -890,45 +966,60 @@ void ParameterValue::onCreateFloatItem() void ParameterValue::onCreateBoolItem() { bool ok; - QString name = QInputDialog::getText(this, QObject::tr("New Boolean item"), QObject::tr("Enter the name:"), - QLineEdit::Normal, QString(), &ok, Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText(this, + QObject::tr("New Boolean item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint); - if (!ok || !Gui::validateInput(this, name)) + if (!ok || !Gui::validateInput(this, name)) { return; + } - std::vector > bmap = _hcGrp->GetBoolMap(); - for (const auto & it : bmap) { - if (name == QLatin1String(it.first.c_str())) - { - QMessageBox::critical( this, tr("Existing item"), - tr("The item '%1' already exists.").arg( name ) ); + std::vector> bmap = _hcGrp->GetBoolMap(); + for (const auto& it : bmap) { + if (name == QLatin1String(it.first.c_str())) { + QMessageBox::critical(this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name)); return; } } - QStringList list; list << QString::fromLatin1("true") - << QString::fromLatin1("false"); - QString val = QInputDialog::getItem (this, QObject::tr("New boolean item"), QObject::tr("Choose an item:"), - list, 0, false, &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { - ParameterValueItem *pcItem; - pcItem = new ParameterBool(this,name,(val == list[0] ? true : false), _hcGrp); + QStringList list; + list << QString::fromLatin1("true") << QString::fromLatin1("false"); + QString val = QInputDialog::getItem(this, + QObject::tr("New boolean item"), + QObject::tr("Choose an item:"), + list, + 0, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok) { + ParameterValueItem* pcItem; + pcItem = new ParameterBool(this, name, (val == list[0] ? true : false), _hcGrp); pcItem->appendToGroup(); } } // --------------------------------------------------------------------------- -ParameterGroupItem::ParameterGroupItem( ParameterGroupItem * parent, const Base::Reference &hcGrp ) - : QTreeWidgetItem( parent, QTreeWidgetItem::UserType+1 ), _hcGrp(hcGrp) +ParameterGroupItem::ParameterGroupItem(ParameterGroupItem* parent, + const Base::Reference& hcGrp) + : QTreeWidgetItem(parent, QTreeWidgetItem::UserType + 1) + , _hcGrp(hcGrp) { setFlags(flags() | Qt::ItemIsEditable); fillUp(); } -ParameterGroupItem::ParameterGroupItem( QTreeWidget* parent, const Base::Reference &hcGrp) - : QTreeWidgetItem( parent, QTreeWidgetItem::UserType+1 ), _hcGrp(hcGrp) +ParameterGroupItem::ParameterGroupItem(QTreeWidget* parent, + const Base::Reference& hcGrp) + : QTreeWidgetItem(parent, QTreeWidgetItem::UserType + 1) + , _hcGrp(hcGrp) { setFlags(flags() | Qt::ItemIsEditable); fillUp(); @@ -936,66 +1027,70 @@ ParameterGroupItem::ParameterGroupItem( QTreeWidget* parent, const Base::Referen ParameterGroupItem::~ParameterGroupItem() { - // if the group has already been removed from the parameters then clear the observer list - // as we cannot notify the attached observers here - if (_hcGrp.getRefCount() == 1) - _hcGrp->ClearObserver(); + // if the group has already been removed from the parameters then clear the observer list + // as we cannot notify the attached observers here + if (_hcGrp.getRefCount() == 1) { + _hcGrp->ClearObserver(); + } } void ParameterGroupItem::fillUp() { // filling up groups - std::vector > vhcParamGrp = _hcGrp->GetGroups(); + std::vector> vhcParamGrp = _hcGrp->GetGroups(); - setText(0,QString::fromUtf8(_hcGrp->GetGroupName())); - for(const auto & It : vhcParamGrp) - (void)new ParameterGroupItem(this,It); + setText(0, QString::fromUtf8(_hcGrp->GetGroupName())); + for (const auto& It : vhcParamGrp) { + (void)new ParameterGroupItem(this, It); + } } -void ParameterGroupItem::setData ( int column, int role, const QVariant & value ) +void ParameterGroupItem::setData(int column, int role, const QVariant& value) { if (role == Qt::EditRole) { QString oldName = text(0); QString newName = value.toString(); - if (newName.isEmpty() || oldName == newName) + if (newName.isEmpty() || oldName == newName) { return; + } - if (!Gui::validateInput(treeWidget(), newName)) + if (!Gui::validateInput(treeWidget(), newName)) { return; + } // first check if there is already a group with name "newName" auto item = static_cast(parent()); - if ( !item ) - { - QMessageBox::critical( treeWidget(), QObject::tr("Rename group"), - QObject::tr("The group '%1' cannot be renamed.").arg( oldName ) ); + if (!item) { + QMessageBox::critical(treeWidget(), + QObject::tr("Rename group"), + QObject::tr("The group '%1' cannot be renamed.").arg(oldName)); return; } - if ( item->_hcGrp->HasGroup( newName.toLatin1() ) ) - { - QMessageBox::critical( treeWidget(), QObject::tr("Existing group"), - QObject::tr("The group '%1' already exists.").arg( newName ) ); + if (item->_hcGrp->HasGroup(newName.toLatin1())) { + QMessageBox::critical(treeWidget(), + QObject::tr("Existing group"), + QObject::tr("The group '%1' already exists.").arg(newName)); return; } - else - { + else { // rename the group by adding a new group, copy the content and remove the old group - if (!item->_hcGrp->RenameGrp(oldName.toLatin1(), newName.toLatin1())) + if (!item->_hcGrp->RenameGrp(oldName.toLatin1(), newName.toLatin1())) { return; + } } } QTreeWidgetItem::setData(column, role, value); } -QVariant ParameterGroupItem::data ( int column, int role ) const +QVariant ParameterGroupItem::data(int column, int role) const { if (role == Qt::DecorationRole) { // The root item should keep its special pixmap if (parent()) { - return this->isExpanded() ? - QApplication::style()->standardPixmap(QStyle::SP_DirOpenIcon): - QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon); + return this->isExpanded() + ? QApplication::style()->standardPixmap(QStyle::SP_DirOpenIcon) + : QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon); } } @@ -1004,26 +1099,30 @@ QVariant ParameterGroupItem::data ( int column, int role ) const // -------------------------------------------------------------------- -ParameterValueItem::ParameterValueItem ( QTreeWidget* parent, const Base::Reference &hcGrp) - : QTreeWidgetItem( parent ), _hcGrp(hcGrp) +ParameterValueItem::ParameterValueItem(QTreeWidget* parent, + const Base::Reference& hcGrp) + : QTreeWidgetItem(parent) + , _hcGrp(hcGrp) { setFlags(flags() | Qt::ItemIsEditable); } ParameterValueItem::~ParameterValueItem() = default; -void ParameterValueItem::setData ( int column, int role, const QVariant & value ) +void ParameterValueItem::setData(int column, int role, const QVariant& value) { if (role == Qt::EditRole) { QString oldName = text(0); QString newName = value.toString(); - if (newName.isEmpty() || oldName == newName) + if (newName.isEmpty() || oldName == newName) { return; + } - if (!Gui::validateInput(treeWidget(), newName)) + if (!Gui::validateInput(treeWidget(), newName)) { return; + } - replace( oldName, newName ); + replace(oldName, newName); } QTreeWidgetItem::setData(column, role, value); @@ -1031,10 +1130,13 @@ void ParameterValueItem::setData ( int column, int role, const QVariant & value // -------------------------------------------------------------------- -ParameterText::ParameterText ( QTreeWidget * parent, QString label, const char* value, const Base::Reference &hcGrp) - :ParameterValueItem( parent, hcGrp) +ParameterText::ParameterText(QTreeWidget* parent, + QString label, + const char* value, + const Base::Reference& hcGrp) + : ParameterValueItem(parent, hcGrp) { - setIcon(0, BitmapFactory().iconFromTheme("Param_Text") ); + setIcon(0, BitmapFactory().iconFromTheme("Param_Text")); setText(0, label); setText(1, QString::fromLatin1("Text")); setText(2, QString::fromUtf8(value)); @@ -1045,21 +1147,25 @@ ParameterText::~ParameterText() = default; void ParameterText::changeValue() { bool ok; - QString txt = QInputDialog::getText(treeWidget(), QObject::tr("Change value"), QObject::tr("Enter your text:"), - QLineEdit::Normal, text(2), &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { - setText( 2, txt ); + QString txt = QInputDialog::getText(treeWidget(), + QObject::tr("Change value"), + QObject::tr("Enter your text:"), + QLineEdit::Normal, + text(2), + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok) { + setText(2, txt); _hcGrp->SetASCII(text(0).toLatin1(), txt.toUtf8()); } } -void ParameterText::removeFromGroup () +void ParameterText::removeFromGroup() { _hcGrp->RemoveASCII(text(0).toLatin1()); } -void ParameterText::replace( const QString& oldName, const QString& newName ) +void ParameterText::replace(const QString& oldName, const QString& newName) { std::string val = _hcGrp->GetASCII(oldName.toLatin1()); _hcGrp->RemoveASCII(oldName.toLatin1()); @@ -1073,10 +1179,13 @@ void ParameterText::appendToGroup() // -------------------------------------------------------------------- -ParameterInt::ParameterInt ( QTreeWidget * parent, QString label, long value, const Base::Reference &hcGrp) - :ParameterValueItem( parent, hcGrp) +ParameterInt::ParameterInt(QTreeWidget* parent, + QString label, + long value, + const Base::Reference& hcGrp) + : ParameterValueItem(parent, hcGrp) { - setIcon(0, BitmapFactory().iconFromTheme("Param_Int") ); + setIcon(0, BitmapFactory().iconFromTheme("Param_Int")); setText(0, label); setText(1, QString::fromLatin1("Integer")); setText(2, QString::fromLatin1("%1").arg(value)); @@ -1087,21 +1196,27 @@ ParameterInt::~ParameterInt() = default; void ParameterInt::changeValue() { bool ok; - int num = QInputDialog::getInt(treeWidget(), QObject::tr("Change value"), QObject::tr("Enter your number:"), - text(2).toInt(), -2147483647, 2147483647, 1, &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { + int num = QInputDialog::getInt(treeWidget(), + QObject::tr("Change value"), + QObject::tr("Enter your number:"), + text(2).toInt(), + -2147483647, + 2147483647, + 1, + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok) { setText(2, QString::fromLatin1("%1").arg(num)); _hcGrp->SetInt(text(0).toLatin1(), (long)num); } } -void ParameterInt::removeFromGroup () +void ParameterInt::removeFromGroup() { _hcGrp->RemoveInt(text(0).toLatin1()); } -void ParameterInt::replace( const QString& oldName, const QString& newName ) +void ParameterInt::replace(const QString& oldName, const QString& newName) { long val = _hcGrp->GetInt(oldName.toLatin1()); _hcGrp->RemoveInt(oldName.toLatin1()); @@ -1115,10 +1230,13 @@ void ParameterInt::appendToGroup() // -------------------------------------------------------------------- -ParameterUInt::ParameterUInt ( QTreeWidget * parent, QString label, unsigned long value, const Base::Reference &hcGrp) - :ParameterValueItem( parent, hcGrp) +ParameterUInt::ParameterUInt(QTreeWidget* parent, + QString label, + unsigned long value, + const Base::Reference& hcGrp) + : ParameterValueItem(parent, hcGrp) { - setIcon(0, BitmapFactory().iconFromTheme("Param_UInt") ); + setIcon(0, BitmapFactory().iconFromTheme("Param_UInt")); setText(0, label); setText(1, QString::fromLatin1("Unsigned")); setText(2, QString::fromLatin1("%1").arg(value)); @@ -1129,30 +1247,31 @@ ParameterUInt::~ParameterUInt() = default; void ParameterUInt::changeValue() { bool ok; - DlgInputDialogImp dlg(QObject::tr("Enter your number:"),treeWidget(), true, DlgInputDialogImp::UIntBox); + DlgInputDialogImp dlg(QObject::tr("Enter your number:"), + treeWidget(), + true, + DlgInputDialogImp::UIntBox); dlg.setWindowTitle(QObject::tr("Change value")); UIntSpinBox* edit = dlg.getUIntBox(); - edit->setRange(0,UINT_MAX); + edit->setRange(0, UINT_MAX); edit->setValue(text(2).toULong()); - if (dlg.exec() == QDialog::Accepted) - { + if (dlg.exec() == QDialog::Accepted) { QString value = edit->text(); unsigned long num = value.toULong(&ok); - if ( ok ) - { + if (ok) { setText(2, QString::fromLatin1("%1").arg(num)); _hcGrp->SetUnsigned(text(0).toLatin1(), (unsigned long)num); } } } -void ParameterUInt::removeFromGroup () +void ParameterUInt::removeFromGroup() { _hcGrp->RemoveUnsigned(text(0).toLatin1()); } -void ParameterUInt::replace( const QString& oldName, const QString& newName ) +void ParameterUInt::replace(const QString& oldName, const QString& newName) { unsigned long val = _hcGrp->GetUnsigned(oldName.toLatin1()); _hcGrp->RemoveUnsigned(oldName.toLatin1()); @@ -1166,10 +1285,13 @@ void ParameterUInt::appendToGroup() // -------------------------------------------------------------------- -ParameterFloat::ParameterFloat ( QTreeWidget * parent, QString label, double value, const Base::Reference &hcGrp) - :ParameterValueItem( parent, hcGrp) +ParameterFloat::ParameterFloat(QTreeWidget* parent, + QString label, + double value, + const Base::Reference& hcGrp) + : ParameterValueItem(parent, hcGrp) { - setIcon(0, BitmapFactory().iconFromTheme("Param_Float") ); + setIcon(0, BitmapFactory().iconFromTheme("Param_Float")); setText(0, label); setText(1, QString::fromLatin1("Float")); setText(2, QString::fromLatin1("%1").arg(value)); @@ -1180,21 +1302,27 @@ ParameterFloat::~ParameterFloat() = default; void ParameterFloat::changeValue() { bool ok; - double num = QInputDialog::getDouble(treeWidget(), QObject::tr("Change value"), QObject::tr("Enter your number:"), - text(2).toDouble(), -2147483647, 2147483647, 12, &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { + double num = QInputDialog::getDouble(treeWidget(), + QObject::tr("Change value"), + QObject::tr("Enter your number:"), + text(2).toDouble(), + -2147483647, + 2147483647, + 12, + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok) { setText(2, QString::fromLatin1("%1").arg(num)); _hcGrp->SetFloat(text(0).toLatin1(), num); } } -void ParameterFloat::removeFromGroup () +void ParameterFloat::removeFromGroup() { _hcGrp->RemoveFloat(text(0).toLatin1()); } -void ParameterFloat::replace( const QString& oldName, const QString& newName ) +void ParameterFloat::replace(const QString& oldName, const QString& newName) { double val = _hcGrp->GetFloat(oldName.toLatin1()); _hcGrp->RemoveFloat(oldName.toLatin1()); @@ -1208,10 +1336,13 @@ void ParameterFloat::appendToGroup() // -------------------------------------------------------------------- -ParameterBool::ParameterBool ( QTreeWidget * parent, QString label, bool value, const Base::Reference &hcGrp) - :ParameterValueItem( parent, hcGrp) +ParameterBool::ParameterBool(QTreeWidget* parent, + QString label, + bool value, + const Base::Reference& hcGrp) + : ParameterValueItem(parent, hcGrp) { - setIcon(0, BitmapFactory().iconFromTheme("Param_Bool") ); + setIcon(0, BitmapFactory().iconFromTheme("Param_Bool")); setText(0, label); setText(1, QString::fromLatin1("Boolean")); setText(2, QString::fromLatin1((value ? "true" : "false"))); @@ -1222,25 +1353,30 @@ ParameterBool::~ParameterBool() = default; void ParameterBool::changeValue() { bool ok; - QStringList list; list << QString::fromLatin1("true") - << QString::fromLatin1("false"); + QStringList list; + list << QString::fromLatin1("true") << QString::fromLatin1("false"); int pos = (text(2) == list[0] ? 0 : 1); - QString txt = QInputDialog::getItem (treeWidget(), QObject::tr("Change value"), QObject::tr("Choose an item:"), - list, pos, false, &ok, Qt::MSWindowsFixedSizeDialogHint); - if ( ok ) - { - setText( 2, txt ); - _hcGrp->SetBool(text(0).toLatin1(), (txt == list[0] ? true : false) ); + QString txt = QInputDialog::getItem(treeWidget(), + QObject::tr("Change value"), + QObject::tr("Choose an item:"), + list, + pos, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint); + if (ok) { + setText(2, txt); + _hcGrp->SetBool(text(0).toLatin1(), (txt == list[0] ? true : false)); } } -void ParameterBool::removeFromGroup () +void ParameterBool::removeFromGroup() { _hcGrp->RemoveBool(text(0).toLatin1()); } -void ParameterBool::replace( const QString& oldName, const QString& newName ) +void ParameterBool::replace(const QString& oldName, const QString& newName) { bool val = _hcGrp->GetBool(oldName.toLatin1()); _hcGrp->RemoveBool(oldName.toLatin1()); diff --git a/src/Gui/DlgPropertyLink.cpp b/src/Gui/DlgPropertyLink.cpp index 95213926d8..869d541670 100644 --- a/src/Gui/DlgPropertyLink.cpp +++ b/src/Gui/DlgPropertyLink.cpp @@ -22,10 +22,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include +#include +#include +#include +#include #endif #include @@ -51,15 +51,20 @@ using namespace Gui::Dialog; -class ItemDelegate: public QStyledItemDelegate { +class ItemDelegate: public QStyledItemDelegate +{ public: - explicit ItemDelegate(QObject* parent=nullptr): QStyledItemDelegate(parent) {} + explicit ItemDelegate(QObject* parent = nullptr) + : QStyledItemDelegate(parent) + {} - QWidget* createEditor(QWidget *parent, - const QStyleOptionViewItem &option, const QModelIndex &index) const override + QWidget* createEditor(QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index) const override { - if(index.column() != 1) + if (index.column() != 1) { return nullptr; + } return QStyledItemDelegate::createEditor(parent, option, index); } }; @@ -67,9 +72,11 @@ public: /* TRANSLATOR Gui::Dialog::DlgPropertyLink */ DlgPropertyLink::DlgPropertyLink(QWidget* parent) - : QDialog(parent), SelectionObserver(false, ResolveMode::NoResolve) - , ui(new Ui_DlgPropertyLink) + : QDialog(parent) + , SelectionObserver(false, ResolveMode::NoResolve) + , ui(new Ui_DlgPropertyLink) { + // clang-format off ui->setupUi(this); connect(ui->checkObjectType, &QCheckBox::toggled, this, &DlgPropertyLink::onObjectTypeToggled); @@ -105,6 +112,7 @@ DlgPropertyLink::DlgPropertyLink(QWidget* parent) refreshButton = ui->buttonBox->addButton(tr("Reset"), QDialogButtonBox::ActionRole); resetButton = ui->buttonBox->addButton(tr("Clear"), QDialogButtonBox::ResetRole); + // clang-format on } /** @@ -118,108 +126,125 @@ DlgPropertyLink::~DlgPropertyLink() delete ui; } -QList DlgPropertyLink::getLinksFromProperty(const App::PropertyLinkBase *prop) +QList DlgPropertyLink::getLinksFromProperty(const App::PropertyLinkBase* prop) { QList res; - if(!prop) + if (!prop) { return res; + } std::vector objs; std::vector subs; - prop->getLinks(objs,true,&subs,false); - if(subs.empty()) { - for(auto obj : objs) - res.push_back(App::SubObjectT(obj,nullptr)); - } else if (objs.size()==1) { - for(auto &sub : subs) - res.push_back(App::SubObjectT(objs.front(),sub.c_str())); - } else { - int i=0; - for(auto obj : objs) - res.push_back(App::SubObjectT(obj,subs[i++].c_str())); + prop->getLinks(objs, true, &subs, false); + if (subs.empty()) { + for (auto obj : objs) { + res.push_back(App::SubObjectT(obj, nullptr)); + } + } + else if (objs.size() == 1) { + for (auto& sub : subs) { + res.push_back(App::SubObjectT(objs.front(), sub.c_str())); + } + } + else { + int i = 0; + for (auto obj : objs) { + res.push_back(App::SubObjectT(obj, subs[i++].c_str())); + } } return res; } -QString DlgPropertyLink::formatObject(App::Document *ownerDoc, App::DocumentObject *obj, const char *sub) +QString +DlgPropertyLink::formatObject(App::Document* ownerDoc, App::DocumentObject* obj, const char* sub) { - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return QLatin1String("?"); + } - const char *objName = obj->getNameInDocument(); + const char* objName = obj->getNameInDocument(); std::string _objName; - if(ownerDoc && ownerDoc!=obj->getDocument()) { + if (ownerDoc && ownerDoc != obj->getDocument()) { _objName = obj->getFullName(); objName = _objName.c_str(); } - if(!sub || !sub[0]) { - if(obj->Label.getStrValue() == obj->getNameInDocument()) + if (!sub || !sub[0]) { + if (obj->Label.getStrValue() == obj->getNameInDocument()) { return QLatin1String(objName); + } return QString::fromLatin1("%1 (%2)").arg(QLatin1String(objName), QString::fromUtf8(obj->Label.getValue())); } auto sobj = obj->getSubObject(sub); - if(!sobj || sobj->Label.getStrValue() == sobj->getNameInDocument()) - return QString::fromLatin1("%1.%2").arg(QLatin1String(objName), - QString::fromUtf8(sub)); + if (!sobj || sobj->Label.getStrValue() == sobj->getNameInDocument()) { + return QString::fromLatin1("%1.%2").arg(QLatin1String(objName), QString::fromUtf8(sub)); + } - return QString::fromLatin1("%1.%2 (%3)").arg(QLatin1String(objName), - QString::fromUtf8(sub), - QString::fromUtf8(sobj->Label.getValue())); + return QString::fromLatin1("%1.%2 (%3)") + .arg(QLatin1String(objName), + QString::fromUtf8(sub), + QString::fromUtf8(sobj->Label.getValue())); } static inline bool isLinkSub(const QList& links) { - for(const auto &link : links) { - if(&link == &links.front()) + for (const auto& link : links) { + if (&link == &links.front()) { continue; - if(link.getDocumentName() != links.front().getDocumentName() - || link.getObjectName() != links.front().getObjectName()) - { + } + if (link.getDocumentName() != links.front().getDocumentName() + || link.getObjectName() != links.front().getObjectName()) { return false; } } return true; } -QString DlgPropertyLink::formatLinks(App::Document *ownerDoc, QList links) +QString DlgPropertyLink::formatLinks(App::Document* ownerDoc, QList links) { - if(!ownerDoc || links.empty()) + if (!ownerDoc || links.empty()) { return {}; + } auto obj = links.front().getObject(); - if(!obj) + if (!obj) { return QLatin1String("?"); + } - if(links.size() == 1 && links.front().getSubName().empty()) + if (links.size() == 1 && links.front().getSubName().empty()) { return formatObject(ownerDoc, links.front()); + } QStringList list; - if(isLinkSub(links)) { + if (isLinkSub(links)) { int i = 0; - for(auto &link : links) { + for (auto& link : links) { list << QString::fromUtf8(link.getSubName().c_str()); - if( ++i >= 3) + if (++i >= 3) { break; + } } - return QString::fromLatin1("%1 [%2%3]").arg(formatObject(ownerDoc,obj,nullptr), - list.join(QLatin1String(", ")), - QLatin1String(links.size()>3?" ...":"")); + return QString::fromLatin1("%1 [%2%3]") + .arg(formatObject(ownerDoc, obj, nullptr), + list.join(QLatin1String(", ")), + QLatin1String(links.size() > 3 ? " ..." : "")); } int i = 0; - for(auto &link : links) { - list << formatObject(ownerDoc,link); - if( ++i >= 3) + for (auto& link : links) { + list << formatObject(ownerDoc, link); + if (++i >= 3) { break; + } } return QString::fromLatin1("[%1%2]").arg(list.join(QLatin1String(", ")), - QLatin1String(links.size()>3?" ...":"")); + QLatin1String(links.size() > 3 ? " ..." : "")); } -void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { +void DlgPropertyLink::init(const App::DocumentObjectT& prop, bool tryFilter) +{ ui->treeWidget->blockSignals(true); ui->treeWidget->clear(); ui->treeWidget->blockSignals(false); @@ -239,20 +264,22 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { subSelections.clear(); selections.clear(); - objProp = prop; + objProp = prop; auto owner = objProp.getObject(); - if(!owner || !owner->isAttachedToDocument()) + if (!owner || !owner->isAttachedToDocument()) { return; + } ui->searchBox->setDocumentObject(owner); auto propLink = Base::freecad_dynamic_cast(objProp.getProperty()); - if(!propLink) + if (!propLink) { return; + } oldLinks = getLinksFromProperty(propLink); - if(propLink->getScope() != App::LinkScope::Hidden) { + if (propLink->getScope() != App::LinkScope::Hidden) { // populate inList to filter out any objects that contains the owner object // of the editing link property inList = owner->getInListEx(true); @@ -262,43 +289,47 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { std::vector docs; singleSelect = false; - if(propLink->isDerivedFrom(App::PropertyXLinkSub::getClassTypeId()) - || propLink->isDerivedFrom(App::PropertyLinkSub::getClassTypeId())) - { + if (propLink->isDerivedFrom(App::PropertyXLinkSub::getClassTypeId()) + || propLink->isDerivedFrom(App::PropertyLinkSub::getClassTypeId())) { allowSubObject = true; singleParent = true; - } else if (propLink->isDerivedFrom(App::PropertyLink::getClassTypeId())) { + } + else if (propLink->isDerivedFrom(App::PropertyLink::getClassTypeId())) { singleSelect = true; - } else if (propLink->isDerivedFrom(App::PropertyLinkSubList::getClassTypeId())) { + } + else if (propLink->isDerivedFrom(App::PropertyLinkSubList::getClassTypeId())) { allowSubObject = true; } - if(App::PropertyXLink::supportXLink(propLink)) { + if (App::PropertyXLink::supportXLink(propLink)) { allowSubObject = true; docs = App::GetApplication().getDocuments(); - } else + } + else { docs.push_back(owner->getDocument()); + } bool isLinkList = false; if (propLink->isDerivedFrom(App::PropertyXLinkList::getClassTypeId()) - || propLink->isDerivedFrom(App::PropertyLinkList::getClassTypeId())) - { + || propLink->isDerivedFrom(App::PropertyLinkList::getClassTypeId())) { isLinkList = true; allowSubObject = false; } - if(singleSelect) { + if (singleSelect) { singleParent = true; ui->treeWidget->setSelectionMode(QAbstractItemView::SingleSelection); - } else { + } + else { ui->treeWidget->setSelectionMode(QAbstractItemView::MultiSelection); } ui->checkSubObject->setVisible(allowSubObject); - if(!allowSubObject) { + if (!allowSubObject) { ui->treeWidget->setColumnCount(1); - } else { + } + else { ui->treeWidget->setColumnCount(2); // make sure to show a horizontal scrollbar if needed @@ -307,37 +338,41 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { std::set expandDocs; - if(oldLinks.empty()) { + if (oldLinks.empty()) { expandDocs.insert(owner->getDocument()); - } else { - for(auto &link : oldLinks) { + } + else { + for (auto& link : oldLinks) { auto doc = link.getDocument(); - if(doc) + if (doc) { expandDocs.insert(doc); + } } } QPixmap docIcon(Gui::BitmapFactory().pixmap("Document")); - for(auto d : docs) { + for (auto d : docs) { auto item = new QTreeWidgetItem(ui->treeWidget); item->setIcon(0, docIcon); item->setText(0, QString::fromUtf8(d->Label.getValue())); item->setData(0, Qt::UserRole, QByteArray("")); - item->setData(0, Qt::UserRole+1, QByteArray(d->getName())); + item->setData(0, Qt::UserRole + 1, QByteArray(d->getName())); item->setFlags(Qt::ItemIsEnabled); item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); - if(expandDocs.count(d)) + if (expandDocs.count(d)) { item->setExpanded(true); + } docItems[d] = item; } - if(allowSubObject) { - if (propLink->testFlag(App::PropertyLinkBase::LinkSyncSubObject)) + if (allowSubObject) { + if (propLink->testFlag(App::PropertyLinkBase::LinkSyncSubObject)) { ui->checkSubObject->setChecked(true); + } else { - for(auto &link : oldLinks) { + for (auto& link : oldLinks) { auto sobj = link.getSubObject(); - if(sobj && sobj!=link.getObject()) { + if (sobj && sobj != link.getObject()) { ui->checkSubObject->setChecked(true); break; } @@ -345,13 +380,14 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { } } - if(oldLinks.isEmpty()) + if (oldLinks.isEmpty()) { return; + } // Try to select items corresponding to the current links inside the // property ui->treeWidget->blockSignals(true); - for(auto &link : oldLinks) { + for (auto& link : oldLinks) { onSelectionChanged(Gui::SelectionChanges(SelectionChanges::AddSelection, link.getDocumentName(), link.getObjectName(), @@ -360,30 +396,33 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { ui->treeWidget->blockSignals(false); // For link list type property, try to auto filter type - if(tryFilter && isLinkList) { + if (tryFilter && isLinkList) { Base::Type objType; - for(const auto& link : std::as_const(oldLinks)) { + for (const auto& link : std::as_const(oldLinks)) { auto obj = link.getSubObject(); - if(!obj) + if (!obj) { continue; - if(objType.isBad()) { + } + if (objType.isBad()) { objType = obj->getTypeId(); continue; } - for(;objType != App::DocumentObject::getClassTypeId(); - objType = objType.getParent()) - { - if(obj->isDerivedFrom(objType)) + for (; objType != App::DocumentObject::getClassTypeId(); + objType = objType.getParent()) { + if (obj->isDerivedFrom(objType)) { break; + } } } Base::Type baseType; // get only geometric types - if (objType.isDerivedFrom(App::GeoFeature::getClassTypeId())) + if (objType.isDerivedFrom(App::GeoFeature::getClassTypeId())) { baseType = App::GeoFeature::getClassTypeId(); - else + } + else { baseType = App::DocumentObject::getClassTypeId(); + } // get the direct base class of App::DocumentObject which 'obj' is derived from while (!objType.isBad()) { @@ -395,103 +434,121 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { objType = parType; } - if(!baseType.isBad()) { - const char *name = baseType.getName(); - auto it = typeItems.find(QByteArray::fromRawData(name,strlen(name)+1)); - if(it != typeItems.end()) + if (!baseType.isBad()) { + const char* name = baseType.getName(); + auto it = typeItems.find(QByteArray::fromRawData(name, strlen(name) + 1)); + if (it != typeItems.end()) { it->second->setSelected(true); + } ui->checkObjectType->setChecked(true); } } } -void DlgPropertyLink::onClicked(QAbstractButton *button) { - if(button == resetButton) { +void DlgPropertyLink::onClicked(QAbstractButton* button) +{ + if (button == resetButton) { ui->treeWidget->blockSignals(true); ui->treeWidget->selectionModel()->clearSelection(); - for(auto item : subSelections) + for (auto item : subSelections) { item->setText(1, QString()); + } ui->treeWidget->blockSignals(false); subSelections.clear(); Gui::Selection().clearSelection(); - } else if (button == refreshButton) { + } + else if (button == refreshButton) { init(objProp); } } -void DlgPropertyLink::hideEvent(QHideEvent *ev) { +void DlgPropertyLink::hideEvent(QHideEvent* ev) +{ detachObserver(); QDialog::hideEvent(ev); } -void DlgPropertyLink::closeEvent(QCloseEvent *ev) { +void DlgPropertyLink::closeEvent(QCloseEvent* ev) +{ detachObserver(); QDialog::closeEvent(ev); } -void DlgPropertyLink::attachObserver() { - if(isSelectionAttached()) +void DlgPropertyLink::attachObserver() +{ + if (isSelectionAttached()) { return; + } Gui::Selection().selStackPush(); attachSelection(); - if(!parentView) { - for(auto p=parent(); p; p=p->parent()) { + if (!parentView) { + for (auto p = parent(); p; p = p->parent()) { auto view = qobject_cast(p); - if(view) { + if (view) { parentView = view; - for(auto &sel : Gui::Selection().getCompleteSelection(ResolveMode::NoResolve)) + for (auto& sel : Gui::Selection().getCompleteSelection(ResolveMode::NoResolve)) { savedSelections.emplace_back(sel.DocName, sel.FeatName, sel.SubName); + } break; } } } auto view = qobject_cast(parentView.data()); - if(view) + if (view) { view->blockSelection(true); + } } -void DlgPropertyLink::showEvent(QShowEvent *ev) { +void DlgPropertyLink::showEvent(QShowEvent* ev) +{ attachObserver(); QDialog::showEvent(ev); } -void DlgPropertyLink::onItemEntered(QTreeWidgetItem *) { - int timeout = Gui::TreeParams::getPreSelectionDelay()/2; - if(timeout < 0) +void DlgPropertyLink::onItemEntered(QTreeWidgetItem*) +{ + int timeout = Gui::TreeParams::getPreSelectionDelay() / 2; + if (timeout < 0) { timeout = 1; + } timer->start(timeout); Gui::Selection().rmvPreselect(); } -void DlgPropertyLink::leaveEvent(QEvent *ev) { +void DlgPropertyLink::leaveEvent(QEvent* ev) +{ Gui::Selection().rmvPreselect(); QDialog::leaveEvent(ev); } -void DlgPropertyLink::detachObserver() { - if(isSelectionAttached()) +void DlgPropertyLink::detachObserver() +{ + if (isSelectionAttached()) { detachSelection(); + } auto view = qobject_cast(parentView.data()); - if(view && !savedSelections.empty()) { + if (view && !savedSelections.empty()) { try { Gui::Selection().clearSelection(); } catch (Py::Exception& e) { e.clear(); } - for(auto &sel : savedSelections) { - if(sel.getSubObject()) + for (auto& sel : savedSelections) { + if (sel.getSubObject()) { Gui::Selection().addSelection(sel.getDocumentName().c_str(), sel.getObjectName().c_str(), sel.getSubName().c_str()); + } } savedSelections.clear(); } - if(view) + if (view) { view->blockSelection(false); + } parentView = nullptr; } @@ -500,33 +557,34 @@ void DlgPropertyLink::onItemSelectionChanged() { auto newSelections = ui->treeWidget->selectedItems(); - if(newSelections.isEmpty() || selections.contains(newSelections.back())) { + if (newSelections.isEmpty() || selections.contains(newSelections.back())) { selections = newSelections; - if(newSelections.isEmpty()) + if (newSelections.isEmpty()) { currentObj = nullptr; + } return; } selections = newSelections; auto sobjs = getLinkFromItem(newSelections.back()); - App::DocumentObject *obj = !sobjs.empty()?sobjs.front().getObject():nullptr; - if(!obj) { + App::DocumentObject* obj = !sobjs.empty() ? sobjs.front().getObject() : nullptr; + if (!obj) { Gui::Selection().clearSelection(); return; } bool focus = false; // Do auto view switch if tree view does not do it - if(!TreeParams::getSyncView()) { + if (!TreeParams::getSyncView()) { focus = ui->treeWidget->hasFocus(); auto doc = Gui::Application::Instance->getDocument(sobjs.front().getDocumentName().c_str()); - if(doc) { + if (doc) { auto vp = Base::freecad_dynamic_cast( - doc->getViewProvider(obj)); - if(vp) { + doc->getViewProvider(obj)); + if (vp) { // If the view provider uses a special window for rendering, switch to it - MDIView *view = vp->getMDIView(); + MDIView* view = vp->getMDIView(); if (view) { doc->setActiveWindow(view); } @@ -541,19 +599,21 @@ void DlgPropertyLink::onItemSelectionChanged() // only keep the latest selection. bool blocked = blockSelection(true); Gui::Selection().clearSelection(); - for(auto &sobj : sobjs) + for (auto& sobj : sobjs) { Gui::Selection().addSelection(sobj.getDocumentName().c_str(), sobj.getObjectName().c_str(), sobj.getSubName().c_str()); + } blockSelection(blocked); // Enforce single parent - if(singleParent && currentObj && currentObj!=obj) { + if (singleParent && currentObj && currentObj != obj) { ui->treeWidget->blockSignals(true); const auto items = ui->treeWidget->selectedItems(); - for(auto item : items) { - if(item != selections.back()) + for (auto item : items) { + if (item != selections.back()) { item->setSelected(false); + } } auto last = selections.back(); selections.clear(); @@ -562,100 +622,113 @@ void DlgPropertyLink::onItemSelectionChanged() } currentObj = obj; - if(focus) { + if (focus) { // FIXME: does not work, why? ui->treeWidget->setFocus(); } } -QTreeWidgetItem *DlgPropertyLink::findItem( - App::DocumentObject *obj, const char *subname, bool *pfound) +QTreeWidgetItem* +DlgPropertyLink::findItem(App::DocumentObject* obj, const char* subname, bool* pfound) { - if(pfound) + if (pfound) { *pfound = false; + } - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return nullptr; + } - std::vector sobjs; - if(subname && subname[0]) { - if(!allowSubObject) { + std::vector sobjs; + if (subname && subname[0]) { + if (!allowSubObject) { obj = obj->getSubObject(subname); - if(!obj) + if (!obj) { return nullptr; - } else { + } + } + else { sobjs = obj->getSubObjectList(subname); } } auto itDoc = docItems.find(obj->getDocument()); - if(itDoc == docItems.end()) + if (itDoc == docItems.end()) { return nullptr; + } onItemExpanded(itDoc->second); auto it = itemMap.find(obj); - if(it == itemMap.end() || it->second->isHidden()) + if (it == itemMap.end() || it->second->isHidden()) { return nullptr; + } - if(!allowSubObject) { - if(pfound) + if (!allowSubObject) { + if (pfound) { *pfound = true; + } return it->second; } - QTreeWidgetItem *item = it->second; + QTreeWidgetItem* item = it->second; bool first = true; - for(auto o : sobjs) { - if(first) { + for (auto o : sobjs) { + if (first) { first = false; continue; } onItemExpanded(item); bool found = false; - for(int i=0,count=item->childCount();ichildCount(); i < count; ++i) { auto child = item->child(i); - if(strcmp(o->getNameInDocument(), - child->data(0, Qt::UserRole).toByteArray().constData())==0) - { + if (strcmp(o->getNameInDocument(), + child->data(0, Qt::UserRole).toByteArray().constData()) + == 0) { item = child; found = true; break; } } - if(!found) + if (!found) { return item; + } } - if(pfound) + if (pfound) { *pfound = true; + } return item; } void DlgPropertyLink::onSelectionChanged(const Gui::SelectionChanges& msg) { - if (msg.Type != SelectionChanges::AddSelection) + if (msg.Type != SelectionChanges::AddSelection) { return; + } bool found = false; auto selObj = msg.Object.getObject(); App::ElementNamePair elementName; - const char *subname = msg.pSubName; - if(!ui->checkSubObject->isChecked()) { - selObj = App::GeoFeature::resolveElement(selObj,subname,elementName); - if(!selObj) + const char* subname = msg.pSubName; + if (!ui->checkSubObject->isChecked()) { + selObj = App::GeoFeature::resolveElement(selObj, subname, elementName); + if (!selObj) { return; + } subname = elementName.oldName.c_str(); } auto item = findItem(selObj, msg.pSubName, &found); - if(!item) + if (!item) { return; + } - if(!item->isSelected()) { + if (!item->isSelected()) { ui->treeWidget->blockSignals(true); - if(singleSelect || (singleParent && currentObj && currentObj!=selObj)) + if (singleSelect || (singleParent && currentObj && currentObj != selObj)) { ui->treeWidget->selectionModel()->clearSelection(); + } currentObj = selObj; item->setSelected(true); selections.append(item); @@ -663,20 +736,23 @@ void DlgPropertyLink::onSelectionChanged(const Gui::SelectionChanges& msg) } ui->treeWidget->scrollToItem(item); - if(allowSubObject) { + if (allowSubObject) { QString element = QString::fromLatin1(msg.Object.getOldElementName().c_str()); - if(element.size()) { + if (element.size()) { QStringList list; QString text = item->text(1); - if(text.size()) + if (text.size()) { list = text.split(QLatin1Char(',')); - if(list.indexOf(element)<0) { + } + if (list.indexOf(element) < 0) { list << element; item->setText(1, list.join(QLatin1String(","))); subSelections.insert(item); } - } else if (subSelections.erase(item)) + } + else if (subSelections.erase(item)) { item->setText(1, QString()); + } } } @@ -685,47 +761,52 @@ void DlgPropertyLink::accept() QDialog::accept(); } -static QTreeWidgetItem *_getLinkFromItem(std::ostringstream &ss, QTreeWidgetItem *item, const char *objName) { +static QTreeWidgetItem* +_getLinkFromItem(std::ostringstream& ss, QTreeWidgetItem* item, const char* objName) +{ auto parent = item->parent(); assert(parent); QByteArray nextName = parent->data(0, Qt::UserRole).toByteArray(); - if (nextName.isEmpty()) + if (nextName.isEmpty()) { return item; + } item = _getLinkFromItem(ss, parent, nextName); ss << objName << '.'; return item; } -QList -DlgPropertyLink::getLinkFromItem(QTreeWidgetItem *item, bool needSubName) const +QList DlgPropertyLink::getLinkFromItem(QTreeWidgetItem* item, + bool needSubName) const { QList res; auto parent = item->parent(); - if(!parent) + if (!parent) { return res; + } std::ostringstream ss; - auto parentItem = _getLinkFromItem(ss, item, - item->data(0,Qt::UserRole).toByteArray().constData()); + auto parentItem = + _getLinkFromItem(ss, item, item->data(0, Qt::UserRole).toByteArray().constData()); - App::SubObjectT sobj(parentItem->data(0, Qt::UserRole+1).toByteArray().constData(), + App::SubObjectT sobj(parentItem->data(0, Qt::UserRole + 1).toByteArray().constData(), parentItem->data(0, Qt::UserRole).toByteArray().constData(), ss.str().c_str()); QString elements; - if(needSubName && allowSubObject) + if (needSubName && allowSubObject) { elements = item->text(1); + } - if(elements.isEmpty()) { + if (elements.isEmpty()) { res.append(App::SubObjectT()); res.last() = std::move(sobj); return res; } const auto split = elements.split(QLatin1Char(',')); - for(const QString &element : split) { + for (const QString& element : split) { res.append(App::SubObjectT()); res.last() = App::SubObjectT(sobj.getDocumentName().c_str(), sobj.getObjectName().c_str(), @@ -734,27 +815,33 @@ DlgPropertyLink::getLinkFromItem(QTreeWidgetItem *item, bool needSubName) const return res; } -void DlgPropertyLink::onTimer() { - auto item = ui->treeWidget->itemAt( - ui->treeWidget->viewport()->mapFromGlobal(QCursor::pos())); - if(!item) +void DlgPropertyLink::onTimer() +{ + auto item = ui->treeWidget->itemAt(ui->treeWidget->viewport()->mapFromGlobal(QCursor::pos())); + if (!item) { return; + } auto sobjs = getLinkFromItem(item); - if(sobjs.isEmpty()) + if (sobjs.isEmpty()) { return; - const auto &sobj = sobjs.front(); + } + const auto& sobj = sobjs.front(); Gui::Selection().setPreselect(sobj.getDocumentName().c_str(), sobj.getObjectName().c_str(), sobj.getSubName().c_str(), - 0, 0, 0, Gui::SelectionChanges::MsgSource::TreeView); + 0, + 0, + 0, + Gui::SelectionChanges::MsgSource::TreeView); } QList DlgPropertyLink::currentLinks() const { auto items = ui->treeWidget->selectedItems(); QList res; - for(auto item : items) + for (auto item : items) { res.append(getLinkFromItem(item)); + } return res; } @@ -763,27 +850,33 @@ QList DlgPropertyLink::originalLinks() const return oldLinks; } -QString DlgPropertyLink::linksToPython(const QList& links) { - if(links.isEmpty()) +QString DlgPropertyLink::linksToPython(const QList& links) +{ + if (links.isEmpty()) { return QLatin1String("None"); + } - if(links.size() == 1) + if (links.size() == 1) { return QString::fromLatin1(links.front().getSubObjectPython(false).c_str()); + } std::ostringstream ss; - if(isLinkSub(links)) { + if (isLinkSub(links)) { ss << '(' << links.front().getObjectPython() << ", ["; - for(const auto& link : links) { - const auto &sub = link.getSubName(); - if(!sub.empty()) + for (const auto& link : links) { + const auto& sub = link.getSubName(); + if (!sub.empty()) { ss << "u'" << Base::Tools::escapedUnicodeFromUtf8(sub.c_str()) << "',"; + } } ss << "])"; - } else { + } + else { ss << '['; - for(const auto& link : links) + for (const auto& link : links) { ss << link.getSubObjectPython(false) << ','; + } ss << ']'; } @@ -792,178 +885,210 @@ QString DlgPropertyLink::linksToPython(const QList& links) { void DlgPropertyLink::filterObjects() { - for(int i=0, count=ui->treeWidget->topLevelItemCount(); itreeWidget->topLevelItemCount(); i < count; ++i) { auto item = ui->treeWidget->topLevelItem(i); - for(int j=0, c=item->childCount(); jchildCount(); j < c; ++j) { filterItem(item->child(j)); + } } } -void DlgPropertyLink::filterItem(QTreeWidgetItem *item) { - if(filterType(item)) { +void DlgPropertyLink::filterItem(QTreeWidgetItem* item) +{ + if (filterType(item)) { item->setHidden(true); return; } item->setHidden(false); - for(int i=0, count=item->childCount(); ichildCount(); i < count; ++i) { filterItem(item->child(i)); + } } -bool DlgPropertyLink::eventFilter(QObject *obj, QEvent *e) { - if(obj == ui->searchBox - && e->type() == QEvent::KeyPress - && static_cast(e)->key() == Qt::Key_Escape) - { +bool DlgPropertyLink::eventFilter(QObject* obj, QEvent* e) +{ + if (obj == ui->searchBox && e->type() == QEvent::KeyPress + && static_cast(e)->key() == Qt::Key_Escape) { ui->searchBox->setText(QString()); return true; } - return QDialog::eventFilter(obj,e); + return QDialog::eventFilter(obj, e); } -void DlgPropertyLink::onItemSearch() { +void DlgPropertyLink::onItemSearch() +{ itemSearch(ui->searchBox->text(), true); } -void DlgPropertyLink::keyPressEvent(QKeyEvent *ev) +void DlgPropertyLink::keyPressEvent(QKeyEvent* ev) { - if(ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return) { - if(ui->searchBox->hasFocus()) + if (ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return) { + if (ui->searchBox->hasFocus()) { return; + } } QDialog::keyPressEvent(ev); } -void DlgPropertyLink::itemSearch(const QString &text, bool select) { - if(searchItem) +void DlgPropertyLink::itemSearch(const QString& text, bool select) +{ + if (searchItem) { searchItem->setBackground(0, bgBrush); + } auto owner = objProp.getObject(); - if(!owner) + if (!owner) { return; + } std::string txt(text.toUtf8().constData()); try { - if(txt.empty()) + if (txt.empty()) { return; - if(txt.find("<<") == std::string::npos) { + } + if (txt.find("<<") == std::string::npos) { auto pos = txt.find('.'); - if(pos==std::string::npos) + if (pos == std::string::npos) { txt += '.'; - else if(pos!=txt.size()-1) { - txt.insert(pos+1,"<<"); - if(txt.back()!='.') + } + else if (pos != txt.size() - 1) { + txt.insert(pos + 1, "<<"); + if (txt.back() != '.') { txt += '.'; + } txt += ">>."; } - }else if(txt.back() != '.') + } + else if (txt.back() != '.') { txt += '.'; + } txt += "_self"; - auto path = App::ObjectIdentifier::parse(owner,txt); - if(path.getPropertyName() != "_self") + auto path = App::ObjectIdentifier::parse(owner, txt); + if (path.getPropertyName() != "_self") { return; + } - App::DocumentObject *obj = path.getDocumentObject(); - if(!obj) + App::DocumentObject* obj = path.getDocumentObject(); + if (!obj) { return; + } bool found; - const char *subname = path.getSubObjectName().c_str(); - QTreeWidgetItem *item = findItem(obj, subname, &found); - if(!item) + const char* subname = path.getSubObjectName().c_str(); + QTreeWidgetItem* item = findItem(obj, subname, &found); + if (!item) { return; + } - if(select) { - if(!found) + if (select) { + if (!found) { return; + } Gui::Selection().addSelection(obj->getDocument()->getName(), - obj->getNameInDocument(),subname); - }else{ + obj->getNameInDocument(), + subname); + } + else { Selection().setPreselect(obj->getDocument()->getName(), - obj->getNameInDocument(), subname, 0, 0, 0, - Gui::SelectionChanges::MsgSource::TreeView); + obj->getNameInDocument(), + subname, + 0, + 0, + 0, + Gui::SelectionChanges::MsgSource::TreeView); searchItem = item; ui->treeWidget->scrollToItem(searchItem); bgBrush = searchItem->background(0); searchItem->setBackground(0, QColor(255, 255, 0, 100)); } - } catch(...) - { + } + catch (...) { } } -QTreeWidgetItem *DlgPropertyLink::createItem( - App::DocumentObject *obj, QTreeWidgetItem *parent) +QTreeWidgetItem* DlgPropertyLink::createItem(App::DocumentObject* obj, QTreeWidgetItem* parent) { - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return nullptr; + } - if(inList.find(obj)!=inList.end()) + if (inList.find(obj) != inList.end()) { return nullptr; + } auto vp = Base::freecad_dynamic_cast( - Application::Instance->getViewProvider(obj)); - if(!vp) + Application::Instance->getViewProvider(obj)); + if (!vp) { return nullptr; + } QTreeWidgetItem* item; - if(parent) + if (parent) { item = new QTreeWidgetItem(parent); - else + } + else { item = new QTreeWidgetItem(ui->treeWidget); + } item->setIcon(0, vp->getIcon()); item->setText(0, QString::fromUtf8((obj)->Label.getValue())); item->setData(0, Qt::UserRole, QByteArray(obj->getNameInDocument())); - item->setData(0, Qt::UserRole+1, QByteArray(obj->getDocument()->getName())); + item->setData(0, Qt::UserRole + 1, QByteArray(obj->getDocument()->getName())); - if(allowSubObject) { - item->setChildIndicatorPolicy(!obj->getLinkedObject(true)->getOutList().empty()? - QTreeWidgetItem::ShowIndicator:QTreeWidgetItem::DontShowIndicator); + if (allowSubObject) { + item->setChildIndicatorPolicy(!obj->getLinkedObject(true)->getOutList().empty() + ? QTreeWidgetItem::ShowIndicator + : QTreeWidgetItem::DontShowIndicator); item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable); } - const char *typeName = obj->getTypeId().getName(); - QByteArray typeData = QByteArray::fromRawData(typeName, strlen(typeName)+1); - item->setData(0, Qt::UserRole+2, typeData); + const char* typeName = obj->getTypeId().getName(); + QByteArray typeData = QByteArray::fromRawData(typeName, strlen(typeName) + 1); + item->setData(0, Qt::UserRole + 2, typeData); QByteArray proxyType; - auto prop = Base::freecad_dynamic_cast( - obj->getPropertyByName("Proxy")); - if(prop) { + auto prop = + Base::freecad_dynamic_cast(obj->getPropertyByName("Proxy")); + if (prop) { Base::PyGILStateLocker lock; Py::Object proxy = prop->getValue(); - if(!proxy.isNone() && !proxy.isString()) { - const char *name = nullptr; - if (proxy.hasAttr("__class__")) + if (!proxy.isNone() && !proxy.isString()) { + const char* name = nullptr; + if (proxy.hasAttr("__class__")) { proxyType = QByteArray(proxy.getAttr("__class__").as_string().c_str()); + } else { name = proxy.ptr()->ob_type->tp_name; - proxyType = QByteArray::fromRawData(name, strlen(name)+1); + proxyType = QByteArray::fromRawData(name, strlen(name) + 1); } auto it = typeItems.find(proxyType); - if(it != typeItems.end()) + if (it != typeItems.end()) { proxyType = it->first; - else if (name) + } + else if (name) { proxyType = QByteArray(name, proxyType.size()); + } } } - item->setData(0, Qt::UserRole+3, proxyType); + item->setData(0, Qt::UserRole + 3, proxyType); filterItem(item); return item; } -QTreeWidgetItem *DlgPropertyLink::createTypeItem(Base::Type type) { - if(type.isBad()) +QTreeWidgetItem* DlgPropertyLink::createTypeItem(Base::Type type) +{ + if (type.isBad()) { return nullptr; + } - QTreeWidgetItem *item = nullptr; - if(!type.isBad() && type!=App::DocumentObject::getClassTypeId()) { + QTreeWidgetItem* item = nullptr; + if (!type.isBad() && type != App::DocumentObject::getClassTypeId()) { Base::Type parentType = type.getParent(); - if(!parentType.isBad()) { - const char *name = parentType.getName(); - auto typeData = QByteArray::fromRawData(name,strlen(name)+1); - auto &typeItem = typeItems[typeData]; - if(!typeItem) { + if (!parentType.isBad()) { + const char* name = parentType.getName(); + auto typeData = QByteArray::fromRawData(name, strlen(name) + 1); + auto& typeItem = typeItems[typeData]; + if (!typeItem) { typeItem = createTypeItem(parentType); typeItem->setData(0, Qt::UserRole, typeData); } @@ -971,92 +1096,110 @@ QTreeWidgetItem *DlgPropertyLink::createTypeItem(Base::Type type) { } } - if(!item) + if (!item) { item = new QTreeWidgetItem(ui->typeTree); - else + } + else { item = new QTreeWidgetItem(item); + } item->setExpanded(true); item->setText(0, QString::fromLatin1(type.getName())); - if(type == App::DocumentObject::getClassTypeId()) + if (type == App::DocumentObject::getClassTypeId()) { item->setFlags(Qt::ItemIsEnabled); + } return item; } -bool DlgPropertyLink::filterType(QTreeWidgetItem *item) { - auto proxyType = item->data(0, Qt::UserRole+3).toByteArray(); - QTreeWidgetItem *proxyItem = nullptr; - if(proxyType.size()) { - auto &pitem = typeItems[proxyType]; - if(!pitem) { +bool DlgPropertyLink::filterType(QTreeWidgetItem* item) +{ + auto proxyType = item->data(0, Qt::UserRole + 3).toByteArray(); + QTreeWidgetItem* proxyItem = nullptr; + if (proxyType.size()) { + auto& pitem = typeItems[proxyType]; + if (!pitem) { pitem = new QTreeWidgetItem(ui->typeTree); - pitem->setText(0,QString::fromLatin1(proxyType)); - pitem->setIcon(0,item->icon(0)); - pitem->setData(0,Qt::UserRole,proxyType); + pitem->setText(0, QString::fromLatin1(proxyType)); + pitem->setIcon(0, item->icon(0)); + pitem->setData(0, Qt::UserRole, proxyType); } proxyItem = pitem; } - auto typeData = item->data(0, Qt::UserRole+2).toByteArray(); + auto typeData = item->data(0, Qt::UserRole + 2).toByteArray(); Base::Type type = Base::Type::fromName(typeData.constData()); - if(type.isBad()) + if (type.isBad()) { return false; + } - QTreeWidgetItem *&typeItem = typeItems[typeData]; - if(!typeItem) { + QTreeWidgetItem*& typeItem = typeItems[typeData]; + if (!typeItem) { typeItem = createTypeItem(type); typeItem->setData(0, Qt::UserRole, typeData); } - if(!proxyType.size()) { + if (!proxyType.size()) { QIcon icon = typeItem->icon(0); - if(icon.isNull()) + if (icon.isNull()) { typeItem->setIcon(0, item->icon(0)); + } } - if(!ui->checkObjectType->isChecked() || selectedTypes.empty()) + if (!ui->checkObjectType->isChecked() || selectedTypes.empty()) { return false; + } - if(proxyItem && selectedTypes.count(proxyType)) + if (proxyItem && selectedTypes.count(proxyType)) { return false; + } - for(auto t=type; !t.isBad() && t!=App::DocumentObject::getClassTypeId(); t=t.getParent()) { - const char *name = t.getName(); - if(selectedTypes.count(QByteArray::fromRawData(name, strlen(name)+1))) + for (auto t = type; !t.isBad() && t != App::DocumentObject::getClassTypeId(); + t = t.getParent()) { + const char* name = t.getName(); + if (selectedTypes.count(QByteArray::fromRawData(name, strlen(name) + 1))) { return false; + } } return true; } -void DlgPropertyLink::onItemExpanded(QTreeWidgetItem * item) { - if(item->childCount()) +void DlgPropertyLink::onItemExpanded(QTreeWidgetItem* item) +{ + if (item->childCount()) { return; + } - QByteArray docName = item->data(0, Qt::UserRole+1).toByteArray(); + QByteArray docName = item->data(0, Qt::UserRole + 1).toByteArray(); auto doc = App::GetApplication().getDocument(docName); - if (!doc) + if (!doc) { return; + } QByteArray objName = item->data(0, Qt::UserRole).toByteArray(); if (objName.isEmpty()) { - for(auto obj : doc->getObjects()) { - auto newItem = createItem(obj,item); - if(newItem) + for (auto obj : doc->getObjects()) { + auto newItem = createItem(obj, item); + if (newItem) { itemMap[obj] = newItem; + } } - } else if(allowSubObject) { + } + else if (allowSubObject) { auto obj = doc->getObject(objName); - if(!obj) + if (!obj) { return; + } std::set childSet; std::string sub; - for(auto child : obj->getLinkedObject(true)->getOutList()) { - if(!childSet.insert(child).second) + for (auto child : obj->getLinkedObject(true)->getOutList()) { + if (!childSet.insert(child).second) { continue; + } sub = child->getNameInDocument(); sub += "."; - if(obj->getSubObject(sub.c_str())) - createItem(child,item); + if (obj->getSubObject(sub.c_str())) { + createItem(child, item); + } } } } @@ -1067,20 +1210,23 @@ void DlgPropertyLink::onObjectTypeToggled(bool on) filterObjects(); } -void DlgPropertyLink::onTypeTreeItemSelectionChanged() { +void DlgPropertyLink::onTypeTreeItemSelectionChanged() +{ selectedTypes.clear(); const auto items = ui->typeTree->selectedItems(); - for(auto item : items) + for (auto item : items) { selectedTypes.insert(item->data(0, Qt::UserRole).toByteArray()); + } - if(ui->checkObjectType->isChecked()) + if (ui->checkObjectType->isChecked()) { filterObjects(); + } } void DlgPropertyLink::onSearchBoxTextChanged(const QString& text) { - itemSearch(text,false); + itemSearch(text, false); } #include "moc_DlgPropertyLink.cpp" diff --git a/src/Gui/DlgRunExternal.cpp b/src/Gui/DlgRunExternal.cpp index 39d831dbb8..0bcdfe6bf5 100644 --- a/src/Gui/DlgRunExternal.cpp +++ b/src/Gui/DlgRunExternal.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "DlgRunExternal.h" @@ -41,12 +41,13 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgRunExternal::DlgRunExternal( QWidget* parent, Qt::WindowFlags fl ) +DlgRunExternal::DlgRunExternal(QWidget* parent, Qt::WindowFlags fl) : QDialog(parent, fl) , process(this) , advancedHidden(true) , ui(new Ui_DlgRunExternal) { + // clang-format off ui->setupUi(this); connect(ui->chooseProgram, &QPushButton::clicked, this, &DlgRunExternal::onChooseProgramClicked); connect(&process, qOverload(&QProcess::finished), @@ -55,6 +56,7 @@ DlgRunExternal::DlgRunExternal( QWidget* parent, Qt::WindowFlags fl ) connect(ui->buttonDiscard, &QPushButton::clicked, this, &DlgRunExternal::reject); connect(ui->buttonAbort, &QPushButton::clicked, this, &DlgRunExternal::abort); connect(ui->buttonAdvanced, &QPushButton::clicked, this, &DlgRunExternal::advanced); + // clang-format on ui->gridLayout->setSizeConstraint(QLayout::SetFixedSize); ui->extensionWidget->hide(); @@ -72,36 +74,36 @@ void DlgRunExternal::addArgument(const QString& arg) int DlgRunExternal::runProcess() { - QFileInfo ifo (ProcName); + QFileInfo ifo(ProcName); ui->programName->setText(ifo.baseName()); ui->programPath->setText(ProcName); - process.start(ProcName,arguments); + process.start(ProcName, arguments); ui->buttonAccept->setEnabled(false); ui->buttonDiscard->setEnabled(false); return exec(); } -void DlgRunExternal::reject () +void DlgRunExternal::reject() { QDialog::reject(); } -void DlgRunExternal::accept () +void DlgRunExternal::accept() { QDialog::accept(); } -void DlgRunExternal::abort () +void DlgRunExternal::abort() { process.terminate(); DlgRunExternal::reject(); } -void DlgRunExternal::advanced () +void DlgRunExternal::advanced() { - if (advancedHidden){ + if (advancedHidden) { ui->extensionWidget->show(); advancedHidden = false; } @@ -111,7 +113,7 @@ void DlgRunExternal::advanced () } } -void DlgRunExternal::finished (int exitCode, QProcess::ExitStatus exitStatus) +void DlgRunExternal::finished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitCode); Q_UNUSED(exitStatus); @@ -130,4 +132,3 @@ void DlgRunExternal::onChooseProgramClicked() } #include "moc_DlgRunExternal.cpp" - diff --git a/src/Gui/DlgSettingsColorGradientImp.cpp b/src/Gui/DlgSettingsColorGradientImp.cpp index b6d817ac0d..5979f363f2 100644 --- a/src/Gui/DlgSettingsColorGradientImp.cpp +++ b/src/Gui/DlgSettingsColorGradientImp.cpp @@ -22,13 +22,13 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #endif #include "DlgSettingsColorGradientImp.h" @@ -46,10 +46,11 @@ using namespace Gui::Dialog; * name 'name' and widget flags set to 'f'. */ DlgSettingsColorGradientImp::DlgSettingsColorGradientImp(const App::ColorGradient& cg, - QWidget* parent, Qt::WindowFlags fl) - : QDialog( parent, fl ) - , validator(nullptr) - , ui(new Ui_DlgSettingsColorGradient) + QWidget* parent, + Qt::WindowFlags fl) + : QDialog(parent, fl) + , validator(nullptr) + , ui(new Ui_DlgSettingsColorGradient) { ui->setupUi(this); ui->spinBoxLabel->setRange(5, 30); @@ -67,7 +68,8 @@ DlgSettingsColorGradientImp::DlgSettingsColorGradientImp(const App::ColorGradien // assure that the LineEdit is as wide to contain numbers with 4 digits and 6 decimals QFontMetrics fm(ui->floatLineEditMax->font()); - ui->floatLineEditMax->setMinimumWidth(QtTools::horizontalAdvance(fm, QString::fromLatin1("-8000.000000"))); + ui->floatLineEditMax->setMinimumWidth( + QtTools::horizontalAdvance(fm, QString::fromLatin1("-8000.000000"))); setColorModelNames(cg.getColorModelNames()); setProfile(cg.getProfile()); @@ -81,6 +83,7 @@ DlgSettingsColorGradientImp::~DlgSettingsColorGradientImp() = default; void DlgSettingsColorGradientImp::setupConnections() { + // clang-format off auto group = new QButtonGroup(this); group->setExclusive(true); group->addButton(ui->radioButtonFlow); @@ -112,6 +115,7 @@ void DlgSettingsColorGradientImp::setupConnections() connect(ui->spinBoxDecimals, qOverload(&QSpinBox::valueChanged), this, &DlgSettingsColorGradientImp::colorModelChanged); + // clang-format on } App::ColorGradientProfile DlgSettingsColorGradientImp::getProfile() const @@ -154,16 +158,15 @@ void DlgSettingsColorGradientImp::setColorModelNames(const std::vectorradioButtonFlow->setChecked(true); - break; - case App::ColorBarStyle::ZERO_BASED: - ui->radioButtonZero->setChecked(true); - break; + switch (tStyle) { + case App::ColorBarStyle::FLOW: + ui->radioButtonFlow->setChecked(true); + break; + case App::ColorBarStyle::ZERO_BASED: + ui->radioButtonZero->setChecked(true); + break; } } @@ -173,9 +176,9 @@ App::ColorBarStyle DlgSettingsColorGradientImp::colorStyle() const : App::ColorBarStyle::FLOW; } -void DlgSettingsColorGradientImp::setOutGrayed( bool grayed ) +void DlgSettingsColorGradientImp::setOutGrayed(bool grayed) { - ui->checkBoxGrayed->setChecked( grayed ); + ui->checkBoxGrayed->setChecked(grayed); } bool DlgSettingsColorGradientImp::isOutGrayed() const @@ -183,9 +186,9 @@ bool DlgSettingsColorGradientImp::isOutGrayed() const return ui->checkBoxGrayed->isChecked(); } -void DlgSettingsColorGradientImp::setOutInvisible( bool invisible ) +void DlgSettingsColorGradientImp::setOutInvisible(bool invisible) { - ui->checkBoxInvisible->setChecked( invisible ); + ui->checkBoxInvisible->setChecked(invisible); } bool DlgSettingsColorGradientImp::isOutInvisible() const @@ -224,7 +227,7 @@ void DlgSettingsColorGradientImp::getRange(float& fMin, float& fMax) const void DlgSettingsColorGradientImp::setNumberOfLabels(int val) { - ui->spinBoxLabel->setValue( val ); + ui->spinBoxLabel->setValue(val); } int DlgSettingsColorGradientImp::numberOfLabels() const @@ -249,8 +252,9 @@ void DlgSettingsColorGradientImp::accept() double fMin = QLocale().toDouble(ui->floatLineEditMin->text()); if (fMax <= fMin) { - QMessageBox::warning(this, tr("Wrong parameter"), - tr("The maximum value must be higher than the minimum value.")); + QMessageBox::warning(this, + tr("Wrong parameter"), + tr("The maximum value must be higher than the minimum value.")); } else { QDialog::accept(); @@ -258,4 +262,3 @@ void DlgSettingsColorGradientImp::accept() } #include "moc_DlgSettingsColorGradientImp.cpp" - diff --git a/src/Gui/DlgSettingsImageImp.cpp b/src/Gui/DlgSettingsImageImp.cpp index 4d4da8b2b5..659c34f9b1 100644 --- a/src/Gui/DlgSettingsImageImp.cpp +++ b/src/Gui/DlgSettingsImageImp.cpp @@ -22,8 +22,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include "DlgSettingsImageImp.h" @@ -39,9 +39,9 @@ using namespace std; * Constructs a DlgSettingsImageImp as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ -DlgSettingsImageImp::DlgSettingsImageImp( QWidget* parent ) - : QWidget( parent ) - , ui(new Ui_DlgSettingsImage) +DlgSettingsImageImp::DlgSettingsImageImp(QWidget* parent) + : QWidget(parent) + , ui(new Ui_DlgSettingsImage) { ui->setupUi(this); setupConnections(); @@ -52,7 +52,7 @@ DlgSettingsImageImp::DlgSettingsImageImp( QWidget* parent ) _width = width(); _height = height(); - _fRatio = (float)_width/(float)_height; + _fRatio = (float)_width / (float)_height; ui->comboMethod->addItem(tr("Offscreen (New)"), QByteArray("QtOffscreenRenderer")); ui->comboMethod->addItem(tr("Offscreen (Old)"), QByteArray("CoinOffscreenRenderer")); @@ -67,6 +67,7 @@ DlgSettingsImageImp::~DlgSettingsImageImp() = default; void DlgSettingsImageImp::setupConnections() { + // clang-format off connect(ui->buttonRatioScreen, &QToolButton::clicked, this, &DlgSettingsImageImp::onButtonRatioScreenClicked); connect(ui->buttonRatio4x3, &QToolButton::clicked, @@ -79,9 +80,10 @@ void DlgSettingsImageImp::setupConnections() this, &DlgSettingsImageImp::onStandardSizeBoxActivated); connect(ui->comboMethod, qOverload(&QComboBox::activated), this, &DlgSettingsImageImp::onComboMethodActivated); + // clang-format on } -void DlgSettingsImageImp::changeEvent(QEvent *e) +void DlgSettingsImageImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -95,32 +97,32 @@ void DlgSettingsImageImp::changeEvent(QEvent *e) void DlgSettingsImageImp::setImageSize(int w, int h) { // set current screen size - ui->standardSizeBox->setItemData(0, QSize(w,h)); + ui->standardSizeBox->setItemData(0, QSize(w, h)); ui->spinWidth->setValue(w); ui->spinHeight->setValue(h); // As the image size is in pixel why shouldn't _width and _height be integers? - _width = w; + _width = w; _height = h; - _fRatio = (float)_width/(float)_height; + _fRatio = (float)_width / (float)_height; } /** * Sets the image size to \a s. */ -void DlgSettingsImageImp::setImageSize( const QSize& s ) +void DlgSettingsImageImp::setImageSize(const QSize& s) { // set current screen size ui->standardSizeBox->setItemData(0, s); - ui->spinWidth->setValue( s.width() ); - ui->spinHeight->setValue( s.height() ); + ui->spinWidth->setValue(s.width()); + ui->spinHeight->setValue(s.height()); // As the image size is in pixel why shouldn't _width and _height be integers? - _width = s.width(); + _width = s.width(); _height = s.height(); - _fRatio = (float)_width/(float)_height; + _fRatio = (float)_width / (float)_height; } /** @@ -128,7 +130,7 @@ void DlgSettingsImageImp::setImageSize( const QSize& s ) */ QSize DlgSettingsImageImp::imageSize() const { - return { ui->spinWidth->value(), ui->spinHeight->value() }; + return {ui->spinWidth->value(), ui->spinHeight->value()}; } /** @@ -148,15 +150,17 @@ int DlgSettingsImageImp::imageHeight() const } /** - * Returns the comment of the picture. If for the currently selected image format no comments are supported - * QString() is returned. + * Returns the comment of the picture. If for the currently selected image format no comments are + * supported QString() is returned. */ QString DlgSettingsImageImp::comment() const { - if ( !ui->textEditComment->isEnabled() ) + if (!ui->textEditComment->isEnabled()) { return {}; - else + } + else { return ui->textEditComment->toPlainText(); + } } int DlgSettingsImageImp::backgroundType() const @@ -169,8 +173,9 @@ int DlgSettingsImageImp::backgroundType() const */ void DlgSettingsImageImp::setBackgroundType(int t) { - if ( t < ui->comboBackground->count() ) + if (t < ui->comboBackground->count()) { ui->comboBackground->setCurrentIndex(t); + } } bool DlgSettingsImageImp::addWatermark() const @@ -180,26 +185,24 @@ bool DlgSettingsImageImp::addWatermark() const void DlgSettingsImageImp::onSelectedFilter(const QString& filter) { - bool ok = (filter.startsWith(QLatin1String("JPG")) || - filter.startsWith(QLatin1String("JPEG")) || - filter.startsWith(QLatin1String("PNG"))); - ui->buttonGroupComment->setEnabled( ok ); + bool ok = (filter.startsWith(QLatin1String("JPG")) || filter.startsWith(QLatin1String("JPEG")) + || filter.startsWith(QLatin1String("PNG"))); + ui->buttonGroupComment->setEnabled(ok); } void DlgSettingsImageImp::adjustImageSize(float fRatio) { // if width has changed then adjust height and vice versa, if both has changed then adjust width - if (_height != ui->spinHeight->value()) - { + if (_height != ui->spinHeight->value()) { _height = ui->spinHeight->value(); - _width = (int)((float)_height*fRatio); - ui->spinWidth->setValue( (int)_width ); + _width = (int)((float)_height * fRatio); + ui->spinWidth->setValue((int)_width); } - else // if( _width != spinWidth->value() ) + else // if( _width != spinWidth->value() ) { _width = ui->spinWidth->value(); - _height = (int)((float)_width/fRatio); - ui->spinHeight->setValue( (int)_height ); + _height = (int)((float)_width / fRatio); + ui->spinHeight->setValue((int)_height); } } @@ -210,12 +213,12 @@ void DlgSettingsImageImp::onButtonRatioScreenClicked() void DlgSettingsImageImp::onButtonRatio4x3Clicked() { - adjustImageSize(4.0f/3.0f); + adjustImageSize(4.0f / 3.0f); } void DlgSettingsImageImp::onButtonRatio16x9Clicked() { - adjustImageSize(16.0f/9.0f); + adjustImageSize(16.0f / 9.0f); } void DlgSettingsImageImp::onButtonRatio1x1Clicked() @@ -256,8 +259,9 @@ void DlgSettingsImageImp::onStandardSizeBoxActivated(int index) void DlgSettingsImageImp::setMethod(const QByteArray& m) { int index = ui->comboMethod->findData(m); - if (index >= 0) + if (index >= 0) { ui->comboMethod->setCurrentIndex(index); + } } QByteArray DlgSettingsImageImp::method() const diff --git a/src/Gui/DlgToolbarsImp.cpp b/src/Gui/DlgToolbarsImp.cpp index 703030d8ca..36d6e4a25d 100644 --- a/src/Gui/DlgToolbarsImp.cpp +++ b/src/Gui/DlgToolbarsImp.cpp @@ -22,12 +22,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #endif #include "DlgToolbarsImp.h" @@ -85,14 +85,16 @@ DlgCustomToolbars::DlgCustomToolbars(DlgCustomToolbars::Type t, QWidget* parent) int index = 1; ui->workbenchBox->addItem(QApplication::windowIcon(), tr("Global")); ui->workbenchBox->setItemData(0, QVariant(QString::fromLatin1("Global")), Qt::UserRole); - for (const auto & workbench : workbenches) { + for (const auto& workbench : workbenches) { QPixmap px = Application::Instance->workbenchIcon(workbench); QString mt = Application::Instance->workbenchMenuText(workbench); if (mt != QLatin1String("")) { - if (px.isNull()) + if (px.isNull()) { ui->workbenchBox->addItem(mt); - else + } + else { ui->workbenchBox->addItem(px, mt); + } ui->workbenchBox->setItemData(index, QVariant(workbench), Qt::UserRole); index++; } @@ -117,6 +119,7 @@ DlgCustomToolbars::~DlgCustomToolbars() = default; void DlgCustomToolbars::setupConnections() { + // clang-format off connect(ui->workbenchBox, qOverload(&QComboBox::activated), this, &DlgCustomToolbars::onWorkbenchBoxActivated); connect(ui->moveActionRightButton, &QPushButton::clicked, @@ -133,37 +136,31 @@ void DlgCustomToolbars::setupConnections() this, &DlgCustomToolbars::onRenameButtonClicked); connect(ui->deleteButton, &QPushButton::clicked, this, &DlgCustomToolbars::onDeleteButtonClicked); + // clang-format on } void DlgCustomToolbars::addCustomToolbar(const QString&) -{ -} +{} void DlgCustomToolbars::removeCustomToolbar(const QString&) -{ -} +{} void DlgCustomToolbars::renameCustomToolbar(const QString&, const QString&) -{ -} +{} void DlgCustomToolbars::addCustomCommand(const QString&, const QByteArray&) -{ -} +{} void DlgCustomToolbars::removeCustomCommand(const QString&, const QByteArray&) -{ -} +{} void DlgCustomToolbars::moveUpCustomCommand(const QString&, const QByteArray&) -{ -} +{} void DlgCustomToolbars::moveDownCustomCommand(const QString&, const QByteArray&) -{ -} +{} -void DlgCustomToolbars::hideEvent(QHideEvent * event) +void DlgCustomToolbars::hideEvent(QHideEvent* event) { QVariant data = ui->workbenchBox->itemData(ui->workbenchBox->currentIndex(), Qt::UserRole); QString workbench = data.toString(); @@ -173,8 +170,7 @@ void DlgCustomToolbars::hideEvent(QHideEvent * event) } void DlgCustomToolbars::onActivateCategoryBox() -{ -} +{} void DlgCustomToolbars::onWorkbenchBoxActivated(int index) { @@ -188,27 +184,30 @@ void DlgCustomToolbars::onWorkbenchBoxActivated(int index) void DlgCustomToolbars::importCustomToolbars(const QByteArray& name) { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); + ParameterGrp::handle hGrp = + App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); const char* subgroup = (type == Toolbar ? "Toolbar" : "Toolboxbar"); - if (!hGrp->HasGroup(name.constData())) + if (!hGrp->HasGroup(name.constData())) { return; + } hGrp = hGrp->GetGroup(name.constData()); - if (!hGrp->HasGroup(subgroup)) + if (!hGrp->HasGroup(subgroup)) { return; + } hGrp = hGrp->GetGroup(subgroup); std::string separator = "Separator"; - std::vector > hGrps = hGrp->GetGroups(); + std::vector> hGrps = hGrp->GetGroups(); CommandManager& rMgr = Application::Instance->commandManager(); - for (const auto & hGrp : hGrps) { + for (const auto& hGrp : hGrps) { // create a toplevel item auto toplevel = new QTreeWidgetItem(ui->toolbarTreeWidget); bool active = hGrp->GetBool("Active", true); toplevel->setCheckState(0, (active ? Qt::Checked : Qt::Unchecked)); // get the elements of the subgroups - std::vector > items = hGrp->GetASCIIMap(); - for (const auto & it2 : items) { + std::vector> items = hGrp->GetASCIIMap(); + for (const auto& it2 : items) { // since we have stored the separators to the user parameters as (key, pair) we had to // make sure to use a unique key because otherwise we cannot store more than // one. @@ -230,14 +229,17 @@ void DlgCustomToolbars::importCustomToolbars(const QByteArray& name) item->setText(0, Action::commandMenuText(pCmd)); item->setToolTip(0, Action::commandToolTip(pCmd)); item->setData(0, Qt::UserRole, QByteArray(it2.first.c_str())); - if (pCmd->getPixmap()) + if (pCmd->getPixmap()) { item->setIcon(0, BitmapFactory().iconFromTheme(pCmd->getPixmap())); + } item->setSizeHint(0, QSize(32, 32)); } else { // If corresponding module is not yet loaded do not lose the entry auto item = new QTreeWidgetItem(toplevel); - item->setText(0, tr("%1 module not loaded").arg(QString::fromStdString(it2.second))); + item->setText( + 0, + tr("%1 module not loaded").arg(QString::fromStdString(it2.second))); item->setData(0, Qt::UserRole, QByteArray(it2.first.c_str())); item->setData(0, Qt::WhatsThisPropertyRole, QByteArray(it2.second.c_str())); item->setSizeHint(0, QSize(32, 32)); @@ -249,15 +251,16 @@ void DlgCustomToolbars::importCustomToolbars(const QByteArray& name) void DlgCustomToolbars::exportCustomToolbars(const QByteArray& workbench) { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); + ParameterGrp::handle hGrp = + App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); const char* subgroup = (type == Toolbar ? "Toolbar" : "Toolboxbar"); hGrp = hGrp->GetGroup(workbench.constData())->GetGroup(subgroup); hGrp->Clear(); CommandManager& rMgr = Application::Instance->commandManager(); - for (int i=0; itoolbarTreeWidget->topLevelItemCount(); i++) { + for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i); - QString groupName = QString::fromLatin1("Custom_%1").arg(i+1); + QString groupName = QString::fromLatin1("Custom_%1").arg(i + 1); QByteArray toolbarName = toplevel->text(0).toUtf8(); ParameterGrp::handle hToolGrp = hGrp->GetGroup(groupName.toLatin1()); hToolGrp->SetASCII("Name", toolbarName.constData()); @@ -267,7 +270,7 @@ void DlgCustomToolbars::exportCustomToolbars(const QByteArray& workbench) // make sure to use a unique key because otherwise we cannot store more than // one. int suffixSeparator = 1; - for (int j=0; jchildCount(); j++) { + for (int j = 0; j < toplevel->childCount(); j++) { QTreeWidgetItem* child = toplevel->child(j); QByteArray commandName = child->data(0, Qt::UserRole).toByteArray(); if (commandName == "Separator") { @@ -295,10 +298,12 @@ void DlgCustomToolbars::onMoveActionRightButtonClicked() QTreeWidgetItem* item = ui->commandTreeWidget->currentItem(); if (item) { QTreeWidgetItem* current = ui->toolbarTreeWidget->currentItem(); - if (!current) + if (!current) { current = ui->toolbarTreeWidget->topLevelItem(0); - else if (current->parent()) + } + else if (current->parent()) { current = current->parent(); + } if (current && !current->parent()) { auto copy = new QTreeWidgetItem(current); copy->setText(0, item->text(1)); @@ -331,7 +336,7 @@ void DlgCustomToolbars::onMoveActionLeftButtonClicked() QByteArray data = item->data(0, Qt::UserRole).toByteArray(); if (data == "Separator") { int countSep = 1; - for (int i=0; ichild(i)->data(0, Qt::UserRole).toByteArray(); if (d == "Separator") { countSep++; @@ -364,7 +369,7 @@ void DlgCustomToolbars::onMoveActionUpButtonClicked() QByteArray data = item->data(0, Qt::UserRole).toByteArray(); if (data == "Separator") { int countSep = 1; - for (int i=0; ichild(i)->data(0, Qt::UserRole).toByteArray(); if (d == "Separator") { countSep++; @@ -375,7 +380,7 @@ void DlgCustomToolbars::onMoveActionUpButtonClicked() } parent->takeChild(index); - parent->insertChild(index-1, item); + parent->insertChild(index - 1, item); ui->toolbarTreeWidget->setCurrentItem(item); moveUpCustomCommand(parent->text(0), data); @@ -394,7 +399,7 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked() if (item && item->parent() && item->isSelected()) { QTreeWidgetItem* parent = item->parent(); int index = parent->indexOfChild(item); - if (index < parent->childCount()-1) { + if (index < parent->childCount() - 1) { // In case a separator should be moved we have to count the separators // which come before this one. // This is needed so that we can distinguish in moveDownCustomCommand @@ -402,7 +407,7 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked() QByteArray data = item->data(0, Qt::UserRole).toByteArray(); if (data == "Separator") { int countSep = 1; - for (int i=0; ichild(i)->data(0, Qt::UserRole).toByteArray(); if (d == "Separator") { countSep++; @@ -413,7 +418,7 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked() } parent->takeChild(index); - parent->insertChild(index+1, item); + parent->insertChild(index + 1, item); ui->toolbarTreeWidget->setCurrentItem(item); moveDownCustomCommand(parent->text(0), data); @@ -428,15 +433,24 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked() void DlgCustomToolbars::onNewButtonClicked() { bool ok; - QString text = QString::fromLatin1("Custom%1").arg(ui->toolbarTreeWidget->topLevelItemCount()+1); - text = QInputDialog::getText(this, tr("New toolbar"), tr("Toolbar name:"), QLineEdit::Normal, text, &ok, Qt::MSWindowsFixedSizeDialogHint); + QString text = + QString::fromLatin1("Custom%1").arg(ui->toolbarTreeWidget->topLevelItemCount() + 1); + text = QInputDialog::getText(this, + tr("New toolbar"), + tr("Toolbar name:"), + QLineEdit::Normal, + text, + &ok, + Qt::MSWindowsFixedSizeDialogHint); if (ok) { // Check for duplicated name - for (int i=0; itoolbarTreeWidget->topLevelItemCount(); i++) { + for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i); QString groupName = toplevel->text(0); if (groupName == text) { - QMessageBox::warning(this, tr("Duplicated name"), tr("The toolbar name '%1' is already used").arg(text)); + QMessageBox::warning(this, + tr("Duplicated name"), + tr("The toolbar name '%1' is already used").arg(text)); return; } } @@ -475,15 +489,22 @@ void DlgCustomToolbars::onRenameButtonClicked() if (item && !item->parent() && item->isSelected()) { bool ok; QString old_text = item->text(0); - QString text = QInputDialog::getText(this, tr("Rename toolbar"), tr("Toolbar name:"), - QLineEdit::Normal, old_text, &ok, Qt::MSWindowsFixedSizeDialogHint); + QString text = QInputDialog::getText(this, + tr("Rename toolbar"), + tr("Toolbar name:"), + QLineEdit::Normal, + old_text, + &ok, + Qt::MSWindowsFixedSizeDialogHint); if (ok && text != old_text) { // Check for duplicated name - for (int i=0; itoolbarTreeWidget->topLevelItemCount(); i++) { + for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i); QString groupName = toplevel->text(0); if (groupName == text && toplevel != item) { - QMessageBox::warning(this, tr("Duplicated name"), tr("The toolbar name '%1' is already used").arg(text)); + QMessageBox::warning(this, + tr("Duplicated name"), + tr("The toolbar name '%1' is already used").arg(text)); return; } } @@ -502,32 +523,30 @@ void DlgCustomToolbars::onRenameButtonClicked() } void DlgCustomToolbars::onAddMacroAction(const QByteArray&) -{ -} +{} void DlgCustomToolbars::onRemoveMacroAction(const QByteArray&) -{ -} +{} void DlgCustomToolbars::onModifyMacroAction(const QByteArray& macro) { QVariant data = ui->categoryBox->itemData(ui->categoryBox->currentIndex(), Qt::UserRole); QString group = data.toString(); - if (group == QLatin1String("Macros")) - { - CommandManager & cCmdMgr = Application::Instance->commandManager(); + if (group == QLatin1String("Macros")) { + CommandManager& cCmdMgr = Application::Instance->commandManager(); Command* pCmd = cCmdMgr.getCommandByName(macro); // the right side - for (int i=0; itoolbarTreeWidget->topLevelItemCount(); i++) { + for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i); - for (int j=0; jchildCount(); j++) { + for (int j = 0; j < toplevel->childCount(); j++) { QTreeWidgetItem* item = toplevel->child(j); QByteArray command = item->data(0, Qt::UserRole).toByteArray(); if (command == macro) { item->setText(0, Action::commandMenuText(pCmd)); item->setToolTip(0, Action::commandToolTip(pCmd)); - if (pCmd->getPixmap()) + if (pCmd->getPixmap()) { item->setIcon(0, BitmapFactory().iconFromTheme(pCmd->getPixmap())); + } } } } @@ -535,14 +554,14 @@ void DlgCustomToolbars::onModifyMacroAction(const QByteArray& macro) } } -void DlgCustomToolbars::changeEvent(QEvent *e) +void DlgCustomToolbars::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); int count = ui->categoryBox->count(); - CommandManager & cCmdMgr = Application::Instance->commandManager(); - for (int i=0; icommandManager(); + for (int i = 0; i < count; i++) { QVariant data = ui->categoryBox->itemData(i, Qt::UserRole); std::vector aCmds = cCmdMgr.getGroupCommands(data.toByteArray()); if (!aCmds.empty()) { @@ -570,10 +589,9 @@ void DlgCustomToolbars::changeEvent(QEvent *e) * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgCustomToolbarsImp::DlgCustomToolbarsImp( QWidget* parent ) +DlgCustomToolbarsImp::DlgCustomToolbarsImp(QWidget* parent) : DlgCustomToolbars(DlgCustomToolbars::Toolbar, parent) -{ -} +{} /** Destroys the object and frees any allocated resources */ DlgCustomToolbarsImp::~DlgCustomToolbarsImp() = default; @@ -594,8 +612,9 @@ void DlgCustomToolbarsImp::removeCustomToolbar(const QString& name) Workbench* w = WorkbenchManager::instance()->active(); if (w && w->name() == std::string((const char*)data.toByteArray())) { QList bars = getMainWindow()->findChildren(name); - if (bars.size() != 1) + if (bars.size() != 1) { return; + } QToolBar* tb = bars.front(); getMainWindow()->removeToolBar(tb); @@ -609,8 +628,9 @@ void DlgCustomToolbarsImp::renameCustomToolbar(const QString& old_name, const QS Workbench* w = WorkbenchManager::instance()->active(); if (w && w->name() == std::string((const char*)data.toByteArray())) { QList bars = getMainWindow()->findChildren(old_name); - if (bars.size() != 1) + if (bars.size() != 1) { return; + } QToolBar* tb = bars.front(); tb->setObjectName(new_name); @@ -621,12 +641,12 @@ void DlgCustomToolbarsImp::renameCustomToolbar(const QString& old_name, const QS QList DlgCustomToolbarsImp::getActionGroup(QAction* action) { QList group; -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QList widgets = action->associatedWidgets(); #else QList widgets = action->associatedObjects(); #endif - for (const auto & widget : widgets) { + for (const auto& widget : widgets) { auto tb = qobject_cast(widget); if (tb) { QMenu* menu = tb->menu(); @@ -642,12 +662,12 @@ QList DlgCustomToolbarsImp::getActionGroup(QAction* action) void DlgCustomToolbarsImp::setActionGroup(QAction* action, const QList& group) { // See also ActionGroup::addTo() -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QList widgets = action->associatedWidgets(); #else QList widgets = action->associatedObjects(); #endif - for (const auto & widget : widgets) { + for (const auto& widget : widgets) { auto tb = qobject_cast(widget); if (tb) { QMenu* menu = tb->menu(); @@ -668,8 +688,9 @@ void DlgCustomToolbarsImp::addCustomCommand(const QString& name, const QByteArra Workbench* w = WorkbenchManager::instance()->active(); if (w && w->name() == std::string((const char*)data.toByteArray())) { QList bars = getMainWindow()->findChildren(name); - if (bars.size() != 1) + if (bars.size() != 1) { return; + } if (cmd == "Separator") { QAction* action = bars.front()->addSeparator(); @@ -682,8 +703,9 @@ void DlgCustomToolbarsImp::addCustomCommand(const QString& name, const QByteArra // See ToolBarManager::setup(ToolBarItem* , QToolBar* ) // We have to add the user data in order to identify the command in // removeCustomCommand(), moveUpCustomCommand() or moveDownCustomCommand() - if (action && action->data().isNull()) + if (action && action->data().isNull()) { action->setData(cmd); + } } } } @@ -695,8 +717,9 @@ void DlgCustomToolbarsImp::removeCustomCommand(const QString& name, const QByteA Workbench* w = WorkbenchManager::instance()->active(); if (w && w->name() == std::string((const char*)data.toByteArray())) { QList bars = getMainWindow()->findChildren(name); - if (bars.size() != 1) + if (bars.size() != 1) { return; + } QByteArray cmd = userdata; int numSep = 0, indexSep = 0; @@ -705,12 +728,13 @@ void DlgCustomToolbarsImp::removeCustomCommand(const QString& name, const QByteA cmd = "Separator"; } QList actions = bars.front()->actions(); - for (const auto & action : actions) { + for (const auto& action : actions) { if (action->data().toByteArray() == cmd) { // if we move a separator then make sure to pick up the right one if (numSep > 0) { - if (++indexSep < numSep) + if (++indexSep < numSep) { continue; + } } bars.front()->removeAction(action); break; @@ -725,8 +749,9 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA Workbench* w = WorkbenchManager::instance()->active(); if (w && w->name() == std::string((const char*)data.toByteArray())) { QList bars = getMainWindow()->findChildren(name); - if (bars.size() != 1) + if (bars.size() != 1) { return; + } QByteArray cmd = userdata; int numSep = 0, indexSep = 0; @@ -735,8 +760,8 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA cmd = "Separator"; } QList actions = bars.front()->actions(); - QAction* before=nullptr; - for (const auto & action : actions) { + QAction* before = nullptr; + for (const auto& action : actions) { if (action->data().toByteArray() == cmd) { // if we move a separator then make sure to pick up the right one if (numSep > 0) { @@ -749,8 +774,9 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA QList group = getActionGroup(action); bars.front()->removeAction(action); bars.front()->insertAction(before, action); - if (!group.isEmpty()) + if (!group.isEmpty()) { setActionGroup(action, group); + } break; } } @@ -766,8 +792,9 @@ void DlgCustomToolbarsImp::moveDownCustomCommand(const QString& name, const QByt Workbench* w = WorkbenchManager::instance()->active(); if (w && w->name() == std::string((const char*)data.toByteArray())) { QList bars = getMainWindow()->findChildren(name); - if (bars.size() != 1) + if (bars.size() != 1) { return; + } QByteArray cmd = userdata; int numSep = 0, indexSep = 0; @@ -780,28 +807,32 @@ void DlgCustomToolbarsImp::moveDownCustomCommand(const QString& name, const QByt if ((*it)->data().toByteArray() == cmd) { // if we move a separator then make sure to pick up the right one if (numSep > 0) { - if (++indexSep < numSep) + if (++indexSep < numSep) { continue; + } } QAction* act = *it; - if (*it == actions.back()) - break; // we're already on the last element + if (*it == actions.back()) { + break; // we're already on the last element + } ++it; // second last item if (*it == actions.back()) { QList group = getActionGroup(act); bars.front()->removeAction(act); bars.front()->addAction(act); - if (!group.isEmpty()) + if (!group.isEmpty()) { setActionGroup(act, group); + } break; } ++it; QList group = getActionGroup(act); bars.front()->removeAction(act); bars.front()->insertAction(*it, act); - if (!group.isEmpty()) + if (!group.isEmpty()) { setActionGroup(act, group); + } break; } } @@ -819,7 +850,7 @@ void DlgCustomToolbarsImp::showEvent(QShowEvent* event) } } -void DlgCustomToolbarsImp::changeEvent(QEvent *e) +void DlgCustomToolbarsImp::changeEvent(QEvent* e) { DlgCustomToolbars::changeEvent(e); } @@ -834,19 +865,19 @@ void DlgCustomToolbarsImp::changeEvent(QEvent *e) * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgCustomToolBoxbarsImp::DlgCustomToolBoxbarsImp( QWidget* parent ) +DlgCustomToolBoxbarsImp::DlgCustomToolBoxbarsImp(QWidget* parent) : DlgCustomToolbars(DlgCustomToolbars::Toolboxbar, parent) { - setWindowTitle( tr( "Toolbox bars" ) ); + setWindowTitle(tr("Toolbox bars")); } /** Destroys the object and frees any allocated resources */ DlgCustomToolBoxbarsImp::~DlgCustomToolBoxbarsImp() = default; -void DlgCustomToolBoxbarsImp::changeEvent(QEvent *e) +void DlgCustomToolBoxbarsImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { - setWindowTitle( tr( "Toolbox bars" ) ); + setWindowTitle(tr("Toolbox bars")); } DlgCustomToolbars::changeEvent(e); } diff --git a/src/Gui/DlgUnitsCalculatorImp.cpp b/src/Gui/DlgUnitsCalculatorImp.cpp index ad36fa1ab6..0718370ac2 100644 --- a/src/Gui/DlgUnitsCalculatorImp.cpp +++ b/src/Gui/DlgUnitsCalculatorImp.cpp @@ -23,9 +23,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include "DlgUnitsCalculatorImp.h" @@ -43,8 +43,9 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WindowFlags fl ) - : QDialog(parent, fl), ui(new Ui_DlgUnitCalculator) +DlgUnitsCalculator::DlgUnitsCalculator(QWidget* parent, Qt::WindowFlags fl) + : QDialog(parent, fl) + , ui(new Ui_DlgUnitCalculator) { // create widgets ui->setupUi(this); @@ -52,11 +53,12 @@ DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WindowFlags fl ) ui->comboBoxScheme->addItem(QString::fromLatin1("Preference system"), static_cast(-1)); int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - for (int i=0; i(i)); ui->comboBoxScheme->addItem(item, i); } + // clang-format off connect(ui->unitsBox, qOverload(&QComboBox::activated), this, &DlgUnitsCalculator::onUnitsBoxActivated); connect(ui->comboBoxScheme, qOverload(&QComboBox::activated), @@ -67,63 +69,41 @@ DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WindowFlags fl ) this, &DlgUnitsCalculator::valueChanged); connect(ui->ValueInput, &InputField::returnPressed, this, &DlgUnitsCalculator::returnPressed); - connect(ui->ValueInput, &InputField::parseError, this, &DlgUnitsCalculator::parseError); - connect(ui->UnitInput, &QLineEdit::textChanged, this, &DlgUnitsCalculator::textChanged); - connect(ui->UnitInput, &QLineEdit::returnPressed, this, &DlgUnitsCalculator::returnPressed); - connect(ui->pushButton_Close, &QPushButton::clicked, this, &DlgUnitsCalculator::accept); - connect(ui->pushButton_Copy, &QPushButton::clicked, this, &DlgUnitsCalculator::copy); + connect(ui->ValueInput, &InputField::parseError, + this, &DlgUnitsCalculator::parseError); + connect(ui->UnitInput, &QLineEdit::textChanged, + this, &DlgUnitsCalculator::textChanged); + connect(ui->UnitInput, &QLineEdit::returnPressed, + this, &DlgUnitsCalculator::returnPressed); + connect(ui->pushButton_Close, &QPushButton::clicked, + this, &DlgUnitsCalculator::accept); + connect(ui->pushButton_Copy, &QPushButton::clicked, + this, &DlgUnitsCalculator::copy); + // clang-format on ui->ValueInput->setParamGrpPath(QByteArray("User parameter:BaseApp/History/UnitsCalculator")); // set a default that also illustrates how the dialog works ui->ValueInput->setText(QString::fromLatin1("1 cm")); ui->UnitInput->setText(QString::fromLatin1("in")); - units << Base::Unit::Acceleration - << Base::Unit::AmountOfSubstance - << Base::Unit::Angle - << Base::Unit::Area - << Base::Unit::Density - << Base::Unit::CurrentDensity - << Base::Unit::DissipationRate - << Base::Unit::DynamicViscosity - << Base::Unit::ElectricalCapacitance - << Base::Unit::ElectricalInductance - << Base::Unit::ElectricalConductance - << Base::Unit::ElectricalResistance - << Base::Unit::ElectricalConductivity - << Base::Unit::ElectricCharge - << Base::Unit::ElectricCurrent - << Base::Unit::ElectricPotential - << Base::Unit::Force - << Base::Unit::Frequency - << Base::Unit::HeatFlux - << Base::Unit::InverseArea - << Base::Unit::InverseLength - << Base::Unit::InverseVolume - << Base::Unit::KinematicViscosity - << Base::Unit::Length - << Base::Unit::LuminousIntensity - << Base::Unit::Mass - << Base::Unit::MagneticFieldStrength - << Base::Unit::MagneticFlux - << Base::Unit::MagneticFluxDensity - << Base::Unit::Magnetization - << Base::Unit::Power - << Base::Unit::Pressure - << Base::Unit::SpecificEnergy - << Base::Unit::SpecificHeat - << Base::Unit::Stiffness - << Base::Unit::Temperature - << Base::Unit::ThermalConductivity - << Base::Unit::ThermalExpansionCoefficient - << Base::Unit::ThermalTransferCoefficient - << Base::Unit::TimeSpan - << Base::Unit::VacuumPermittivity - << Base::Unit::Velocity - << Base::Unit::Volume - << Base::Unit::VolumeFlowRate - << Base::Unit::VolumetricThermalExpansionCoefficient - << Base::Unit::Work; + units << Base::Unit::Acceleration << Base::Unit::AmountOfSubstance << Base::Unit::Angle + << Base::Unit::Area << Base::Unit::Density << Base::Unit::CurrentDensity + << Base::Unit::DissipationRate << Base::Unit::DynamicViscosity + << Base::Unit::ElectricalCapacitance << Base::Unit::ElectricalInductance + << Base::Unit::ElectricalConductance << Base::Unit::ElectricalResistance + << Base::Unit::ElectricalConductivity << Base::Unit::ElectricCharge + << Base::Unit::ElectricCurrent << Base::Unit::ElectricPotential << Base::Unit::Force + << Base::Unit::Frequency << Base::Unit::HeatFlux << Base::Unit::InverseArea + << Base::Unit::InverseLength << Base::Unit::InverseVolume + << Base::Unit::KinematicViscosity << Base::Unit::Length << Base::Unit::LuminousIntensity + << Base::Unit::Mass << Base::Unit::MagneticFieldStrength << Base::Unit::MagneticFlux + << Base::Unit::MagneticFluxDensity << Base::Unit::Magnetization << Base::Unit::Power + << Base::Unit::Pressure << Base::Unit::SpecificEnergy << Base::Unit::SpecificHeat + << Base::Unit::Stiffness << Base::Unit::Temperature << Base::Unit::ThermalConductivity + << Base::Unit::ThermalExpansionCoefficient << Base::Unit::ThermalTransferCoefficient + << Base::Unit::TimeSpan << Base::Unit::VacuumPermittivity << Base::Unit::Velocity + << Base::Unit::Volume << Base::Unit::VolumeFlowRate + << Base::Unit::VolumetricThermalExpansionCoefficient << Base::Unit::Work; for (const Base::Unit& it : units) { ui->unitsBox->addItem(it.getTypeString()); } @@ -157,28 +137,34 @@ void DlgUnitsCalculator::valueChanged(const Base::Quantity& quant) // first check the unit, if it is invalid, getTypeString() outputs an empty string // explicitly check for "ee" like in "eeV" because this would trigger an exception in Base::Unit // since it expects then a scientific notation number like "1e3" - if ( (ui->UnitInput->text().mid(0, 2) == QString::fromLatin1("ee")) || - Base::Unit(ui->UnitInput->text()).getTypeString().isEmpty()) { - ui->ValueOutput->setText(QString::fromLatin1("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text())); + if ((ui->UnitInput->text().mid(0, 2) == QString::fromLatin1("ee")) + || Base::Unit(ui->UnitInput->text()).getTypeString().isEmpty()) { + ui->ValueOutput->setText( + QString::fromLatin1("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text())); ui->pushButton_Copy->setEnabled(false); - } else { // the unit is valid + } + else { // the unit is valid // we can only convert units of the same type, thus check if (Base::Unit(ui->UnitInput->text()).getTypeString() != quant.getUnit().getTypeString()) { ui->ValueOutput->setText(tr("unit mismatch")); ui->pushButton_Copy->setEnabled(false); - } else { // the unit is valid and has the same type - double convertValue = Base::Quantity::parse(QString::fromLatin1("1") + ui->UnitInput->text()).getValue(); + } + else { // the unit is valid and has the same type + double convertValue = + Base::Quantity::parse(QString::fromLatin1("1") + ui->UnitInput->text()).getValue(); // we got now e.g. for "1 in" the value '25.4' because 1 in = 25.4 mm - // the result is now just quant / convertValue because the input is always in a base unit - // (an input of "1 cm" will immediately be converted to "10 mm" by Gui::InputField of the dialog) + // the result is now just quant / convertValue because the input is always in a base + // unit (an input of "1 cm" will immediately be converted to "10 mm" by Gui::InputField + // of the dialog) double value = quant.getValue() / convertValue; // determine how many decimals we will need to avoid an output like "0.00" - // at first use scientific notation, if there is no "e", we can round it to the user-defined decimals, - // but the user-defined decimals might be too low for cases like "10 um" in "in", - // thus only if value > 0.005 because FC's default are 2 decimals + // at first use scientific notation, if there is no "e", we can round it to the + // user-defined decimals, but the user-defined decimals might be too low for cases like + // "10 um" in "in", thus only if value > 0.005 because FC's default are 2 decimals QString val = QLocale().toString(value, 'g'); - if (!val.contains(QChar::fromLatin1('e')) && (value > 0.005)) + if (!val.contains(QChar::fromLatin1('e')) && (value > 0.005)) { val = QLocale().toString(value, 'f', Base::UnitsApi::getDecimals()); + } // create the output string QString out = QString::fromLatin1("%1 %2").arg(val, ui->UnitInput->text()); ui->ValueOutput->setText(out); @@ -197,14 +183,15 @@ void DlgUnitsCalculator::parseError(const QString& errorText) void DlgUnitsCalculator::copy() { - QClipboard *cb = QApplication::clipboard(); + QClipboard* cb = QApplication::clipboard(); cb->setText(ui->ValueOutput->text()); } void DlgUnitsCalculator::returnPressed() { if (ui->pushButton_Copy->isEnabled()) { - ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ") + ui->ValueOutput->text()); + ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ") + + ui->ValueOutput->text()); ui->ValueInput->pushToHistory(); } } @@ -219,16 +206,18 @@ void DlgUnitsCalculator::onUnitsBoxActivated(int index) Base::Unit unit = units[index]; int32_t len = unit.getSignature().Length; - ui->quantitySpinBox->setValue(Base::Quantity(value * std::pow(10.0, 3*(len-old)), unit)); + ui->quantitySpinBox->setValue(Base::Quantity(value * std::pow(10.0, 3 * (len - old)), unit)); } void DlgUnitsCalculator::onComboBoxSchemeActivated(int index) { int item = ui->comboBoxScheme->itemData(index).toInt(); - if (item > 0) + if (item > 0) { ui->quantitySpinBox->setSchema(static_cast(item)); - else + } + else { ui->quantitySpinBox->clearSchema(); + } } void DlgUnitsCalculator::onSpinBoxDecimalsValueChanged(int value) diff --git a/src/Gui/DownloadItem.cpp b/src/Gui/DownloadItem.cpp index 486c7972e8..8831de1868 100644 --- a/src/Gui/DownloadItem.cpp +++ b/src/Gui/DownloadItem.cpp @@ -53,47 +53,49 @@ using namespace Gui::Dialog; -EditTableView::EditTableView(QWidget *parent) +EditTableView::EditTableView(QWidget* parent) : QTableView(parent) -{ -} +{} -void EditTableView::keyPressEvent(QKeyEvent *event) +void EditTableView::keyPressEvent(QKeyEvent* event) { - if ((event->matches(QKeySequence::Delete) - || event->matches(QKeySequence::Backspace)) + if ((event->matches(QKeySequence::Delete) || event->matches(QKeySequence::Backspace)) && model()) { removeOne(); - } else { + } + else { QAbstractItemView::keyPressEvent(event); } } void EditTableView::removeOne() { - if (!model() || !selectionModel()) + if (!model() || !selectionModel()) { return; + } int row = currentIndex().row(); model()->removeRow(row, rootIndex()); QModelIndex idx = model()->index(row, 0, rootIndex()); - if (!idx.isValid()) + if (!idx.isValid()) { idx = model()->index(row - 1, 0, rootIndex()); + } selectionModel()->select(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } void EditTableView::removeAll() { - if (model()) + if (model()) { model()->removeRows(0, model()->rowCount(rootIndex()), rootIndex()); + } } // ---------------------------------------------------------------------------- -SqueezeLabel::SqueezeLabel(QWidget *parent) : QLabel(parent) -{ -} +SqueezeLabel::SqueezeLabel(QWidget* parent) + : QLabel(parent) +{} -void SqueezeLabel::paintEvent(QPaintEvent *event) +void SqueezeLabel::paintEvent(QPaintEvent* event) { QFontMetrics fm = fontMetrics(); if (Gui::QtTools::horizontalAdvance(fm, text()) > contentsRect().width()) { @@ -102,52 +104,59 @@ void SqueezeLabel::paintEvent(QPaintEvent *event) setText(elided); QLabel::paintEvent(event); setText(oldText); - } else { + } + else { QLabel::paintEvent(event); } } // ---------------------------------------------------------------------------- -#define AUTOSAVE_IN 1000 * 3 // seconds -#define MAXWAIT 1000 * 15 // seconds +#define AUTOSAVE_IN 1000 * 3 // seconds +#define MAXWAIT 1000 * 15 // seconds -AutoSaver::AutoSaver(QObject *parent) : QObject(parent) +AutoSaver::AutoSaver(QObject* parent) + : QObject(parent) { Q_ASSERT(parent); } AutoSaver::~AutoSaver() { - if (m_timer.isActive()) + if (m_timer.isActive()) { qWarning() << "AutoSaver: still active when destroyed, changes not saved."; + } } void AutoSaver::changeOccurred() { - if (!m_firstChange.isValid()) + if (!m_firstChange.isValid()) { m_firstChange.start(); + } if (m_firstChange.elapsed() > MAXWAIT) { saveIfNecessary(); - } else { + } + else { m_timer.start(AUTOSAVE_IN, this); } } -void AutoSaver::timerEvent(QTimerEvent *event) +void AutoSaver::timerEvent(QTimerEvent* event) { if (event->timerId() == m_timer.timerId()) { saveIfNecessary(); - } else { + } + else { QObject::timerEvent(event); } } void AutoSaver::saveIfNecessary() { - if (!m_timer.isActive()) + if (!m_timer.isActive()) { return; + } m_timer.stop(); m_firstChange = QElapsedTimer(); if (!QMetaObject::invokeMethod(parent(), "save", Qt::DirectConnection)) { @@ -157,13 +166,17 @@ void AutoSaver::saveIfNecessary() // ---------------------------------------------------------------------------- -NetworkAccessManager::NetworkAccessManager(QObject *parent) +NetworkAccessManager::NetworkAccessManager(QObject* parent) : QNetworkAccessManager(parent) { - connect(this, &QNetworkAccessManager::authenticationRequired, - this, &NetworkAccessManager::authenticationRequired); - connect(this, &QNetworkAccessManager::proxyAuthenticationRequired, - this, &NetworkAccessManager::proxyAuthenticationRequired); + connect(this, + &QNetworkAccessManager::authenticationRequired, + this, + &NetworkAccessManager::authenticationRequired); + connect(this, + &QNetworkAccessManager::proxyAuthenticationRequired, + this, + &NetworkAccessManager::proxyAuthenticationRequired); auto diskCache = new QNetworkDiskCache(this); QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); @@ -171,9 +184,9 @@ NetworkAccessManager::NetworkAccessManager(QObject *parent) setCache(diskCache); } -void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthenticator *auth) +void NetworkAccessManager::authenticationRequired(QNetworkReply* reply, QAuthenticator* auth) { - QWidget *mainWindow = Gui::getMainWindow(); + QWidget* mainWindow = Gui::getMainWindow(); QDialog dialog(mainWindow); dialog.setWindowFlags(Qt::Sheet); @@ -183,7 +196,8 @@ void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthent dialog.adjustSize(); QString introMessage = tr("Enter username and password for \"%1\" at %2"); - introMessage = introMessage.arg(QString(reply->url().toString()).toHtmlEscaped(), QString(reply->url().toString()).toHtmlEscaped()); + introMessage = introMessage.arg(QString(reply->url().toString()).toHtmlEscaped(), + QString(reply->url().toString()).toHtmlEscaped()); passwordDialog.siteDescription->setText(introMessage); passwordDialog.siteDescription->setWordWrap(true); @@ -193,9 +207,10 @@ void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthent } } -void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *auth) +void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy& proxy, + QAuthenticator* auth) { - QWidget *mainWindow = Gui::getMainWindow(); + QWidget* mainWindow = Gui::getMainWindow(); QDialog dialog(mainWindow); dialog.setWindowFlags(Qt::Sheet); @@ -217,7 +232,7 @@ void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy &prox // ---------------------------------------------------------------------------- -DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget *parent) +DownloadItem::DownloadItem(QNetworkReply* reply, bool requestFileName, QWidget* parent) : QWidget(parent) , m_reply(reply) , m_requestFileName(requestFileName) @@ -238,6 +253,7 @@ DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget * void DownloadItem::init() { + // clang-format off if (!m_reply) return; @@ -266,6 +282,7 @@ void DownloadItem::init() error(m_reply->error()); finished(); } + // clang-format on } QString DownloadItem::getDownloadDirectory() const @@ -273,8 +290,11 @@ QString DownloadItem::getDownloadDirectory() const QString exe = QString::fromStdString(App::Application::getExecutableName()); QString path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); QString dirPath = QDir(path).filePath(exe); - Base::Reference hPath = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences")->GetGroup("General"); + Base::Reference hPath = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("General"); std::string dir = hPath->GetASCII("DownloadPath", ""); if (!dir.empty()) { dirPath = QString::fromUtf8(dir.c_str()); @@ -292,11 +312,14 @@ void DownloadItem::getFileName() { QSettings settings; settings.beginGroup(QLatin1String("downloadmanager")); - //QString defaultLocation = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation); + // QString defaultLocation = + // QDesktopServices::storageLocation(QDesktopServices::DesktopLocation); QString defaultLocation = getDownloadDirectory(); - QString downloadDirectory = settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString(); - if (!downloadDirectory.isEmpty()) + QString downloadDirectory = + settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString(); + if (!downloadDirectory.isEmpty()) { downloadDirectory += QLatin1Char('/'); + } QString defaultFileName = saveFileName(downloadDirectory); QString fileName = defaultFileName; @@ -304,23 +327,26 @@ void DownloadItem::getFileName() fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName); if (fileName.isEmpty()) { m_reply->close(); - fileNameLabel->setText(tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName())); + fileNameLabel->setText( + tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName())); return; } } m_output.setFileName(fileName); fileNameLabel->setText(QFileInfo(m_output.fileName()).fileName()); fileNameLabel->setToolTip(m_output.fileName()); - if (m_requestFileName) + if (m_requestFileName) { downloadReadyRead(); + } } -QString DownloadItem::saveFileName(const QString &directory) const +QString DownloadItem::saveFileName(const QString& directory) const { // Move this function into QNetworkReply to also get file name sent from the server QString path = m_url.path(); - if (!m_fileName.isEmpty()) + if (!m_fileName.isEmpty()) { path = m_fileName; + } QFileInfo info(path); QString baseName = info.completeBaseName(); QString endName = info.suffix(); @@ -334,7 +360,8 @@ QString DownloadItem::saveFileName(const QString &directory) const // already exists, don't overwrite int i = 1; do { - name = directory + baseName + QLatin1Char('-') + QString::number(i++) + QLatin1Char('.') + endName; + name = directory + baseName + QLatin1Char('-') + QString::number(i++) + QLatin1Char('.') + + endName; } while (QFile::exists(name)); } return name; @@ -366,7 +393,8 @@ void DownloadItem::open() if (doc) { for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) { Gui::Application::Instance->importFrom(it.key().toUtf8(), - doc->getDocument()->getName(), it.value().toLatin1()); + doc->getDocument()->getName(), + it.value().toLatin1()); } } else { @@ -390,8 +418,9 @@ void DownloadItem::openFolder() void DownloadItem::tryAgain() { - if (!tryAgainButton->isEnabled()) + if (!tryAgainButton->isEnabled()) { return; + } tryAgainButton->setEnabled(false); tryAgainButton->setVisible(false); @@ -399,17 +428,20 @@ void DownloadItem::tryAgain() stopButton->setVisible(true); progressBar->setVisible(true); - QNetworkReply *r = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(m_url)); - if (m_reply) + QNetworkReply* r = + DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(m_url)); + if (m_reply) { m_reply->deleteLater(); - if (m_output.exists()) + } + if (m_output.exists()) { m_output.remove(); + } m_reply = r; init(); Q_EMIT statusChanged(); } -void DownloadItem::contextMenuEvent (QContextMenuEvent * e) +void DownloadItem::contextMenuEvent(QContextMenuEvent* e) { QMenu menu; QAction* a = menu.addAction(tr("Open containing folder"), this, &DownloadItem::openFolder); @@ -419,15 +451,17 @@ void DownloadItem::contextMenuEvent (QContextMenuEvent * e) void DownloadItem::downloadReadyRead() { - if (m_requestFileName && m_output.fileName().isEmpty()) + if (m_requestFileName && m_output.fileName().isEmpty()) { return; + } if (!m_output.isOpen()) { // in case someone else has already put a file there - if (!m_requestFileName) + if (!m_requestFileName) { getFileName(); + } if (!m_output.open(QIODevice::WriteOnly)) { - downloadInfoLabel->setText(tr("Error opening saved file: %1") - .arg(m_output.errorString())); + downloadInfoLabel->setText( + tr("Error opening saved file: %1").arg(m_output.errorString())); stopButton->click(); Q_EMIT statusChanged(); return; @@ -436,8 +470,7 @@ void DownloadItem::downloadReadyRead() Q_EMIT statusChanged(); } if (-1 == m_output.write(m_reply->readAll())) { - downloadInfoLabel->setText(tr("Error saving: %1") - .arg(m_output.errorString())); + downloadInfoLabel->setText(tr("Error saving: %1").arg(m_output.errorString())); stopButton->click(); } } @@ -457,26 +490,32 @@ void DownloadItem::metaDataChanged() QByteArray header = m_reply->rawHeader(QByteArray("Content-Disposition")); int index = header.indexOf("filename="); if (index >= 0) { - header = header.mid(index+9); - if (header.startsWith("\"") || header.startsWith("'")) + header = header.mid(index + 9); + if (header.startsWith("\"") || header.startsWith("'")) { header = header.mid(1); - if ((index = header.lastIndexOf("\"")) > 0) + } + if ((index = header.lastIndexOf("\"")) > 0) { header = header.left(index); - else if ((index = header.lastIndexOf("'")) > 0) + } + else if ((index = header.lastIndexOf("'")) > 0) { header = header.left(index); + } m_fileName = QUrl::fromPercentEncoding(header); } // Sometimes "filename=" and "filename*=UTF-8''" is set. // So, search for this too. index = header.indexOf("filename*=UTF-8''"); if (index >= 0) { - header = header.mid(index+17); - if (header.startsWith("\"") || header.startsWith("'")) + header = header.mid(index + 17); + if (header.startsWith("\"") || header.startsWith("'")) { header = header.mid(1); - if ((index = header.lastIndexOf("\"")) > 0) + } + if ((index = header.lastIndexOf("\"")) > 0) { header = header.left(index); - else if ((index = header.lastIndexOf("'")) > 0) + } + else if ((index = header.lastIndexOf("'")) > 0) { header = header.left(index); + } m_fileName = QUrl::fromPercentEncoding(header); } } @@ -497,18 +536,28 @@ void DownloadItem::metaDataChanged() url = redirectUrl; disconnect(m_reply, &QNetworkReply::readyRead, this, &DownloadItem::downloadReadyRead); -#if QT_VERSION < QT_VERSION_CHECK(5,15,0) - disconnect(m_reply, qOverload(&QNetworkReply::error), this, &DownloadItem::error); +#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) + disconnect(m_reply, + qOverload(&QNetworkReply::error), + this, + &DownloadItem::error); #else disconnect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error); #endif - disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress); - disconnect(m_reply, &QNetworkReply::metaDataChanged, this, &DownloadItem::metaDataChanged); + disconnect(m_reply, + &QNetworkReply::downloadProgress, + this, + &DownloadItem::downloadProgress); + disconnect(m_reply, + &QNetworkReply::metaDataChanged, + this, + &DownloadItem::metaDataChanged); disconnect(m_reply, &QNetworkReply::finished, this, &DownloadItem::finished); m_reply->close(); m_reply->deleteLater(); - m_reply = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url)); + m_reply = + DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url)); init(); } } @@ -520,7 +569,8 @@ void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) if (bytesTotal == -1) { progressBar->setValue(0); progressBar->setMaximum(0); - } else { + } + else { progressBar->setValue(bytesReceived); progressBar->setMaximum(bytesTotal); } @@ -543,28 +593,30 @@ void DownloadItem::updateInfoLabel() timeRemaining = floor(timeRemaining); // When downloading the eta should never be 0 - if (timeRemaining == 0) + if (timeRemaining == 0) { timeRemaining = 1; + } QString info; if (running) { QString remaining; - if (bytesTotal != 0) - remaining = tr("- %4 %5 remaining") - .arg(timeRemaining) - .arg(timeRemainingString); + if (bytesTotal != 0) { + remaining = tr("- %4 %5 remaining").arg(timeRemaining).arg(timeRemainingString); + } info = QString(tr("%1 of %2 (%3/sec) %4")) - .arg(dataString(m_bytesReceived), - bytesTotal == 0 ? tr("?") : dataString(bytesTotal), - dataString((int)speed), - remaining); - } else { - if (m_bytesReceived == bytesTotal) + .arg(dataString(m_bytesReceived), + bytesTotal == 0 ? tr("?") : dataString(bytesTotal), + dataString((int)speed), + remaining); + } + else { + if (m_bytesReceived == bytesTotal) { info = dataString(m_output.size()); - else - info = tr("%1 of %2 - Stopped") - .arg(dataString(m_bytesReceived), - dataString(bytesTotal)); + } + else { + info = + tr("%1 of %2 - Stopped").arg(dataString(m_bytesReceived), dataString(bytesTotal)); + } } downloadInfoLabel->setText(info); } @@ -574,11 +626,13 @@ QString DownloadItem::dataString(int size) const QString unit; if (size < 1024) { unit = tr("bytes"); - } else if (size < 1024*1024) { + } + else if (size < 1024 * 1024) { size /= 1024; unit = tr("kB"); - } else { - size /= 1024*1024; + } + else { + size /= 1024 * 1024; unit = tr("MB"); } return QString(QLatin1String("%1 %2")).arg(size).arg(unit); diff --git a/src/Gui/EditorView.cpp b/src/Gui/EditorView.cpp index 409d137aab..0f7e94fb67 100644 --- a/src/Gui/EditorView.cpp +++ b/src/Gui/EditorView.cpp @@ -23,25 +23,25 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# 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 #endif #include "EditorView.h" @@ -59,21 +59,23 @@ using namespace Gui; -namespace Gui { -class EditorViewP { +namespace Gui +{ +class EditorViewP +{ public: TextEdit* textEdit; SearchBar* searchBar; QString fileName; EditorView::DisplayName displayName; - QTimer* activityTimer; + QTimer* activityTimer; qint64 timeStamp; bool lock; bool aboutToClose; QStringList undos; QStringList redos; }; -} +} // namespace Gui // ------------------------------------------------------- @@ -87,7 +89,7 @@ TYPESYSTEM_SOURCE_ABSTRACT(Gui::EditorView, Gui::MDIView) */ EditorView::EditorView(TextEdit* editor, QWidget* parent) : MDIView(nullptr, parent, Qt::WindowFlags()) - , WindowParameter( "Editor" ) + , WindowParameter("Editor") { d = new EditorViewP; d->lock = false; @@ -101,6 +103,7 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent) d->searchBar = new SearchBar(); d->searchBar->setEditor(editor); + // clang-format off // update editor actions on request Gui::MainWindow* mw = Gui::getMainWindow(); connect(editor, &QPlainTextEdit::undoAvailable, mw, &MainWindow::updateEditorActions); @@ -110,6 +113,7 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent) connect(editor, &TextEdit::showSearchBar, d->searchBar, &SearchBar::activate); connect(editor, &TextEdit::findNext, d->searchBar, &SearchBar::findNext); connect(editor, &TextEdit::findPrevious, d->searchBar, &SearchBar::findPrevious); + // clang-format on // Create the layout containing the workspace and a tab bar auto hbox = new QFrame(this); @@ -130,10 +134,11 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent) setWindowIcon(d->textEdit->windowIcon()); ParameterGrp::handle hPrefGrp = getWindowParameter(); - hPrefGrp->Attach( this ); + hPrefGrp->Attach(this); hPrefGrp->NotifyAll(); d->activityTimer = new QTimer(this); + // clang-format off connect(d->activityTimer, &QTimer::timeout, this, &EditorView::checkTimestamp); connect(d->textEdit->document(), &QTextDocument::modificationChanged, @@ -144,6 +149,7 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent) this, &EditorView::redoAvailable); connect(d->textEdit->document(), &QTextDocument::contentsChange, this, &EditorView::contentsChange); + // clang-format on } /** Destroys the object and frees any allocated resources */ @@ -152,7 +158,7 @@ EditorView::~EditorView() d->activityTimer->stop(); delete d->activityTimer; delete d; - getWindowParameter()->Detach( this ); + getWindowParameter()->Detach(this); } QPlainTextEdit* EditorView::getEditor() const @@ -182,27 +188,30 @@ void EditorView::closeEvent(QCloseEvent* event) } } -void EditorView::OnChange(Base::Subject &rCaller,const char* rcReason) +void EditorView::OnChange(Base::Subject& rCaller, const char* rcReason) { Q_UNUSED(rCaller); ParameterGrp::handle hPrefGrp = getWindowParameter(); if (strcmp(rcReason, "EnableLineNumber") == 0) { - //bool show = hPrefGrp->GetBool( "EnableLineNumber", true ); + // bool show = hPrefGrp->GetBool( "EnableLineNumber", true ); } } void EditorView::checkTimestamp() { QFileInfo fi(d->fileName); - qint64 timeStamp = fi.lastModified().toSecsSinceEpoch(); + qint64 timeStamp = fi.lastModified().toSecsSinceEpoch(); if (timeStamp != d->timeStamp) { - switch( QMessageBox::question( this, tr("Modified file"), - tr("%1.\n\nThis has been modified outside of the source editor. Do you want to reload it?").arg(d->fileName), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) ) - { + switch (QMessageBox::question(this, + tr("Modified file"), + tr("%1.\n\nThis has been modified outside of the source " + "editor. Do you want to reload it?") + .arg(d->fileName), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes)) { case QMessageBox::Yes: // updates time stamp and timer - open( d->fileName ); + open(d->fileName); return; case QMessageBox::No: d->timeStamp = timeStamp; @@ -219,11 +228,12 @@ void EditorView::checkTimestamp() /** * Runs the action specified by \a pMsg. */ -bool EditorView::onMsg(const char* pMsg,const char** /*ppReturn*/) +bool EditorView::onMsg(const char* pMsg, const char** /*ppReturn*/) { // don't allow any actions if the editor is being closed - if (d->aboutToClose) + if (d->aboutToClose) { return false; + } if (strcmp(pMsg, "Save") == 0) { saveFile(); @@ -268,22 +278,30 @@ bool EditorView::onMsg(const char* pMsg,const char** /*ppReturn*/) bool EditorView::onHasMsg(const char* pMsg) const { // don't allow any actions if the editor is being closed - if (d->aboutToClose) + if (d->aboutToClose) { return false; - if (strcmp(pMsg, "Run") == 0) + } + if (strcmp(pMsg, "Run") == 0) { return true; - if (strcmp(pMsg, "DebugStart") == 0) + } + if (strcmp(pMsg, "DebugStart") == 0) { return true; - if (strcmp(pMsg, "DebugStop") == 0) + } + if (strcmp(pMsg, "DebugStop") == 0) { return true; - if (strcmp(pMsg, "SaveAs") == 0) + } + if (strcmp(pMsg, "SaveAs") == 0) { return true; - if (strcmp(pMsg, "Print") == 0) + } + if (strcmp(pMsg, "Print") == 0) { return true; - if (strcmp(pMsg, "PrintPreview") == 0) + } + if (strcmp(pMsg, "PrintPreview") == 0) { return true; - if (strcmp(pMsg, "PrintPdf") == 0) + } + if (strcmp(pMsg, "PrintPdf") == 0) { return true; + } if (strcmp(pMsg, "Save") == 0) { return d->textEdit->document()->isModified(); } @@ -292,23 +310,23 @@ bool EditorView::onHasMsg(const char* pMsg) const return (canWrite && (d->textEdit->textCursor().hasSelection())); } else if (strcmp(pMsg, "Copy") == 0) { - return ( d->textEdit->textCursor().hasSelection() ); + return (d->textEdit->textCursor().hasSelection()); } else if (strcmp(pMsg, "Paste") == 0) { - QClipboard *cb = QApplication::clipboard(); + QClipboard* cb = QApplication::clipboard(); QString text; // Copy text from the clipboard (paste) text = cb->text(); bool canWrite = !d->textEdit->isReadOnly(); - return ( !text.isEmpty() && canWrite ); + return (!text.isEmpty() && canWrite); } else if (strcmp(pMsg, "Undo") == 0) { - return d->textEdit->document()->isUndoAvailable (); + return d->textEdit->document()->isUndoAvailable(); } else if (strcmp(pMsg, "Redo") == 0) { - return d->textEdit->document()->isRedoAvailable (); + return d->textEdit->document()->isRedoAvailable(); } return false; @@ -317,14 +335,16 @@ bool EditorView::onHasMsg(const char* pMsg) const /** Checking on close state. */ bool EditorView::canClose() { - if ( !d->textEdit->document()->isModified() ) + if (!d->textEdit->document()->isModified()) { return true; - this->setFocus(); // raises the view to front - switch( QMessageBox::question(this, tr("Unsaved document"), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel)) - { + } + this->setFocus(); // raises the view to front + switch (QMessageBox::question(this, + tr("Unsaved document"), + tr("The document has been modified.\n" + "Do you want to save your changes?"), + QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, + QMessageBox::Cancel)) { case QMessageBox::Yes: return saveFile(); case QMessageBox::No: @@ -346,10 +366,14 @@ void EditorView::setDisplayName(EditorView::DisplayName type) */ bool EditorView::saveAs() { - QString fn = FileDialog::getSaveFileName(this, QObject::tr("Save Macro"), - QString(), QString::fromLatin1("%1 (*.FCMacro);;Python (*.py)").arg(tr("FreeCAD macro"))); - if (fn.isEmpty()) + QString fn = FileDialog::getSaveFileName( + this, + QObject::tr("Save Macro"), + QString(), + QString::fromLatin1("%1 (*.FCMacro);;Python (*.py)").arg(tr("FreeCAD macro"))); + if (fn.isEmpty()) { return false; + } setCurrentFileName(fn); return saveFile(); } @@ -359,11 +383,13 @@ bool EditorView::saveAs() */ bool EditorView::open(const QString& fileName) { - if (!QFile::exists(fileName)) + if (!QFile::exists(fileName)) { return false; + } QFile file(fileName); - if (!file.open(QFile::ReadOnly)) + if (!file.open(QFile::ReadOnly)) { return false; + } d->lock = true; d->textEdit->setPlainText(QString::fromUtf8(file.readAll())); @@ -373,7 +399,7 @@ bool EditorView::open(const QString& fileName) file.close(); QFileInfo fi(fileName); - d->timeStamp = fi.lastModified().toSecsSinceEpoch(); + d->timeStamp = fi.lastModified().toSecsSinceEpoch(); d->activityTimer->setSingleShot(true); d->activityTimer->start(3000); @@ -409,7 +435,8 @@ void EditorView::paste() /** * Undoes the last operation. - * If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing happens. + * If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing + * happens. */ void EditorView::undo() { @@ -424,7 +451,8 @@ void EditorView::undo() /** * Redoes the last operation. - * If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing happens. + * If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing + * happens. */ void EditorView::redo() { @@ -454,8 +482,10 @@ void EditorView::printPreview() { QPrinter printer(QPrinter::ScreenResolution); QPrintPreviewDialog dlg(&printer, this); - connect(&dlg, &QPrintPreviewDialog::paintRequested, - this, qOverload(&EditorView::print)); + connect(&dlg, + &QPrintPreviewDialog::paintRequested, + this, + qOverload(&EditorView::print)); dlg.exec(); } @@ -469,11 +499,15 @@ void EditorView::print(QPrinter* printer) */ void EditorView::printPdf() { - QString filename = FileDialog::getSaveFileName(this, tr("Export PDF"), QString(), - QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file"))); + QString filename = + FileDialog::getSaveFileName(this, + tr("Export PDF"), + QString(), + QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file"))); if (!filename.isEmpty()) { QPrinter printer(QPrinter::ScreenResolution); - // setPdfVersion sets the printied PDF Version to comply with PDF/A-1b, more details under: https://www.kdab.com/creating-pdfa-documents-qt/ + // setPdfVersion sets the printied PDF Version to comply with PDF/A-1b, more details under: + // https://www.kdab.com/creating-pdfa-documents-qt/ printer.setPdfVersion(QPagedPaintDevice::PdfVersion_A1b); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(filename); @@ -481,7 +515,7 @@ void EditorView::printPdf() } } -void EditorView::setCurrentFileName(const QString &fileName) +void EditorView::setCurrentFileName(const QString& fileName) { d->fileName = fileName; Q_EMIT changeFileName(d->fileName); @@ -490,22 +524,24 @@ void EditorView::setCurrentFileName(const QString &fileName) QString name; QFileInfo fi(fileName); switch (d->displayName) { - case FullName: - name = fileName; - break; - case FileName: - name = fi.fileName(); - break; - case BaseName: - name = fi.baseName(); - break; + case FullName: + name = fileName; + break; + case FileName: + name = fi.fileName(); + break; + case BaseName: + name = fi.baseName(); + break; } QString shownName; - if (fileName.isEmpty()) + if (fileName.isEmpty()) { shownName = tr("untitled[*]"); - else + } + else { shownName = QString::fromLatin1("%1[*]").arg(name); + } shownName += tr(" - Editor"); setWindowTitle(shownName); setWindowModified(false); @@ -521,12 +557,14 @@ QString EditorView::fileName() const */ bool EditorView::saveFile() { - if (d->fileName.isEmpty()) + if (d->fileName.isEmpty()) { return saveAs(); + } QFile file(d->fileName); - if (!file.open(QFile::WriteOnly)) + if (!file.open(QFile::WriteOnly)) { return false; + } QTextStream ts(&file); #if QT_VERSION < 0x060000 ts.setCodec("UTF-8"); @@ -536,35 +574,42 @@ bool EditorView::saveFile() d->textEdit->document()->setModified(false); QFileInfo fi(d->fileName); - d->timeStamp = fi.lastModified().toSecsSinceEpoch(); + d->timeStamp = fi.lastModified().toSecsSinceEpoch(); return true; } void EditorView::undoAvailable(bool undo) { - if (!undo) + if (!undo) { d->undos.clear(); + } } void EditorView::redoAvailable(bool redo) { - if (!redo) + if (!redo) { d->redos.clear(); + } } void EditorView::contentsChange(int position, int charsRemoved, int charsAdded) { Q_UNUSED(position); - if (d->lock) + if (d->lock) { return; - if (charsRemoved > 0 && charsAdded > 0) - return; // syntax highlighting - else if (charsRemoved > 0) + } + if (charsRemoved > 0 && charsAdded > 0) { + return; // syntax highlighting + } + else if (charsRemoved > 0) { d->undos << tr("%1 chars removed").arg(charsRemoved); - else if (charsAdded > 0) + } + else if (charsAdded > 0) { d->undos << tr("%1 chars added").arg(charsAdded); - else + } + else { d->undos << tr("Formatted"); + } d->redos.clear(); } @@ -581,10 +626,11 @@ QStringList EditorView::undoActions() const */ QStringList EditorView::redoActions() const { - return d->redos;; + return d->redos; + ; } -void EditorView::focusInEvent (QFocusEvent *) +void EditorView::focusInEvent(QFocusEvent*) { d->textEdit->setFocus(); } @@ -594,10 +640,10 @@ void EditorView::focusInEvent (QFocusEvent *) TYPESYSTEM_SOURCE_ABSTRACT(Gui::PythonEditorView, Gui::EditorView) PythonEditorView::PythonEditorView(PythonEditor* editor, QWidget* parent) - : EditorView(editor, parent), _pye(editor) + : EditorView(editor, parent) + , _pye(editor) { - connect(this, &PythonEditorView::changeFileName, - editor, &PythonEditor::setFileName); + connect(this, &PythonEditorView::changeFileName, editor, &PythonEditor::setFileName); watcher = new PythonTracingWatcher(this); } @@ -609,17 +655,17 @@ PythonEditorView::~PythonEditorView() /** * Runs the action specified by \a pMsg. */ -bool PythonEditorView::onMsg(const char* pMsg,const char** ppReturn) +bool PythonEditorView::onMsg(const char* pMsg, const char** ppReturn) { - if (strcmp(pMsg,"Run")==0) { + if (strcmp(pMsg, "Run") == 0) { executeScript(); return true; } - else if (strcmp(pMsg,"StartDebug")==0) { + else if (strcmp(pMsg, "StartDebug") == 0) { QTimer::singleShot(300, this, &PythonEditorView::startDebug); return true; } - else if (strcmp(pMsg,"ToggleBreakpoint")==0) { + else if (strcmp(pMsg, "ToggleBreakpoint") == 0) { toggleBreakpoint(); return true; } @@ -632,12 +678,15 @@ bool PythonEditorView::onMsg(const char* pMsg,const char** ppReturn) */ bool PythonEditorView::onHasMsg(const char* pMsg) const { - if (strcmp(pMsg,"Run")==0) + if (strcmp(pMsg, "Run") == 0) { return true; - if (strcmp(pMsg,"StartDebug")==0) + } + if (strcmp(pMsg, "StartDebug") == 0) { return true; - if (strcmp(pMsg,"ToggleBreakpoint")==0) + } + if (strcmp(pMsg, "ToggleBreakpoint") == 0) { return true; + } return EditorView::onHasMsg(pMsg); } @@ -647,12 +696,13 @@ bool PythonEditorView::onHasMsg(const char* pMsg) const void PythonEditorView::executeScript() { // always save the macro when it is modified - if (EditorView::onHasMsg("Save")) + if (EditorView::onHasMsg("Save")) { EditorView::onMsg("Save", nullptr); + } try { getMainWindow()->setCursor(Qt::WaitCursor); PythonTracingLocker tracelock(watcher->getTrace()); - Application::Instance->macroManager()->run(Gui::MacroManager::File,fileName().toUtf8()); + Application::Instance->macroManager()->run(Gui::MacroManager::File, fileName().toUtf8()); getMainWindow()->unsetCursor(); } catch (const Base::SystemExitException&) { @@ -771,8 +821,9 @@ void SearchBar::activate() void SearchBar::deactivate() { - if (textEditor) + if (textEditor) { textEditor->setFocus(); + } hide(); } @@ -793,32 +844,39 @@ void SearchBar::findCurrent() void SearchBar::findText(bool skip, bool next, const QString& str) { - if (!textEditor) + if (!textEditor) { return; + } QTextCursor cursor = textEditor->textCursor(); - QTextDocument *doc = textEditor->document(); - if (!doc || cursor.isNull()) + QTextDocument* doc = textEditor->document(); + if (!doc || cursor.isNull()) { return; + } - if (cursor.hasSelection()) + if (cursor.hasSelection()) { cursor.setPosition((skip && next) ? cursor.position() : cursor.anchor()); + } bool found = true; QTextCursor newCursor = cursor; if (!str.isEmpty()) { QTextDocument::FindFlags options; - if (!next) + if (!next) { options |= QTextDocument::FindBackward; - if (matchCase->isChecked()) + } + if (matchCase->isChecked()) { options |= QTextDocument::FindCaseSensitively; - if (matchWord->isChecked()) + } + if (matchWord->isChecked()) { options |= QTextDocument::FindWholeWords; + } newCursor = doc->find(str, cursor, options); if (newCursor.isNull()) { QTextCursor ac(doc); - ac.movePosition(options & QTextDocument::FindBackward ? QTextCursor::End : QTextCursor::Start); + ac.movePosition(options & QTextDocument::FindBackward ? QTextCursor::End + : QTextCursor::Start); newCursor = doc->find(str, ac, options); if (newCursor.isNull()) { found = false; @@ -827,18 +885,17 @@ void SearchBar::findText(bool skip, bool next, const QString& str) } } - if (!isVisible()) + if (!isVisible()) { show(); + } textEditor->setTextCursor(newCursor); QString styleSheet; if (!found) { - styleSheet = QString::fromLatin1( - " QLineEdit {\n" - " background-color: rgb(221,144,161);\n" - " }\n" - ); + styleSheet = QString::fromLatin1(" QLineEdit {\n" + " background-color: rgb(221,144,161);\n" + " }\n"); } searchText->setStyleSheet(styleSheet); diff --git a/src/Gui/ExpressionCompleter.cpp b/src/Gui/ExpressionCompleter.cpp index 015a2dc135..a44143018d 100644 --- a/src/Gui/ExpressionCompleter.cpp +++ b/src/Gui/ExpressionCompleter.cpp @@ -23,12 +23,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #endif #include @@ -53,11 +53,12 @@ class ExpressionCompleterModel: public QAbstractItemModel { public: ExpressionCompleterModel(QObject* parent, bool noProperty) - :QAbstractItemModel(parent), noProperty(noProperty) - { - } + : QAbstractItemModel(parent) + , noProperty(noProperty) + {} - void setNoProperty(bool enabled) { + void setNoProperty(bool enabled) + { noProperty = enabled; } @@ -79,6 +80,7 @@ public: endResetModel(); } + // clang-format off // This ExpressionCompleter model works without any physical items. // Everything item related is stored inside QModelIndex.InternalPointer/InternalId(), // using the following Info structure. @@ -154,6 +156,7 @@ public: // |-- prop2.path1 (contextual) - (row 0, [ 6,-1,-1,0]) = encode as parent => INVALID, LEAF ITEM // |-- prop2.path2 (contextual) - (row 1, [ 6,-1,-1,0]) = encode as parent => INVALID, LEAF ITEM // + // clang-format on struct Info { @@ -165,20 +168,21 @@ public: static const Info root; }; - static const quint64 k_numBitsProp = 16ULL; // 0 .. 15 - static const quint64 k_numBitsObj = 24ULL; // 16.. 39 - static const quint64 k_numBitsContextualHierarchy = 1; // 40 - static const quint64 k_numBitsDocuments = 23ULL; // 41.. 63 + static const quint64 k_numBitsProp = 16ULL; // 0 .. 15 + static const quint64 k_numBitsObj = 24ULL; // 16.. 39 + static const quint64 k_numBitsContextualHierarchy = 1; // 40 + static const quint64 k_numBitsDocuments = 23ULL; // 41.. 63 - static const quint64 k_offsetProp = 0; - static const quint64 k_offsetObj = k_offsetProp + k_numBitsProp; - static const quint64 k_offsetContextualHierarchy = k_offsetObj + k_numBitsObj; - static const quint64 k_offsetDocuments = k_offsetContextualHierarchy + k_numBitsContextualHierarchy; + static const quint64 k_offsetProp = 0; + static const quint64 k_offsetObj = k_offsetProp + k_numBitsProp; + static const quint64 k_offsetContextualHierarchy = k_offsetObj + k_numBitsObj; + static const quint64 k_offsetDocuments = + k_offsetContextualHierarchy + k_numBitsContextualHierarchy; - static const quint64 k_maskProp = ((1ULL << k_numBitsProp) - 1); - static const quint64 k_maskObj = ((1ULL << k_numBitsObj) - 1); - static const quint64 k_maskContextualHierarchy = ((1ULL << k_numBitsContextualHierarchy) - 1); - static const quint64 k_maskDocuments = ((1ULL << k_numBitsDocuments) - 1); + static const quint64 k_maskProp = ((1ULL << k_numBitsProp) - 1); + static const quint64 k_maskObj = ((1ULL << k_numBitsObj) - 1); + static const quint64 k_maskContextualHierarchy = ((1ULL << k_numBitsContextualHierarchy) - 1); + static const quint64 k_maskDocuments = ((1ULL << k_numBitsDocuments) - 1); union InfoPtrEncoding { @@ -249,8 +253,9 @@ public: QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { - if (role != Qt::EditRole && role != Qt::DisplayRole && role != Qt::UserRole) + if (role != Qt::EditRole && role != Qt::DisplayRole && role != Qt::UserRole) { return {}; + } QVariant variant; Info info = getInfo(index); _data(info, index.row(), &variant, nullptr, role == Qt::UserRole); @@ -265,10 +270,11 @@ public: if (prop) { prop->getPaths(result); // need to filter out irrelevant paths (len 1, aka just this object identifier) - auto res = std::remove_if( - result.begin(), result.end(), [](const App::ObjectIdentifier& path) -> bool { - return path.getComponents().empty(); - }); + auto res = std::remove_if(result.begin(), + result.end(), + [](const App::ObjectIdentifier& path) -> bool { + return path.getComponents().empty(); + }); result.erase(res, result.end()); } return result; @@ -295,11 +301,11 @@ public: // identify the document index. For any children of the root, it is given by traversing // the flat list and identified by [row] idx = info.doc < 0 ? row : info.doc; - const auto &docs = App::GetApplication().getDocuments(); + const auto& docs = App::GetApplication().getDocuments(); int docSize = (int)docs.size() * 2; int objSize = 0; int propSize = 0; - std::vector > props; + std::vector> props; App::Document* doc = nullptr; App::DocumentObject* obj = nullptr; const char* propName = nullptr; @@ -311,28 +317,33 @@ public: } else { // if we're looking at the ROOT, or the row identifies one of the other ROOT elements - // |----- current documents' objects, rows: docs.size ... docs.size + objs.size - // |----- current objects' props, rows: docs.size + objs.size ... docs.size + objs.size+ props.size + // |----- current documents' objects, rows: docs.size ... docs.size + + // objs.size + // |----- current objects' props, rows: docs.size + objs.size ... docs.size + + // objs.size+ props.size // // We need to process the ROOT so we get the correct count for its children doc = App::GetApplication().getDocument(currentDoc.c_str()); - if (!doc)// no current, there are no additional objects + if (!doc) { // no current, there are no additional objects return; + } // move to the current documents' objects' range idx -= docSize; - if (info.doc < 0) + if (info.doc < 0) { row = idx; + } - const auto &objs = doc->getObjects(); + const auto& objs = doc->getObjects(); objSize = (int)objs.size() * 2; // if this is a valid object, we found our object and break. // if not, this may be the root or one of current object's properties if (idx >= 0 && idx < objSize) { obj = objs[idx / 2]; // if they are in the ignore list skip - if (inList.count(obj)) + if (inList.count(obj)) { return; + } } else if (!noProperty) { // need to check the current object's props range, or we're parsing the ROOT @@ -340,18 +351,21 @@ public: if (cobj) { // move to the props range of the current object idx -= objSize; - if (info.doc < 0) + if (info.doc < 0) { row = idx; + } // get the properties cobj->getPropertyNamedList(props); propSize = (int)props.size(); // if this is an invalid index, bail out // if it's the ROOT break! - if (idx >= propSize) + if (idx >= propSize) { return; + } if (idx >= 0) { - obj = cobj; // we only set the active object if we're not processing the root. + obj = cobj; // we only set the active object if we're not processing the + // root. propName = props[idx].first; prop = props[idx].second; } @@ -373,26 +387,35 @@ public: if (propName) { res = QString::fromLatin1(propName); // resolve the property - if (sep && !noProperty && !retrieveSubPaths(prop).empty()) + if (sep && !noProperty && !retrieveSubPaths(prop).empty()) { res += QLatin1Char('.'); + } } else if (obj) { - // the object has been resolved, use the saved idx to figure out quotation or not. - if (idx & 1) + // the object has been resolved, use the saved idx to figure out quotation or + // not. + if (idx & 1) { res = QString::fromUtf8(quote(obj->Label.getStrValue()).c_str()); - else + } + else { res = QString::fromLatin1(obj->getNameInDocument()); - if (sep && !noProperty) + } + if (sep && !noProperty) { res += QLatin1Char('.'); + } } else { - // the document has been resolved, use the saved idx to figure out quotation or not. - if (idx & 1) + // the document has been resolved, use the saved idx to figure out quotation or + // not. + if (idx & 1) { res = QString::fromUtf8(quote(doc->Label.getStrValue()).c_str()); - else + } + else { res = QString::fromLatin1(doc->getName()); - if (sep) + } + if (sep) { res += QLatin1Char('#'); + } } v->setValue(res); } @@ -404,34 +427,40 @@ public: if (!obj) { // are we pointing to an object item, or our father (info) is an object idx = info.obj < 0 ? row : info.obj; - const auto &objs = doc->getObjects(); + const auto& objs = doc->getObjects(); objSize = (int)objs.size() * 2; // if invalid index, or in the ignore list bail out - if (idx < 0 || idx >= objSize || inList.count(obj)) + if (idx < 0 || idx >= objSize || inList.count(obj)) { return; + } obj = objs[idx / 2]; if (info.obj < 0) { // if this is AN actual Object item and not a root - if (count) - *count = objSize; // set the correct count if requested + if (count) { + *count = objSize; // set the correct count if requested + } if (v) { // resolve the name QString res; - if (idx & 1) + if (idx & 1) { res = QString::fromUtf8(quote(obj->Label.getStrValue()).c_str()); - else + } + else { res = QString::fromLatin1(obj->getNameInDocument()); - if (sep && !noProperty) + } + if (sep && !noProperty) { res += QLatin1Char('.'); + } v->setValue(res); } return; } } - if (noProperty) + if (noProperty) { return; + } if (!propName) { idx = info.prop < 0 ? row : info.prop; obj->getPropertyNamedList(props); @@ -452,8 +481,9 @@ public: QString res = QString::fromLatin1(propName); // check to see if we have accessible paths from this prop name? - if (sep && !retrieveSubPaths(prop).empty()) + if (sep && !retrieveSubPaths(prop).empty()) { res += QLatin1Char('.'); + } *v = res; } return; @@ -489,9 +519,11 @@ public: return; } - QModelIndex parent(const QModelIndex & index) const override { - if (!index.isValid()) + QModelIndex parent(const QModelIndex& index) const override + { + if (!index.isValid()) { return {}; + } Info parentInfo = getInfo(index); Info grandParentInfo = parentInfo; @@ -505,7 +537,8 @@ public: grandParentInfo.prop = -1; return createIndex(parentInfo.prop, 0, infoId(grandParentInfo)); } - // if the parent is the object or a prop attached to the root, we just need the below line + // if the parent is the object or a prop attached to the root, we just need the below + // line return createIndex(parentInfo.doc, 0, infoId(Info::root)); } else { @@ -528,7 +561,7 @@ public: } // returns true if successful, false if 'element' identifies a Leaf - bool modelIndexToParentInfo(QModelIndex element, Info & info) const + bool modelIndexToParentInfo(QModelIndex element, Info& info) const { Info parentInfo; info = Info::root; @@ -545,8 +578,8 @@ public: info.doc = element.row(); - // if my element is a contextual descendant of root (current doc object list, current object prop list) - // mark it as such + // if my element is a contextual descendant of root (current doc object list, + // current object prop list) mark it as such if (element.row() >= docsSize) { info.contextualHierarchy = 1; } @@ -559,18 +592,21 @@ public: int objsSize = static_cast(cdoc->getObjects().size() * 2); int idx = parentInfo.doc - static_cast(docs.size()); if (idx < objsSize) { - // |-- Parent (OBJECT) - (row 4, [-1,-1,-1,0]) = encode as element => [parent.row,-1,-1,1] - // |- element (PROP) - (row 0, [parent.row,-1,-1,1]) = encode as element => [parent.row,-1,parent.row,1] + // |-- Parent (OBJECT) - (row 4, [-1,-1,-1,0]) = encode as element => + // [parent.row,-1,-1,1] + // |- element (PROP) - (row 0, [parent.row,-1,-1,1]) = encode as + // element => [parent.row,-1,parent.row,1] info.doc = parentInfo.doc; - info.obj = -1;// object information is determined by the DOC index actually + info.obj = + -1; // object information is determined by the DOC index actually info.prop = element.row(); info.contextualHierarchy = 1; } else { - // if my parent (parentInfo) is a prop, it means that our element is a prop path - // and that is a leaf item (we don't split prop paths further) - // we can't encode leaf items into an "Info" + // if my parent (parentInfo) is a prop, it means that our element is a prop + // path and that is a leaf item (we don't split prop paths further) we can't + // encode leaf items into an "Info" return false; } } @@ -578,7 +614,6 @@ public: // no contextual document return false; } - } // regular hierarchy else if (parentInfo.obj <= 0) { @@ -594,10 +629,11 @@ public: return true; } - QModelIndex index(int row, int column, - const QModelIndex & parent = QModelIndex()) const override { - if (row < 0) + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override + { + if (row < 0) { return {}; + } Info myParentInfoEncoded = Info::root; // encode the parent's QModelIndex into an 'Info' structure @@ -655,47 +691,59 @@ const ExpressionCompleterModel::Info ExpressionCompleterModel::Info::root = {-1, */ ExpressionCompleter::ExpressionCompleter(const App::DocumentObject* currentDocObj, - QObject* parent, bool noProperty, bool checkInList) - : QCompleter(parent), currentObj(currentDocObj) - , noProperty(noProperty), checkInList(checkInList) + QObject* parent, + bool noProperty, + bool checkInList) + : QCompleter(parent) + , currentObj(currentDocObj) + , noProperty(noProperty) + , checkInList(checkInList) { setCaseSensitivity(Qt::CaseInsensitive); } -void ExpressionCompleter::init() { - if (model()) +void ExpressionCompleter::init() +{ + if (model()) { return; + } - auto m = new ExpressionCompleterModel(this,noProperty); - m->setDocumentObject(currentObj.getObject(),checkInList); + auto m = new ExpressionCompleterModel(this, noProperty); + m->setDocumentObject(currentObj.getObject(), checkInList); setModel(m); } void ExpressionCompleter::setDocumentObject(const App::DocumentObject* obj, bool _checkInList) { - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { currentObj = App::DocumentObjectT(); - else + } + else { currentObj = obj; + } setCompletionPrefix(QString()); checkInList = _checkInList; auto m = model(); - if (m) + if (m) { static_cast(m)->setDocumentObject(obj, checkInList); + } } -void ExpressionCompleter::setNoProperty(bool enabled) { +void ExpressionCompleter::setNoProperty(bool enabled) +{ noProperty = enabled; auto m = model(); - if (m) + if (m) { static_cast(m)->setNoProperty(enabled); + } } QString ExpressionCompleter::pathFromIndex(const QModelIndex& index) const { auto m = model(); - if (!m || !index.isValid()) + if (!m || !index.isValid()) { return {}; + } QString res; auto parent = index; @@ -706,8 +754,8 @@ QString ExpressionCompleter::pathFromIndex(const QModelIndex& index) const auto info = ExpressionCompleterModel::getInfo(index); FC_TRACE("join path " << info.doc << "," << info.obj << "," << info.prop << "," - << info.contextualHierarchy << "," << index.row() - << ": " << res.toUtf8().constData()); + << info.contextualHierarchy << "," << index.row() << ": " + << res.toUtf8().constData()); return res; } @@ -715,8 +763,9 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const { QStringList resultList; std::string path = input.toUtf8().constData(); - if (path.empty()) + if (path.empty()) { return resultList; + } int retry = 0; std::string lastElem; // used to recover in case of parse failure after ".". @@ -726,17 +775,18 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const // this will not work for incomplete Tokens at the end // "Sketch." will fail to parse and complete. - App::ObjectIdentifier ident = ObjectIdentifier::parse( - currentObj.getObject(), path); + App::ObjectIdentifier ident = ObjectIdentifier::parse(currentObj.getObject(), path); std::vector stringList = ident.getStringList(); auto stringListIter = stringList.begin(); - if (retry > 1 && !stringList.empty()) + if (retry > 1 && !stringList.empty()) { stringList.pop_back(); + } if (!stringList.empty()) { - if (!trim.empty() && boost::ends_with(stringList.back(), trim)) + if (!trim.empty() && boost::ends_with(stringList.back(), trim)) { stringList.back().resize(stringList.back().size() - trim.size()); + } while (stringListIter != stringList.end()) { resultList << Base::Tools::fromStdString(*stringListIter); ++stringListIter; @@ -748,7 +798,8 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const // erase the separator lastElem.erase(lastElem.begin()); resultList << Base::Tools::fromStdString(lastElem); - } else { + } + else { // add empty string to allow completion after "." or "#" resultList << QString(); } @@ -778,7 +829,8 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const path = path + lastElem; lastElem = ""; } - // else... we don't reset lastElem if it's a '.' or '#' to allow chaining completions + // else... we don't reset lastElem if it's a '.' or '#' to allow chaining + // completions if (!path.empty()) { char last = path[path.size() - 1]; if (last != '#' && last != '.' && path.find('#') != std::string::npos) { @@ -810,7 +862,7 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const // Code below inspired by blog entry: // https://john.nachtimwald.com/2009/07/04/qcompleter-and-comma-separated-tags/ -void ExpressionCompleter::slotUpdate(const QString & prefix, int pos) +void ExpressionCompleter::slotUpdate(const QString& prefix, int pos) { FC_TRACE("SlotUpdate:" << prefix.toUtf8().constData()); @@ -818,8 +870,9 @@ void ExpressionCompleter::slotUpdate(const QString & prefix, int pos) QString completionPrefix = tokenizer.perform(prefix, pos); if (completionPrefix.isEmpty()) { - if (auto itemView = popup()) + if (auto itemView = popup()) { itemView->setVisible(false); + } return; } @@ -831,15 +884,16 @@ void ExpressionCompleter::slotUpdate(const QString & prefix, int pos) FC_TRACE("Complete on Prefix" << completionPrefix.toUtf8().constData()); complete(); FC_TRACE("Complete Done"); - } else if (auto itemView = popup()) { itemView->setVisible(false); } } -ExpressionLineEdit::ExpressionLineEdit(QWidget* parent, bool noProperty, - char checkPrefix, bool checkInList) +ExpressionLineEdit::ExpressionLineEdit(QWidget* parent, + bool noProperty, + char checkPrefix, + bool checkInList) : QLineEdit(parent) , completer(nullptr) , block(true) @@ -851,12 +905,13 @@ ExpressionLineEdit::ExpressionLineEdit(QWidget* parent, bool noProperty, connect(this, &QLineEdit::textEdited, this, &ExpressionLineEdit::slotTextChanged); } -void ExpressionLineEdit::setPrefix(char prefix) { +void ExpressionLineEdit::setPrefix(char prefix) +{ checkPrefix = prefix; } void ExpressionLineEdit::setDocumentObject(const App::DocumentObject* currentDocObj, - bool _checkInList) + bool _checkInList) { checkInList = _checkInList; if (completer) { @@ -867,29 +922,38 @@ void ExpressionLineEdit::setDocumentObject(const App::DocumentObject* currentDoc completer = new ExpressionCompleter(currentDocObj, this, noProperty, checkInList); completer->setWidget(this); completer->setCaseSensitivity(Qt::CaseInsensitive); - if (!exactMatch) + if (!exactMatch) { completer->setFilterMode(Qt::MatchContains); - connect(completer, qOverload(&QCompleter::activated), - this, &ExpressionLineEdit::slotCompleteTextSelected); + } + connect(completer, + qOverload(&QCompleter::activated), + this, + &ExpressionLineEdit::slotCompleteTextSelected); connect(completer, qOverload(&QCompleter::highlighted), - this, &ExpressionLineEdit::slotCompleteTextHighlighted); - connect(this, &ExpressionLineEdit::textChanged2, - completer, &ExpressionCompleter::slotUpdate); + this, + &ExpressionLineEdit::slotCompleteTextHighlighted); + connect(this, + &ExpressionLineEdit::textChanged2, + completer, + &ExpressionCompleter::slotUpdate); } } -void ExpressionLineEdit::setNoProperty(bool enabled) { +void ExpressionLineEdit::setNoProperty(bool enabled) +{ noProperty = enabled; - if (completer) + if (completer) { completer->setNoProperty(enabled); + } } -void ExpressionLineEdit::setExactMatch(bool enabled) { +void ExpressionLineEdit::setExactMatch(bool enabled) +{ exactMatch = enabled; - if (completer) + if (completer) { completer->setFilterMode(exactMatch ? Qt::MatchStartsWith : Qt::MatchContains); - + } } bool ExpressionLineEdit::completerActive() const @@ -899,23 +963,25 @@ bool ExpressionLineEdit::completerActive() const void ExpressionLineEdit::hideCompleter() { - if (completer && completer->popup()) + if (completer && completer->popup()) { completer->popup()->setVisible(false); -} - -void ExpressionLineEdit::slotTextChanged(const QString & text) -{ - if (!block) { - if (!text.size() || (checkPrefix && text[0] != QLatin1Char(checkPrefix))) - return; - Q_EMIT textChanged2(text,cursorPosition()); } } -void ExpressionLineEdit::slotCompleteText(const QString & completionPrefix, bool isActivated) +void ExpressionLineEdit::slotTextChanged(const QString& text) { - int start,end; - completer->getPrefixRange(start,end); + if (!block) { + if (!text.size() || (checkPrefix && text[0] != QLatin1Char(checkPrefix))) { + return; + } + Q_EMIT textChanged2(text, cursorPosition()); + } +} + +void ExpressionLineEdit::slotCompleteText(const QString& completionPrefix, bool isActivated) +{ + int start, end; + completer->getPrefixRange(start, end); QString before(text().left(start)); QString after(text().mid(end)); @@ -952,7 +1018,7 @@ void ExpressionLineEdit::slotCompleteTextSelected(const QString& completionPrefi void ExpressionLineEdit::keyPressEvent(QKeyEvent* e) { - Base::FlagToggler flag(block,true); + Base::FlagToggler flag(block, true); QLineEdit::keyPressEvent(e); } @@ -962,11 +1028,10 @@ void ExpressionLineEdit::contextMenuEvent(QContextMenuEvent* event) if (completer) { menu->addSeparator(); - QAction *match = menu->addAction(tr("Exact match")); + QAction* match = menu->addAction(tr("Exact match")); match->setCheckable(true); match->setChecked(completer->filterMode() == Qt::MatchStartsWith); - QObject::connect(match, &QAction::toggled, - this, &Gui::ExpressionLineEdit::setExactMatch); + QObject::connect(match, &QAction::toggled, this, &Gui::ExpressionLineEdit::setExactMatch); } menu->setAttribute(Qt::WA_DeleteOnClose); @@ -988,8 +1053,9 @@ ExpressionTextEdit::ExpressionTextEdit(QWidget* parent) void ExpressionTextEdit::setExactMatch(bool enabled) { exactMatch = enabled; - if (completer) + if (completer) { completer->setFilterMode(exactMatch ? Qt::MatchStartsWith : Qt::MatchContains); + } } void ExpressionTextEdit::setDocumentObject(const App::DocumentObject* currentDocObj) @@ -1001,16 +1067,23 @@ void ExpressionTextEdit::setDocumentObject(const App::DocumentObject* currentDoc if (currentDocObj) { completer = new ExpressionCompleter(currentDocObj, this); - if (!exactMatch) + if (!exactMatch) { completer->setFilterMode(Qt::MatchContains); + } completer->setWidget(this); completer->setCaseSensitivity(Qt::CaseInsensitive); - connect(completer, qOverload(&QCompleter::activated), this, - &ExpressionTextEdit::slotCompleteText); - connect(completer, qOverload(&QCompleter::highlighted), this, - &ExpressionTextEdit::slotCompleteText); - connect(this, &ExpressionTextEdit::textChanged2, completer, - &ExpressionCompleter::slotUpdate); + connect(completer, + qOverload(&QCompleter::activated), + this, + &ExpressionTextEdit::slotCompleteText); + connect(completer, + qOverload(&QCompleter::highlighted), + this, + &ExpressionTextEdit::slotCompleteText); + connect(this, + &ExpressionTextEdit::textChanged2, + completer, + &ExpressionCompleter::slotUpdate); } } @@ -1021,36 +1094,37 @@ bool ExpressionTextEdit::completerActive() const void ExpressionTextEdit::hideCompleter() { - if (completer && completer->popup()) + if (completer && completer->popup()) { completer->popup()->setVisible(false); + } } void ExpressionTextEdit::slotTextChanged() { if (!block) { QTextCursor cursor = textCursor(); - Q_EMIT textChanged2(cursor.block().text(),cursor.positionInBlock()); + Q_EMIT textChanged2(cursor.block().text(), cursor.positionInBlock()); } } void ExpressionTextEdit::slotCompleteText(const QString& completionPrefix) { QTextCursor cursor = textCursor(); - int start,end; - completer->getPrefixRange(start,end); + int start, end; + completer->getPrefixRange(start, end); int pos = cursor.positionInBlock(); if (pos < end) { cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, end - pos); } - cursor.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor,end-start); - Base::FlagToggler flag(block,false); + cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, end - start); + Base::FlagToggler flag(block, false); cursor.insertText(completionPrefix); completer->updatePrefixEnd(cursor.positionInBlock()); } void ExpressionTextEdit::keyPressEvent(QKeyEvent* e) { - Base::FlagToggler flag(block,true); + Base::FlagToggler flag(block, true); QPlainTextEdit::keyPressEvent(e); } @@ -1071,8 +1145,9 @@ void ExpressionTextEdit::contextMenuEvent(QContextMenuEvent* event) QAction* action = menu->exec(event->globalPos()); if (completer) { - if (action == match) + if (action == match) { setExactMatch(match->isChecked()); + } } delete menu; @@ -1088,15 +1163,15 @@ ExpressionParameter* ExpressionParameter::instance() bool ExpressionParameter::isCaseSensitive() const { - auto handle = GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Expression"); + auto handle = + GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Expression"); return handle->GetBool("CompleterCaseSensitive", false); } bool ExpressionParameter::isExactMatch() const { - auto handle = GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Expression"); + auto handle = + GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Expression"); return handle->GetBool("CompleterMatchExact", false); } diff --git a/src/Gui/MouseSelection.cpp b/src/Gui/MouseSelection.cpp index bc15741e3b..7160f06bee 100644 --- a/src/Gui/MouseSelection.cpp +++ b/src/Gui/MouseSelection.cpp @@ -23,13 +23,13 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #endif #include "MouseSelection.h" @@ -70,38 +70,39 @@ void AbstractMouseSelection::releaseMouseModel(bool abort) int AbstractMouseSelection::handleEvent(const SoEvent* const ev, const SbViewportRegion& vp) { - int ret=Continue; + int ret = Continue; const SbVec2s& sz = vp.getWindowSize(); - short w,h; - sz.getValue(w,h); + short w, h; + sz.getValue(w, h); SbVec2s loc = ev->getPosition(); - short x,y; - loc.getValue(x,y); - y = h-y; // the origin is at the left bottom corner (instead of left top corner) + short x, y; + loc.getValue(x, y); + y = h - y; // the origin is at the left bottom corner (instead of left top corner) if (ev->getTypeId().isDerivedFrom(SoMouseButtonEvent::getClassTypeId())) { - const auto event = (const SoMouseButtonEvent*) ev; + const auto event = (const SoMouseButtonEvent*)ev; const SbBool press = event->getState() == SoButtonEvent::DOWN ? true : false; if (press) { _clPoly.push_back(ev->getPosition()); - ret = mouseButtonEvent(static_cast(ev), QPoint(x,y)); + ret = mouseButtonEvent(static_cast(ev), QPoint(x, y)); } else { - ret = mouseButtonEvent(static_cast(ev), QPoint(x,y)); + ret = mouseButtonEvent(static_cast(ev), QPoint(x, y)); } } else if (ev->getTypeId().isDerivedFrom(SoLocation2Event::getClassTypeId())) { - ret = locationEvent(static_cast(ev), QPoint(x,y)); + ret = locationEvent(static_cast(ev), QPoint(x, y)); } else if (ev->getTypeId().isDerivedFrom(SoKeyboardEvent::getClassTypeId())) { ret = keyboardEvent(static_cast(ev)); } - if (ret == Restart) + if (ret == Restart) { _clPoly.clear(); + } return ret; } @@ -110,9 +111,9 @@ int AbstractMouseSelection::handleEvent(const SoEvent* const ev, const SbViewpor BaseMouseSelection::BaseMouseSelection() : AbstractMouseSelection() -{ -} +{} +// clang-format off static const char* cursor_cut_scissors[]= { "32 32 6 1", "a c #800000", @@ -154,6 +155,7 @@ static const char* cursor_cut_scissors[]= { "................................", "................................" }; +// clang-format on PolyPickerSelection::PolyPickerSelection() { @@ -162,7 +164,7 @@ PolyPickerSelection::PolyPickerSelection() void PolyPickerSelection::setColor(float r, float g, float b, float a) { - polyline.setColor(r,g,b,a); + polyline.setColor(r, g, b, a); } void PolyPickerSelection::setLineWidth(float l) @@ -179,7 +181,7 @@ void PolyPickerSelection::initialize() polyline.setViewer(_pcView3D); _pcView3D->addGraphicsItem(&polyline); - _pcView3D->redraw(); // needed to get an up-to-date image + _pcView3D->redraw(); // needed to get an up-to-date image _pcView3D->setRenderType(View3DInventorViewer::Image); _pcView3D->redraw(); @@ -209,17 +211,21 @@ int PolyPickerSelection::popupMenu() menu.addAction(QObject::tr("Clear")); QAction* ca = menu.addAction(QObject::tr("Cancel")); - if(getPositions().size() < 3) + if (getPositions().size() < 3) { fi->setEnabled(false); + } QAction* id = menu.exec(QCursor::pos()); - if (id == fi) + if (id == fi) { return Finish; - else if (id == ca) + } + else if (id == ca) { return Cancel; - else + } + else { return Restart; + } } int PolyPickerSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos) @@ -228,63 +234,57 @@ int PolyPickerSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, con const SbBool press = e->getState() == SoButtonEvent::DOWN ? true : false; if (press) { - switch(button) - { - case SoMouseButtonEvent::BUTTON1: - { - if (!polyline.isWorking()) { - polyline.setWorking(true); - polyline.clear(); - }; - polyline.addNode(pos); - lastConfirmed = true; - m_iXnew = pos.x(); m_iYnew = pos.y(); - m_iXold = pos.x(); m_iYold = pos.y(); - } - break; + switch (button) { + case SoMouseButtonEvent::BUTTON1: { + if (!polyline.isWorking()) { + polyline.setWorking(true); + polyline.clear(); + }; + polyline.addNode(pos); + lastConfirmed = true; + m_iXnew = pos.x(); + m_iYnew = pos.y(); + m_iXold = pos.x(); + m_iYold = pos.y(); + } break; - case SoMouseButtonEvent::BUTTON2: - { - polyline.addNode(pos); - m_iXnew = pos.x(); m_iYnew = pos.y(); - m_iXold = pos.x(); m_iYold = pos.y(); - } - break; + case SoMouseButtonEvent::BUTTON2: { + polyline.addNode(pos); + m_iXnew = pos.x(); + m_iYnew = pos.y(); + m_iXold = pos.x(); + m_iYold = pos.y(); + } break; - default: - { - } break; + default: { + } break; } } // release else { - switch(button) - { - case SoMouseButtonEvent::BUTTON2: - { - QCursor cur = _pcView3D->getWidget()->cursor(); - _pcView3D->getWidget()->setCursor(m_cPrevCursor); + switch (button) { + case SoMouseButtonEvent::BUTTON2: { + QCursor cur = _pcView3D->getWidget()->cursor(); + _pcView3D->getWidget()->setCursor(m_cPrevCursor); - // The pop-up menu should be shown when releasing mouse button because - // otherwise the navigation style doesn't get the UP event and gets into - // an inconsistent state. - int id = popupMenu(); + // The pop-up menu should be shown when releasing mouse button because + // otherwise the navigation style doesn't get the UP event and gets into + // an inconsistent state. + int id = popupMenu(); - if (id == Finish || id == Cancel) { - releaseMouseModel(); - } - else if (id == Restart) { - _pcView3D->getWidget()->setCursor(cur); - } + if (id == Finish || id == Cancel) { + releaseMouseModel(); + } + else if (id == Restart) { + _pcView3D->getWidget()->setCursor(cur); + } - polyline.setWorking(false); - return id; - } - break; + polyline.setWorking(false); + return id; + } break; - default: - { - } break; + default: { + } break; } } @@ -301,22 +301,26 @@ int PolyPickerSelection::locationEvent(const SoLocation2Event* const, const QPoi qreal dpr = _pcView3D->getGLWidget()->devicePixelRatioF(); QRect r = _pcView3D->getGLWidget()->rect(); if (dpr != 1.0) { - r.setHeight(r.height()*dpr); - r.setWidth(r.width()*dpr); + r.setHeight(r.height() * dpr); + r.setWidth(r.width() * dpr); } if (!r.contains(clPoint)) { - if (clPoint.x() < r.left()) + if (clPoint.x() < r.left()) { clPoint.setX(r.left()); + } - if (clPoint.x() > r.right()) + if (clPoint.x() > r.right()) { clPoint.setX(r.right()); + } - if (clPoint.y() < r.top()) + if (clPoint.y() < r.top()) { clPoint.setY(r.top()); + } - if (clPoint.y() > r.bottom()) + if (clPoint.y() > r.bottom()) { clPoint.setY(r.bottom()); + } #ifdef FC_OS_WINDOWS QPoint newPos = _pcView3D->getGLWidget()->mapToGlobal(clPoint); @@ -324,8 +328,9 @@ int PolyPickerSelection::locationEvent(const SoLocation2Event* const, const QPoi #endif } - if (!lastConfirmed) + if (!lastConfirmed) { polyline.popNode(); + } polyline.addNode(clPoint); lastConfirmed = false; @@ -413,16 +418,20 @@ int FreehandSelection::popupMenu() menu.addAction(QObject::tr("Clear")); QAction* ca = menu.addAction(QObject::tr("Cancel")); - if (getPositions().size() < 3) + if (getPositions().size() < 3) { fi->setEnabled(false); + } QAction* id = menu.exec(QCursor::pos()); - if (id == fi) + if (id == fi) { return Finish; - else if (id == ca) + } + else if (id == ca) { return Cancel; - else + } + else { return Restart; + } } int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos) @@ -431,9 +440,8 @@ int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const const SbBool press = e->getState() == SoButtonEvent::DOWN ? true : false; if (press) { - switch(button) { - case SoMouseButtonEvent::BUTTON1: - { + switch (button) { + case SoMouseButtonEvent::BUTTON1: { if (!polyline.isWorking()) { polyline.setWorking(true); polyline.clear(); @@ -441,35 +449,34 @@ int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const polyline.addNode(pos); polyline.setCoords(pos.x(), pos.y()); - m_iXnew = pos.x(); m_iYnew = pos.y(); - m_iXold = pos.x(); m_iYold = pos.y(); - } - break; + m_iXnew = pos.x(); + m_iYnew = pos.y(); + m_iXold = pos.x(); + m_iYold = pos.y(); + } break; - case SoMouseButtonEvent::BUTTON2: - { - polyline.addNode(pos); - m_iXnew = pos.x(); m_iYnew = pos.y(); - m_iXold = pos.x(); m_iYold = pos.y(); - } - break; + case SoMouseButtonEvent::BUTTON2: { + polyline.addNode(pos); + m_iXnew = pos.x(); + m_iYnew = pos.y(); + m_iXold = pos.x(); + m_iYold = pos.y(); + } break; - default: - break; + default: + break; } } // release else { - switch(button) - { - case SoMouseButtonEvent::BUTTON1: - if (polyline.isWorking()) { - releaseMouseModel(); - return Finish; - } - break; - case SoMouseButtonEvent::BUTTON2: - { + switch (button) { + case SoMouseButtonEvent::BUTTON1: + if (polyline.isWorking()) { + releaseMouseModel(); + return Finish; + } + break; + case SoMouseButtonEvent::BUTTON2: { QCursor cur = _pcView3D->getWidget()->cursor(); _pcView3D->getWidget()->setCursor(m_cPrevCursor); @@ -487,11 +494,10 @@ int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const polyline.setWorking(false); return id; - } - break; + } break; - default: - break; + default: + break; } } @@ -508,29 +514,34 @@ int FreehandSelection::locationEvent(const SoLocation2Event* const e, const QPoi qreal dpr = _pcView3D->getGLWidget()->devicePixelRatioF(); QRect r = _pcView3D->getGLWidget()->rect(); if (dpr != 1.0) { - r.setHeight(r.height()*dpr); - r.setWidth(r.width()*dpr); + r.setHeight(r.height() * dpr); + r.setWidth(r.width() * dpr); } if (!r.contains(clPoint)) { - if (clPoint.x() < r.left()) + if (clPoint.x() < r.left()) { clPoint.setX(r.left()); + } - if (clPoint.x() > r.right()) + if (clPoint.x() > r.right()) { clPoint.setX(r.right()); + } - if (clPoint.y() < r.top()) + if (clPoint.y() < r.top()) { clPoint.setY(r.top()); + } - if (clPoint.y() > r.bottom()) + if (clPoint.y() > r.bottom()) { clPoint.setY(r.bottom()); + } } SbVec2s last = _clPoly.back(); SbVec2s curr = e->getPosition(); - if (abs(last[0]-curr[0]) > 20 || abs(last[1]-curr[1]) > 20) + if (abs(last[0] - curr[0]) > 20 || abs(last[1] - curr[1]) > 20) { _clPoly.push_back(curr); + } polyline.addNode(clPoint); polyline.setCoords(clPoint.x(), clPoint.y()); @@ -556,7 +567,7 @@ RubberbandSelection::~RubberbandSelection() = default; void RubberbandSelection::setColor(float r, float g, float b, float a) { - rubberband.setColor(r,g,b,a); + rubberband.setColor(r, g, b, a); } void RubberbandSelection::initialize() @@ -594,35 +605,28 @@ int RubberbandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, con int ret = Continue; if (press) { - switch(button) - { - case SoMouseButtonEvent::BUTTON1: - { - rubberband.setWorking(true); - m_iXold = m_iXnew = pos.x(); - m_iYold = m_iYnew = pos.y(); - } - break; + switch (button) { + case SoMouseButtonEvent::BUTTON1: { + rubberband.setWorking(true); + m_iXold = m_iXnew = pos.x(); + m_iYold = m_iYnew = pos.y(); + } break; - default: - { - } break; + default: { + } break; } } else { - switch(button) { - case SoMouseButtonEvent::BUTTON1: - { - rubberband.setWorking(false); - releaseMouseModel(); - _clPoly.push_back(e->getPosition()); - ret = Finish; - } - break; + switch (button) { + case SoMouseButtonEvent::BUTTON1: { + rubberband.setWorking(false); + releaseMouseModel(); + _clPoly.push_back(e->getPosition()); + ret = Finish; + } break; - default: - { - } break; + default: { + } break; } } @@ -645,9 +649,10 @@ int RubberbandSelection::keyboardEvent(const SoKeyboardEvent* const) // ----------------------------------------------------------------------------------- -RectangleSelection::RectangleSelection() : RubberbandSelection() +RectangleSelection::RectangleSelection() + : RubberbandSelection() { - rubberband.setColor(0.0,0.0,1.0,1.0); + rubberband.setColor(0.0, 0.0, 1.0, 1.0); } RectangleSelection::~RectangleSelection() = default; diff --git a/src/Gui/OnlineDocumentation.cpp b/src/Gui/OnlineDocumentation.cpp index 793d1d9bb1..3ec8517057 100644 --- a/src/Gui/OnlineDocumentation.cpp +++ b/src/Gui/OnlineDocumentation.cpp @@ -22,11 +22,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #endif #include @@ -39,6 +39,7 @@ using namespace Gui; // the favicon +// clang-format off // NOLINTBEGIN static const unsigned int navicon_data_len = 318; static const unsigned char navicon_data[] = { @@ -66,6 +67,7 @@ static const unsigned char navicon_data[] = { 0x9c,0x3d,0x00,0x00,0x9f,0xfd,0x00,0x00,0x80,0xfd,0x00,0x00,0xff,0x7d, 0x00,0x00,0xfe,0x01,0x00,0x00,0xff,0x7f,0x00,0x00}; // NOLINTEND +// clang-format on PythonOnlineHelp::PythonOnlineHelp() = default; @@ -103,7 +105,7 @@ QByteArray PythonOnlineHelp::loadFavicon() const else { // fallback res.reserve(navicon_data_len); - for (int i=0; i<(int)navicon_data_len;i++) { + for (int i = 0; i < (int)navicon_data_len; i++) { res[i] = navicon_data[i]; } } @@ -175,7 +177,8 @@ QByteArray PythonOnlineHelp::fileNotFound() const "" "" "" + " 
FreeCAD " + "Documentation
" "
 
" - " 
FreeCAD Documentation
" " 
" "

" @@ -184,13 +187,13 @@ QByteArray PythonOnlineHelp::fileNotFound() const "

" "" "" - "\r\n" - ); + "\r\n"); QString header = QString::fromLatin1("content-type: %1\r\n").arg(contentType); QString http(QLatin1String("HTTP/1.1 %1 %2\r\n%3\r\n")); - QString httpResponseHeader = http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header); + QString httpResponseHeader = + http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header); QByteArray res = httpResponseHeader.toLatin1(); return res; @@ -199,37 +202,40 @@ QByteArray PythonOnlineHelp::fileNotFound() const QByteArray PythonOnlineHelp::loadFailed(const QString& error) const { const int pageNotFound = 404; - QString contentType = QString::fromLatin1( - "text/html\r\n" - "\r\n" - "Error" - "" - "" - "" - "" - "
 
" - " 
FreeCAD Documentation
" - " 
" - "

" - "

%1

" - "" - "" - "\r\n" - ).arg(error); + QString contentType = + QString::fromLatin1( + "text/html\r\n" + "\r\n" + "Error" + "" + "" + "" + "" + "
 
" + " 
FreeCAD " + "Documentation
" + " 
" + "

" + "

%1

" + "" + "" + "\r\n") + .arg(error); QString header = QString::fromLatin1("content-type: %1\r\n").arg(contentType); QString http(QLatin1String("HTTP/1.1 %1 %2\r\n%3\r\n")); - QString httpResponseHeader = http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header); + QString httpResponseHeader = + http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header); QByteArray res = httpResponseHeader.toLatin1(); return res; } HttpServer::HttpServer(QObject* parent) - : QTcpServer(parent), disabled(false) -{ -} + : QTcpServer(parent) + , disabled(false) +{} void HttpServer::incomingConnection(qintptr socket) { @@ -279,8 +285,8 @@ void HttpServer::readClient() QString p = lst[1]; if (lst.count() > 2) { QString v = lst[2]; - if (v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") && - v[5].isDigit() && v[6] == QLatin1Char('.') && v[7].isDigit()) { + if (v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") && v[5].isDigit() + && v[6] == QLatin1Char('.') && v[7].isDigit()) { method = m; path = p; } @@ -293,7 +299,7 @@ void HttpServer::readClient() socket->write(help.loadResource(path)); socket->close(); if (socket->state() == QTcpSocket::UnconnectedState) { - //mark the socket for deletion but do not destroy immediately + // mark the socket for deletion but do not destroy immediately socket->deleteLater(); } } @@ -312,14 +318,15 @@ void HttpServer::discardClient() /* TRANSLATOR Gui::StdCmdPythonHelp */ StdCmdPythonHelp::StdCmdPythonHelp() - : Command("Std_PythonHelp"), server(nullptr) + : Command("Std_PythonHelp") + , server(nullptr) { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Automatic Python modules documentation"); - sToolTipText = QT_TR_NOOP("Opens a browser to show the Python modules documentation"); - sWhatsThis = "Std_PythonHelp"; - sStatusTip = QT_TR_NOOP("Opens a browser to show the Python modules documentation"); - sPixmap = "applications-python"; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Automatic Python modules documentation"); + sToolTipText = QT_TR_NOOP("Opens a browser to show the Python modules documentation"); + sWhatsThis = "Std_PythonHelp"; + sStatusTip = QT_TR_NOOP("Opens a browser to show the Python modules documentation"); + sPixmap = "applications-python"; } StdCmdPythonHelp::~StdCmdPythonHelp() @@ -340,19 +347,22 @@ void StdCmdPythonHelp::activated(int iMsg) } // if server is not yet running try to open one - if (this->server->isListening() || - this->server->listen(QHostAddress(QHostAddress::LocalHost), port)) { + if (this->server->isListening() + || this->server->listen(QHostAddress(QHostAddress::LocalHost), port)) { std::string url = "http://localhost:"; url += std::to_string(port); OpenURLInBrowser(url.c_str()); } else { - QMessageBox::critical(Gui::getMainWindow(), QObject::tr("No Server"), - QObject::tr("Unable to start the server to port %1: %2.").arg(port).arg(server->errorString())); + QMessageBox::critical(Gui::getMainWindow(), + QObject::tr("No Server"), + QObject::tr("Unable to start the server to port %1: %2.") + .arg(port) + .arg(server->errorString())); } } -bool Gui::OpenURLInBrowser(const char * URL) +bool Gui::OpenURLInBrowser(const char* URL) { // The webbrowser Python module allows to start the system browser in an OS-independent way Base::PyGILStateLocker lock; @@ -368,12 +378,12 @@ bool Gui::OpenURLInBrowser(const char * URL) } catch (Py::Exception& e) { e.clear(); - QMessageBox::critical(Gui::getMainWindow(), QObject::tr("No Browser"), - QObject::tr("Unable to open your system browser.")); + QMessageBox::critical(Gui::getMainWindow(), + QObject::tr("No Browser"), + QObject::tr("Unable to open your system browser.")); return false; } } #include "moc_OnlineDocumentation.cpp" - diff --git a/src/Gui/PreferencePages/DlgSettingsEditor.cpp b/src/Gui/PreferencePages/DlgSettingsEditor.cpp index f260886f8d..5f92058c18 100644 --- a/src/Gui/PreferencePages/DlgSettingsEditor.cpp +++ b/src/Gui/PreferencePages/DlgSettingsEditor.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -37,14 +37,16 @@ using namespace Gui; using namespace Gui::Dialog; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ struct DlgSettingsEditorP { - QVector > colormap; // Color map + QVector> colormap; // Color map }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui namespace { @@ -58,20 +60,24 @@ namespace QFont getMonospaceFont() { QFont font(QString::fromLatin1("monospace")); - if (font.fixedPitch()) + if (font.fixedPitch()) { return font; + } font.setStyleHint(QFont::Monospace); - if (font.fixedPitch()) + if (font.fixedPitch()) { return font; + } font.setStyleHint(QFont::TypeWriter); - if (font.fixedPitch()) + if (font.fixedPitch()) { return font; + } font.setFamily(QString::fromLatin1("courier")); - if (font.fixedPitch()) + if (font.fixedPitch()) { return font; - return font; // We failed, but return whatever we have anyway -} + } + return font; // We failed, but return whatever we have anyway } +} // namespace /* TRANSLATOR Gui::Dialog::DlgSettingsEditor */ @@ -82,12 +88,12 @@ QFont getMonospaceFont() * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgSettingsEditor::DlgSettingsEditor( QWidget* parent ) - : PreferencePage( parent ) - , ui(new Ui_DlgSettingsEditor) +DlgSettingsEditor::DlgSettingsEditor(QWidget* parent) + : PreferencePage(parent) + , ui(new Ui_DlgSettingsEditor) { ui->setupUi(this); - ui->EnableFolding->hide(); // Switch off until we have an editor with folding + ui->EnableFolding->hide(); // Switch off until we have an editor with folding setupConnections(); @@ -101,70 +107,71 @@ DlgSettingsEditor::DlgSettingsEditor( QWidget* parent ) QColor col; col = qApp->palette().windowText().color(); unsigned int lText = App::Color::asPackedRGB(col); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Text")), lText)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Text")), lText)); unsigned int lBookmarks = App::Color::asPackedRGB(QColor(Qt::cyan)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Bookmark")), lBookmarks)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Bookmark")), lBookmarks)); unsigned int lBreakpnts = App::Color::asPackedRGB(QColor(Qt::red)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Breakpoint")), lBreakpnts)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Breakpoint")), lBreakpnts)); unsigned int lKeywords = App::Color::asPackedRGB(QColor(Qt::blue)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Keyword")), lKeywords)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Keyword")), lKeywords)); unsigned int lComments = App::Color::asPackedRGB(QColor(0, 170, 0)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Comment")), lComments)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Comment")), lComments)); unsigned int lBlockCom = App::Color::asPackedRGB(QColor(160, 160, 164)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Block comment")), lBlockCom)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Block comment")), lBlockCom)); unsigned int lNumbers = App::Color::asPackedRGB(QColor(Qt::blue)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Number")), lNumbers)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Number")), lNumbers)); unsigned int lStrings = App::Color::asPackedRGB(QColor(Qt::red)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("String")), lStrings)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("String")), lStrings)); unsigned int lCharacter = App::Color::asPackedRGB(QColor(Qt::red)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Character")), lCharacter)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Character")), lCharacter)); unsigned int lClass = App::Color::asPackedRGB(QColor(255, 170, 0)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Class name")), lClass)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Class name")), lClass)); unsigned int lDefine = App::Color::asPackedRGB(QColor(255, 170, 0)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Define name")), lDefine)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Define name")), lDefine)); unsigned int lOperat = App::Color::asPackedRGB(QColor(160, 160, 164)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Operator")), lOperat)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Operator")), lOperat)); unsigned int lPyOutput = App::Color::asPackedRGB(QColor(170, 170, 127)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Python output")), lPyOutput)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Python output")), lPyOutput)); unsigned int lPyError = App::Color::asPackedRGB(QColor(Qt::red)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Python error")), lPyError)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Python error")), lPyError)); unsigned int lCLine = App::Color::asPackedRGB(QColor(224, 224, 224)); - d->colormap.push_back(QPair - (QString::fromLatin1(QT_TR_NOOP("Current line highlight")), lCLine)); + d->colormap.push_back( + QPair(QString::fromLatin1(QT_TR_NOOP("Current line highlight")), + lCLine)); - QStringList labels; labels << tr("Items"); + QStringList labels; + labels << tr("Items"); ui->displayItems->setHeaderLabels(labels); ui->displayItems->header()->hide(); - for (const auto &[textType, textColor]: d->colormap) - { + for (const auto& [textType, textColor] : d->colormap) { auto item = new QTreeWidgetItem(ui->displayItems); item->setText(0, tr(textType.toLatin1())); } @@ -182,6 +189,7 @@ DlgSettingsEditor::~DlgSettingsEditor() void DlgSettingsEditor::setupConnections() { + // clang-format off connect(ui->displayItems, &QTreeWidget::currentItemChanged, this, &DlgSettingsEditor::onDisplayItemsCurrentItemChanged); connect(ui->colorButton, &ColorButton::changed, @@ -197,13 +205,14 @@ void DlgSettingsEditor::setupConnections() connect(ui->fontSize, &PrefSpinBox::textChanged, this, &DlgSettingsEditor::onFontSizeValueChanged); #endif + // clang-format on } /** Searches for the color value corresponding to \e name in current editor * settings ColorMap and assigns it to the color button * @see Gui::ColorButton */ -void DlgSettingsEditor::onDisplayItemsCurrentItemChanged(QTreeWidgetItem *item) +void DlgSettingsEditor::onDisplayItemsCurrentItemChanged(QTreeWidgetItem* item) { int index = ui->displayItems->indexOfTopLevelItem(item); unsigned int col = d->colormap[index].second; @@ -218,7 +227,7 @@ void DlgSettingsEditor::onColorButtonChanged() int index = ui->displayItems->indexOfTopLevelItem(ui->displayItems->currentItem()); d->colormap[index].second = lcol; - pythonSyntax->setColor( d->colormap[index].first, col ); + pythonSyntax->setColor(d->colormap[index].first, col); } void DlgSettingsEditor::setEditorTabWidth(int tabWidth) @@ -244,13 +253,12 @@ void DlgSettingsEditor::saveSettings() // Saves the color map ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("Editor"); - for (const auto &[textType, textColor] : d->colormap) - { + for (const auto& [textType, textColor] : d->colormap) { auto col = static_cast(textColor); hGrp->SetUnsigned(textType.toLatin1(), col); } - hGrp->SetInt( "FontSize", ui->fontSize->value() ); - hGrp->SetASCII( "Font", ui->fontFamily->currentText().toLatin1() ); + hGrp->SetInt("FontSize", ui->fontSize->value()); + hGrp->SetASCII("Font", ui->fontFamily->currentText().toLatin1()); setEditorTabWidth(ui->tabSize->value()); } @@ -281,8 +289,7 @@ void DlgSettingsEditor::loadSettings() // Restores the color map ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("Editor"); - for (auto &[textType, textColor] : d->colormap) - { + for (auto& [textType, textColor] : d->colormap) { auto col = static_cast(textColor); col = hGrp->GetUnsigned(textType.toLatin1(), col); textColor = static_cast(col); @@ -300,7 +307,7 @@ void DlgSettingsEditor::loadSettings() #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QStringList familyNames = QFontDatabase().families(QFontDatabase::Any); QStringList fixedFamilyNames; - for (const auto &name : familyNames) { + for (const auto& name : familyNames) { if (QFontDatabase().isFixedPitch(name)) { if (name.compare(QLatin1String("8514oem"), Qt::CaseInsensitive) != 0) { fixedFamilyNames.append(name); @@ -310,7 +317,7 @@ void DlgSettingsEditor::loadSettings() #else QStringList familyNames = QFontDatabase::families(QFontDatabase::Any); QStringList fixedFamilyNames; - for (const auto &name : familyNames) { + for (const auto& name : familyNames) { if (QFontDatabase::isFixedPitch(name)) { if (name.compare(QLatin1String("8514oem"), Qt::CaseInsensitive) != 0) { fixedFamilyNames.append(name); @@ -321,8 +328,9 @@ void DlgSettingsEditor::loadSettings() ui->fontFamily->addItems(fixedFamilyNames); int index = fixedFamilyNames.indexOf( QString::fromLatin1(hGrp->GetASCII("Font", defaultMonospaceFont).c_str())); - if (index < 0) + if (index < 0) { index = 0; + } ui->fontFamily->setCurrentIndex(index); onFontFamilyActivated(ui->fontFamily->currentText()); ui->displayItems->setCurrentItem(ui->displayItems->topLevelItem(0)); @@ -332,31 +340,32 @@ void DlgSettingsEditor::resetSettingsToDefaults() { ParameterGrp::handle hGrp; hGrp = WindowParameter::getDefaultParameter()->GetGroup("Editor"); - //reset the parameters in the "Editor" group - for (const auto &[textType, textColor] : d->colormap) - { + // reset the parameters in the "Editor" group + for (const auto& [textType, textColor] : d->colormap) { hGrp->RemoveUnsigned(textType.toLatin1()); } - //reset "FontSize" parameter + // reset "FontSize" parameter hGrp->RemoveInt("FontSize"); - //reset "Font" parameter + // reset "Font" parameter hGrp->RemoveASCII("Font"); - //finally reset all the parameters associated to Gui::Pref* widgets + // finally reset all the parameters associated to Gui::Pref* widgets PreferencePage::resetSettingsToDefaults(); } /** * Sets the strings of the subwidgets using the current language. */ -void DlgSettingsEditor::changeEvent(QEvent *e) +void DlgSettingsEditor::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { int index = 0; - for (const auto &[textType, textColor]: d->colormap) + for (const auto& [textType, textColor] : d->colormap) { ui->displayItems->topLevelItem(index++)->setText(0, tr(textType.toLatin1())); + } ui->retranslateUi(this); - } else { + } + else { QWidget::changeEvent(e); } } diff --git a/src/Gui/PreferencePages/DlgSettingsViewColor.cpp b/src/Gui/PreferencePages/DlgSettingsViewColor.cpp index 4f3c7d2209..4e0e647e77 100644 --- a/src/Gui/PreferencePages/DlgSettingsViewColor.cpp +++ b/src/Gui/PreferencePages/DlgSettingsViewColor.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include "DlgSettingsViewColor.h" @@ -41,6 +41,7 @@ DlgSettingsViewColor::DlgSettingsViewColor(QWidget* parent) : PreferencePage(parent) , ui(new Ui_DlgSettingsViewColor) { + // clang-format off ui->setupUi(this); connect(ui->SwitchGradientColors, &QPushButton::pressed, this, &DlgSettingsViewColor::onSwitchGradientColorsPressed); @@ -56,6 +57,7 @@ DlgSettingsViewColor::DlgSettingsViewColor(QWidget* parent) connect(ui->checkMidColor, &QCheckBox::toggled, this, &DlgSettingsViewColor::onCheckMidColorToggled); + // clang-format on } /** @@ -93,19 +95,22 @@ void DlgSettingsViewColor::loadSettings() ui->TreeActiveColor->onRestore(); ui->CbLabelColor->onRestore(); ui->CbLabelTextSize->onRestore(); - - if (ui->radioButtonSimple->isChecked()) + + if (ui->radioButtonSimple->isChecked()) { onRadioButtonSimpleToggled(true); - else if(ui->radioButtonGradient->isChecked()) + } + else if (ui->radioButtonGradient->isChecked()) { onRadioButtonGradientToggled(true); - else + } + else { onRadioButtonRadialGradientToggled(true); + } } /** * Sets the strings of the subwidgets using the current language. */ -void DlgSettingsViewColor::changeEvent(QEvent *e) +void DlgSettingsViewColor::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -161,8 +166,9 @@ void DlgSettingsViewColor::setGradientColorVisibility(bool val) ui->checkMidColor->setVisible(val); ui->SwitchGradientColors->setVisible(val); - if (val) + if (val) { onCheckMidColorToggled(ui->checkMidColor->isChecked()); + } } #include "moc_DlgSettingsViewColor.cpp" diff --git a/src/Gui/SelectionView.cpp b/src/Gui/SelectionView.cpp index 0e7aab2dfe..aa5c0c08a0 100644 --- a/src/Gui/SelectionView.cpp +++ b/src/Gui/SelectionView.cpp @@ -22,15 +22,15 @@ #include "PreCompiled.h" #ifndef _PreComp_ - #include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include @@ -52,11 +52,13 @@ using namespace Gui::DockWnd; /* TRANSLATOR Gui::DockWnd::SelectionView */ -SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent) - : DockWindow(pcDocument,parent) - , SelectionObserver(true, ResolveMode::NoResolve) - , x(0.0f), y(0.0f), z(0.0f) - , openedAutomatically(false) +SelectionView::SelectionView(Gui::Document* pcDocument, QWidget* parent) + : DockWindow(pcDocument, parent) + , SelectionObserver(true, ResolveMode::NoResolve) + , x(0.0f) + , y(0.0f) + , z(0.0f) + , openedAutomatically(false) { setWindowTitle(tr("Selection View")); @@ -80,13 +82,13 @@ SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent) countLabel->setText(QString::fromUtf8("0")); countLabel->setToolTip(tr("The number of selected items")); hLayout->addWidget(searchBox); - hLayout->addWidget(clearButton,0,Qt::AlignRight); - hLayout->addWidget(countLabel,0,Qt::AlignRight); + hLayout->addWidget(clearButton, 0, Qt::AlignRight); + hLayout->addWidget(countLabel, 0, Qt::AlignRight); vLayout->addLayout(hLayout); selectionView = new QListWidget(this); selectionView->setContextMenuPolicy(Qt::CustomContextMenu); - vLayout->addWidget( selectionView ); + vLayout->addWidget(selectionView); enablePickList = new QCheckBox(this); enablePickList->setText(tr("Picked object list")); @@ -95,11 +97,12 @@ SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent) pickList->setVisible(false); vLayout->addWidget(pickList); - selectionView->setMouseTracking(true); // needed for itemEntered() to work + selectionView->setMouseTracking(true); // needed for itemEntered() to work pickList->setMouseTracking(true); resize(200, 200); + // clang-format off connect(clearButton, &QToolButton::clicked, searchBox, &QLineEdit::clear); connect(searchBox, &QLineEdit::textChanged, this, &SelectionView::search); connect(searchBox, &QLineEdit::editingFinished, this, &SelectionView::validateSearch); @@ -109,11 +112,12 @@ SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent) connect(pickList, &QListWidget::itemEntered, this, &SelectionView::preselect); connect(selectionView, &QListWidget::customContextMenuRequested, this, &SelectionView::onItemContextMenu); connect(enablePickList, &QCheckBox::stateChanged, this, &SelectionView::onEnablePickList); + // clang-format on } SelectionView::~SelectionView() = default; -void SelectionView::leaveEvent(QEvent *) +void SelectionView::leaveEvent(QEvent*) { Selection().rmvPreselect(); } @@ -279,7 +283,7 @@ void SelectionView::search(const QString& text) selectionView->clear(); for (auto it : objects) { QString label = QString::fromUtf8(it->Label.getValue()); - if (label.contains(text,Qt::CaseInsensitive)) { + if (label.contains(text, Qt::CaseInsensitive)) { searchList.push_back(it); // save as user data QString selObject; @@ -310,7 +314,7 @@ void SelectionView::validateSearch() if (doc) { Gui::Selection().clearSelection(); for (auto it : searchList) { - Gui::Selection().addSelection(doc->getName(),it->getNameInDocument(),nullptr); + Gui::Selection().addSelection(doc->getName(), it->getNameInDocument(), nullptr); } } } @@ -318,110 +322,141 @@ void SelectionView::validateSearch() void SelectionView::select(QListWidgetItem* item) { - if (!item) + if (!item) { item = selectionView->currentItem(); - if (!item) + } + if (!item) { return; + } QStringList elements = item->data(Qt::UserRole).toStringList(); - if (elements.size() < 2) + if (elements.size() < 2) { return; + } try { - //Gui::Selection().clearSelection(); - Gui::Command::runCommand(Gui::Command::Gui,"Gui.Selection.clearSelection()"); - //Gui::Selection().addSelection(elements[0].toLatin1(),elements[1].toLatin1(),0); - QString cmd = QString::fromLatin1(R"(Gui.Selection.addSelection(App.getDocument("%1").getObject("%2")))").arg(elements[0],elements[1]); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); - }catch(Base::Exception &e) { + // Gui::Selection().clearSelection(); + Gui::Command::runCommand(Gui::Command::Gui, "Gui.Selection.clearSelection()"); + // Gui::Selection().addSelection(elements[0].toLatin1(),elements[1].toLatin1(),0); + QString cmd = QString::fromLatin1( + R"(Gui.Selection.addSelection(App.getDocument("%1").getObject("%2")))") + .arg(elements[0], elements[1]); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); + } + catch (Base::Exception& e) { e.ReportException(); } } void SelectionView::deselect() { - QListWidgetItem *item = selectionView->currentItem(); - if (!item) + QListWidgetItem* item = selectionView->currentItem(); + if (!item) { return; + } QStringList elements = item->data(Qt::UserRole).toStringList(); - if (elements.size() < 2) + if (elements.size() < 2) { return; + } - //Gui::Selection().rmvSelection(elements[0].toLatin1(),elements[1].toLatin1(),0); - QString cmd = QString::fromLatin1(R"(Gui.Selection.removeSelection(App.getDocument("%1").getObject("%2")))").arg(elements[0],elements[1]); + // Gui::Selection().rmvSelection(elements[0].toLatin1(),elements[1].toLatin1(),0); + QString cmd = QString::fromLatin1( + R"(Gui.Selection.removeSelection(App.getDocument("%1").getObject("%2")))") + .arg(elements[0], elements[1]); try { - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); - }catch(Base::Exception &e) { + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); + } + catch (Base::Exception& e) { e.ReportException(); } } void SelectionView::toggleSelect(QListWidgetItem* item) { - if (!item) + if (!item) { return; + } std::string name = item->text().toLatin1().constData(); - char *docname = &name.at(0); - char *objname = std::strchr(docname,'#'); - if(!objname) + char* docname = &name.at(0); + char* objname = std::strchr(docname, '#'); + if (!objname) { return; + } *objname++ = 0; - char *subname = std::strchr(objname,'.'); - if(subname) { + char* subname = std::strchr(objname, '.'); + if (subname) { *subname++ = 0; - char *end = std::strchr(subname,' '); - if(end) *end = 0; - }else { - char *end = std::strchr(objname,' '); - if(end) *end = 0; + char* end = std::strchr(subname, ' '); + if (end) { + *end = 0; + } + } + else { + char* end = std::strchr(objname, ' '); + if (end) { + *end = 0; + } } QString cmd; - if(Gui::Selection().isSelected(docname,objname,subname)) + if (Gui::Selection().isSelected(docname, objname, subname)) { cmd = QString::fromLatin1("Gui.Selection.removeSelection(" - "App.getDocument('%1').getObject('%2'),'%3')") - .arg(QString::fromLatin1(docname), - QString::fromLatin1(objname), - QString::fromLatin1(subname)); - else + "App.getDocument('%1').getObject('%2'),'%3')") + .arg(QString::fromLatin1(docname), + QString::fromLatin1(objname), + QString::fromLatin1(subname)); + } + else { cmd = QString::fromLatin1("Gui.Selection.addSelection(" - "App.getDocument('%1').getObject('%2'),'%3',%4,%5,%6)") - .arg(QString::fromLatin1(docname), - QString::fromLatin1(objname), - QString::fromLatin1(subname)) - .arg(x).arg(y).arg(z); + "App.getDocument('%1').getObject('%2'),'%3',%4,%5,%6)") + .arg(QString::fromLatin1(docname), + QString::fromLatin1(objname), + QString::fromLatin1(subname)) + .arg(x) + .arg(y) + .arg(z); + } try { - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); - }catch(Base::Exception &e) { + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); + } + catch (Base::Exception& e) { e.ReportException(); } } void SelectionView::preselect(QListWidgetItem* item) { - if (!item) + if (!item) { return; + } std::string name = item->text().toLatin1().constData(); - char *docname = &name.at(0); - char *objname = std::strchr(docname,'#'); - if(!objname) + char* docname = &name.at(0); + char* objname = std::strchr(docname, '#'); + if (!objname) { return; + } *objname++ = 0; - char *subname = std::strchr(objname,'.'); - if(subname) { + char* subname = std::strchr(objname, '.'); + if (subname) { *subname++ = 0; - char *end = std::strchr(subname,' '); - if(end) *end = 0; - }else { - char *end = std::strchr(objname,' '); - if(end) *end = 0; + char* end = std::strchr(subname, ' '); + if (end) { + *end = 0; + } + } + else { + char* end = std::strchr(objname, ' '); + if (end) { + *end = 0; + } } QString cmd = QString::fromLatin1("Gui.Selection.setPreselection(" - "App.getDocument('%1').getObject('%2'),'%3',tp=2)") - .arg(QString::fromLatin1(docname), - QString::fromLatin1(objname), - QString::fromLatin1(subname)); + "App.getDocument('%1').getObject('%2'),'%3',tp=2)") + .arg(QString::fromLatin1(docname), + QString::fromLatin1(objname), + QString::fromLatin1(subname)); try { - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); - }catch(Base::Exception &e) { + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); + } + catch (Base::Exception& e) { e.ReportException(); } } @@ -430,8 +465,9 @@ void SelectionView::zoom() { select(); try { - Gui::Command::runCommand(Gui::Command::Gui,"Gui.SendMsgToActiveView(\"ViewSelection\")"); - }catch(Base::Exception &e) { + Gui::Command::runCommand(Gui::Command::Gui, "Gui.SendMsgToActiveView(\"ViewSelection\")"); + } + catch (Base::Exception& e) { e.ReportException(); } } @@ -440,53 +476,61 @@ void SelectionView::treeSelect() { select(); try { - Gui::Command::runCommand(Gui::Command::Gui,"Gui.runCommand(\"Std_TreeSelection\")"); - }catch(Base::Exception &e) { + Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand(\"Std_TreeSelection\")"); + } + catch (Base::Exception& e) { e.ReportException(); } } void SelectionView::touch() { - QListWidgetItem *item = selectionView->currentItem(); - if (!item) + QListWidgetItem* item = selectionView->currentItem(); + if (!item) { return; + } QStringList elements = item->data(Qt::UserRole).toStringList(); - if (elements.size() < 2) + if (elements.size() < 2) { return; - QString cmd = QString::fromLatin1(R"(App.getDocument("%1").getObject("%2").touch())").arg(elements[0],elements[1]); + } + QString cmd = QString::fromLatin1(R"(App.getDocument("%1").getObject("%2").touch())") + .arg(elements[0], elements[1]); try { - Gui::Command::runCommand(Gui::Command::Doc,cmd.toLatin1()); - }catch(Base::Exception &e) { + Gui::Command::runCommand(Gui::Command::Doc, cmd.toLatin1()); + } + catch (Base::Exception& e) { e.ReportException(); } } void SelectionView::toPython() { - QListWidgetItem *item = selectionView->currentItem(); - if (!item) + QListWidgetItem* item = selectionView->currentItem(); + if (!item) { return; + } QStringList elements = item->data(Qt::UserRole).toStringList(); - if (elements.size() < 2) + if (elements.size() < 2) { return; + } try { - QString cmd = QString::fromLatin1(R"(obj = App.getDocument("%1").getObject("%2"))").arg(elements[0], elements[1]); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + QString cmd = QString::fromLatin1(R"(obj = App.getDocument("%1").getObject("%2"))") + .arg(elements[0], elements[1]); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); if (elements.length() > 2) { App::Document* doc = App::GetApplication().getDocument(elements[0].toLatin1()); App::DocumentObject* obj = doc->getObject(elements[1].toLatin1()); QString property = getProperty(obj); cmd = QString::fromLatin1(R"(shp = App.getDocument("%1").getObject("%2").%3)") - .arg(elements[0], elements[1], property); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + .arg(elements[0], elements[1], property); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); if (supportPart(obj, elements[2])) { cmd = QString::fromLatin1(R"(elt = App.getDocument("%1").getObject("%2").%3.%4)") - .arg(elements[0], elements[1], property, elements[2]); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + .arg(elements[0], elements[1], property, elements[2]); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } } } @@ -497,9 +541,10 @@ void SelectionView::toPython() void SelectionView::showPart() { - QListWidgetItem *item = selectionView->currentItem(); - if (!item) + QListWidgetItem* item = selectionView->currentItem(); + if (!item) { return; + } QStringList elements = item->data(Qt::UserRole).toStringList(); if (elements.length() > 2) { App::Document* doc = App::GetApplication().getDocument(elements[0].toLatin1()); @@ -509,9 +554,10 @@ void SelectionView::showPart() if (!module.isEmpty() && !property.isEmpty() && supportPart(obj, elements[2])) { try { Gui::Command::addModule(Gui::Command::Gui, module.toLatin1()); - QString cmd = QString::fromLatin1(R"(%1.show(App.getDocument("%2").getObject("%3").%4.%5))") + QString cmd = + QString::fromLatin1(R"(%1.show(App.getDocument("%2").getObject("%3").%4.%5))") .arg(module, elements[0], elements[1], property, elements[2]); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } catch (const Base::Exception& e) { e.ReportException(); @@ -532,12 +578,15 @@ QString SelectionView::getModule(const char* type) const std::string::size_type pos = temp.find_first_of("::"); std::string module; - if (pos != std::string::npos) - module = std::string(temp,0,pos); - if (module != "App") + if (pos != std::string::npos) { + module = std::string(temp, 0, pos); + } + if (module != "App") { prefix = module; - else + } + else { break; + } typeId = typeId.getParent(); } @@ -568,8 +617,9 @@ bool SelectionView::supportPart(App::DocumentObject* obj, const QString& part) c const Data::ComplexGeoData* geometry = data->getComplexData(); std::vector types = geometry->getElementTypes(); for (auto it : types) { - if (part.startsWith(QString::fromLatin1(it))) + if (part.startsWith(QString::fromLatin1(it))) { return true; + } } } } @@ -579,39 +629,43 @@ bool SelectionView::supportPart(App::DocumentObject* obj, const QString& part) c void SelectionView::onItemContextMenu(const QPoint& point) { - QListWidgetItem *item = selectionView->itemAt(point); - if (!item) + QListWidgetItem* item = selectionView->itemAt(point); + if (!item) { return; + } QMenu menu; - QAction *selectAction = menu.addAction(tr("Select only"), this, [&]{ + QAction* selectAction = menu.addAction(tr("Select only"), this, [&] { this->select(nullptr); }); selectAction->setIcon(QIcon::fromTheme(QString::fromLatin1("view-select"))); selectAction->setToolTip(tr("Selects only this object")); - QAction *deselectAction = menu.addAction(tr("Deselect"), this, &SelectionView::deselect); + QAction* deselectAction = menu.addAction(tr("Deselect"), this, &SelectionView::deselect); deselectAction->setIcon(QIcon::fromTheme(QString::fromLatin1("view-unselectable"))); deselectAction->setToolTip(tr("Deselects this object")); - QAction *zoomAction = menu.addAction(tr("Zoom fit"), this, &SelectionView::zoom); + QAction* zoomAction = menu.addAction(tr("Zoom fit"), this, &SelectionView::zoom); zoomAction->setIcon(QIcon::fromTheme(QString::fromLatin1("zoom-fit-best"))); zoomAction->setToolTip(tr("Selects and fits this object in the 3D window")); - QAction *gotoAction = menu.addAction(tr("Go to selection"), this, &SelectionView::treeSelect); + QAction* gotoAction = menu.addAction(tr("Go to selection"), this, &SelectionView::treeSelect); gotoAction->setToolTip(tr("Selects and locates this object in the tree view")); - QAction *touchAction = menu.addAction(tr("Mark to recompute"), this, &SelectionView::touch); + QAction* touchAction = menu.addAction(tr("Mark to recompute"), this, &SelectionView::touch); touchAction->setIcon(QIcon::fromTheme(QString::fromLatin1("view-refresh"))); touchAction->setToolTip(tr("Mark this object to be recomputed")); - QAction *toPythonAction = menu.addAction(tr("To python console"), this, &SelectionView::toPython); + QAction* toPythonAction = + menu.addAction(tr("To python console"), this, &SelectionView::toPython); toPythonAction->setIcon(QIcon::fromTheme(QString::fromLatin1("applications-python"))); - toPythonAction->setToolTip(tr("Reveals this object and its subelements in the python console.")); + toPythonAction->setToolTip( + tr("Reveals this object and its subelements in the python console.")); QStringList elements = item->data(Qt::UserRole).toStringList(); if (elements.length() > 2) { // subshape-specific entries - QAction *showPart = menu.addAction(tr("Duplicate subshape"), this, &SelectionView::showPart); + QAction* showPart = + menu.addAction(tr("Duplicate subshape"), this, &SelectionView::showPart); showPart->setIcon(QIcon(QString::fromLatin1(":/icons/ClassBrowser/member.svg"))); showPart->setToolTip(tr("Creates a standalone copy of this subshape in the document")); } @@ -619,24 +673,26 @@ void SelectionView::onItemContextMenu(const QPoint& point) } void SelectionView::onUpdate() -{ -} +{} -bool SelectionView::onMsg(const char* /*pMsg*/,const char** /*ppReturn*/) +bool SelectionView::onMsg(const char* /*pMsg*/, const char** /*ppReturn*/) { return false; } -void SelectionView::hideEvent(QHideEvent *ev) { +void SelectionView::hideEvent(QHideEvent* ev) +{ DockWindow::hideEvent(ev); } -void SelectionView::showEvent(QShowEvent *ev) { +void SelectionView::showEvent(QShowEvent* ev) +{ enablePickList->setChecked(Selection().needPickedList()); Gui::DockWindow::showEvent(ev); } -void SelectionView::onEnablePickList() { +void SelectionView::onEnablePickList() +{ bool enabled = enablePickList->isChecked(); Selection().enablePickedList(enabled); pickList->setVisible(enabled); diff --git a/src/Gui/TaskView/TaskAppearance.cpp b/src/Gui/TaskView/TaskAppearance.cpp index 6acbef72e4..ebeaab46d2 100644 --- a/src/Gui/TaskView/TaskAppearance.cpp +++ b/src/Gui/TaskView/TaskAppearance.cpp @@ -39,8 +39,8 @@ namespace sp = std::placeholders; /* TRANSLATOR Gui::TaskView::TaskAppearance */ -TaskAppearance::TaskAppearance(QWidget *parent) - : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Appearance"),true, parent) +TaskAppearance::TaskAppearance(QWidget* parent) + : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Appearance"), true, parent) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -55,11 +55,10 @@ TaskAppearance::TaskAppearance(QWidget *parent) this->groupLayout()->addWidget(proxy); Gui::Selection().Attach(this); - //NOLINTBEGIN - this->connectChangedObject = - Gui::Application::Instance->signalChangedObject.connect(std::bind - (&TaskAppearance::slotChangedObject, this, sp::_1, sp::_2)); - //NOLINTEND + // NOLINTBEGIN + this->connectChangedObject = Gui::Application::Instance->signalChangedObject.connect( + std::bind(&TaskAppearance::slotChangedObject, this, sp::_1, sp::_2)); + // NOLINTEND } TaskAppearance::~TaskAppearance() @@ -71,6 +70,7 @@ TaskAppearance::~TaskAppearance() void TaskAppearance::setupConnections() { + // clang-format off #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) connect(ui->changeMode, qOverload(&QComboBox::activated), this, &TaskAppearance::onChangeModeActivated); @@ -88,9 +88,10 @@ void TaskAppearance::setupConnections() this, &TaskAppearance::onPointSizeValueChanged); connect(ui->spinLineWidth, qOverload(&QSpinBox::valueChanged), this, &TaskAppearance::onLineWidthValueChanged); + // clang-format on } -void TaskAppearance::changeEvent(QEvent *e) +void TaskAppearance::changeEvent(QEvent* e) { TaskBox::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -99,14 +100,14 @@ void TaskAppearance::changeEvent(QEvent *e) } /// @cond DOXERR -void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType &rCaller, +void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType& rCaller, Gui::SelectionSingleton::MessageType Reason) { - Q_UNUSED(rCaller); - if (Reason.Type == SelectionChanges::AddSelection || - Reason.Type == SelectionChanges::RmvSelection || - Reason.Type == SelectionChanges::SetSelection || - Reason.Type == SelectionChanges::ClrSelection) { + Q_UNUSED(rCaller); + if (Reason.Type == SelectionChanges::AddSelection + || Reason.Type == SelectionChanges::RmvSelection + || Reason.Type == SelectionChanges::SetSelection + || Reason.Type == SelectionChanges::ClrSelection) { std::vector views = getSelection(); setDisplayModes(views); setPointSize(views); @@ -116,14 +117,14 @@ void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType &rCaller, } /// @endcond -void TaskAppearance::slotChangedObject(const Gui::ViewProvider& obj, - const App::Property& prop) +void TaskAppearance::slotChangedObject(const Gui::ViewProvider& obj, const App::Property& prop) { // This method gets called if a property of any view provider is changed. // We pick out all the properties for which we need to update this dialog. const std::vector Provider = getSelection(); - auto vp = std::find_if - (Provider.begin(), Provider.end(), [&obj](Gui::ViewProvider* v) { return v == &obj; }); + auto vp = std::find_if(Provider.begin(), Provider.end(), [&obj](Gui::ViewProvider* v) { + return v == &obj; + }); if (vp != Provider.end()) { std::string prop_name = obj.getPropertyName(&prop); @@ -161,7 +162,7 @@ void TaskAppearance::onChangeModeActivated(const QString& s) { Gui::WaitCursor wc; std::vector Provider = getSelection(); - for (const auto & It : Provider) { + for (const auto& It : Provider) { App::Property* prop = It->getPropertyByName("DisplayMode"); if (prop && prop->is()) { auto Display = static_cast(prop); @@ -170,9 +171,9 @@ void TaskAppearance::onChangeModeActivated(const QString& s) } } -void TaskAppearance::onChangePlotActivated(const QString&s) +void TaskAppearance::onChangePlotActivated(const QString& s) { - Base::Console().Log("Plot = %s\n",(const char*)s.toLatin1()); + Base::Console().Log("Plot = %s\n", (const char*)s.toLatin1()); } /** @@ -181,7 +182,7 @@ void TaskAppearance::onChangePlotActivated(const QString&s) void TaskAppearance::onTransparencyValueChanged(int transparency) { std::vector Provider = getSelection(); - for (const auto & It : Provider) { + for (const auto& It : Provider) { App::Property* prop = It->getPropertyByName("Transparency"); if (prop && prop->isDerivedFrom()) { auto Transparency = static_cast(prop); @@ -196,7 +197,7 @@ void TaskAppearance::onTransparencyValueChanged(int transparency) void TaskAppearance::onPointSizeValueChanged(int pointsize) { std::vector Provider = getSelection(); - for (const auto & It : Provider) { + for (const auto& It : Provider) { App::Property* prop = It->getPropertyByName("PointSize"); if (prop && prop->isDerivedFrom()) { auto PointSize = static_cast(prop); @@ -211,7 +212,7 @@ void TaskAppearance::onPointSizeValueChanged(int pointsize) void TaskAppearance::onLineWidthValueChanged(int linewidth) { std::vector Provider = getSelection(); - for (const auto & It : Provider) { + for (const auto& It : Provider) { App::Property* prop = It->getPropertyByName("LineWidth"); if (prop && prop->isDerivedFrom()) { auto LineWidth = static_cast(prop); @@ -227,17 +228,20 @@ void TaskAppearance::setDisplayModes(const std::vector& view App::Property* prop = (*it)->getPropertyByName("DisplayMode"); if (prop && prop->is()) { auto display = static_cast(prop); - if (!display->hasEnums()) + if (!display->hasEnums()) { return; + } std::vector value = display->getEnumVector(); if (it == views.begin()) { - for (const auto & jt : value) + for (const auto& jt : value) { commonModes << QLatin1String(jt.c_str()); + } } else { - for (const auto & jt : value) { - if (commonModes.contains(QLatin1String(jt.c_str()))) + for (const auto& jt : value) { + if (commonModes.contains(QLatin1String(jt.c_str()))) { modes << QLatin1String(jt.c_str()); + } } commonModes = modes; @@ -268,7 +272,7 @@ void TaskAppearance::setDisplayModes(const std::vector& view void TaskAppearance::setPointSize(const std::vector& views) { bool pointSize = false; - for (const auto & view : views) { + for (const auto& view : views) { App::Property* prop = view->getPropertyByName("PointSize"); if (prop && prop->isDerivedFrom()) { bool blocked = ui->spinPointSize->blockSignals(true); @@ -285,7 +289,7 @@ void TaskAppearance::setPointSize(const std::vector& views) void TaskAppearance::setLineWidth(const std::vector& views) { bool lineWidth = false; - for (const auto & view : views) { + for (const auto& view : views) { App::Property* prop = view->getPropertyByName("LineWidth"); if (prop && prop->isDerivedFrom()) { bool blocked = ui->spinLineWidth->blockSignals(true); @@ -302,7 +306,7 @@ void TaskAppearance::setLineWidth(const std::vector& views) void TaskAppearance::setTransparency(const std::vector& views) { bool transparency = false; - for (const auto & view : views) { + for (const auto& view : views) { App::Property* prop = view->getPropertyByName("Transparency"); if (prop && prop->isDerivedFrom()) { bool blocked = ui->spinTransparency->blockSignals(true); @@ -323,9 +327,12 @@ std::vector TaskAppearance::getSelection() const // get the complete selection std::vector sel = Selection().getCompleteSelection(); - for (const auto & it : sel) { - Gui::ViewProvider* view = Application::Instance->getDocument(it.pDoc)->getViewProvider(it.pObject); - if (view) views.push_back(view); + for (const auto& it : sel) { + Gui::ViewProvider* view = + Application::Instance->getDocument(it.pDoc)->getViewProvider(it.pObject); + if (view) { + views.push_back(view); + } } return views; diff --git a/src/Gui/TaskView/TaskImage.cpp b/src/Gui/TaskView/TaskImage.cpp index 877686f50a..27ef04949c 100644 --- a/src/Gui/TaskView/TaskImage.cpp +++ b/src/Gui/TaskView/TaskImage.cpp @@ -23,16 +23,16 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #include @@ -59,10 +59,10 @@ using namespace Gui; /* TRANSLATOR Gui::TaskImage */ TaskImage::TaskImage(Image::ImagePlane* obj, QWidget* parent) - : QWidget(parent) - , ui(new Ui_TaskImage) - , feature(obj) - , aspectRatio(1.0) + : QWidget(parent) + , ui(new Ui_TaskImage) + , feature(obj) + , aspectRatio(1.0) { ui->setupUi(this); ui->groupBoxCalibration->hide(); @@ -87,6 +87,7 @@ TaskImage::~TaskImage() void TaskImage::connectSignals() { + // clang-format off connect(ui->Reverse_checkBox, &QCheckBox::clicked, this, &TaskImage::onPreview); connect(ui->XY_radioButton, &QRadioButton::clicked, @@ -118,6 +119,7 @@ void TaskImage::connectSignals() this, &TaskImage::acceptScale); connect(ui->pushButtonCancel, &QPushButton::clicked, this, &TaskImage::rejectScale); + // clang-format on } void TaskImage::initialiseTransparency() @@ -179,7 +181,7 @@ View3DInventorViewer* TaskImage::getViewer() const { if (!feature.expired()) { auto vp = Application::Instance->getViewProvider(feature.get()); - auto doc = static_cast(vp)->getDocument(); // NOLINT + auto doc = static_cast(vp)->getDocument(); // NOLINT auto view = dynamic_cast(doc->getViewOfViewProvider(vp)); if (view) { return view->getViewer(); @@ -241,12 +243,9 @@ void TaskImage::onInteractiveScale() if (viewer) { auto vp = Application::Instance->getViewProvider(feature.get()); scale = new InteractiveScale(viewer, vp, feature->globalPlacement()); - connect(scale, &InteractiveScale::scaleRequired, - this, &TaskImage::acceptScale); - connect(scale, &InteractiveScale::scaleCanceled, - this, &TaskImage::rejectScale); - connect(scale, &InteractiveScale::enableApplyBtn, - this, &TaskImage::enableApplyBtn); + connect(scale, &InteractiveScale::scaleRequired, this, &TaskImage::acceptScale); + connect(scale, &InteractiveScale::scaleCanceled, this, &TaskImage::rejectScale); + connect(scale, &InteractiveScale::enableApplyBtn, this, &TaskImage::enableApplyBtn); } } @@ -289,9 +288,9 @@ void TaskImage::onPreview() // NOLINTNEXTLINE void TaskImage::restoreAngles(const Base::Rotation& rot) { - double yaw{}; - double pitch{}; - double roll{}; + double yaw {}; + double pitch {}; + double roll {}; rot.getYawPitchRoll(yaw, pitch, roll); bool reverse = false; @@ -358,7 +357,7 @@ void TaskImage::restore(const Base::Placement& plm) ui->spinBoxWidth->setValue(feature->XSize.getValue()); ui->spinBoxHeight->setValue(feature->YSize.getValue()); - Base::Rotation rot = plm.getRotation(); // NOLINT + Base::Rotation rot = plm.getRotation(); // NOLINT Base::Vector3d pos = plm.getPosition(); restoreAngles(rot); @@ -399,7 +398,9 @@ void TaskImage::updatePlacement() } // NOLINTEND - Base::Vector3d offset = Base::Vector3d(ui->spinBoxX->value().getValue(), ui->spinBoxY->value().getValue(), ui->spinBoxZ->value().getValue()); + Base::Vector3d offset = Base::Vector3d(ui->spinBoxX->value().getValue(), + ui->spinBoxY->value().getValue(), + ui->spinBoxZ->value().getValue()); offset = rot.multVec(offset); Pos = Base::Placement(offset, rot); @@ -426,22 +427,22 @@ void TaskImage::updateIcon() } ui->previewLabel->setPixmap( - Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), - ui->previewLabel->size())); + Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size())); } // ---------------------------------------------------------------------------- InteractiveScale::InteractiveScale(View3DInventorViewer* view, ViewProvider* vp, - const Base::Placement& plc) // NOLINT + const Base::Placement& plc) // NOLINT : active(false) , placement(plc) , viewer(view) , viewProv(vp) - , midPoint(SbVec3f(0,0,0)) + , midPoint(SbVec3f(0, 0, 0)) { - measureLabel = new EditableDatumLabel(viewer, placement, SbColor(1.0F, 0.149F, 0.0F)); //NOLINT + measureLabel = + new EditableDatumLabel(viewer, placement, SbColor(1.0F, 0.149F, 0.0F)); // NOLINT } InteractiveScale::~InteractiveScale() @@ -453,8 +454,12 @@ void InteractiveScale::activate() { if (viewer) { viewer->setEditing(true); - viewer->addEventCallback(SoLocation2Event::getClassTypeId(), InteractiveScale::getMousePosition, this); - viewer->addEventCallback(SoButtonEvent::getClassTypeId(), InteractiveScale::soEventFilter, this); + viewer->addEventCallback(SoLocation2Event::getClassTypeId(), + InteractiveScale::getMousePosition, + this); + viewer->addEventCallback(SoButtonEvent::getClassTypeId(), + InteractiveScale::soEventFilter, + this); viewer->setSelectionEnabled(false); viewer->getWidget()->setCursor(QCursor(Qt::CrossCursor)); active = true; @@ -467,8 +472,12 @@ void InteractiveScale::deactivate() points.clear(); measureLabel->deactivate(); viewer->setEditing(false); - viewer->removeEventCallback(SoLocation2Event::getClassTypeId(), InteractiveScale::getMousePosition, this); - viewer->removeEventCallback(SoButtonEvent::getClassTypeId(), InteractiveScale::soEventFilter, this); + viewer->removeEventCallback(SoLocation2Event::getClassTypeId(), + InteractiveScale::getMousePosition, + this); + viewer->removeEventCallback(SoButtonEvent::getClassTypeId(), + InteractiveScale::soEventFilter, + this); viewer->setSelectionEnabled(true); viewer->getWidget()->setCursor(QCursor(Qt::ArrowCursor)); active = false; @@ -499,8 +508,8 @@ void InteractiveScale::setDistance(const SbVec3f& pos3d) quantity.setValue(getDistance(pos3d)); quantity.setUnit(Base::Unit::Length); - //Update the displayed distance - double factor{}; + // Update the displayed distance + double factor {}; QString unitStr; QString valueStr; valueStr = quantity.getUserString(factor, unitStr); @@ -508,10 +517,10 @@ void InteractiveScale::setDistance(const SbVec3f& pos3d) measureLabel->label->setPoints(getCoordsOnImagePlane(points[0]), getCoordsOnImagePlane(pos3d)); } -void InteractiveScale::findPointOnImagePlane(SoEventCallback * ecb) +void InteractiveScale::findPointOnImagePlane(SoEventCallback* ecb) { - const SoEvent * mbe = ecb->getEvent(); - auto view = static_cast(ecb->getUserData()); + const SoEvent* mbe = ecb->getEvent(); + auto view = static_cast(ecb->getUserData()); std::unique_ptr pp(view->getPointOnRay(mbe->getPosition(), viewProv)); if (pp) { auto pos3d = pp->getPoint(); @@ -540,16 +549,17 @@ void InteractiveScale::collectPoint(const SbVec3f& pos3d) Q_EMIT enableApplyBtn(); } else { - Base::Console().Warning(std::string("Image scale"), "The second point is too close. Retry!\n"); + Base::Console().Warning(std::string("Image scale"), + "The second point is too close. Retry!\n"); } } } -void InteractiveScale::getMousePosition(void * ud, SoEventCallback * ecb) +void InteractiveScale::getMousePosition(void* ud, SoEventCallback* ecb) { auto scale = static_cast(ud); const SoEvent* l2e = ecb->getEvent(); - auto view = static_cast(ecb->getUserData()); + auto view = static_cast(ecb->getUserData()); if (scale->points.size() == 1) { ecb->setHandled(); @@ -569,7 +579,7 @@ void InteractiveScale::soEventFilter(void* ud, SoEventCallback* ecb) const SoEvent* soEvent = ecb->getEvent(); if (soEvent->isOfType(SoKeyboardEvent::getClassTypeId())) { /* If user presses escape, then we cancel the tool.*/ - const auto kbe = static_cast(soEvent); // NOLINT + const auto kbe = static_cast(soEvent); // NOLINT if (kbe->getKey() == SoKeyboardEvent::ESCAPE && kbe->getState() == SoButtonEvent::UP) { ecb->setHandled(); @@ -577,15 +587,15 @@ void InteractiveScale::soEventFilter(void* ud, SoEventCallback* ecb) } } else if (soEvent->isOfType(SoMouseButtonEvent::getClassTypeId())) { - const auto mbe = static_cast(soEvent); // NOLINT + const auto mbe = static_cast(soEvent); // NOLINT - if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) - { + if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 + && mbe->getState() == SoButtonEvent::DOWN) { ecb->setHandled(); scale->findPointOnImagePlane(ecb); } - if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::DOWN) - { + if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 + && mbe->getState() == SoButtonEvent::DOWN) { ecb->setHandled(); Q_EMIT scale->scaleCanceled(); } @@ -595,15 +605,16 @@ void InteractiveScale::soEventFilter(void* ud, SoEventCallback* ecb) bool InteractiveScale::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::KeyRelease) { - auto keyEvent = static_cast(event); // NOLINT + auto keyEvent = static_cast(event); // NOLINT /* If user press enter in the spinbox, then we validate the tool.*/ if ((keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) - && dynamic_cast(object)) { + && dynamic_cast(object)) { Q_EMIT scaleRequired(); } - /* If user press escape, then we cancel the tool. Required here as well for when checkbox has focus.*/ + /* If user press escape, then we cancel the tool. Required here as well for when checkbox + * has focus.*/ if (keyEvent->key() == Qt::Key_Escape) { Q_EMIT scaleCanceled(); } @@ -640,7 +651,7 @@ SbVec3f InteractiveScale::getCoordsOnImagePlane(const SbVec3f& point) // ---------------------------------------------------------------------------- TaskImageDialog::TaskImageDialog(Image::ImagePlane* obj) - : widget{new TaskImage(obj)} + : widget {new TaskImage(obj)} { addTaskBox(Gui::BitmapFactory().pixmap("image-plane"), widget); diff --git a/src/Gui/TaskView/TaskOrientation.cpp b/src/Gui/TaskView/TaskOrientation.cpp index d072a01872..deda8e81b7 100644 --- a/src/Gui/TaskView/TaskOrientation.cpp +++ b/src/Gui/TaskView/TaskOrientation.cpp @@ -23,8 +23,8 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include #endif #include @@ -40,18 +40,24 @@ using namespace Gui; TaskOrientation::TaskOrientation(App::GeoFeature* obj, QWidget* parent) - : QWidget(parent) - , ui(new Ui_TaskOrientation) - , feature(obj) + : QWidget(parent) + , ui(new Ui_TaskOrientation) + , feature(obj) { ui->setupUi(this); - connect(ui->Reverse_checkBox, &QCheckBox::clicked, this, &TaskOrientation::onPreview); - connect(ui->XY_radioButton , &QRadioButton::clicked, this, &TaskOrientation::onPreview); - connect(ui->XZ_radioButton , &QRadioButton::clicked, this, &TaskOrientation::onPreview); - connect(ui->YZ_radioButton , &QRadioButton::clicked, this, &TaskOrientation::onPreview); + // clang-format off + connect(ui->Reverse_checkBox, &QCheckBox::clicked, + this, &TaskOrientation::onPreview); + connect(ui->XY_radioButton , &QRadioButton::clicked, + this, &TaskOrientation::onPreview); + connect(ui->XZ_radioButton , &QRadioButton::clicked, + this, &TaskOrientation::onPreview); + connect(ui->YZ_radioButton , &QRadioButton::clicked, + this, &TaskOrientation::onPreview); connect(ui->Offset_doubleSpinBox, qOverload(&QuantitySpinBox::valueChanged), this, &TaskOrientation::onPreview); + // clang-format on } TaskOrientation::~TaskOrientation() = default; @@ -92,9 +98,7 @@ void TaskOrientation::onPreview() void TaskOrientation::restore(const Base::Placement& plm) { auto isReversed = [](Camera::Orientation type) { - return (type == Camera::Bottom) || - (type == Camera::Rear) || - (type == Camera::Left); + return (type == Camera::Bottom) || (type == Camera::Rear) || (type == Camera::Left); }; std::map rotations { {Camera::Top, Camera::convert(Camera::Top)}, @@ -102,8 +106,7 @@ void TaskOrientation::restore(const Base::Placement& plm) {Camera::Front, Camera::convert(Camera::Front)}, {Camera::Rear, Camera::convert(Camera::Rear)}, {Camera::Right, Camera::convert(Camera::Right)}, - {Camera::Left, Camera::convert(Camera::Left)} - }; + {Camera::Left, Camera::convert(Camera::Left)}}; Base::Rotation rot = plm.getRotation(); Base::Vector3d pos = plm.getPosition(); @@ -111,18 +114,15 @@ void TaskOrientation::restore(const Base::Placement& plm) double prec = 1.0e-5; for (const auto& it : rotations) { if (rot.isSame(it.second, prec)) { - if (it.first == Camera::Top || - it.first == Camera::Bottom) { + if (it.first == Camera::Top || it.first == Camera::Bottom) { ui->XY_radioButton->setChecked(true); ui->Offset_doubleSpinBox->setValue(pos.z); } - else if (it.first == Camera::Front || - it.first == Camera::Rear) { + else if (it.first == Camera::Front || it.first == Camera::Rear) { ui->XZ_radioButton->setChecked(true); ui->Offset_doubleSpinBox->setValue(pos.y); } - else if (it.first == Camera::Right || - it.first == Camera::Left) { + else if (it.first == Camera::Right || it.first == Camera::Left) { ui->YZ_radioButton->setChecked(true); ui->Offset_doubleSpinBox->setValue(pos.x); } @@ -143,32 +143,26 @@ void TaskOrientation::updatePlacement() bool reverse = ui->Reverse_checkBox->isChecked(); if (ui->XY_radioButton->isChecked()) { if (!reverse) { - Pos = Base::Placement(Base::Vector3d(0, 0, offset), - Camera::convert(Camera::Top)); + Pos = Base::Placement(Base::Vector3d(0, 0, offset), Camera::convert(Camera::Top)); } else { - Pos = Base::Placement(Base::Vector3d(0, 0, offset), - Camera::convert(Camera::Bottom)); + Pos = Base::Placement(Base::Vector3d(0, 0, offset), Camera::convert(Camera::Bottom)); } } else if (ui->XZ_radioButton->isChecked()) { if (!reverse) { - Pos = Base::Placement(Base::Vector3d(0, offset, 0), - Camera::convert(Camera::Front)); + Pos = Base::Placement(Base::Vector3d(0, offset, 0), Camera::convert(Camera::Front)); } else { - Pos = Base::Placement(Base::Vector3d(0, offset, 0), - Camera::convert(Camera::Rear)); + Pos = Base::Placement(Base::Vector3d(0, offset, 0), Camera::convert(Camera::Rear)); } } else if (ui->YZ_radioButton->isChecked()) { if (!reverse) { - Pos = Base::Placement(Base::Vector3d(offset, 0, 0), - Camera::convert(Camera::Right)); + Pos = Base::Placement(Base::Vector3d(offset, 0, 0), Camera::convert(Camera::Right)); } else { - Pos = Base::Placement(Base::Vector3d(offset, 0, 0), - Camera::convert(Camera::Left)); + Pos = Base::Placement(Base::Vector3d(offset, 0, 0), Camera::convert(Camera::Left)); } } @@ -192,8 +186,7 @@ void TaskOrientation::updateIcon() } ui->previewLabel->setPixmap( - Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), - ui->previewLabel->size())); + Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size())); } // ---------------------------------------------------------------------------- diff --git a/src/Gui/TaskView/TaskSelectLinkProperty.cpp b/src/Gui/TaskView/TaskSelectLinkProperty.cpp index 7c0ade2819..e4176d7deb 100644 --- a/src/Gui/TaskView/TaskSelectLinkProperty.cpp +++ b/src/Gui/TaskView/TaskSelectLinkProperty.cpp @@ -37,8 +37,13 @@ using namespace Gui::TaskView; /* TRANSLATOR Gui::TaskView::TaskSelectLinkProperty */ -TaskSelectLinkProperty::TaskSelectLinkProperty(const char *sFilter,App::Property *prop,QWidget *parent) - : TaskBox(Gui::BitmapFactory().pixmap("mouse_pointer"),tr("edit selection"),true, parent),Filter(nullptr),LinkSub(nullptr),LinkList(nullptr) +TaskSelectLinkProperty::TaskSelectLinkProperty(const char* sFilter, + App::Property* prop, + QWidget* parent) + : TaskBox(Gui::BitmapFactory().pixmap("mouse_pointer"), tr("edit selection"), true, parent) + , Filter(nullptr) + , LinkSub(nullptr) + , LinkList(nullptr) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -60,18 +65,18 @@ TaskSelectLinkProperty::TaskSelectLinkProperty(const char *sFilter,App::Property ui->Invert->setDisabled(true); ui->Help->setDisabled(true); - // property have to be set! + // property have to be set! assert(prop); StartObject = nullptr; if (prop->isDerivedFrom()) { - LinkSub = dynamic_cast(prop); + LinkSub = dynamic_cast(prop); } else if (prop->isDerivedFrom()) { - LinkList = dynamic_cast(prop); + LinkList = dynamic_cast(prop); } else { Base::Console().Warning("Unknown Link property type in " - "Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()"); + "Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()"); } setFilter(sFilter); @@ -85,6 +90,7 @@ TaskSelectLinkProperty::~TaskSelectLinkProperty() void TaskSelectLinkProperty::setupConnections() { + // clang-format off connect(ui->Remove, &QToolButton::clicked, this, &TaskSelectLinkProperty::onRemoveClicked); connect(ui->Add, &QToolButton::clicked, @@ -93,9 +99,10 @@ void TaskSelectLinkProperty::setupConnections() this, &TaskSelectLinkProperty::onInvertClicked); connect(ui->Help, &QToolButton::clicked, this, &TaskSelectLinkProperty::onHelpClicked); + // clang-format on } -void TaskSelectLinkProperty::changeEvent(QEvent *e) +void TaskSelectLinkProperty::changeEvent(QEvent* e) { TaskBox::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -106,7 +113,7 @@ void TaskSelectLinkProperty::changeEvent(QEvent *e) /// @cond DOXERR -bool TaskSelectLinkProperty::setFilter(const char * sFilter) +bool TaskSelectLinkProperty::setFilter(const char* sFilter) { Filter = new SelectionFilter(sFilter); return Filter->isValid(); @@ -117,34 +124,31 @@ void TaskSelectLinkProperty::activate() { // first clear the selection Gui::Selection().clearSelection(); - // set the gate for the filter + // set the gate for the filter Gui::Selection().addSelectionGate(new SelectionFilterGate(Filter)); - // In case of LinkSub property + // In case of LinkSub property if (LinkSub) { // save the start values for a cnacel operation (reject()) StartValueBuffer = LinkSub->getSubValues(); - StartObject = LinkSub->getValue(); - if(StartObject) { + StartObject = LinkSub->getValue(); + if (StartObject) { std::string ObjName = StartObject->getNameInDocument(); std::string DocName = StartObject->getDocument()->getName(); - for (const auto & it : StartValueBuffer) - { - Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str(),it.c_str()); + for (const auto& it : StartValueBuffer) { + Gui::Selection().addSelection(DocName.c_str(), ObjName.c_str(), it.c_str()); } } - } - // In case of LinkList property + // In case of LinkList property else if (LinkList) { // save the start values for a cnacel operation (reject()) - const std::vector &Values = LinkList->getValues(); - for(const auto & Value : Values) - { + const std::vector& Values = LinkList->getValues(); + for (const auto& Value : Values) { std::string ObjName = Value->getNameInDocument(); std::string DocName = Value->getDocument()->getName(); - Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str()); + Gui::Selection().addSelection(DocName.c_str(), ObjName.c_str()); } } @@ -164,9 +168,9 @@ bool TaskSelectLinkProperty::accept() bool TaskSelectLinkProperty::reject() { - if(LinkSub){ + if (LinkSub) { // restore the old values - LinkSub->setValue(StartObject,StartValueBuffer); + LinkSub->setValue(StartObject, StartValueBuffer); } // clear selection and remove gate (return to normal operation) @@ -180,17 +184,17 @@ void TaskSelectLinkProperty::sendSelection2Property() if (LinkSub) { std::vector temp = Gui::Selection().getSelectionEx(); assert(temp.size() >= 1); - LinkSub->setValue(temp[0].getObject(),temp[0].getSubNames()); + LinkSub->setValue(temp[0].getObject(), temp[0].getSubNames()); } else if (LinkList) { std::vector sel = Gui::Selection().getSelectionEx(); std::vector temp; - for (auto & it : sel) + for (auto& it : sel) { temp.push_back(it.getObject()); - + } + LinkList->setValues(temp); } - } void TaskSelectLinkProperty::checkSelectionStatus() @@ -198,56 +202,52 @@ void TaskSelectLinkProperty::checkSelectionStatus() QPalette palette(QApplication::palette()); if (Filter->match()) { - palette.setBrush(QPalette::Base,QColor(200,250,200)); + palette.setBrush(QPalette::Base, QColor(200, 250, 200)); Q_EMIT emitSelectionFit(); } else { - palette.setBrush(QPalette::Base,QColor(250,200,200)); + palette.setBrush(QPalette::Base, QColor(250, 200, 200)); Q_EMIT emitSelectionMisfit(); } - //ui->listWidget->setAutoFillBackground(true); + // ui->listWidget->setAutoFillBackground(true); ui->listWidget->setPalette(palette); } -void TaskSelectLinkProperty::OnChange(Gui::SelectionSingleton::SubjectType &rCaller, +void TaskSelectLinkProperty::OnChange(Gui::SelectionSingleton::SubjectType& rCaller, Gui::SelectionSingleton::MessageType Reason) { - Q_UNUSED(rCaller); - if (Reason.Type == SelectionChanges::AddSelection || - Reason.Type == SelectionChanges::RmvSelection || - Reason.Type == SelectionChanges::SetSelection || - Reason.Type == SelectionChanges::ClrSelection) { - ui->listWidget->clear(); - std::vector sel = Gui::Selection().getSelection(); - for (const auto & it : sel){ - std::string temp; - temp += it.FeatName; - if (strcmp(it.SubName, "") != 0){ - temp += "::"; - temp += it.SubName; - } - new QListWidgetItem(QString::fromLatin1(temp.c_str()), ui->listWidget); + Q_UNUSED(rCaller); + if (Reason.Type == SelectionChanges::AddSelection + || Reason.Type == SelectionChanges::RmvSelection + || Reason.Type == SelectionChanges::SetSelection + || Reason.Type == SelectionChanges::ClrSelection) { + ui->listWidget->clear(); + std::vector sel = Gui::Selection().getSelection(); + for (const auto& it : sel) { + std::string temp; + temp += it.FeatName; + if (strcmp(it.SubName, "") != 0) { + temp += "::"; + temp += it.SubName; } - checkSelectionStatus(); + new QListWidgetItem(QString::fromLatin1(temp.c_str()), ui->listWidget); + } + checkSelectionStatus(); } } /// @endcond void TaskSelectLinkProperty::onRemoveClicked(bool) -{ -} +{} void TaskSelectLinkProperty::onAddClicked(bool) -{ -} +{} void TaskSelectLinkProperty::onInvertClicked(bool) -{ -} +{} void TaskSelectLinkProperty::onHelpClicked(bool) -{ -} +{} #include "moc_TaskSelectLinkProperty.cpp" diff --git a/src/Gui/propertyeditor/PropertyEditor.cpp b/src/Gui/propertyeditor/PropertyEditor.cpp index ea34e67fdc..561c7f9916 100644 --- a/src/Gui/propertyeditor/PropertyEditor.cpp +++ b/src/Gui/propertyeditor/PropertyEditor.cpp @@ -24,12 +24,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #endif #include @@ -51,7 +51,7 @@ FC_LOG_LEVEL_INIT("PropertyView", true, true) using namespace Gui::PropertyEditor; -PropertyEditor::PropertyEditor(QWidget *parent) +PropertyEditor::PropertyEditor(QWidget* parent) : QTreeView(parent) , autoexpand(false) , autoupdate(false) @@ -76,7 +76,7 @@ PropertyEditor::PropertyEditor(QWidget *parent) setRootIsDecorated(false); setExpandsOnDoubleClick(true); -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QStyleOptionViewItem opt = PropertyEditor::viewOptions(); #else QStyleOptionViewItem opt; @@ -85,22 +85,25 @@ PropertyEditor::PropertyEditor(QWidget *parent) this->background = opt.palette.dark(); this->groupColor = opt.palette.color(QPalette::BrightText); - this->_itemBackground.setColor(QColor(0,0,0,0)); + this->_itemBackground.setColor(QColor(0, 0, 0, 0)); this->setSelectionMode(QAbstractItemView::ExtendedSelection); + // clang-format off connect(this, &QTreeView::activated, this, &PropertyEditor::onItemActivated); connect(this, &QTreeView::clicked, this, &PropertyEditor::onItemActivated); connect(this, &QTreeView::expanded, this, &PropertyEditor::onItemExpanded); connect(this, &QTreeView::collapsed, this, &PropertyEditor::onItemCollapsed); connect(propertyModel, &QAbstractItemModel::rowsMoved, this, &PropertyEditor::onRowsMoved); connect(propertyModel, &QAbstractItemModel::rowsRemoved, this, &PropertyEditor::onRowsRemoved); + // clang-format on setHeaderHidden(true); viewport()->installEventFilter(this); viewport()->setMouseTracking(true); - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DockWindows/PropertyView"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/DockWindows/PropertyView"); int firstColumnSize = hGrp->GetInt("FirstColumnSize", 0); if (firstColumnSize != 0) { header()->resizeSection(0, firstColumnSize); @@ -124,15 +127,16 @@ bool PropertyEditor::isAutomaticExpand(bool) const return autoexpand; } -void PropertyEditor::onItemExpanded(const QModelIndex &index) +void PropertyEditor::onItemExpanded(const QModelIndex& index) { auto item = static_cast(index.internalPointer()); item->setExpanded(true); - for(int i=0, c=item->childCount(); ichildCount(); i < c; ++i) { setExpanded(propertyModel->index(i, 0, index), item->child(i)->isExpanded()); + } } -void PropertyEditor::onItemCollapsed(const QModelIndex &index) +void PropertyEditor::onItemCollapsed(const QModelIndex& index) { auto item = static_cast(index.internalPointer()); item->setExpanded(false); @@ -178,7 +182,7 @@ void PropertyEditor::setItemBackground(const QBrush& c) this->_itemBackground = c; } -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QStyleOptionViewItem PropertyEditor::viewOptions() const { QStyleOptionViewItem option = QTreeView::viewOptions(); @@ -186,7 +190,7 @@ QStyleOptionViewItem PropertyEditor::viewOptions() const return option; } #else -void PropertyEditor::initViewItemOption(QStyleOptionViewItem *option) const +void PropertyEditor::initViewItemOption(QStyleOptionViewItem* option) const { QTreeView::initViewItemOption(option); option->showDecorationSelected = true; @@ -198,27 +202,26 @@ bool PropertyEditor::event(QEvent* event) if (event->type() == QEvent::ShortcutOverride) { auto kevent = static_cast(event); Qt::KeyboardModifiers ShiftKeypadModifier = Qt::ShiftModifier | Qt::KeypadModifier; - if (kevent->modifiers() == Qt::NoModifier || - kevent->modifiers() == Qt::ShiftModifier || - kevent->modifiers() == Qt::KeypadModifier || - kevent->modifiers() == ShiftKeypadModifier) { + if (kevent->modifiers() == Qt::NoModifier || kevent->modifiers() == Qt::ShiftModifier + || kevent->modifiers() == Qt::KeypadModifier + || kevent->modifiers() == ShiftKeypadModifier) { switch (kevent->key()) { - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: - kevent->accept(); - default: - break; + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: + kevent->accept(); + default: + break; } } } return QTreeView::event(event); } -void PropertyEditor::commitData (QWidget * editor) +void PropertyEditor::commitData(QWidget* editor) { committing = true; QTreeView::commitData(editor); @@ -229,7 +232,7 @@ void PropertyEditor::commitData (QWidget * editor) } } -void PropertyEditor::editorDestroyed (QObject * editor) +void PropertyEditor::editorDestroyed(QObject* editor) { QTreeView::editorDestroyed(editor); @@ -239,10 +242,10 @@ void PropertyEditor::editorDestroyed (QObject * editor) closeTransaction(); } -void PropertyEditor::currentChanged ( const QModelIndex & current, const QModelIndex & previous ) +void PropertyEditor::currentChanged(const QModelIndex& current, const QModelIndex& previous) { - FC_LOG("current changed " << current.row()<<","<findChild()) { tabBar = mdiArea->findChild(); if (tabBar) { @@ -280,75 +283,84 @@ void PropertyEditor::closeEditor() #endif editingIndex = QPersistentModelIndex(); activeEditor = nullptr; - if(hasFocus) + if (hasFocus) { setFocus(); + } } } -void PropertyEditor::openEditor(const QModelIndex &index) +void PropertyEditor::openEditor(const QModelIndex& index) { - if(editingIndex == index && activeEditor) + if (editingIndex == index && activeEditor) { return; + } closeEditor(); openPersistentEditor(model()->buddy(index)); - if(!editingIndex.isValid() || !autoupdate) + if (!editingIndex.isValid() || !autoupdate) { return; + } - auto &app = App::GetApplication(); - if(app.getActiveTransaction()) { + auto& app = App::GetApplication(); + if (app.getActiveTransaction()) { FC_LOG("editor already transacting " << app.getActiveTransaction()); return; } auto item = static_cast(editingIndex.internalPointer()); auto items = item->getPropertyData(); - for(auto propItem=item->parent();items.empty() && propItem;propItem=propItem->parent()) + for (auto propItem = item->parent(); items.empty() && propItem; propItem = propItem->parent()) { items = propItem->getPropertyData(); - if(items.empty()) { + } + if (items.empty()) { FC_LOG("editor no item"); return; } auto prop = items[0]; auto parent = prop->getContainer(); - auto obj = Base::freecad_dynamic_cast(parent); + auto obj = Base::freecad_dynamic_cast(parent); if (!obj) { - auto view = Base::freecad_dynamic_cast(parent); - if (view) + auto view = Base::freecad_dynamic_cast(parent); + if (view) { obj = view->getObject(); + } } - if(!obj || !obj->getDocument()) { + if (!obj || !obj->getDocument()) { FC_LOG("invalid object"); return; } - if(obj->getDocument()->hasPendingTransaction()) { + if (obj->getDocument()->hasPendingTransaction()) { FC_LOG("pending transaction"); return; } std::ostringstream str; str << tr("Edit").toUtf8().constData() << ' '; - for(auto prop : items) { - if(prop->getContainer()!=obj) { + for (auto prop : items) { + if (prop->getContainer() != obj) { obj = nullptr; break; } } - if(obj && obj->isAttachedToDocument()) + if (obj && obj->isAttachedToDocument()) { str << obj->getNameInDocument() << '.'; - else + } + else { str << tr("property").toUtf8().constData() << ' '; + } str << prop->getName(); - if(items.size()>1) + if (items.size() > 1) { str << "..."; + } transactionID = app.setActiveTransaction(str.str().c_str()); FC_LOG("editor transaction " << app.getActiveTransaction()); } -void PropertyEditor::onItemActivated ( const QModelIndex & index ) +void PropertyEditor::onItemActivated(const QModelIndex& index) { - if(index.column() != 1) + if (index.column() != 1) { return; + } openEditor(index); } @@ -358,8 +370,9 @@ void PropertyEditor::recomputeDocument(App::Document* doc) if (doc && !doc->isTransactionEmpty()) { // Between opening and committing a transaction a recompute // could already have been done - if (doc->isTouched()) + if (doc->isTouched()) { doc->recompute(); + } } } // do not re-throw @@ -367,11 +380,14 @@ void PropertyEditor::recomputeDocument(App::Document* doc) e.ReportException(); } catch (const std::exception& e) { - Base::Console().Error("Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n" - "The error message is: %s\n", e.what()); + Base::Console().Error( + "Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n" + "The error message is: %s\n", + e.what()); } catch (...) { - Base::Console().Error("Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n"); + Base::Console().Error( + "Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n"); } } @@ -387,10 +403,11 @@ void PropertyEditor::closeTransaction() } } -void PropertyEditor::closeEditor (QWidget * editor, QAbstractItemDelegate::EndEditHint hint) +void PropertyEditor::closeEditor(QWidget* editor, QAbstractItemDelegate::EndEditHint hint) { - if (closingEditor) + if (closingEditor) { return; + } if (removingRows) { // When removing rows, QTreeView will temporary hide the editor which @@ -422,23 +439,29 @@ void PropertyEditor::closeEditor (QWidget * editor, QAbstractItemDelegate::EndEd do { QModelIndex index; if (hint == QAbstractItemDelegate::EditNextItem) { - index = moveCursor(MoveDown,Qt::NoModifier); - } else if(hint == QAbstractItemDelegate::EditPreviousItem) { - index = moveCursor(MoveUp,Qt::NoModifier); - } else + index = moveCursor(MoveDown, Qt::NoModifier); + } + else if (hint == QAbstractItemDelegate::EditPreviousItem) { + index = moveCursor(MoveUp, Qt::NoModifier); + } + else { break; + } if (!index.isValid() || index == lastIndex) { if (wrapped) { setCurrentIndex(propertyModel->buddy(indexSaved)); break; } wrapped = true; - if (hint == QAbstractItemDelegate::EditNextItem) + if (hint == QAbstractItemDelegate::EditNextItem) { index = moveCursor(MoveHome, Qt::NoModifier); - else + } + else { index = moveCursor(MoveEnd, Qt::NoModifier); - if (!index.isValid() || index == indexSaved) + } + if (!index.isValid() || index == indexSaved) { break; + } } lastIndex = index; setCurrentIndex(propertyModel->buddy(index)); @@ -446,8 +469,9 @@ void PropertyEditor::closeEditor (QWidget * editor, QAbstractItemDelegate::EndEd auto item = static_cast(index.internalPointer()); // Skip readonly item, because the editor will be disabled and hence // does not accept focus, and in turn break Tab/Backtab navigation. - if (item && item->isReadOnly()) + if (item && item->isReadOnly()) { continue; + } openEditor(index); @@ -462,74 +486,88 @@ void PropertyEditor::reset() QModelIndex parent; int numRows = propertyModel->rowCount(parent); - for (int i=0; iindex(i, 0, parent); auto item = static_cast(index.internalPointer()); if (item->childCount() == 0) { - if(item->isSeparator()) + if (item->isSeparator()) { setRowHidden(i, parent, true); - } else - setEditorMode(index, 0, item->childCount()-1); - if(item->isExpanded()) + } + } + else { + setEditorMode(index, 0, item->childCount() - 1); + } + if (item->isExpanded()) { setExpanded(index, true); + } } } -void PropertyEditor::onRowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &dst, int) +void PropertyEditor::onRowsMoved(const QModelIndex& parent, + int start, + int end, + const QModelIndex& dst, + int) { - if(parent != dst) { + if (parent != dst) { auto item = static_cast(parent.internalPointer()); - if(item && item->isSeparator() && item->childCount()==0) + if (item && item->isSeparator() && item->childCount() == 0) { setRowHidden(parent.row(), propertyModel->parent(parent), true); + } item = static_cast(dst.internalPointer()); - if(item && item->isSeparator() && item->childCount()==end-start+1) { + if (item && item->isSeparator() && item->childCount() == end - start + 1) { setRowHidden(dst.row(), propertyModel->parent(dst), false); setExpanded(dst, true); } } } -void PropertyEditor::rowsInserted (const QModelIndex & parent, int start, int end) +void PropertyEditor::rowsInserted(const QModelIndex& parent, int start, int end) { QTreeView::rowsInserted(parent, start, end); auto item = static_cast(parent.internalPointer()); - if (item && item->isSeparator() && item->childCount() == end-start+1) { + if (item && item->isSeparator() && item->childCount() == end - start + 1) { setRowHidden(parent.row(), propertyModel->parent(parent), false); - if(item->isExpanded()) + if (item->isExpanded()) { setExpanded(parent, true); + } } - for (int i=start; iindex(i, 0, parent); auto child = static_cast(index.internalPointer()); - if(child->isSeparator()) { + if (child->isSeparator()) { // Set group header rows to span all columns setFirstColumnSpanned(i, parent, true); } - if(child->isExpanded()) + if (child->isExpanded()) { setExpanded(index, true); + } } - if(parent.isValid()) + if (parent.isValid()) { setEditorMode(parent, start, end); + } } -void PropertyEditor::rowsAboutToBeRemoved (const QModelIndex & parent, int start, int end) +void PropertyEditor::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) { QTreeView::rowsAboutToBeRemoved(parent, start, end); auto item = static_cast(parent.internalPointer()); - if (item && item->isSeparator() && item->childCount() == end-start+1) + if (item && item->isSeparator() && item->childCount() == end - start + 1) { setRowHidden(parent.row(), propertyModel->parent(parent), true); + } if (editingIndex.isValid()) { - if (editingIndex.row() >= start && editingIndex.row() <= end) + if (editingIndex.row() >= start && editingIndex.row() <= end) { closeTransaction(); + } else { removingRows = 1; - for (QWidget *w = qApp->focusWidget(); w; w = w->parentWidget()) { - if(w == activeEditor) { + for (QWidget* w = qApp->focusWidget(); w; w = w->parentWidget()) { + if (w == activeEditor) { removingRows = -1; break; } @@ -538,10 +576,11 @@ void PropertyEditor::rowsAboutToBeRemoved (const QModelIndex & parent, int start } } -void PropertyEditor::onRowsRemoved(const QModelIndex &, int, int) +void PropertyEditor::onRowsRemoved(const QModelIndex&, int, int) { - if (removingRows < 0 && activeEditor) + if (removingRows < 0 && activeEditor) { activeEditor->setFocus(); + } removingRows = 0; } @@ -568,12 +607,13 @@ void Gui::PropertyEditor::PropertyEditor::drawRow(QPainter* painter, QTreeView::drawRow(painter, options, index); } -void PropertyEditor::buildUp(PropertyModel::PropertyList &&props, bool _checkDocument) +void PropertyEditor::buildUp(PropertyModel::PropertyList&& props, bool _checkDocument) { checkDocument = _checkDocument; if (committing) { - Base::Console().Warning("While committing the data to the property the selection has changed.\n"); + Base::Console().Warning( + "While committing the data to the property the selection has changed.\n"); delaybuild = true; return; } @@ -585,8 +625,9 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList &&props, bool _checkDoc QModelIndex index = this->currentIndex(); QStringList propertyPath = propertyModel->propertyPathFromIndex(index); - if (!propertyPath.isEmpty()) + if (!propertyPath.isEmpty()) { this->selectedProperty = propertyPath; + } propertyModel->buildUp(props); if (!this->selectedProperty.isEmpty()) { QModelIndex index = propertyModel->propertyIndexFromPath(this->selectedProperty); @@ -595,37 +636,41 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList &&props, bool _checkDoc propList = std::move(props); propOwners.clear(); - for(auto &v : propList) { - for(auto prop : v.second) { + for (auto& v : propList) { + for (auto prop : v.second) { auto container = prop->getContainer(); - if(!container) + if (!container) { continue; + } // Include document to get proper handling in PropertyView::slotDeleteDocument() - if(checkDocument && container->isDerivedFrom(App::DocumentObject::getClassTypeId())) + if (checkDocument && container->isDerivedFrom(App::DocumentObject::getClassTypeId())) { propOwners.insert(static_cast(container)->getDocument()); + } propOwners.insert(container); } } - if (autoexpand) + if (autoexpand) { expandAll(); + } } void PropertyEditor::updateProperty(const App::Property& prop) { // forward this to the model if the property is changed from outside - if (!committing) + if (!committing) { propertyModel->updateProperty(prop); + } } -void PropertyEditor::setEditorMode(const QModelIndex & parent, int start, int end) +void PropertyEditor::setEditorMode(const QModelIndex& parent, int start, int end) { int column = 1; - for (int i=start; i<=end; i++) { + for (int i = start; i <= end; i++) { QModelIndex item = propertyModel->index(i, column, parent); auto propItem = static_cast(item.internalPointer()); if (!PropertyView::showAll() && propItem && propItem->testStatus(App::Property::Hidden)) { - setRowHidden (i, parent, true); + setRowHidden(i, parent, true); } } } @@ -634,7 +679,8 @@ void PropertyEditor::removeProperty(const App::Property& prop) { for (PropertyModel::PropertyList::iterator it = propList.begin(); it != propList.end(); ++it) { // find the given property in the list and remove it if it's there - std::vector::iterator pos = std::find(it->second.begin(), it->second.end(), &prop); + std::vector::iterator pos = + std::find(it->second.begin(), it->second.end(), &prop); if (pos != it->second.end()) { it->second.erase(pos); // if the last property of this name is removed then also remove the whole group @@ -647,7 +693,8 @@ void PropertyEditor::removeProperty(const App::Property& prop) } } -enum MenuAction { +enum MenuAction +{ MA_AutoExpand, MA_ShowHidden, MA_Expression, @@ -664,23 +711,25 @@ enum MenuAction { MA_CopyOnChange, }; -void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { +void PropertyEditor::contextMenuEvent(QContextMenuEvent*) +{ QMenu menu; - QAction *autoExpand = nullptr; + QAction* autoExpand = nullptr; auto contextIndex = currentIndex(); // acquiring the selected properties std::unordered_set props; const auto indexes = selectedIndexes(); - for(const auto& index : indexes) { + for (const auto& index : indexes) { auto item = static_cast(index.internalPointer()); - if(item->isSeparator()) + if (item->isSeparator()) { continue; - for(auto parent=item;parent;parent=parent->parent()) { - const auto &ps = parent->getPropertyData(); - if(!ps.empty()) { - props.insert(ps.begin(),ps.end()); + } + for (auto parent = item; parent; parent = parent->parent()) { + const auto& ps = parent->getPropertyData(); + if (!ps.empty()) { + props.insert(ps.begin(), ps.end()); break; } } @@ -689,10 +738,9 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { // add property menu.addAction(tr("Add property"))->setData(QVariant(MA_AddProp)); if (!props.empty() && std::all_of(props.begin(), props.end(), [](auto prop) { - return prop->testStatus(App::Property::PropDynamic) - && !boost::starts_with(prop->getName(),prop->getGroup()); - })) - { + return prop->testStatus(App::Property::PropDynamic) + && !boost::starts_with(prop->getName(), prop->getGroup()); + })) { menu.addAction(tr("Rename property group"))->setData(QVariant(MA_EditPropGroup)); } @@ -700,23 +748,23 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { bool canRemove = !props.empty(); unsigned long propType = 0; unsigned long propStatus = 0xffffffff; - for(auto prop : props) { + for (auto prop : props) { propType |= prop->getType(); propStatus &= prop->getStatus(); - if(!prop->testStatus(App::Property::PropDynamic) - || prop->testStatus(App::Property::LockDynamic)) - { + if (!prop->testStatus(App::Property::PropDynamic) + || prop->testStatus(App::Property::LockDynamic)) { canRemove = false; } } - if(canRemove) + if (canRemove) { menu.addAction(tr("Remove property"))->setData(QVariant(MA_RemoveProp)); + } // add a separator between adding/removing properties and the rest menu.addSeparator(); // show all - QAction *showHidden = menu.addAction(tr("Show hidden")); + QAction* showHidden = menu.addAction(tr("Show hidden")); showHidden->setCheckable(true); showHidden->setChecked(PropertyView::showAll()); showHidden->setData(QVariant(MA_ShowHidden)); @@ -728,15 +776,12 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { autoExpand->setData(QVariant(MA_AutoExpand)); // expression - if(props.size() == 1) { + if (props.size() == 1) { auto item = static_cast(contextIndex.internalPointer()); auto prop = *props.begin(); - if(item->isBound() - && !prop->isDerivedFrom(App::PropertyExpressionEngine::getClassTypeId()) - && !prop->isReadOnly() - && !prop->testStatus(App::Property::Immutable) - && !(prop->getType() & App::Prop_ReadOnly)) - { + if (item->isBound() && !prop->isDerivedFrom(App::PropertyExpressionEngine::getClassTypeId()) + && !prop->isReadOnly() && !prop->testStatus(App::Property::Immutable) + && !(prop->getType() & App::Prop_ReadOnly)) { contextIndex = propertyModel->buddy(contextIndex); setCurrentIndex(contextIndex); // menu.addSeparator(); @@ -745,29 +790,31 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { } // the various flags - if(!props.empty()) { + if (!props.empty()) { menu.addSeparator(); // the subMenu is allocated on the heap but managed by menu. auto subMenu = new QMenu(QString::fromLatin1("Status"), &menu); - QAction *action; + QAction* action; QString text; -#define _ACTION_SETUP(_name) do { \ - text = tr(#_name); \ - action = subMenu->addAction(text); \ - action->setData(QVariant(MA_##_name)); \ - action->setCheckable(true); \ - if(propStatus & (1<setChecked(true); \ - }while(0) -#define ACTION_SETUP(_name) do { \ - _ACTION_SETUP(_name); \ - if(propType & App::Prop_##_name) { \ - action->setText(text + QString::fromLatin1(" *")); \ - action->setChecked(true); \ - } \ - }while(0) +#define _ACTION_SETUP(_name) \ + do { \ + text = tr(#_name); \ + action = subMenu->addAction(text); \ + action->setData(QVariant(MA_##_name)); \ + action->setCheckable(true); \ + if (propStatus & (1 << App::Property::_name)) \ + action->setChecked(true); \ + } while (0) +#define ACTION_SETUP(_name) \ + do { \ + _ACTION_SETUP(_name); \ + if (propType & App::Prop_##_name) { \ + action->setText(text + QString::fromLatin1(" *")); \ + action->setChecked(true); \ + } \ + } while (0) ACTION_SETUP(Hidden); ACTION_SETUP(Output); @@ -782,112 +829,124 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { } auto action = menu.exec(QCursor::pos()); - if(!action) + if (!action) { return; + } - switch(action->data().toInt()) { - case MA_AutoExpand: - if (autoExpand) { - // Variable autoExpand should not be null when we arrive here, but - // since we explicitly initialize the variable to nullptr, a check - // nonetheless. - autoexpand = autoExpand->isChecked(); - if (autoexpand) - expandAll(); - } - return; - case MA_ShowHidden: - PropertyView::setShowAll(action->isChecked()); - return; -#define ACTION_CHECK(_name) \ - case MA_##_name:\ - for(auto prop : props) \ - prop->setStatus(App::Property::_name,action->isChecked());\ - break - ACTION_CHECK(Transient); - ACTION_CHECK(ReadOnly); - ACTION_CHECK(Output); - ACTION_CHECK(Hidden); - ACTION_CHECK(EvalOnRestore); - ACTION_CHECK(CopyOnChange); - case MA_Touched: - for(auto prop : props) { - if(action->isChecked()) - prop->touch(); - else - prop->purgeTouched(); - } - break; - case MA_Expression: - if(contextIndex == currentIndex()) { - Base::FlagToggler<> flag(binding); - closeEditor(); - openEditor(contextIndex); - } - break; - case MA_AddProp: { - App::AutoTransaction committer("Add property"); - std::unordered_set containers; - auto sels = Gui::Selection().getSelection("*"); - if(sels.size() == 1) - containers.insert(sels[0].pObject); - else { - for(auto prop : props) - containers.insert(prop->getContainer()); - } - Gui::Dialog::DlgAddProperty dlg( - Gui::getMainWindow(),std::move(containers)); - dlg.exec(); - return; - } - case MA_EditPropGroup: { - // This operation is not undoable yet. - const char *groupName = (*props.begin())->getGroup(); - if(!groupName) - groupName = "Base"; - QString res = QInputDialog::getText(Gui::getMainWindow(), - tr("Rename property group"), tr("Group name:"), - QLineEdit::Normal, QString::fromUtf8(groupName)); - if(res.size()) { - std::string group = res.toUtf8().constData(); - for(auto prop : props) - prop->getContainer()->changeDynamicProperty(prop,group.c_str(),nullptr); - buildUp(PropertyModel::PropertyList(propList),checkDocument); - } - return; - } - case MA_RemoveProp: { - App::AutoTransaction committer("Remove property"); - for(auto prop : props) { - try { - prop->getContainer()->removeDynamicProperty(prop->getName()); - }catch(Base::Exception &e) { - e.ReportException(); + switch (action->data().toInt()) { + case MA_AutoExpand: + if (autoExpand) { + // Variable autoExpand should not be null when we arrive here, but + // since we explicitly initialize the variable to nullptr, a check + // nonetheless. + autoexpand = autoExpand->isChecked(); + if (autoexpand) { + expandAll(); + } } + return; + case MA_ShowHidden: + PropertyView::setShowAll(action->isChecked()); + return; +#define ACTION_CHECK(_name) \ + case MA_##_name: \ + for (auto prop : props) \ + prop->setStatus(App::Property::_name, action->isChecked()); \ + break + ACTION_CHECK(Transient); + ACTION_CHECK(ReadOnly); + ACTION_CHECK(Output); + ACTION_CHECK(Hidden); + ACTION_CHECK(EvalOnRestore); + ACTION_CHECK(CopyOnChange); + case MA_Touched: + for (auto prop : props) { + if (action->isChecked()) { + prop->touch(); + } + else { + prop->purgeTouched(); + } + } + break; + case MA_Expression: + if (contextIndex == currentIndex()) { + Base::FlagToggler<> flag(binding); + closeEditor(); + openEditor(contextIndex); + } + break; + case MA_AddProp: { + App::AutoTransaction committer("Add property"); + std::unordered_set containers; + auto sels = Gui::Selection().getSelection("*"); + if (sels.size() == 1) { + containers.insert(sels[0].pObject); + } + else { + for (auto prop : props) { + containers.insert(prop->getContainer()); + } + } + Gui::Dialog::DlgAddProperty dlg(Gui::getMainWindow(), std::move(containers)); + dlg.exec(); + return; } - break; - } - default: - break; + case MA_EditPropGroup: { + // This operation is not undoable yet. + const char* groupName = (*props.begin())->getGroup(); + if (!groupName) { + groupName = "Base"; + } + QString res = QInputDialog::getText(Gui::getMainWindow(), + tr("Rename property group"), + tr("Group name:"), + QLineEdit::Normal, + QString::fromUtf8(groupName)); + if (res.size()) { + std::string group = res.toUtf8().constData(); + for (auto prop : props) { + prop->getContainer()->changeDynamicProperty(prop, group.c_str(), nullptr); + } + buildUp(PropertyModel::PropertyList(propList), checkDocument); + } + return; + } + case MA_RemoveProp: { + App::AutoTransaction committer("Remove property"); + for (auto prop : props) { + try { + prop->getContainer()->removeDynamicProperty(prop->getName()); + } + catch (Base::Exception& e) { + e.ReportException(); + } + } + break; + } + default: + break; } } -bool PropertyEditor::eventFilter(QObject* object, QEvent* event) { +bool PropertyEditor::eventFilter(QObject* object, QEvent* event) +{ if (object == viewport()) { QMouseEvent* mouse_event = dynamic_cast(event); if (mouse_event) { if (mouse_event->type() == QEvent::MouseMove) { - if (dragInProgress) { // apply dragging + if (dragInProgress) { // apply dragging QHeaderView* header_view = header(); int delta = mouse_event->pos().x() - dragPreviousPos; dragPreviousPos = mouse_event->pos().x(); - //using minimal size = dragSensibility * 2 to prevent collapsing - header_view->resizeSection(dragSection, + // using minimal size = dragSensibility * 2 to prevent collapsing + header_view->resizeSection( + dragSection, qMax(dragSensibility * 2, header_view->sectionSize(dragSection) + delta)); return true; } - else { // set mouse cursor shape + else { // set mouse cursor shape if (indexResizable(mouse_event->pos()).isValid()) { viewport()->setCursor(Qt::SplitHCursor); } @@ -896,10 +955,11 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) { } } } - else if (mouse_event->type() == QEvent::MouseButtonPress && mouse_event->button() == Qt::LeftButton && !dragInProgress) { + else if (mouse_event->type() == QEvent::MouseButtonPress + && mouse_event->button() == Qt::LeftButton && !dragInProgress) { if (indexResizable(mouse_event->pos()).isValid()) { dragInProgress = true; -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) dragPreviousPos = mouse_event->x(); #else dragPreviousPos = mouse_event->position().toPoint().x(); @@ -908,11 +968,12 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) { return true; } } - else if (mouse_event->type() == QEvent::MouseButtonRelease && - mouse_event->button() == Qt::LeftButton && dragInProgress) { + else if (mouse_event->type() == QEvent::MouseButtonRelease + && mouse_event->button() == Qt::LeftButton && dragInProgress) { dragInProgress = false; - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DockWindows/PropertyView"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/DockWindows/PropertyView"); hGrp->SetInt("FirstColumnSize", header()->sectionSize(0)); return true; } @@ -921,11 +982,12 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) { return false; } -QModelIndex PropertyEditor::indexResizable(QPoint mouse_pos) { +QModelIndex PropertyEditor::indexResizable(QPoint mouse_pos) +{ QModelIndex index = indexAt(mouse_pos - QPoint(dragSensibility + 1, 0)); if (index.isValid()) { - if (qAbs(visualRect(index).right() - mouse_pos.x()) < dragSensibility && - header()->sectionResizeMode(index.column()) == QHeaderView::Interactive) { + if (qAbs(visualRect(index).right() - mouse_pos.x()) < dragSensibility + && header()->sectionResizeMode(index.column()) == QHeaderView::Interactive) { return index; } } diff --git a/src/Gui/resource.cpp b/src/Gui/resource.cpp index ee3ff5d8ab..e7a1af48f7 100644 --- a/src/Gui/resource.cpp +++ b/src/Gui/resource.cpp @@ -82,7 +82,7 @@ WidgetFactorySupplier::WidgetFactorySupplier() new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","General") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") ); - new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") ); + new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Display") );