From 78ae9c1d7d8a5ed6961a1ec5c19f9d08025a89bb Mon Sep 17 00:00:00 2001 From: Abdullah Tahiri Date: Thu, 25 May 2023 15:09:30 +0200 Subject: [PATCH] SketcherGui: apply clang-format --- src/Mod/Sketcher/Gui/AppSketcherGui.cpp | 51 +- src/Mod/Sketcher/Gui/AutoConstraint.h | 10 +- src/Mod/Sketcher/Gui/Command.cpp | 1189 +-- src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp | 86 +- src/Mod/Sketcher/Gui/CommandConstraints.cpp | 8031 ++++++++++------- src/Mod/Sketcher/Gui/CommandConstraints.h | 62 +- src/Mod/Sketcher/Gui/CommandCreateGeo.cpp | 1402 +-- .../Sketcher/Gui/CommandSketcherBSpline.cpp | 743 +- src/Mod/Sketcher/Gui/CommandSketcherTools.cpp | 185 +- .../Gui/CommandSketcherVirtualSpace.cpp | 95 +- src/Mod/Sketcher/Gui/ConstraintFilters.h | 228 +- src/Mod/Sketcher/Gui/DrawSketchHandler.cpp | 616 +- src/Mod/Sketcher/Gui/DrawSketchHandler.h | 181 +- src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h | 273 +- .../Gui/DrawSketchHandlerArcOfEllipse.h | 264 +- .../Gui/DrawSketchHandlerArcOfHyperbola.h | 241 +- .../Gui/DrawSketchHandlerArcOfParabola.h | 175 +- .../Sketcher/Gui/DrawSketchHandlerBSpline.h | 277 +- .../DrawSketchHandlerBSplineByInterpolation.h | 45 +- .../Gui/DrawSketchHandlerCarbonCopy.h | 100 +- .../Sketcher/Gui/DrawSketchHandlerCircle.h | 190 +- .../Sketcher/Gui/DrawSketchHandlerEllipse.h | 303 +- .../Sketcher/Gui/DrawSketchHandlerExtend.h | 192 +- .../Sketcher/Gui/DrawSketchHandlerExternal.h | 148 +- .../Sketcher/Gui/DrawSketchHandlerFillet.h | 214 +- src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h | 89 +- .../Sketcher/Gui/DrawSketchHandlerLineSet.h | 461 +- src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h | 52 +- .../Sketcher/Gui/DrawSketchHandlerPolygon.h | 115 +- .../Sketcher/Gui/DrawSketchHandlerRectangle.h | 478 +- src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h | 160 +- .../Sketcher/Gui/DrawSketchHandlerSplitting.h | 65 +- .../Sketcher/Gui/DrawSketchHandlerTrimming.h | 91 +- src/Mod/Sketcher/Gui/EditDatumDialog.cpp | 114 +- src/Mod/Sketcher/Gui/EditDatumDialog.h | 19 +- src/Mod/Sketcher/Gui/EditModeCoinManager.cpp | 648 +- src/Mod/Sketcher/Gui/EditModeCoinManager.h | 161 +- .../Gui/EditModeCoinManagerParameters.cpp | 53 +- .../Gui/EditModeCoinManagerParameters.h | 366 +- .../Gui/EditModeConstraintCoinManager.cpp | 2899 +++--- .../Gui/EditModeConstraintCoinManager.h | 128 +- .../Gui/EditModeGeometryCoinConverter.cpp | 289 +- .../Gui/EditModeGeometryCoinConverter.h | 139 +- .../Gui/EditModeGeometryCoinManager.cpp | 352 +- .../Gui/EditModeGeometryCoinManager.h | 71 +- ...ditModeInformationOverlayCoinConverter.cpp | 324 +- .../EditModeInformationOverlayCoinConverter.h | 135 +- src/Mod/Sketcher/Gui/GeometryCreationMode.h | 11 +- src/Mod/Sketcher/Gui/PreCompiled.cpp | 2 +- src/Mod/Sketcher/Gui/PreCompiled.h | 22 +- .../Gui/PropertyConstraintListItem.cpp | 177 +- .../Sketcher/Gui/PropertyConstraintListItem.h | 56 +- .../Sketcher/Gui/PropertyVisualLayerList.cpp | 27 +- .../Sketcher/Gui/PropertyVisualLayerList.h | 22 +- src/Mod/Sketcher/Gui/ShortcutListener.cpp | 19 +- src/Mod/Sketcher/Gui/ShortcutListener.h | 21 +- src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp | 27 +- src/Mod/Sketcher/Gui/SketchMirrorDialog.h | 9 +- .../Sketcher/Gui/SketchOrientationDialog.cpp | 32 +- .../Sketcher/Gui/SketchOrientationDialog.h | 11 +- .../Gui/SketchRectangularArrayDialog.cpp | 20 +- .../Gui/SketchRectangularArrayDialog.h | 12 +- .../Gui/SketcherRegularPolygonDialog.cpp | 10 +- .../Gui/SketcherRegularPolygonDialog.h | 10 +- src/Mod/Sketcher/Gui/SketcherSettings.cpp | 93 +- src/Mod/Sketcher/Gui/SketcherSettings.h | 25 +- src/Mod/Sketcher/Gui/SnapManager.cpp | 83 +- src/Mod/Sketcher/Gui/SnapManager.h | 42 +- src/Mod/Sketcher/Gui/SoZoomTranslation.cpp | 63 +- src/Mod/Sketcher/Gui/SoZoomTranslation.h | 34 +- src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp | 45 +- src/Mod/Sketcher/Gui/TaskDlgEditSketch.h | 34 +- .../Sketcher/Gui/TaskSketcherConstraints.cpp | 1212 +-- .../Sketcher/Gui/TaskSketcherConstraints.h | 128 +- .../Gui/TaskSketcherCreateCommands.cpp | 55 +- .../Sketcher/Gui/TaskSketcherCreateCommands.h | 28 +- src/Mod/Sketcher/Gui/TaskSketcherElements.cpp | 1308 +-- src/Mod/Sketcher/Gui/TaskSketcherElements.h | 36 +- src/Mod/Sketcher/Gui/TaskSketcherMessages.cpp | 138 +- src/Mod/Sketcher/Gui/TaskSketcherMessages.h | 23 +- .../Gui/TaskSketcherSolverAdvanced.cpp | 555 +- .../Sketcher/Gui/TaskSketcherSolverAdvanced.h | 17 +- .../Sketcher/Gui/TaskSketcherValidation.cpp | 279 +- src/Mod/Sketcher/Gui/TaskSketcherValidation.h | 22 +- src/Mod/Sketcher/Gui/Utils.cpp | 216 +- src/Mod/Sketcher/Gui/Utils.h | 140 +- src/Mod/Sketcher/Gui/ViewProviderPython.cpp | 20 +- src/Mod/Sketcher/Gui/ViewProviderPython.h | 10 +- src/Mod/Sketcher/Gui/ViewProviderSketch.cpp | 2338 +++-- src/Mod/Sketcher/Gui/ViewProviderSketch.h | 487 +- .../Gui/ViewProviderSketchCoinAttorney.h | 185 +- .../ViewProviderSketchGeometryExtension.cpp | 33 +- .../Gui/ViewProviderSketchGeometryExtension.h | 48 +- ...ewProviderSketchGeometryExtensionPyImp.cpp | 17 +- src/Mod/Sketcher/Gui/VisualLayer.cpp | 22 +- src/Mod/Sketcher/Gui/VisualLayer.h | 27 +- src/Mod/Sketcher/Gui/Workbench.cpp | 450 +- src/Mod/Sketcher/Gui/Workbench.h | 9 +- 98 files changed, 17648 insertions(+), 13572 deletions(-) diff --git a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp index f1a1a5f4d6..eb389779bd 100644 --- a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp +++ b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp @@ -57,16 +57,19 @@ void loadSketcherResource() Gui::Translator::instance()->refresh(); } -namespace SketcherGui { -class Module : public Py::ExtensionModule +namespace SketcherGui +{ +class Module: public Py::ExtensionModule { public: - Module() : Py::ExtensionModule("SketcherGui") + Module() + : Py::ExtensionModule("SketcherGui") { - initialize("This module is the SketcherGui module."); // register with Python + initialize("This module is the SketcherGui module.");// register with Python } - ~Module() override {} + ~Module() override + {} private: }; @@ -76,7 +79,7 @@ PyObject* initModule() return Base::Interpreter().addModule(new Module); } -} // namespace SketcherGui +}// namespace SketcherGui /* Python entry */ PyMOD_INIT_FUNC(SketcherGui) @@ -89,7 +92,7 @@ PyMOD_INIT_FUNC(SketcherGui) Base::Interpreter().runString("import PartGui"); Base::Interpreter().runString("import Sketcher"); } - catch(const Base::Exception& e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ImportError, e.what()); PyMOD_Return(nullptr); } @@ -101,7 +104,7 @@ PyMOD_INIT_FUNC(SketcherGui) Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/elements")); Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/general")); Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/geometry")); - //Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/obsolete")); + // Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/obsolete")); Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/pointers")); Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/splines")); Gui::BitmapFactory().addPath(QString::fromLatin1(":/icons/tools")); @@ -118,23 +121,29 @@ PyMOD_INIT_FUNC(SketcherGui) SketcherGui::Workbench::init(); // Add Types to module - Base::Interpreter().addType(&SketcherGui::ViewProviderSketchGeometryExtensionPy ::Type,sketcherGuiModule,"ViewProviderSketchGeometryExtension"); + Base::Interpreter().addType(&SketcherGui::ViewProviderSketchGeometryExtensionPy ::Type, + sketcherGuiModule, + "ViewProviderSketchGeometryExtension"); // init objects - SketcherGui::ViewProviderSketch ::init(); - SketcherGui::ViewProviderPython ::init(); - SketcherGui::ViewProviderCustom ::init(); - SketcherGui::ViewProviderCustomPython ::init(); - SketcherGui::SoZoomTranslation ::initClass(); - SketcherGui::PropertyConstraintListItem ::init(); - SketcherGui::ViewProviderSketchGeometryExtension ::init(); + SketcherGui::ViewProviderSketch ::init(); + SketcherGui::ViewProviderPython ::init(); + SketcherGui::ViewProviderCustom ::init(); + SketcherGui::ViewProviderCustomPython ::init(); + SketcherGui::SoZoomTranslation ::initClass(); + SketcherGui::PropertyConstraintListItem ::init(); + SketcherGui::ViewProviderSketchGeometryExtension ::init(); - (void)new Gui::PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Sketcher") ); - (void)new Gui::PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Sketcher") ); - (void)new Gui::PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Sketcher") ); - (void)new Gui::PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","Sketcher") ); + (void)new Gui::PrefPageProducer( + QT_TRANSLATE_NOOP("QObject", "Sketcher")); + (void)new Gui::PrefPageProducer( + QT_TRANSLATE_NOOP("QObject", "Sketcher")); + (void)new Gui::PrefPageProducer( + QT_TRANSLATE_NOOP("QObject", "Sketcher")); + (void)new Gui::PrefPageProducer( + QT_TRANSLATE_NOOP("QObject", "Sketcher")); - // add resources and reloads the translators + // add resources and reloads the translators loadSketcherResource(); PyMOD_Return(sketcherGuiModule); diff --git a/src/Mod/Sketcher/Gui/AutoConstraint.h b/src/Mod/Sketcher/Gui/AutoConstraint.h index 46de42f78b..4f70f2d16f 100644 --- a/src/Mod/Sketcher/Gui/AutoConstraint.h +++ b/src/Mod/Sketcher/Gui/AutoConstraint.h @@ -24,7 +24,10 @@ #ifndef SKETCHERGUI_AutoConstraint_H #define SKETCHERGUI_AutoConstraint_H -namespace SketcherGui { +#include + +namespace SketcherGui +{ // A Simple data type to hold basic information for suggested constraints struct AutoConstraint @@ -40,8 +43,7 @@ struct AutoConstraint Sketcher::PointPos PosId; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_AutoConstraint_H - +#endif// SKETCHERGUI_AutoConstraint_H diff --git a/src/Mod/Sketcher/Gui/Command.cpp b/src/Mod/Sketcher/Gui/Command.cpp index e43a2bc1da..ceb66eab49 100644 --- a/src/Mod/Sketcher/Gui/Command.cpp +++ b/src/Mod/Sketcher/Gui/Command.cpp @@ -22,21 +22,21 @@ #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 -#include #include #include +#include #include #include #include @@ -47,17 +47,17 @@ #include #include #include +#include +#include +#include #include #include -#include -#include -#include #include "SketchMirrorDialog.h" #include "SketchOrientationDialog.h" #include "TaskSketcherValidation.h" -#include "ViewProviderSketch.h" #include "Utils.h" +#include "ViewProviderSketch.h" using namespace std; @@ -66,92 +66,96 @@ using namespace Part; using namespace Attacher; -namespace SketcherGui { +namespace SketcherGui +{ - class ExceptionWrongInput : public Base::Exception { - public: - ExceptionWrongInput() - : ErrMsg(QString()) - { +class ExceptionWrongInput: public Base::Exception +{ +public: + ExceptionWrongInput() + : ErrMsg(QString()) + {} - } - - //Pass untranslated strings, enclosed in QT_TR_NOOP() - explicit ExceptionWrongInput(const char* ErrMsg){ - this->ErrMsg = QObject::tr( ErrMsg ); - this->setMessage(ErrMsg); - } - - ~ExceptionWrongInput() throw() override {} - - QString ErrMsg; - }; - - - Attacher::eMapMode SuggestAutoMapMode(Attacher::SuggestResult::eSuggestResult* pMsgId = nullptr, - QString* message = nullptr, - std::vector* allmodes = nullptr){ - //convert pointers into valid references, to avoid checking for null pointers everywhere - Attacher::SuggestResult::eSuggestResult buf; - if (!pMsgId) - pMsgId = &buf; - Attacher::SuggestResult::eSuggestResult &msg = *pMsgId; - QString buf2; - if (!message) - message = &buf2; - QString &msg_str = *message; - - App::PropertyLinkSubList tmpSupport; - Gui::Selection().getAsPropertyLinkSubList(tmpSupport); - - Attacher::SuggestResult sugr; - AttachEngine3D eng; - eng.setUp(tmpSupport); - eng.suggestMapModes(sugr); - if (allmodes) - *allmodes = sugr.allApplicableModes; - msg = sugr.message; - switch(msg){ - case Attacher::SuggestResult::srOK: - break; - case Attacher::SuggestResult::srNoModesFit: - msg_str = QObject::tr("There are no modes that accept the selected set of subelements"); - break; - case Attacher::SuggestResult::srLinkBroken: - msg_str = QObject::tr("Broken link to support subelements"); - break; - case Attacher::SuggestResult::srUnexpectedError: - msg_str = QObject::tr("Unexpected error"); - break; - case Attacher::SuggestResult::srIncompatibleGeometry: - if(tmpSupport.getSubValues()[0].substr(0,4) == std::string("Face")) - msg_str = QObject::tr("Face is non-planar"); - else - msg_str = QObject::tr("Selected shapes are of wrong form (e.g., a curved edge where a straight one is needed)"); - break; - default: - msg_str = QObject::tr("Unexpected error"); - assert(0/*no message for eSuggestResult enum item*/); - } - - return sugr.bestFitMode; + // Pass untranslated strings, enclosed in QT_TR_NOOP() + explicit ExceptionWrongInput(const char* ErrMsg) + { + this->ErrMsg = QObject::tr(ErrMsg); + this->setMessage(ErrMsg); } -} //namespace SketcherGui + + ~ExceptionWrongInput() throw() override + {} + + QString ErrMsg; +}; + + +Attacher::eMapMode SuggestAutoMapMode(Attacher::SuggestResult::eSuggestResult* pMsgId = nullptr, + QString* message = nullptr, + std::vector* allmodes = nullptr) +{ + // convert pointers into valid references, to avoid checking for null pointers everywhere + Attacher::SuggestResult::eSuggestResult buf; + if (!pMsgId) + pMsgId = &buf; + Attacher::SuggestResult::eSuggestResult& msg = *pMsgId; + QString buf2; + if (!message) + message = &buf2; + QString& msg_str = *message; + + App::PropertyLinkSubList tmpSupport; + Gui::Selection().getAsPropertyLinkSubList(tmpSupport); + + Attacher::SuggestResult sugr; + AttachEngine3D eng; + eng.setUp(tmpSupport); + eng.suggestMapModes(sugr); + if (allmodes) + *allmodes = sugr.allApplicableModes; + msg = sugr.message; + switch (msg) { + case Attacher::SuggestResult::srOK: + break; + case Attacher::SuggestResult::srNoModesFit: + msg_str = QObject::tr("There are no modes that accept the selected set of subelements"); + break; + case Attacher::SuggestResult::srLinkBroken: + msg_str = QObject::tr("Broken link to support subelements"); + break; + case Attacher::SuggestResult::srUnexpectedError: + msg_str = QObject::tr("Unexpected error"); + break; + case Attacher::SuggestResult::srIncompatibleGeometry: + if (tmpSupport.getSubValues()[0].substr(0, 4) == std::string("Face")) + msg_str = QObject::tr("Face is non-planar"); + else + msg_str = QObject::tr("Selected shapes are of wrong form (e.g., a curved edge " + "where a straight one is needed)"); + break; + default: + msg_str = QObject::tr("Unexpected error"); + assert(0 /*no message for eSuggestResult enum item*/); + } + + return sugr.bestFitMode; +} +}// namespace SketcherGui /* Sketch commands =======================================================*/ DEF_STD_CMD_A(CmdSketcherNewSketch) CmdSketcherNewSketch::CmdSketcherNewSketch() - :Command("Sketcher_NewSketch") + : Command("Sketcher_NewSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create sketch"); - sToolTipText = QT_TR_NOOP("Create a new sketch."); - sWhatsThis = "Sketcher_NewSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_NewSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create sketch"); + sToolTipText = QT_TR_NOOP("Create a new sketch."); + sWhatsThis = "Sketcher_NewSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_NewSketch"; } void CmdSketcherNewSketch::activated(int iMsg) @@ -159,44 +163,54 @@ void CmdSketcherNewSketch::activated(int iMsg) Q_UNUSED(iMsg); Attacher::eMapMode mapmode = Attacher::mmDeactivated; bool bAttach = false; - if (Gui::Selection().hasSelection()){ + if (Gui::Selection().hasSelection()) { Attacher::SuggestResult::eSuggestResult msgid = Attacher::SuggestResult::srOK; QString msg_str; std::vector validModes; mapmode = SuggestAutoMapMode(&msgid, &msg_str, &validModes); if (msgid == Attacher::SuggestResult::srOK) bAttach = true; - if (msgid != Attacher::SuggestResult::srOK && msgid != Attacher::SuggestResult::srNoModesFit){ - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Sketch mapping"), - QObject::tr("Can't map the sketch to selected object. %1.").arg(msg_str)); + if (msgid != Attacher::SuggestResult::srOK + && msgid != Attacher::SuggestResult::srNoModesFit) { + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + QObject::tr("Sketch mapping"), + QObject::tr("Can't map the sketch to selected object. %1.").arg(msg_str)); return; } - if (validModes.size() > 1){ + if (validModes.size() > 1) { validModes.insert(validModes.begin(), Attacher::mmDeactivated); bool ok; QStringList items; items.push_back(QObject::tr("Don't attach")); - int iSugg = 0;//index of the auto-suggested mode in the list of valid modes - for (size_t i = 0 ; i < validModes.size() ; ++i){ - auto uiStrings = AttacherGui::getUIStrings(AttachEnginePlane::getClassTypeId(), validModes[i]); + int iSugg = 0;// index of the auto-suggested mode in the list of valid modes + for (size_t i = 0; i < validModes.size(); ++i) { + auto uiStrings = + AttacherGui::getUIStrings(AttachEnginePlane::getClassTypeId(), validModes[i]); items.push_back(uiStrings[0]); if (validModes[i] == mapmode) - iSugg = items.size()-1; + iSugg = items.size() - 1; } - QString text = QInputDialog::getItem(Gui::getMainWindow(), + QString text = QInputDialog::getItem( + Gui::getMainWindow(), qApp->translate("Sketcher_NewSketch", "Sketch attachment"), - qApp->translate("Sketcher_NewSketch", "Select the method to attach this sketch to selected object"), - items, iSugg, false, &ok, Qt::MSWindowsFixedSizeDialogHint); + qApp->translate("Sketcher_NewSketch", + "Select the method to attach this sketch to selected object"), + items, + iSugg, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint); if (!ok) return; int index = items.indexOf(text); - if (index == 0){ + if (index == 0) { bAttach = false; mapmode = Attacher::mmDeactivated; - } else { + } + else { bAttach = true; - mapmode = validModes[index-1]; + mapmode = validModes[index - 1]; } } } @@ -204,8 +218,8 @@ void CmdSketcherNewSketch::activated(int iMsg) if (bAttach) { std::vector objects = Gui::Selection().getSelectionEx(); - //assert (objects.size() == 1); //should have been filtered out by SuggestAutoMapMode - //Gui::SelectionObject &sel_support = objects[0]; + // assert (objects.size() == 1); //should have been filtered out by SuggestAutoMapMode + // Gui::SelectionObject &sel_support = objects[0]; App::PropertyLinkSubList support; Gui::Selection().getAsPropertyLinkSubList(support); std::string supportString = support.getPyReprString(); @@ -214,22 +228,31 @@ void CmdSketcherNewSketch::activated(int iMsg) std::string FeatName = getUniqueObjectName("Sketch"); openCommand(QT_TRANSLATE_NOOP("Command", "Create a new sketch on a face")); - doCommand(Doc,"App.activeDocument().addObject('Sketcher::SketchObject', '%s')", FeatName.c_str()); + doCommand(Doc, + "App.activeDocument().addObject('Sketcher::SketchObject', '%s')", + FeatName.c_str()); if (mapmode < Attacher::mmDummy_NumberOfModes) - doCommand(Gui,"App.activeDocument().%s.MapMode = \"%s\"",FeatName.c_str(),AttachEngine::getModeName(mapmode).c_str()); + doCommand(Gui, + "App.activeDocument().%s.MapMode = \"%s\"", + FeatName.c_str(), + AttachEngine::getModeName(mapmode).c_str()); else assert(0 /* mapmode index out of range */); - doCommand(Gui,"App.activeDocument().%s.Support = %s", FeatName.c_str(), supportString.c_str()); - doCommand(Gui,"App.activeDocument().recompute()"); // recompute the sketch placement based on its support - doCommand(Gui,"Gui.activeDocument().setEdit('%s')", FeatName.c_str()); + doCommand( + Gui, "App.activeDocument().%s.Support = %s", FeatName.c_str(), supportString.c_str()); + doCommand(Gui, "App.activeDocument().recompute()");// recompute the sketch placement based + // on its support + doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); - Part::Feature *part = static_cast(support.getValue()); // if multi-part support, this will return 0 - if (part){ + Part::Feature* part = static_cast( + support.getValue());// if multi-part support, this will return 0 + if (part) { App::DocumentObjectGroup* grp = part->getGroup(); if (grp) { doCommand(Doc, "App.activeDocument().%s.addObject(App.activeDocument().%s)", - grp->getNameInDocument(), FeatName.c_str()); + grp->getNameInDocument(), + FeatName.c_str()); } } } @@ -239,22 +262,33 @@ void CmdSketcherNewSketch::activated(int iMsg) Dlg.adjustSize(); if (Dlg.exec() != QDialog::Accepted) - return; // canceled + return;// canceled Base::Vector3d p = Dlg.Pos.getPosition(); Base::Rotation r = Dlg.Pos.getRotation(); std::string FeatName = getUniqueObjectName("Sketch"); openCommand(QT_TRANSLATE_NOOP("Command", "Create a new sketch")); - doCommand(Doc, "App.activeDocument().addObject('Sketcher::SketchObject', '%s')", FeatName.c_str()); doCommand(Doc, - "App.activeDocument().%s.Placement = App.Placement(App.Vector(%f, %f, %f), App.Rotation(%f, %f, %f, %f))", - FeatName.c_str(), p.x, p.y, p.z, r[0], r[1], r[2], r[3]); - doCommand(Doc,"App.activeDocument().%s.MapMode = \"%s\"", - FeatName.c_str(), AttachEngine::getModeName(Attacher::mmDeactivated).c_str()); - doCommand(Gui,"Gui.activeDocument().setEdit('%s')", FeatName.c_str()); + "App.activeDocument().addObject('Sketcher::SketchObject', '%s')", + FeatName.c_str()); + doCommand(Doc, + "App.activeDocument().%s.Placement = App.Placement(App.Vector(%f, %f, %f), " + "App.Rotation(%f, %f, %f, %f))", + FeatName.c_str(), + p.x, + p.y, + p.z, + r[0], + r[1], + r[2], + r[3]); + doCommand(Doc, + "App.activeDocument().%s.MapMode = \"%s\"", + FeatName.c_str(), + AttachEngine::getModeName(Attacher::mmDeactivated).c_str()); + doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } - } bool CmdSketcherNewSketch::isActive() @@ -268,15 +302,15 @@ bool CmdSketcherNewSketch::isActive() DEF_STD_CMD_A(CmdSketcherEditSketch) CmdSketcherEditSketch::CmdSketcherEditSketch() - :Command("Sketcher_EditSketch") + : Command("Sketcher_EditSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Edit sketch"); - sToolTipText = QT_TR_NOOP("Edit the selected sketch."); - sWhatsThis = "Sketcher_EditSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_EditSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Edit sketch"); + sToolTipText = QT_TR_NOOP("Edit the selected sketch."); + sWhatsThis = "Sketcher_EditSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_EditSketch"; } void CmdSketcherEditSketch::activated(int iMsg) @@ -285,8 +319,9 @@ void CmdSketcherEditSketch::activated(int iMsg) Gui::SelectionFilter SketchFilter("SELECT Sketcher::SketchObject COUNT 1"); if (SketchFilter.match()) { - Sketcher::SketchObject *Sketch = static_cast(SketchFilter.Result[0][0].getObject()); - doCommand(Gui,"Gui.activeDocument().setEdit('%s')",Sketch->getNameInDocument()); + Sketcher::SketchObject* Sketch = + static_cast(SketchFilter.Result[0][0].getObject()); + doCommand(Gui, "Gui.activeDocument().setEdit('%s')", Sketch->getNameInDocument()); } } @@ -298,33 +333,34 @@ bool CmdSketcherEditSketch::isActive() DEF_STD_CMD_A(CmdSketcherLeaveSketch) CmdSketcherLeaveSketch::CmdSketcherLeaveSketch() - : Command("Sketcher_LeaveSketch") + : Command("Sketcher_LeaveSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Leave sketch"); - sToolTipText = QT_TR_NOOP("Finish editing the active sketch."); - sWhatsThis = "Sketcher_LeaveSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_LeaveSketch"; - eType = 0; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Leave sketch"); + sToolTipText = QT_TR_NOOP("Finish editing the active sketch."); + sWhatsThis = "Sketcher_LeaveSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_LeaveSketch"; + eType = 0; } void CmdSketcherLeaveSketch::activated(int iMsg) { Q_UNUSED(iMsg); - Gui::Document *doc = getActiveGuiDocument(); + Gui::Document* doc = getActiveGuiDocument(); if (doc) { // checks if a Sketch Viewprovider is in Edit and is in no special mode - SketcherGui::ViewProviderSketch* vp = dynamic_cast(doc->getInEdit()); + SketcherGui::ViewProviderSketch* vp = + dynamic_cast(doc->getInEdit()); if (vp && vp->getSketchMode() != ViewProviderSketch::STATUS_NONE) vp->purgeHandler(); } // See also TaskDlgEditSketch::reject - doCommand(Gui,"Gui.activeDocument().resetEdit()"); - doCommand(Doc,"App.ActiveDocument.recompute()"); + doCommand(Gui, "Gui.activeDocument().resetEdit()"); + doCommand(Doc, "App.ActiveDocument.recompute()"); } bool CmdSketcherLeaveSketch::isActive() @@ -335,27 +371,28 @@ bool CmdSketcherLeaveSketch::isActive() DEF_STD_CMD_A(CmdSketcherStopOperation) CmdSketcherStopOperation::CmdSketcherStopOperation() - : Command("Sketcher_StopOperation") + : Command("Sketcher_StopOperation") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Stop operation"); - sToolTipText = QT_TR_NOOP("When in edit mode, " - "stop the active operation " - "(drawing, constraining, etc.)."); - sWhatsThis = "Sketcher_StopOperation"; - sStatusTip = sToolTipText; - sPixmap = "process-stop"; - eType = 0; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Stop operation"); + sToolTipText = QT_TR_NOOP("When in edit mode, " + "stop the active operation " + "(drawing, constraining, etc.)."); + sWhatsThis = "Sketcher_StopOperation"; + sStatusTip = sToolTipText; + sPixmap = "process-stop"; + eType = 0; } void CmdSketcherStopOperation::activated(int iMsg) { Q_UNUSED(iMsg); - Gui::Document *doc = getActiveGuiDocument(); + Gui::Document* doc = getActiveGuiDocument(); if (doc) { - SketcherGui::ViewProviderSketch* vp = dynamic_cast(doc->getInEdit()); + SketcherGui::ViewProviderSketch* vp = + dynamic_cast(doc->getInEdit()); if (vp) { vp->purgeHandler(); } @@ -370,28 +407,31 @@ bool CmdSketcherStopOperation::isActive() DEF_STD_CMD_A(CmdSketcherReorientSketch) CmdSketcherReorientSketch::CmdSketcherReorientSketch() - :Command("Sketcher_ReorientSketch") + : Command("Sketcher_ReorientSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Reorient sketch..."); - sToolTipText = QT_TR_NOOP("Place the selected sketch on one of the global coordinate planes.\n" - "This will clear the 'Support' property, if any."); - sWhatsThis = "Sketcher_ReorientSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_ReorientSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Reorient sketch..."); + sToolTipText = QT_TR_NOOP("Place the selected sketch on one of the global coordinate planes.\n" + "This will clear the 'Support' property, if any."); + sWhatsThis = "Sketcher_ReorientSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_ReorientSketch"; } void CmdSketcherReorientSketch::activated(int iMsg) { Q_UNUSED(iMsg); - Sketcher::SketchObject* sketch = Gui::Selection().getObjectsOfType().front(); + Sketcher::SketchObject* sketch = + Gui::Selection().getObjectsOfType().front(); if (sketch->Support.getValue()) { - int ret = QMessageBox::question(Gui::getMainWindow(), - qApp->translate("Sketcher_ReorientSketch","Sketch has support"), - qApp->translate("Sketcher_ReorientSketch","Sketch with a support face cannot be reoriented.\n" - "Do you want to detach it from the support?"), - QMessageBox::Yes|QMessageBox::No); + int ret = QMessageBox::question( + Gui::getMainWindow(), + qApp->translate("Sketcher_ReorientSketch", "Sketch has support"), + qApp->translate("Sketcher_ReorientSketch", + "Sketch with a support face cannot be reoriented.\n" + "Do you want to detach it from the support?"), + QMessageBox::Yes | QMessageBox::No); if (ret == QMessageBox::No) return; sketch->Support.setValue(nullptr); @@ -401,7 +441,7 @@ void CmdSketcherReorientSketch::activated(int iMsg) SketchOrientationDialog Dlg; if (Dlg.exec() != QDialog::Accepted) - return; // canceled + return;// canceled Base::Vector3d p = Dlg.Pos.getPosition(); Base::Rotation r = Dlg.Pos.getRotation(); @@ -410,83 +450,90 @@ void CmdSketcherReorientSketch::activated(int iMsg) switch (Dlg.DirType) { case 0: camstring = "#Inventor V2.1 ascii\\n" - "OrthographicCamera {\\n" - " viewportMapping ADJUST_CAMERA\\n" - " position 0 0 87\\n" - " orientation 0 0 1 0\\n" - " nearDistance -112.88701\\n" - " farDistance 287.28702\\n" - " aspectRatio 1\\n" - " focalDistance 87\\n" - " height 143.52005 }"; + "OrthographicCamera {\\n" + " viewportMapping ADJUST_CAMERA\\n" + " position 0 0 87\\n" + " orientation 0 0 1 0\\n" + " nearDistance -112.88701\\n" + " farDistance 287.28702\\n" + " aspectRatio 1\\n" + " focalDistance 87\\n" + " height 143.52005 }"; break; case 1: camstring = "#Inventor V2.1 ascii\\n" - "OrthographicCamera {\\n" - " viewportMapping ADJUST_CAMERA\\n" - " position 0 0 -87\\n" - " orientation -1 0 0 3.1415927\\n" - " nearDistance -112.88701\\n" - " farDistance 287.28702\\n " - " aspectRatio 1\\n" - " focalDistance 87\\n" - " height 143.52005 }"; + "OrthographicCamera {\\n" + " viewportMapping ADJUST_CAMERA\\n" + " position 0 0 -87\\n" + " orientation -1 0 0 3.1415927\\n" + " nearDistance -112.88701\\n" + " farDistance 287.28702\\n " + " aspectRatio 1\\n" + " focalDistance 87\\n" + " height 143.52005 }"; break; case 2: camstring = "#Inventor V2.1 ascii\\n" - "OrthographicCamera {\\n" - " viewportMapping ADJUST_CAMERA\\n" - " position 0 -87 0\\n" - " orientation -1 0 0 4.712389\\n" - " nearDistance -112.88701\\n" - " farDistance 287.28702\\n" - " aspectRatio 1\\n" - " focalDistance 87\\n" - " height 143.52005\\n\\n}"; + "OrthographicCamera {\\n" + " viewportMapping ADJUST_CAMERA\\n" + " position 0 -87 0\\n" + " orientation -1 0 0 4.712389\\n" + " nearDistance -112.88701\\n" + " farDistance 287.28702\\n" + " aspectRatio 1\\n" + " focalDistance 87\\n" + " height 143.52005\\n\\n}"; break; case 3: camstring = "#Inventor V2.1 ascii\\n" - "OrthographicCamera {\\n" - " viewportMapping ADJUST_CAMERA\\n" - " position 0 87 0\\n" - " orientation 0 0.70710683 0.70710683 3.1415927\\n" - " nearDistance -112.88701\\n" - " farDistance 287.28702\\n" - " aspectRatio 1\\n" - " focalDistance 87\\n" - " height 143.52005\\n\\n}"; + "OrthographicCamera {\\n" + " viewportMapping ADJUST_CAMERA\\n" + " position 0 87 0\\n" + " orientation 0 0.70710683 0.70710683 3.1415927\\n" + " nearDistance -112.88701\\n" + " farDistance 287.28702\\n" + " aspectRatio 1\\n" + " focalDistance 87\\n" + " height 143.52005\\n\\n}"; break; case 4: camstring = "#Inventor V2.1 ascii\\n" - "OrthographicCamera {\\n" - " viewportMapping ADJUST_CAMERA\\n" - " position 87 0 0\\n" - " orientation 0.57735026 0.57735026 0.57735026 2.0943952\\n" - " nearDistance -112.887\\n" - " farDistance 287.28699\\n" - " aspectRatio 1\\n" - " focalDistance 87\\n" - " height 143.52005\\n\\n}"; + "OrthographicCamera {\\n" + " viewportMapping ADJUST_CAMERA\\n" + " position 87 0 0\\n" + " orientation 0.57735026 0.57735026 0.57735026 2.0943952\\n" + " nearDistance -112.887\\n" + " farDistance 287.28699\\n" + " aspectRatio 1\\n" + " focalDistance 87\\n" + " height 143.52005\\n\\n}"; break; case 5: camstring = "#Inventor V2.1 ascii\\n" - "OrthographicCamera {\\n" - " viewportMapping ADJUST_CAMERA\\n" - " position -87 0 0\\n" - " orientation -0.57735026 0.57735026 0.57735026 4.1887903\\n" - " nearDistance -112.887\\n" - " farDistance 287.28699\\n" - " aspectRatio 1\\n" - " focalDistance 87\\n" - " height 143.52005\\n\\n}"; + "OrthographicCamera {\\n" + " viewportMapping ADJUST_CAMERA\\n" + " position -87 0 0\\n" + " orientation -0.57735026 0.57735026 0.57735026 4.1887903\\n" + " nearDistance -112.887\\n" + " farDistance 287.28699\\n" + " aspectRatio 1\\n" + " focalDistance 87\\n" + " height 143.52005\\n\\n}"; break; } openCommand(QT_TRANSLATE_NOOP("Command", "Reorient sketch")); - Gui::cmdAppObjectArgs(sketch, - "Placement = App.Placement(App.Vector(%f, %f, %f), App.Rotation(%f, %f, %f, %f))", - p.x, p.y, p.z, r[0], r[1], r[2], r[3]); - doCommand(Gui,"Gui.ActiveDocument.setEdit('%s')", sketch->getNameInDocument()); + Gui::cmdAppObjectArgs( + sketch, + "Placement = App.Placement(App.Vector(%f, %f, %f), App.Rotation(%f, %f, %f, %f))", + p.x, + p.y, + p.z, + r[0], + r[1], + r[2], + r[3]); + doCommand(Gui, "Gui.ActiveDocument.setEdit('%s')", sketch->getNameInDocument()); } bool CmdSketcherReorientSketch::isActive() @@ -497,17 +544,18 @@ bool CmdSketcherReorientSketch::isActive() DEF_STD_CMD_A(CmdSketcherMapSketch) CmdSketcherMapSketch::CmdSketcherMapSketch() - : Command("Sketcher_MapSketch") + : Command("Sketcher_MapSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Map sketch to face..."); - sToolTipText = QT_TR_NOOP("Set the 'Support' of a sketch.\n" - "First select the supporting geometry, for example, a face or an edge of a solid object,\n" - "then call this command, then choose the desired sketch."); - sWhatsThis = "Sketcher_MapSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_MapSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Map sketch to face..."); + sToolTipText = QT_TR_NOOP( + "Set the 'Support' of a sketch.\n" + "First select the supporting geometry, for example, a face or an edge of a solid object,\n" + "then call this command, then choose the desired sketch."); + sWhatsThis = "Sketcher_MapSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_MapSketch"; } void CmdSketcherMapSketch::activated(int iMsg) @@ -518,27 +566,36 @@ void CmdSketcherMapSketch::activated(int iMsg) Attacher::eMapMode suggMapMode; std::vector validModes; - //check that selection is valid for at least some mapping mode. + // check that selection is valid for at least some mapping mode. Attacher::SuggestResult::eSuggestResult msgid = Attacher::SuggestResult::srOK; suggMapMode = SuggestAutoMapMode(&msgid, &msg_str, &validModes); App::Document* doc = App::GetApplication().getActiveDocument(); - std::vector sketches = doc->getObjectsOfType(Part::Part2DObject::getClassTypeId()); + std::vector sketches = + doc->getObjectsOfType(Part::Part2DObject::getClassTypeId()); if (sketches.empty()) { - Gui::TranslatedUserWarning(doc->Label.getStrValue(), - qApp->translate("Sketcher_MapSketch", "No sketch found"), - qApp->translate("Sketcher_MapSketch", "The document doesn't have a sketch")); + Gui::TranslatedUserWarning( + doc->Label.getStrValue(), + qApp->translate("Sketcher_MapSketch", "No sketch found"), + qApp->translate("Sketcher_MapSketch", "The document doesn't have a sketch")); return; } bool ok; QStringList items; - for (std::vector::iterator it = sketches.begin(); it != sketches.end(); ++it) + for (std::vector::iterator it = sketches.begin(); + it != sketches.end(); + ++it) items.push_back(QString::fromUtf8((*it)->Label.getValue())); - QString text = QInputDialog::getItem(Gui::getMainWindow(), + QString text = QInputDialog::getItem( + Gui::getMainWindow(), qApp->translate("Sketcher_MapSketch", "Select sketch"), qApp->translate("Sketcher_MapSketch", "Select a sketch from the list"), - items, 0, false, &ok, Qt::MSWindowsFixedSizeDialogHint); + items, + 0, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint); if (!ok) return; int index = items.indexOf(text); @@ -550,23 +607,25 @@ void CmdSketcherMapSketch::activated(int iMsg) App::DocumentObject* part = static_cast(selobjs[i].getObject()); if (!part) { assert(0); - throw Base::ValueError("Unexpected null pointer in CmdSketcherMapSketch::activated"); + throw Base::ValueError( + "Unexpected null pointer in CmdSketcherMapSketch::activated"); } std::vector input = part->getOutListRecursive(); if (std::find(input.begin(), input.end(), sketch) != input.end()) { - throw ExceptionWrongInput(QT_TR_NOOP("Some of the selected objects depend on the sketch to be mapped. " - "Circular dependencies are not allowed.")); + throw ExceptionWrongInput( + QT_TR_NOOP("Some of the selected objects depend on the sketch to be mapped. " + "Circular dependencies are not allowed.")); } } - //Ask for a new mode. - //outline: - // * find out the modes that are compatible with selection. - // * Test if current mode is OK. - // * fill in the dialog - // * execute the dialog - // * collect dialog result - // * action + // Ask for a new mode. + // outline: + // * find out the modes that are compatible with selection. + // * Test if current mode is OK. + // * fill in the dialog + // * execute the dialog + // * collect dialog result + // * action bool bAttach = true; bool bCurIncompatible = false; @@ -578,50 +637,53 @@ void CmdSketcherMapSketch::activated(int iMsg) // * fill in the dialog validModes.insert(validModes.begin(), Attacher::mmDeactivated); - if(bCurIncompatible) + if (bCurIncompatible) validModes.push_back(curMapMode); - //bool ok; //already defined - //QStringList items; //already defined + // bool ok; //already defined + // QStringList items; //already defined items.clear(); items.push_back(QObject::tr("Don't attach")); - int iSugg = 0; //index of the auto-suggested mode in the list of valid modes - int iCurr = 0; //index of current mode in the list of valid modes + int iSugg = 0;// index of the auto-suggested mode in the list of valid modes + int iCurr = 0;// index of current mode in the list of valid modes for (size_t i = 0; i < validModes.size(); ++i) { // Get the 2-element vector of caption, tooltip -- this class cannot use the tooltip, // so it is just ignored. - auto uiStrings = AttacherGui::getUIStrings(AttachEnginePlane::getClassTypeId(), validModes[i]); + auto uiStrings = + AttacherGui::getUIStrings(AttachEnginePlane::getClassTypeId(), validModes[i]); items.push_back(uiStrings[0]); if (validModes[i] == curMapMode) { iCurr = items.size() - 1; - items.back().append(bCurIncompatible? - qApp->translate("Sketcher_MapSketch", " (incompatible with selection)") - : - qApp->translate("Sketcher_MapSketch", " (current)")); + items.back().append( + bCurIncompatible + ? qApp->translate("Sketcher_MapSketch", " (incompatible with selection)") + : qApp->translate("Sketcher_MapSketch", " (current)")); } if (validModes[i] == suggMapMode) { iSugg = items.size() - 1; - if(iSugg == 1) { - iSugg = 0; // redirect deactivate to detach - } else { + if (iSugg == 1) { + iSugg = 0;// redirect deactivate to detach + } + else { items.back().append(qApp->translate("Sketcher_MapSketch", " (suggested)")); } } } // * execute the dialog - text = QInputDialog::getItem(Gui::getMainWindow(), - qApp->translate("Sketcher_MapSketch", "Sketch attachment"), - bCurIncompatible ? - qApp->translate("Sketcher_MapSketch", - "Current attachment mode is incompatible with the new selection.\n" - "Select the method to attach this sketch to selected objects.") - : - qApp->translate("Sketcher_MapSketch", - "Select the method to attach this sketch to selected objects."), - items, - bCurIncompatible ? iSugg : iCurr, - false, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + text = QInputDialog::getItem( + Gui::getMainWindow(), + qApp->translate("Sketcher_MapSketch", "Sketch attachment"), + bCurIncompatible + ? qApp->translate( + "Sketcher_MapSketch", + "Current attachment mode is incompatible with the new selection.\n" + "Select the method to attach this sketch to selected objects.") + : qApp->translate("Sketcher_MapSketch", + "Select the method to attach this sketch to selected objects."), + items, + bCurIncompatible ? iSugg : iCurr, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint); // * collect dialog result if (!ok) return; @@ -629,9 +691,10 @@ void CmdSketcherMapSketch::activated(int iMsg) if (index == 0) { bAttach = false; suggMapMode = Attacher::mmDeactivated; - } else { + } + else { bAttach = true; - suggMapMode = validModes[index-1]; + suggMapMode = validModes[index - 1]; } // * action @@ -641,23 +704,28 @@ void CmdSketcherMapSketch::activated(int iMsg) std::string supportString = support.getPyReprString(); openCommand(QT_TRANSLATE_NOOP("Command", "Attach sketch")); - Gui::cmdAppObjectArgs(sketch, "MapMode = \"%s\"",AttachEngine::getModeName(suggMapMode).c_str()); - Gui::cmdAppObjectArgs(sketch, "Support = %s",supportString.c_str()); + Gui::cmdAppObjectArgs( + sketch, "MapMode = \"%s\"", AttachEngine::getModeName(suggMapMode).c_str()); + Gui::cmdAppObjectArgs(sketch, "Support = %s", supportString.c_str()); commitCommand(); - doCommand(Gui,"App.activeDocument().recompute()"); - } else { + doCommand(Gui, "App.activeDocument().recompute()"); + } + else { openCommand(QT_TRANSLATE_NOOP("Command", "Detach sketch")); - Gui::cmdAppObjectArgs(sketch, "MapMode = \"%s\"",AttachEngine::getModeName(suggMapMode).c_str()); + Gui::cmdAppObjectArgs( + sketch, "MapMode = \"%s\"", AttachEngine::getModeName(suggMapMode).c_str()); Gui::cmdAppObjectArgs(sketch, "Support = None"); commitCommand(); - doCommand(Gui,"App.activeDocument().recompute()"); + doCommand(Gui, "App.activeDocument().recompute()"); } - } catch (ExceptionWrongInput &e) { + } + catch (ExceptionWrongInput& e) { Gui::TranslatedUserWarning(getActiveGuiDocument(), - qApp->translate("Sketcher_MapSketch", "Map sketch"), - qApp->translate("Sketcher_MapSketch", - "Can't map a sketch to support:\n" - "%1").arg(e.ErrMsg.length() ? e.ErrMsg : msg_str)); + qApp->translate("Sketcher_MapSketch", "Map sketch"), + qApp->translate("Sketcher_MapSketch", + "Can't map a sketch to support:\n" + "%1") + .arg(e.ErrMsg.length() ? e.ErrMsg : msg_str)); } } @@ -677,26 +745,28 @@ DEF_STD_CMD_A(CmdSketcherViewSketch) CmdSketcherViewSketch::CmdSketcherViewSketch() : Command("Sketcher_ViewSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("View sketch"); - sToolTipText = QT_TR_NOOP("When in edit mode, " - "set the camera orientation perpendicular to the sketch plane."); - sWhatsThis = "Sketcher_ViewSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_ViewSketch"; - sAccel = "Q, P"; - eType = 0; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("View sketch"); + sToolTipText = QT_TR_NOOP("When in edit mode, " + "set the camera orientation perpendicular to the sketch plane."); + sWhatsThis = "Sketcher_ViewSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_ViewSketch"; + sAccel = "Q, P"; + eType = 0; } void CmdSketcherViewSketch::activated(int iMsg) { Q_UNUSED(iMsg); - Gui::Document *doc = getActiveGuiDocument(); - SketcherGui::ViewProviderSketch* vp = dynamic_cast(doc->getInEdit()); + Gui::Document* doc = getActiveGuiDocument(); + SketcherGui::ViewProviderSketch* vp = + dynamic_cast(doc->getInEdit()); if (vp) { - runCommand(Gui,"Gui.ActiveDocument.ActiveView.setCameraOrientation(" - "App.Placement(Gui.editDocument().EditingTransform).Rotation.Q)"); + runCommand(Gui, + "Gui.ActiveDocument.ActiveView.setCameraOrientation(" + "App.Placement(Gui.editDocument().EditingTransform).Rotation.Q)"); } } @@ -708,27 +778,29 @@ bool CmdSketcherViewSketch::isActive() DEF_STD_CMD_A(CmdSketcherValidateSketch) CmdSketcherValidateSketch::CmdSketcherValidateSketch() - : Command("Sketcher_ValidateSketch") + : Command("Sketcher_ValidateSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Validate sketch..."); - sToolTipText = QT_TR_NOOP("Validate a sketch by looking at missing coincidences,\n" - "invalid constraints, degenerated geometry, etc."); - sWhatsThis = "Sketcher_ValidateSketch"; - sStatusTip = sToolTipText; - eType = 0; - sPixmap = "Sketcher_ValidateSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Validate sketch..."); + sToolTipText = QT_TR_NOOP("Validate a sketch by looking at missing coincidences,\n" + "invalid constraints, degenerated geometry, etc."); + sWhatsThis = "Sketcher_ValidateSketch"; + sStatusTip = sToolTipText; + eType = 0; + sPixmap = "Sketcher_ValidateSketch"; } void CmdSketcherValidateSketch::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector selection = getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); + std::vector selection = + getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); if (selection.size() != 1) { - Gui::TranslatedUserWarning(getActiveGuiDocument(), - qApp->translate("CmdSketcherValidateSketch", "Wrong selection"), - qApp->translate("CmdSketcherValidateSketch", "Select only one sketch.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + qApp->translate("CmdSketcherValidateSketch", "Wrong selection"), + qApp->translate("CmdSketcherValidateSketch", "Select only one sketch.")); return; } @@ -748,26 +820,28 @@ DEF_STD_CMD_A(CmdSketcherMirrorSketch) CmdSketcherMirrorSketch::CmdSketcherMirrorSketch() : Command("Sketcher_MirrorSketch") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Mirror sketch"); - sToolTipText = QT_TR_NOOP("Create a new mirrored sketch for each selected sketch\n" - "by using the X or Y axes, or the origin point,\n" - "as mirroring reference."); - sWhatsThis = "Sketcher_MirrorSketch"; - sStatusTip = sToolTipText; - eType = 0; - sPixmap = "Sketcher_MirrorSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Mirror sketch"); + sToolTipText = QT_TR_NOOP("Create a new mirrored sketch for each selected sketch\n" + "by using the X or Y axes, or the origin point,\n" + "as mirroring reference."); + sWhatsThis = "Sketcher_MirrorSketch"; + sStatusTip = sToolTipText; + eType = 0; + sPixmap = "Sketcher_MirrorSketch"; } void CmdSketcherMirrorSketch::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector selection = getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); + std::vector selection = + getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); if (selection.empty()) { - Gui::TranslatedUserWarning(getActiveGuiDocument(), - qApp->translate("CmdSketcherMirrorSketch", "Wrong selection"), - qApp->translate("CmdSketcherMirrorSketch", "Select one or more sketches.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + qApp->translate("CmdSketcherMirrorSketch", "Wrong selection"), + qApp->translate("CmdSketcherMirrorSketch", "Select one or more sketches.")); return; } @@ -784,21 +858,34 @@ void CmdSketcherMirrorSketch::activated(int iMsg) App::Document* doc = App::GetApplication().getActiveDocument(); openCommand(QT_TRANSLATE_NOOP("Command", "Create a mirrored sketch for each selected sketch")); - for (std::vector::const_iterator it=selection.begin(); it != selection.end(); ++it) { + for (std::vector::const_iterator it = selection.begin(); + it != selection.end(); + ++it) { // create Sketch std::string FeatName = getUniqueObjectName("MirroredSketch"); - doCommand(Doc,"App.activeDocument().addObject('Sketcher::SketchObject', '%s')", FeatName.c_str()); - Sketcher::SketchObject* mirrorsketch = static_cast(doc->getObject(FeatName.c_str())); + doCommand(Doc, + "App.activeDocument().addObject('Sketcher::SketchObject', '%s')", + FeatName.c_str()); + Sketcher::SketchObject* mirrorsketch = + static_cast(doc->getObject(FeatName.c_str())); - const Sketcher::SketchObject* Obj = static_cast((*it).getObject()); + const Sketcher::SketchObject* Obj = + static_cast((*it).getObject()); Base::Placement pl = Obj->Placement.getValue(); Base::Vector3d p = pl.getPosition(); Base::Rotation r = pl.getRotation(); doCommand(Doc, - "App.activeDocument().%s.Placement = App.Placement(App.Vector(%f, %f, %f), App.Rotation(%f, %f, %f, %f))", + "App.activeDocument().%s.Placement = App.Placement(App.Vector(%f, %f, %f), " + "App.Rotation(%f, %f, %f, %f))", FeatName.c_str(), - p.x, p.y, p.z, r[0], r[1], r[2], r[3]); + p.x, + p.y, + p.z, + r[0], + r[1], + r[2], + r[3]); Sketcher::SketchObject* tempsketch = new Sketcher::SketchObject(); int addedGeometries = tempsketch->addGeometry(Obj->getInternalGeometry()); @@ -806,33 +893,38 @@ void CmdSketcherMirrorSketch::activated(int iMsg) std::vector geoIdList; - for (int i=0; i<=addedGeometries; i++) + for (int i = 0; i <= addedGeometries; i++) geoIdList.push_back(i); tempsketch->addSymmetric(geoIdList, refgeoid, refposid); - std::vector tempgeo = tempsketch->getInternalGeometry(); - std::vector tempconstr = tempsketch->Constraints.getValues(); + std::vector tempgeo = tempsketch->getInternalGeometry(); + std::vector tempconstr = tempsketch->Constraints.getValues(); - // If value of addedGeometries or addedConstraints is -1, it gets added to vector begin iterator and that is invalid - std::vector mirrorgeo(tempgeo.begin() + (addedGeometries + 1), tempgeo.end()); - std::vector mirrorconstr(tempconstr.begin() + (addedConstraints + 1), tempconstr.end()); + // If value of addedGeometries or addedConstraints is -1, it gets added to vector begin + // iterator and that is invalid + std::vector mirrorgeo(tempgeo.begin() + (addedGeometries + 1), + tempgeo.end()); + std::vector mirrorconstr(tempconstr.begin() + (addedConstraints + 1), + tempconstr.end()); - for (std::vector::const_iterator itc=mirrorconstr.begin(); itc != mirrorconstr.end(); ++itc) { + for (std::vector::const_iterator itc = mirrorconstr.begin(); + itc != mirrorconstr.end(); + ++itc) { if ((*itc)->First != Sketcher::GeoEnum::GeoUndef - || (*itc)->First == Sketcher::GeoEnum::HAxis - || (*itc)->First == Sketcher::GeoEnum::VAxis) + || (*itc)->First == Sketcher::GeoEnum::HAxis + || (*itc)->First == Sketcher::GeoEnum::VAxis) // not x, y axes or origin (*itc)->First -= (addedGeometries + 1); if ((*itc)->Second != Sketcher::GeoEnum::GeoUndef - || (*itc)->Second == Sketcher::GeoEnum::HAxis - || (*itc)->Second == Sketcher::GeoEnum::VAxis) + || (*itc)->Second == Sketcher::GeoEnum::HAxis + || (*itc)->Second == Sketcher::GeoEnum::VAxis) // not x, y axes or origin (*itc)->Second -= (addedGeometries + 1); if ((*itc)->Third != Sketcher::GeoEnum::GeoUndef - || (*itc)->Third == Sketcher::GeoEnum::HAxis - || (*itc)->Third == Sketcher::GeoEnum::VAxis) + || (*itc)->Third == Sketcher::GeoEnum::HAxis + || (*itc)->Third == Sketcher::GeoEnum::VAxis) // not x, y axes or origin (*itc)->Third -= (addedGeometries + 1); } @@ -842,7 +934,7 @@ void CmdSketcherMirrorSketch::activated(int iMsg) delete tempsketch; } - doCommand(Gui,"App.activeDocument().recompute()"); + doCommand(Gui, "App.activeDocument().recompute()"); } bool CmdSketcherMirrorSketch::isActive() @@ -853,26 +945,28 @@ bool CmdSketcherMirrorSketch::isActive() DEF_STD_CMD_A(CmdSketcherMergeSketches) CmdSketcherMergeSketches::CmdSketcherMergeSketches() -: Command("Sketcher_MergeSketches") + : Command("Sketcher_MergeSketches") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Merge sketches"); - sToolTipText = QT_TR_NOOP("Create a new sketch from merging two or more selected sketches."); - sWhatsThis = "Sketcher_MergeSketches"; - sStatusTip = sToolTipText; - eType = 0; - sPixmap = "Sketcher_MergeSketch"; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Merge sketches"); + sToolTipText = QT_TR_NOOP("Create a new sketch from merging two or more selected sketches."); + sWhatsThis = "Sketcher_MergeSketches"; + sStatusTip = sToolTipText; + eType = 0; + sPixmap = "Sketcher_MergeSketch"; } void CmdSketcherMergeSketches::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector selection = getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); + std::vector selection = + getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); if (selection.size() < 2) { - Gui::TranslatedUserWarning(getActiveGuiDocument(), - qApp->translate("CmdSketcherMergeSketches", "Wrong selection"), - qApp->translate("CmdSketcherMergeSketches", "Select at least two sketches.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + qApp->translate("CmdSketcherMergeSketches", "Wrong selection"), + qApp->translate("CmdSketcherMergeSketches", "Select at least two sketches.")); return; } @@ -882,41 +976,47 @@ void CmdSketcherMergeSketches::activated(int iMsg) std::string FeatName = getUniqueObjectName("Sketch"); openCommand(QT_TRANSLATE_NOOP("Command", "Merge sketches")); - doCommand(Doc,"App.activeDocument().addObject('Sketcher::SketchObject', '%s')", FeatName.c_str()); + doCommand( + Doc, "App.activeDocument().addObject('Sketcher::SketchObject', '%s')", FeatName.c_str()); - Sketcher::SketchObject* mergesketch = static_cast(doc->getObject(FeatName.c_str())); + Sketcher::SketchObject* mergesketch = + static_cast(doc->getObject(FeatName.c_str())); int baseGeometry = 0; int baseConstraints = 0; - for (std::vector::const_iterator it=selection.begin(); it != selection.end(); ++it) { - const Sketcher::SketchObject* Obj = static_cast((*it).getObject()); - int addedGeometries=mergesketch->addGeometry(Obj->getInternalGeometry()); + for (std::vector::const_iterator it = selection.begin(); + it != selection.end(); + ++it) { + const Sketcher::SketchObject* Obj = + static_cast((*it).getObject()); + int addedGeometries = mergesketch->addGeometry(Obj->getInternalGeometry()); - int addedConstraints=mergesketch->addCopyOfConstraints(*Obj); + int addedConstraints = mergesketch->addCopyOfConstraints(*Obj); - for (int i=0; i<=(addedConstraints-baseConstraints); i++){ - Sketcher::Constraint * constraint= mergesketch->Constraints.getValues()[i+baseConstraints]; + for (int i = 0; i <= (addedConstraints - baseConstraints); i++) { + Sketcher::Constraint* constraint = + mergesketch->Constraints.getValues()[i + baseConstraints]; - if (constraint->First != Sketcher::GeoEnum::GeoUndef && - constraint->First != Sketcher::GeoEnum::HAxis && - constraint->First != Sketcher::GeoEnum::VAxis) + if (constraint->First != Sketcher::GeoEnum::GeoUndef + && constraint->First != Sketcher::GeoEnum::HAxis + && constraint->First != Sketcher::GeoEnum::VAxis) // not x, y axes or origin constraint->First += baseGeometry; - if (constraint->Second != Sketcher::GeoEnum::GeoUndef && - constraint->Second != Sketcher::GeoEnum::HAxis && - constraint->Second != Sketcher::GeoEnum::VAxis) + if (constraint->Second != Sketcher::GeoEnum::GeoUndef + && constraint->Second != Sketcher::GeoEnum::HAxis + && constraint->Second != Sketcher::GeoEnum::VAxis) // not x, y axes or origin constraint->Second += baseGeometry; - if (constraint->Third != Sketcher::GeoEnum::GeoUndef && - constraint->Third != Sketcher::GeoEnum::HAxis && - constraint->Third != Sketcher::GeoEnum::VAxis) + if (constraint->Third != Sketcher::GeoEnum::GeoUndef + && constraint->Third != Sketcher::GeoEnum::HAxis + && constraint->Third != Sketcher::GeoEnum::VAxis) // not x, y axes or origin constraint->Third += baseGeometry; } - baseGeometry=addedGeometries+1; - baseConstraints=addedConstraints+1; + baseGeometry = addedGeometries + 1; + baseConstraints = addedConstraints + 1; } // apply the placement of the first sketch in the list (#0002434) @@ -937,33 +1037,35 @@ bool CmdSketcherMergeSketches::isActive() DEF_STD_CMD_A(CmdSketcherViewSection) CmdSketcherViewSection::CmdSketcherViewSection() -: Command("Sketcher_ViewSection") + : Command("Sketcher_ViewSection") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("View section"); - sToolTipText = QT_TR_NOOP("When in edit mode, " - "switch between section view and full view."); - sWhatsThis = "Sketcher_ViewSection"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_ViewSection"; - sAccel = "Q, S"; - eType = 0; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("View section"); + sToolTipText = QT_TR_NOOP("When in edit mode, " + "switch between section view and full view."); + sWhatsThis = "Sketcher_ViewSection"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_ViewSection"; + sAccel = "Q, S"; + eType = 0; } void CmdSketcherViewSection::activated(int iMsg) { Q_UNUSED(iMsg); - QString cmdStr = QLatin1String("ActiveSketch.ViewObject.TempoVis.sketchClipPlane(ActiveSketch, None, %1)\n"); - Gui::Document *doc = getActiveGuiDocument(); + QString cmdStr = + QLatin1String("ActiveSketch.ViewObject.TempoVis.sketchClipPlane(ActiveSketch, None, %1)\n"); + Gui::Document* doc = getActiveGuiDocument(); bool revert = false; - if(doc) { - SketcherGui::ViewProviderSketch* vp = dynamic_cast(doc->getInEdit()); + if (doc) { + SketcherGui::ViewProviderSketch* vp = + dynamic_cast(doc->getInEdit()); if (vp) { - revert = vp->getViewOrientationFactor() < 0?true:false; + revert = vp->getViewOrientationFactor() < 0 ? true : false; } } - cmdStr = cmdStr.arg(revert?QLatin1String("True"):QLatin1String("False")); + cmdStr = cmdStr.arg(revert ? QLatin1String("True") : QLatin1String("False")); doCommand(Doc, cmdStr.toLatin1()); } @@ -973,29 +1075,33 @@ bool CmdSketcherViewSection::isActive() } /* Grid tool */ -class GridSpaceAction : public QWidgetAction +class GridSpaceAction: public QWidgetAction { public: - GridSpaceAction(QObject* parent) : QWidgetAction(parent) { + GridSpaceAction(QObject* parent) + : QWidgetAction(parent) + { setEnabled(false); } - void updateWidget() { + void updateWidget() + { auto* sketchView = getView(); - if(sketchView) { + if (sketchView) { - auto updateCheckBox = [](QCheckBox * checkbox, bool value) { + auto updateCheckBox = [](QCheckBox* checkbox, bool value) { auto checked = checkbox->checkState() == Qt::Checked; - if( value != checked ) { + if (value != checked) { const QSignalBlocker blocker(checkbox); checkbox->setChecked(value); } }; - auto updateCheckBoxFromProperty = [updateCheckBox](QCheckBox * checkbox, App::PropertyBool & property) { + auto updateCheckBoxFromProperty = [updateCheckBox](QCheckBox* checkbox, + App::PropertyBool& property) { auto propvalue = property.getValue(); updateCheckBox(checkbox, propvalue); @@ -1041,27 +1147,30 @@ protected: QObject::connect(gridAutoSpacing, &QCheckBox::stateChanged, [this](int state) { auto* sketchView = getView(); - if(sketchView) { + if (sketchView) { auto enable = (state == Qt::Checked); sketchView->GridAuto.setValue(enable); } }); - QObject::connect(gridSizeBox, qOverload(&Gui::QuantitySpinBox::valueChanged), [this](double val) { - auto* sketchView = getView(); - if(sketchView) { - sketchView->GridSize.setValue(val); - } - }); + QObject::connect(gridSizeBox, + qOverload(&Gui::QuantitySpinBox::valueChanged), + [this](double val) { + auto* sketchView = getView(); + if (sketchView) { + sketchView->GridSize.setValue(val); + } + }); return gridSizeW; } private: - ViewProviderSketch * getView() { + ViewProviderSketch* getView() + { Gui::Document* doc = Gui::Application::Instance->activeDocument(); - if(doc) { + if (doc) { return dynamic_cast(doc->getInEdit()); } @@ -1069,31 +1178,36 @@ private: } private: - QCheckBox * gridAutoSpacing; - QLabel * sizeLabel; - Gui::QuantitySpinBox * gridSizeBox; + QCheckBox* gridAutoSpacing; + QLabel* sizeLabel; + Gui::QuantitySpinBox* gridSizeBox; }; -class CmdSketcherGrid : public Gui::Command +class CmdSketcherGrid: public Gui::Command { public: CmdSketcherGrid(); - virtual ~CmdSketcherGrid(){} + virtual ~CmdSketcherGrid() + {} virtual const char* className() const override - { return "CmdSketcherGrid"; } + { + return "CmdSketcherGrid"; + } virtual void languageChange() override; + protected: virtual void activated(int iMsg) override; virtual bool isActive(void) override; - virtual Gui::Action * createAction(void) override; + virtual Gui::Action* createAction(void) override; + private: void updateIcon(bool value); void updateInactiveHandlerIcon(); CmdSketcherGrid(const CmdSketcherGrid&) = delete; CmdSketcherGrid(CmdSketcherGrid&&) = delete; - CmdSketcherGrid& operator= (const CmdSketcherGrid&) = delete; - CmdSketcherGrid& operator= (CmdSketcherGrid&&) = delete; + CmdSketcherGrid& operator=(const CmdSketcherGrid&) = delete; + CmdSketcherGrid& operator=(CmdSketcherGrid&&) = delete; }; CmdSketcherGrid::CmdSketcherGrid() @@ -1102,7 +1216,8 @@ CmdSketcherGrid::CmdSketcherGrid() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Toggle grid"); - sToolTipText = QT_TR_NOOP("Toggle the grid in the sketch. In the menu you can change grid settings"); + sToolTipText = + QT_TR_NOOP("Toggle the grid in the sketch. In the menu you can change grid settings"); sWhatsThis = "Sketcher_Grid"; sStatusTip = sToolTipText; eType = 0; @@ -1113,15 +1228,15 @@ void CmdSketcherGrid::updateIcon(bool value) static QIcon active = Gui::BitmapFactory().iconFromTheme("Sketcher_GridToggle"); static QIcon inactive = Gui::BitmapFactory().iconFromTheme("Sketcher_GridToggle_Deactivated"); - auto * pcAction = qobject_cast(getAction()); + auto* pcAction = qobject_cast(getAction()); pcAction->setIcon(value ? active : inactive); } void CmdSketcherGrid::updateInactiveHandlerIcon() { - auto * vp = getInactiveHandlerEditModeSketchViewProvider(); + auto* vp = getInactiveHandlerEditModeSketchViewProvider(); - if(vp) { + if (vp) { auto value = vp->ShowGrid.getValue(); updateIcon(value); @@ -1145,7 +1260,7 @@ void CmdSketcherGrid::activated(int iMsg) Gui::Action* CmdSketcherGrid::createAction() { - auto * pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); + auto* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); pcAction->setExclusive(false); applyCommandData(this->className(), pcAction); @@ -1155,7 +1270,7 @@ Gui::Action* CmdSketcherGrid::createAction() _pcAction = pcAction; - QObject::connect(pcAction, &Gui::ActionGroup::aboutToShow, [gsa](QMenu * menu) { + QObject::connect(pcAction, &Gui::ActionGroup::aboutToShow, [gsa](QMenu* menu) { Q_UNUSED(menu) gsa->updateWidget(); }); @@ -1176,13 +1291,13 @@ void CmdSketcherGrid::languageChange() Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); - auto* gsa = static_cast(a[0]); + auto* gsa = static_cast(a[0]); gsa->languageChange(); } bool CmdSketcherGrid::isActive() { - auto * vp = getInactiveHandlerEditModeSketchViewProvider(); + auto* vp = getInactiveHandlerEditModeSketchViewProvider(); if (vp) { auto value = vp->ShowGrid.getValue(); @@ -1196,14 +1311,17 @@ bool CmdSketcherGrid::isActive() } /* Snap tool */ -class SnapSpaceAction : public QWidgetAction +class SnapSpaceAction: public QWidgetAction { public: - SnapSpaceAction(QObject* parent) : QWidgetAction(parent) { + SnapSpaceAction(QObject* parent) + : QWidgetAction(parent) + { setEnabled(false); } - void updateWidget(bool snapenabled) { + void updateWidget(bool snapenabled) + { auto updateCheckBox = [](QCheckBox* checkbox, bool value) { auto checked = checkbox->checkState() == Qt::Checked; @@ -1240,15 +1358,20 @@ public: void languageChange() { snapToObjects->setText(tr("Snap to objects")); - snapToObjects->setToolTip(tr("New points will snap to the currently preselected object. It will also snap to the middle of lines and arcs.")); + snapToObjects->setToolTip(tr("New points will snap to the currently preselected object. It " + "will also snap to the middle of lines and arcs.")); snapToObjects->setStatusTip(snapToObjects->toolTip()); snapToGrid->setText(tr("Snap to grid")); - snapToGrid->setToolTip(tr("New points will snap to the nearest grid line.\nPoints must be set closer than a fifth of the grid spacing to a grid line to snap.")); + snapToGrid->setToolTip( + tr("New points will snap to the nearest grid line.\nPoints must be set closer than a " + "fifth of the grid spacing to a grid line to snap.")); snapToGrid->setStatusTip(snapToGrid->toolTip()); angleLabel->setText(tr("Snap angle")); - snapAngle->setToolTip(tr("Angular step for tools that use 'Snap at Angle' (line for instance). Hold CTRL to enable 'Snap at Angle'. The angle start from the East axis (horizontal right)")); + snapAngle->setToolTip( + tr("Angular step for tools that use 'Snap at Angle' (line for instance). Hold CTRL to " + "enable 'Snap at Angle'. The angle start from the East axis (horizontal right)")); } protected: @@ -1285,17 +1408,20 @@ protected: hGrp->SetBool("SnapToGrid", state == Qt::Checked); }); - QObject::connect(snapAngle, qOverload(&Gui::QuantitySpinBox::valueChanged), [this](double val) { - ParameterGrp::handle hGrp = this->getParameterPath(); - hGrp->SetFloat("SnapAngle", val); - }); + QObject::connect( + snapAngle, qOverload(&Gui::QuantitySpinBox::valueChanged), [this](double val) { + ParameterGrp::handle hGrp = this->getParameterPath(); + hGrp->SetFloat("SnapAngle", val); + }); return snapW; } private: - ParameterGrp::handle getParameterPath() { - return App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); + ParameterGrp::handle getParameterPath() + { + return App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); } private: @@ -1305,7 +1431,7 @@ private: Gui::QuantitySpinBox* snapAngle; }; -class CmdSketcherSnap : public Gui::Command, public ParameterGrp::ObserverType +class CmdSketcherSnap: public Gui::Command, public ParameterGrp::ObserverType { public: CmdSketcherSnap(); @@ -1316,22 +1442,26 @@ public: } virtual void languageChange() override; - void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject& rCaller, const char* sReason) override; + protected: virtual void activated(int iMsg) override; virtual bool isActive(void) override; virtual Gui::Action* createAction(void) override; + private: void updateIcon(bool value); - ParameterGrp::handle getParameterPath() { - return App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); + ParameterGrp::handle getParameterPath() + { + return App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); } CmdSketcherSnap(const CmdSketcherSnap&) = delete; CmdSketcherSnap(CmdSketcherSnap&&) = delete; - CmdSketcherSnap& operator= (const CmdSketcherSnap&) = delete; - CmdSketcherSnap& operator= (CmdSketcherSnap&&) = delete; + CmdSketcherSnap& operator=(const CmdSketcherSnap&) = delete; + CmdSketcherSnap& operator=(CmdSketcherSnap&&) = delete; bool snapEnabled = true; }; @@ -1342,7 +1472,9 @@ CmdSketcherSnap::CmdSketcherSnap() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Toggle snap"); - sToolTipText = QT_TR_NOOP("Toggle all snap functionality. In the menu you can toggle 'Snap to grid' and 'Snap to objects' individually, and change further snap settings"); + sToolTipText = + QT_TR_NOOP("Toggle all snap functionality. In the menu you can toggle 'Snap to grid' and " + "'Snap to objects' individually, and change further snap settings"); sWhatsThis = "Sketcher_Snap"; sStatusTip = sToolTipText; eType = 0; @@ -1351,13 +1483,14 @@ CmdSketcherSnap::CmdSketcherSnap() hGrp->Attach(this); } -CmdSketcherSnap::~CmdSketcherSnap() { +CmdSketcherSnap::~CmdSketcherSnap() +{ ParameterGrp::handle hGrp = this->getParameterPath(); hGrp->Detach(this); } -void CmdSketcherSnap::OnChange(Base::Subject &rCaller, const char * sReason) +void CmdSketcherSnap::OnChange(Base::Subject& rCaller, const char* sReason) { Q_UNUSED(rCaller) @@ -1384,7 +1517,7 @@ void CmdSketcherSnap::activated(int iMsg) // snapEnable updated via observer updateIcon(snapEnabled); - //Update the widget : + // Update the widget : if (!_pcAction) return; @@ -1409,7 +1542,7 @@ Gui::Action* CmdSketcherSnap::createAction() QObject::connect(pcAction, &Gui::ActionGroup::aboutToShow, [ssa, this](QMenu* menu) { Q_UNUSED(menu) - ssa->updateWidget(snapEnabled); + ssa->updateWidget(snapEnabled); }); // set the right pixmap @@ -1447,14 +1580,17 @@ bool CmdSketcherSnap::isActive() /* Rendering Order */ -class RenderingOrderAction : public QWidgetAction +class RenderingOrderAction: public QWidgetAction { public: - RenderingOrderAction(QObject* parent) : QWidgetAction(parent) { + RenderingOrderAction(QObject* parent) + : QWidgetAction(parent) + { setEnabled(false); } - void updateWidget() { + void updateWidget() + { auto hGrp = getParameterPath(); @@ -1469,17 +1605,23 @@ public: QListWidgetItem* newItem = new QListWidgetItem; newItem->setData(Qt::UserRole, QVariant(topid)); - newItem->setText(topid == 1 ? tr("Normal Geometry") : topid == 2 ? tr("Construction Geometry") : tr("External Geometry")); + newItem->setText(topid == 1 ? tr("Normal Geometry") + : topid == 2 ? tr("Construction Geometry") + : tr("External Geometry")); list->insertItem(0, newItem); newItem = new QListWidgetItem; newItem->setData(Qt::UserRole, QVariant(midid)); - newItem->setText(midid == 1 ? tr("Normal Geometry") : midid == 2 ? tr("Construction Geometry") : tr("External Geometry")); + newItem->setText(midid == 1 ? tr("Normal Geometry") + : midid == 2 ? tr("Construction Geometry") + : tr("External Geometry")); list->insertItem(1, newItem); newItem = new QListWidgetItem; newItem->setData(Qt::UserRole, QVariant(lowid)); - newItem->setText(lowid == 1 ? tr("Normal Geometry") : lowid == 2 ? tr("Construction Geometry") : tr("External Geometry")); + newItem->setText(lowid == 1 ? tr("Normal Geometry") + : lowid == 2 ? tr("Construction Geometry") + : tr("External Geometry")); list->insertItem(2, newItem); } } @@ -1505,67 +1647,81 @@ protected: languageChange(); // Handle change in the order of the list entries - QObject::connect(list->model(), &QAbstractItemModel::rowsMoved, - [this](const QModelIndex &sourceParent, int sourceStart, int sourceEnd, - const QModelIndex &destinationParent, int destinationRow) { - Q_UNUSED(sourceParent) - Q_UNUSED(sourceStart) - Q_UNUSED(sourceEnd) - Q_UNUSED(destinationParent) - Q_UNUSED(destinationRow) + QObject::connect(list->model(), + &QAbstractItemModel::rowsMoved, + [this](const QModelIndex& sourceParent, + int sourceStart, + int sourceEnd, + const QModelIndex& destinationParent, + int destinationRow) { + Q_UNUSED(sourceParent) + Q_UNUSED(sourceStart) + Q_UNUSED(sourceEnd) + Q_UNUSED(destinationParent) + Q_UNUSED(destinationRow) - int topid = list->item(0)->data(Qt::UserRole).toInt(); - int midid = list->item(1)->data(Qt::UserRole).toInt(); - int lowid = list->item(2)->data(Qt::UserRole).toInt(); + int topid = list->item(0)->data(Qt::UserRole).toInt(); + int midid = list->item(1)->data(Qt::UserRole).toInt(); + int lowid = list->item(2)->data(Qt::UserRole).toInt(); - auto hGrp = getParameterPath(); + auto hGrp = getParameterPath(); - hGrp->SetInt("TopRenderGeometryId", topid); - hGrp->SetInt("MidRenderGeometryId", midid); - hGrp->SetInt("LowRenderGeometryId", lowid); - }); + hGrp->SetInt("TopRenderGeometryId", topid); + hGrp->SetInt("MidRenderGeometryId", midid); + hGrp->SetInt("LowRenderGeometryId", lowid); + }); return renderingWidget; } private: - ParameterGrp::handle getParameterPath() { - return App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle getParameterPath() + { + return App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); } private: QListWidget* list; }; -class CmdRenderingOrder : public Gui::Command, public ParameterGrp::ObserverType +class CmdRenderingOrder: public Gui::Command, public ParameterGrp::ObserverType { - enum class ElementType { + enum class ElementType + { Normal = 1, Construction = 2, External = 3, }; + public: CmdRenderingOrder(); virtual ~CmdRenderingOrder(); virtual const char* className() const override - { return "CmdRenderingOrder"; } + { + return "CmdRenderingOrder"; + } virtual void languageChange() override; - void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject& rCaller, const char* sReason) override; + protected: virtual void activated(int iMsg) override; virtual bool isActive(void) override; - virtual Gui::Action * createAction(void) override; + virtual Gui::Action* createAction(void) override; + private: void updateIcon(); - ParameterGrp::handle getParameterPath() { - return App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle getParameterPath() + { + return App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); } CmdRenderingOrder(const CmdRenderingOrder&) = delete; CmdRenderingOrder(CmdRenderingOrder&&) = delete; - CmdRenderingOrder& operator= (const CmdRenderingOrder&) = delete; - CmdRenderingOrder& operator= (CmdRenderingOrder&&) = delete; + CmdRenderingOrder& operator=(const CmdRenderingOrder&) = delete; + CmdRenderingOrder& operator=(CmdRenderingOrder&&) = delete; ElementType TopElement = ElementType::Normal; }; @@ -1587,13 +1743,14 @@ CmdRenderingOrder::CmdRenderingOrder() TopElement = static_cast(getParameterPath()->GetInt("TopRenderGeometryId", 1)); } -CmdRenderingOrder::~CmdRenderingOrder() { +CmdRenderingOrder::~CmdRenderingOrder() +{ ParameterGrp::handle hGrp = this->getParameterPath(); hGrp->Detach(this); } -void CmdRenderingOrder::OnChange(Base::Subject &rCaller, const char * sReason) +void CmdRenderingOrder::OnChange(Base::Subject& rCaller, const char* sReason) { Q_UNUSED(rCaller) @@ -1607,18 +1764,19 @@ void CmdRenderingOrder::OnChange(Base::Subject &rCaller, const char void CmdRenderingOrder::updateIcon() { static QIcon normal = Gui::BitmapFactory().iconFromTheme("Sketcher_RenderingOrder_Normal"); - static QIcon construction = Gui::BitmapFactory().iconFromTheme("Sketcher_RenderingOrder_Construction"); + static QIcon construction = + Gui::BitmapFactory().iconFromTheme("Sketcher_RenderingOrder_Construction"); static QIcon external = Gui::BitmapFactory().iconFromTheme("Sketcher_RenderingOrder_External"); - auto * pcAction = qobject_cast(getAction()); + auto* pcAction = qobject_cast(getAction()); - if(TopElement == ElementType::Normal) { + if (TopElement == ElementType::Normal) { pcAction->setIcon(normal); } - else if(TopElement == ElementType::Construction) { + else if (TopElement == ElementType::Construction) { pcAction->setIcon(construction); } - else if(TopElement == ElementType::External) { + else if (TopElement == ElementType::External) { pcAction->setIcon(external); } } @@ -1630,7 +1788,7 @@ void CmdRenderingOrder::activated(int iMsg) Gui::Action* CmdRenderingOrder::createAction() { - auto * pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); + auto* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); pcAction->setExclusive(false); applyCommandData(this->className(), pcAction); @@ -1640,7 +1798,7 @@ Gui::Action* CmdRenderingOrder::createAction() _pcAction = pcAction; - QObject::connect(pcAction, &Gui::ActionGroup::aboutToShow, [roa](QMenu * menu) { + QObject::connect(pcAction, &Gui::ActionGroup::aboutToShow, [roa](QMenu* menu) { Q_UNUSED(menu) roa->updateWidget(); }); @@ -1661,19 +1819,20 @@ void CmdRenderingOrder::languageChange() Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); - auto* roa = static_cast(a[0]); + auto* roa = static_cast(a[0]); roa->languageChange(); } bool CmdRenderingOrder::isActive() { - return isSketchInEdit(getActiveGuiDocument());; + return isSketchInEdit(getActiveGuiDocument()); + ; } void CreateSketcherCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherNewSketch()); rcCmdMgr.addCommand(new CmdSketcherEditSketch()); diff --git a/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp b/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp index d5ff3faa6f..38ce0aeae8 100644 --- a/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp +++ b/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp @@ -43,20 +43,21 @@ using namespace std; using namespace SketcherGui; using namespace Sketcher; -bool isAlterGeoActive(Gui::Document *doc) +bool isAlterGeoActive(Gui::Document* doc) { - if (doc) { + if (doc) { // checks if a Sketch Viewprovider is in Edit - if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom - (SketcherGui::ViewProviderSketch::getClassTypeId())) { - return true; + if (doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + return true; } } return false; } -namespace SketcherGui { +namespace SketcherGui +{ extern GeometryCreationMode geometryCreationMode; @@ -64,20 +65,20 @@ extern GeometryCreationMode geometryCreationMode; DEF_STD_CMD_A(CmdSketcherToggleConstruction) CmdSketcherToggleConstruction::CmdSketcherToggleConstruction() - :Command("Sketcher_ToggleConstruction") + : Command("Sketcher_ToggleConstruction") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Toggle construction geometry"); - sToolTipText = QT_TR_NOOP("Toggles the toolbar or selected geometry to/from construction mode"); - sWhatsThis = "Sketcher_ToggleConstruction"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_ToggleConstruction"; - sAccel = "G, N"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Toggle construction geometry"); + sToolTipText = QT_TR_NOOP("Toggles the toolbar or selected geometry to/from construction mode"); + sWhatsThis = "Sketcher_ToggleConstruction"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_ToggleConstruction"; + sAccel = "G, N"; + eType = ForEdit; // list of toggle construction commands - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateLine"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateRectangle"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateRectangle_Center"); @@ -115,9 +116,9 @@ void CmdSketcherToggleConstruction::activated(int iMsg) { Q_UNUSED(iMsg); // Option A: nothing is selected change creation mode from/to construction - if(Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) == 0){ + if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) == 0) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); if (geometryCreationMode == Construction) { geometryCreationMode = Normal; @@ -128,28 +129,30 @@ void CmdSketcherToggleConstruction::activated(int iMsg) rcCmdMgr.updateCommands("ToggleConstruction", static_cast(geometryCreationMode)); } - else // there was a selection, so operate in toggle mode. + else// there was a selection, so operate in toggle mode. { // get the selection std::vector selection; - selection = getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); + selection = + getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); - Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); + Sketcher::SketchObject* Obj = + static_cast(selection[0].getObject()); // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select edge(s) from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select edge(s) from the sketch.")); return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select edge(s) from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select edge(s) from the sketch.")); return; } @@ -159,13 +162,14 @@ void CmdSketcherToggleConstruction::activated(int iMsg) // go through the selected subelements bool verticesonly = true; - for(const auto & subname : SubNames) { - if (subname.size() > 4 && subname.substr(0,4) == "Edge") { + for (const auto& subname : SubNames) { + if (subname.size() > 4 && subname.substr(0, 4) == "Edge") { verticesonly = false; } } - for (std::vector::const_iterator it=SubNames.begin();it!=SubNames.end();++it){ + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { // It was decided to provide a special behaviour: // Vertices will only be toggled to/from construction IF ONLY // vertices are within the group. @@ -179,26 +183,26 @@ void CmdSketcherToggleConstruction::activated(int iMsg) // only handle edges - if (it->size() > 4 && it->substr(0,4) == "Edge") { - int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + int GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; // issue the actual commands to toggle Gui::cmdAppObjectArgs(selection[0].getObject(), "toggleConstruction(%d) ", GeoId); } - else if (verticesonly && it->size() > 6 && it->substr(0,6) == "Vertex") { - int vertexId = std::atoi(it->substr(6,4000).c_str()) - 1; + else if (verticesonly && it->size() > 6 && it->substr(0, 6) == "Vertex") { + int vertexId = std::atoi(it->substr(6, 4000).c_str()) - 1; int geoId; PointPos pos; - Obj->getGeoVertexIndex(vertexId,geoId, pos); + Obj->getGeoVertexIndex(vertexId, geoId, pos); auto geo = Obj->getGeometry(geoId); - if(geo && geo->getTypeId() == Part::GeomPoint::getClassTypeId()) { + if (geo && geo->getTypeId() == Part::GeomPoint::getClassTypeId()) { // issue the actual commands to toggle - Gui::cmdAppObjectArgs(selection[0].getObject(), "toggleConstruction(%d) ", geoId); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "toggleConstruction(%d) ", geoId); } } - } // finish the transaction and update commitCommand(); @@ -212,14 +216,14 @@ void CmdSketcherToggleConstruction::activated(int iMsg) bool CmdSketcherToggleConstruction::isActive() { - return isAlterGeoActive( getActiveGuiDocument() ); + return isAlterGeoActive(getActiveGuiDocument()); } -} +}// namespace SketcherGui void CreateSketcherCommandsAlterGeo() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherToggleConstruction()); } diff --git a/src/Mod/Sketcher/Gui/CommandConstraints.cpp b/src/Mod/Sketcher/Gui/CommandConstraints.cpp index 199feab1f1..37b1701d4b 100644 --- a/src/Mod/Sketcher/Gui/CommandConstraints.cpp +++ b/src/Mod/Sketcher/Gui/CommandConstraints.cpp @@ -22,9 +22,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include @@ -47,9 +47,9 @@ #include "CommandConstraints.h" #include "DrawSketchHandler.h" #include "EditDatumDialog.h" -#include "ui_InsertDatum.h" #include "Utils.h" #include "ViewProviderSketch.h" +#include "ui_InsertDatum.h" using namespace std; @@ -59,22 +59,25 @@ using namespace Sketcher; /***** Creation Mode ************/ namespace SketcherGui { - enum ConstraintCreationMode { - Driving, - Reference - }; +enum ConstraintCreationMode +{ + Driving, + Reference +}; } ConstraintCreationMode constraintCreationMode = Driving; -bool isCreateConstraintActive(Gui::Document *doc) +bool isCreateConstraintActive(Gui::Document* doc) { if (doc) { // checks if a Sketch View provider is in Edit and is in no special mode - if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { - if (static_cast(doc->getInEdit()) - ->getSketchMode() == ViewProviderSketch::STATUS_NONE) { - if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) + if (doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + if (static_cast(doc->getInEdit())->getSketchMode() + == ViewProviderSketch::STATUS_NONE) { + if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) + > 0) return true; } } @@ -83,47 +86,57 @@ bool isCreateConstraintActive(Gui::Document *doc) } // Utility method to avoid repeating the same code over and over again -void finishDatumConstraint (Gui::Command* cmd, Sketcher::SketchObject* sketch, bool isDriving=true, unsigned int numberofconstraints = 1) +void finishDatumConstraint(Gui::Command* cmd, Sketcher::SketchObject* sketch, bool isDriving = true, + unsigned int numberofconstraints = 1) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); // Get the latest constraint - const std::vector &ConStr = sketch->Constraints.getValues(); + const std::vector& ConStr = sketch->Constraints.getValues(); auto lastConstraintIndex = ConStr.size() - 1; - Sketcher::Constraint *constr = ConStr[lastConstraintIndex]; + Sketcher::Constraint* constr = ConStr[lastConstraintIndex]; auto lastConstraintType = constr->Type; // Guess some reasonable distance for placing the datum text - Gui::Document *doc = cmd->getActiveGuiDocument(); + Gui::Document* doc = cmd->getActiveGuiDocument(); float scaleFactor = 1.0; double labelPosition = 0.0; float labelPositionRandomness = 0.0; if (lastConstraintType == Radius || lastConstraintType == Diameter) { - labelPosition = hGrp->GetFloat("RadiusDiameterConstraintDisplayBaseAngle", 15.0) * (M_PI / 180); // Get radius/diameter constraint display angle - labelPositionRandomness = hGrp->GetFloat("RadiusDiameterConstraintDisplayAngleRandomness", 0.0) * (M_PI / 180); // Get randomness + labelPosition = hGrp->GetFloat("RadiusDiameterConstraintDisplayBaseAngle", 15.0) + * (M_PI / 180);// Get radius/diameter constraint display angle + labelPositionRandomness = + hGrp->GetFloat("RadiusDiameterConstraintDisplayAngleRandomness", 0.0) + * (M_PI / 180);// Get randomness - // Adds a random value around the base angle, so that possibly overlapping labels get likely a different position. + // Adds a random value around the base angle, so that possibly overlapping labels get likely + // a different position. if (labelPositionRandomness != 0.0) - labelPosition = labelPosition + labelPositionRandomness * (static_cast(std::rand())/static_cast(RAND_MAX) - 0.5); + labelPosition = labelPosition + + labelPositionRandomness + * (static_cast(std::rand()) / static_cast(RAND_MAX) - 0.5); } - if (doc && doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { - SketcherGui::ViewProviderSketch *vp = static_cast(doc->getInEdit()); + if (doc && doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + SketcherGui::ViewProviderSketch* vp = + static_cast(doc->getInEdit()); scaleFactor = vp->getScaleFactor(); int firstConstraintIndex = lastConstraintIndex - numberofconstraints + 1; - for(int i = lastConstraintIndex; i >= firstConstraintIndex; i--) { + for (int i = lastConstraintIndex; i >= firstConstraintIndex; i--) { ConStr[i]->LabelDistance = 2. * scaleFactor; - if(lastConstraintType == Radius || lastConstraintType == Diameter) { - const Part::Geometry *geo = sketch->getGeometry(ConStr[i]->First); - if(geo && geo->getTypeId() == Part::GeomCircle::getClassTypeId()) + if (lastConstraintType == Radius || lastConstraintType == Diameter) { + const Part::Geometry* geo = sketch->getGeometry(ConStr[i]->First); + if (geo && geo->getTypeId() == Part::GeomCircle::getClassTypeId()) ConStr[i]->LabelPosition = labelPosition; } } - vp->draw(false,false); // Redraw + vp->draw(false, false);// Redraw } bool show = hGrp->GetBool("ShowDialogOnDistanceConstraint", true); @@ -142,29 +155,30 @@ void finishDatumConstraint (Gui::Command* cmd, Sketcher::SketchObject* sketch, b cmd->getSelection().clearSelection(); } -void showNoConstraintBetweenExternal(const App::DocumentObject * obj) +void showNoConstraintBetweenExternal(const App::DocumentObject* obj) { - Gui::TranslatedUserWarning(obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a constraint between two external geometries.")); + Gui::TranslatedUserWarning( + obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a constraint between two external geometries.")); } -void showNoConstraintBetweenFixedGeometry(const App::DocumentObject * obj) +void showNoConstraintBetweenFixedGeometry(const App::DocumentObject* obj) { Gui::TranslatedUserWarning(obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a constraint between two fixed geometries. " - "Fixed geometries include external geometry, " - "blocked geometry, and special points " - "such as B-spline knot points.")); - + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a constraint between two fixed geometries. " + "Fixed geometries include external geometry, " + "blocked geometry, and special points " + "such as B-spline knot points.")); } -bool isGeoConcentricCompatible(const Part::Geometry* geo) { - if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { +bool isGeoConcentricCompatible(const Part::Geometry* geo) +{ + if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { return true; } return false; @@ -179,55 +193,64 @@ bool isGeoConcentricCompatible(const Part::Geometry* geo) { /// commits or aborts as appropriate. The reason is for compatibility reasons with /// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp void SketcherGui::makeTangentToEllipseviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomEllipse *ellipse, - const Part::Geometry *geom2, - int geoId1, - int geoId2 -) + const Part::GeomEllipse* ellipse, + const Part::Geometry* geom2, int geoId1, + int geoId2) { - Base::Vector3d center=ellipse->getCenter(); - double majord=ellipse->getMajorRadius(); - double minord=ellipse->getMinorRadius(); - double phi=atan2(ellipse->getMajorAxisDir().y, ellipse->getMajorAxisDir().x); + Base::Vector3d center = ellipse->getCenter(); + double majord = ellipse->getMajorRadius(); + double minord = ellipse->getMinorRadius(); + double phi = atan2(ellipse->getMajorAxisDir().y, ellipse->getMajorAxisDir().x); Base::Vector3d center2; - if( geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() ) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); + if (geom2->getTypeId() == Part::GeomEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); - Base::Vector3d direction=center2-center; - double tapprox=atan2(direction.y,direction.x)-phi; // we approximate the eccentric anomaly by the polar + Base::Vector3d direction = center2 - center; + double tapprox = + atan2(direction.y, direction.x) - phi;// we approximate the eccentric anomaly by the polar - Base::Vector3d PoE = Base::Vector3d(center.x+majord*cos(tapprox)*cos(phi)-minord*sin(tapprox)*sin(phi), - center.y+majord*cos(tapprox)*sin(phi)+minord*sin(tapprox)*cos(phi), 0); + Base::Vector3d PoE = Base::Vector3d( + center.x + majord * cos(tapprox) * cos(phi) - minord * sin(tapprox) * sin(phi), + center.y + majord * cos(tapprox) * sin(phi) + minord * sin(tapprox) * cos(phi), + 0); try { // Add a point - Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - PoE.x,PoE.y); + Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", PoE.x, PoE.y); int GeoIdPoint = Obj->getHighestCurveIndex(); // Point on first object - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId1); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId1);// constrain major axis // Point on second object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId2); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId2);// constrain major axis // tangent via point - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", - geoId1, geoId2 ,GeoIdPoint, static_cast(Sketcher::PointPos::start)); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", + geoId1, + geoId2, + GeoIdPoint, + static_cast(Sketcher::PointPos::start)); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); tryAutoRecompute(Obj); @@ -247,53 +270,62 @@ void SketcherGui::makeTangentToEllipseviaNewPoint(Sketcher::SketchObject* Obj, /// commits or aborts as appropriate. The reason is for compatibility reasons with /// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp void SketcherGui::makeTangentToArcOfEllipseviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfEllipse *aoe, - const Part::Geometry *geom2, - int geoId1, - int geoId2 -) + const Part::GeomArcOfEllipse* aoe, + const Part::Geometry* geom2, int geoId1, + int geoId2) { - Base::Vector3d center=aoe->getCenter(); - double majord=aoe->getMajorRadius(); - double minord=aoe->getMinorRadius(); - double phi=atan2(aoe->getMajorAxisDir().y, aoe->getMajorAxisDir().x); + Base::Vector3d center = aoe->getCenter(); + double majord = aoe->getMajorRadius(); + double minord = aoe->getMinorRadius(); + double phi = atan2(aoe->getMajorAxisDir().y, aoe->getMajorAxisDir().x); Base::Vector3d center2; - if( geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); + if (geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); - Base::Vector3d direction=center2-center; - double tapprox=atan2(direction.y,direction.x)-phi; // we approximate the eccentric anomaly by the polar + Base::Vector3d direction = center2 - center; + double tapprox = + atan2(direction.y, direction.x) - phi;// we approximate the eccentric anomaly by the polar - Base::Vector3d PoE = Base::Vector3d(center.x+majord*cos(tapprox)*cos(phi)-minord*sin(tapprox)*sin(phi), - center.y+majord*cos(tapprox)*sin(phi)+minord*sin(tapprox)*cos(phi), 0); + Base::Vector3d PoE = Base::Vector3d( + center.x + majord * cos(tapprox) * cos(phi) - minord * sin(tapprox) * sin(phi), + center.y + majord * cos(tapprox) * sin(phi) + minord * sin(tapprox) * cos(phi), + 0); try { // Add a point - Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - PoE.x,PoE.y); + Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", PoE.x, PoE.y); int GeoIdPoint = Obj->getHighestCurveIndex(); // Point on first object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId1); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId1);// constrain major axis // Point on second object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId2); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId2);// constrain major axis // tangent via point - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", - geoId1, geoId2 ,GeoIdPoint, static_cast(Sketcher::PointPos::start)); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", + geoId1, + geoId2, + GeoIdPoint, + static_cast(Sketcher::PointPos::start)); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); tryAutoRecompute(Obj); @@ -313,70 +345,78 @@ void SketcherGui::makeTangentToArcOfEllipseviaNewPoint(Sketcher::SketchObject* O /// commits or aborts as appropriate. The reason is for compatibility reasons with /// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp void SketcherGui::makeTangentToArcOfHyperbolaviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfHyperbola *aoh, - const Part::Geometry *geom2, - int geoId1, - int geoId2 -) + const Part::GeomArcOfHyperbola* aoh, + const Part::Geometry* geom2, int geoId1, + int geoId2) { - Base::Vector3d center=aoh->getCenter(); - double majord=aoh->getMajorRadius(); - double minord=aoh->getMinorRadius(); + Base::Vector3d center = aoh->getCenter(); + double majord = aoh->getMajorRadius(); + double minord = aoh->getMinorRadius(); Base::Vector3d dirmaj = aoh->getMajorAxisDir(); - double phi=atan2(dirmaj.y, dirmaj.x); - double df = sqrt(majord*majord+minord*minord); - Base::Vector3d focus = center+df*dirmaj; // positive focus + double phi = atan2(dirmaj.y, dirmaj.x); + double df = sqrt(majord * majord + minord * minord); + Base::Vector3d focus = center + df * dirmaj;// positive focus Base::Vector3d center2; - if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - const Part::GeomArcOfHyperbola *aoh2 = static_cast(geom2); + if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh2 = static_cast(geom2); Base::Vector3d dirmaj2 = aoh2->getMajorAxisDir(); double majord2 = aoh2->getMajorRadius(); double minord2 = aoh2->getMinorRadius(); - double df2 = sqrt(majord2*majord2+minord2*minord2); - center2 = aoh2->getCenter()+df2*dirmaj2; // positive focus + double df2 = sqrt(majord2 * majord2 + minord2 * minord2); + center2 = aoh2->getCenter() + df2 * dirmaj2;// positive focus } - else if( geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomEllipse::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *l2 = static_cast(geom2); - center2= (l2->getStartPoint() + l2->getEndPoint())/2; + else if (geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* l2 = static_cast(geom2); + center2 = (l2->getStartPoint() + l2->getEndPoint()) / 2; } - Base::Vector3d direction=center2-focus; - double tapprox=atan2(direction.y,direction.x)-phi; + Base::Vector3d direction = center2 - focus; + double tapprox = atan2(direction.y, direction.x) - phi; - Base::Vector3d PoH = Base::Vector3d(center.x+majord*cosh(tapprox)*cos(phi)-minord*sinh(tapprox)*sin(phi), - center.y+majord*cosh(tapprox)*sin(phi)+minord*sinh(tapprox)*cos(phi), 0); + Base::Vector3d PoH = Base::Vector3d( + center.x + majord * cosh(tapprox) * cos(phi) - minord * sinh(tapprox) * sin(phi), + center.y + majord * cosh(tapprox) * sin(phi) + minord * sinh(tapprox) * cos(phi), + 0); try { // Add a point - Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - PoH.x,PoH.y); + Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", PoH.x, PoH.y); int GeoIdPoint = Obj->getHighestCurveIndex(); // Point on first object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId1); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId1);// constrain major axis // Point on second object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId2); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId2);// constrain major axis // tangent via point - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", - geoId1, geoId2 ,GeoIdPoint, static_cast(Sketcher::PointPos::start)); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", + geoId1, + geoId2, + GeoIdPoint, + static_cast(Sketcher::PointPos::start)); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); tryAutoRecompute(Obj); @@ -390,71 +430,76 @@ void SketcherGui::makeTangentToArcOfHyperbolaviaNewPoint(Sketcher::SketchObject* /// Makes a simple tangency constraint using extra point + tangent via point /// aop => an arc of parabola -/// geom2 => any of an arc of parabola, an arc of hyperbola an arc of ellipse, a circle, or an arc (of circle) -/// geoId1 => geoid of the arc of parabola -/// geoId2 => geoid of geom2 -/// NOTE: A command must be opened before calling this function, which this function -/// commits or aborts as appropriate. The reason is for compatibility reasons with -/// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp +/// geom2 => any of an arc of parabola, an arc of hyperbola an arc of ellipse, a circle, or an arc +/// (of circle) geoId1 => geoid of the arc of parabola geoId2 => geoid of geom2 NOTE: A command must +/// be opened before calling this function, which this function commits or aborts as appropriate. +/// The reason is for compatibility reasons with other code e.g. "Autoconstraints" in +/// DrawSketchHandler.cpp void SketcherGui::makeTangentToArcOfParabolaviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfParabola *aop, - const Part::Geometry *geom2, - int geoId1, - int geoId2 -) + const Part::GeomArcOfParabola* aop, + const Part::Geometry* geom2, int geoId1, + int geoId2) { Base::Vector3d focus = aop->getFocus(); Base::Vector3d center2; - if( geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) - center2= (static_cast(geom2))->getFocus(); - else if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - const Part::GeomArcOfHyperbola *aoh2 = static_cast(geom2); + if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) + center2 = (static_cast(geom2))->getFocus(); + else if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh2 = static_cast(geom2); Base::Vector3d dirmaj2 = aoh2->getMajorAxisDir(); double majord2 = aoh2->getMajorRadius(); double minord2 = aoh2->getMinorRadius(); - double df2 = sqrt(majord2*majord2+minord2*minord2); - center2 = aoh2->getCenter()+df2*dirmaj2; // positive focus + double df2 = sqrt(majord2 * majord2 + minord2 * minord2); + center2 = aoh2->getCenter() + df2 * dirmaj2;// positive focus } - else if( geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomEllipse::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) - center2= (static_cast(geom2))->getCenter(); - else if( geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *l2 = static_cast(geom2); - center2= (l2->getStartPoint() + l2->getEndPoint())/2; + else if (geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomEllipse::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + center2 = (static_cast(geom2))->getCenter(); + else if (geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* l2 = static_cast(geom2); + center2 = (l2->getStartPoint() + l2->getEndPoint()) / 2; } - Base::Vector3d direction = center2-focus; + Base::Vector3d direction = center2 - focus; Base::Vector3d PoP = focus + direction / 2; try { // Add a point - Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - PoP.x,PoP.y); + Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", PoP.x, PoP.y); int GeoIdPoint = Obj->getHighestCurveIndex(); // Point on first object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId1); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId1);// constrain major axis // Point on second object - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),geoId2); // constrain major axis + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + geoId2);// constrain major axis // tangent via point - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", - geoId1, geoId2 ,GeoIdPoint, static_cast(Sketcher::PointPos::start)); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", + geoId1, + geoId2, + GeoIdPoint, + static_cast(Sketcher::PointPos::start)); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); @@ -466,47 +511,56 @@ void SketcherGui::makeTangentToArcOfParabolaviaNewPoint(Sketcher::SketchObject* tryAutoRecompute(Obj); } -void SketcherGui::doEndpointTangency(Sketcher::SketchObject* Obj, - int GeoId1, int GeoId2, PointPos PosId1, PointPos PosId2) +void SketcherGui::doEndpointTangency(Sketcher::SketchObject* Obj, int GeoId1, int GeoId2, + PointPos PosId1, PointPos PosId2) { // This code supports simple B-spline endpoint tangency to any other geometric curve - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); - if (geom1 && geom2 && - (geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())){ + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { - if(geom1->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + if (geom1->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } // GeoId1 is the B-spline now - } // end of code supports simple B-spline endpoint tangency + }// end of code supports simple B-spline endpoint tangency - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); } -void SketcherGui::doEndpointToEdgeTangency( Sketcher::SketchObject* Obj, int GeoId1, PointPos PosId1, int GeoId2) +void SketcherGui::doEndpointToEdgeTangency(Sketcher::SketchObject* Obj, int GeoId1, PointPos PosId1, + int GeoId2) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2); } -void SketcherGui::notifyConstraintSubstitutions(const QString & message) +void SketcherGui::notifyConstraintSubstitutions(const QString& message) { - Gui::Dialog::DlgCheckableMessageBox::showMessage( QObject::tr("Sketcher Constraint Substitution"), - message, - QLatin1String("User parameter:BaseApp/Preferences/Mod/Sketcher/General"), - QLatin1String("NotifyConstraintSubstitutions"), - true, // Default ParamEntry - true, // checkbox state - QObject::tr("Keep notifying me of constraint substitutions")); + Gui::Dialog::DlgCheckableMessageBox::showMessage( + QObject::tr("Sketcher Constraint Substitution"), + message, + QLatin1String("User parameter:BaseApp/Preferences/Mod/Sketcher/General"), + QLatin1String("NotifyConstraintSubstitutions"), + true,// Default ParamEntry + true,// checkbox state + QObject::tr("Keep notifying me of constraint substitutions")); } // returns true if successful, false otherwise -bool addConstraintSafely(SketchObject * obj, std::function constraintadditionfunction) +bool addConstraintSafely(SketchObject* obj, std::function constraintadditionfunction) { try { constraintadditionfunction(); @@ -515,9 +569,8 @@ bool addConstraintSafely(SketchObject * obj, std::function constraintadd // Exceptions originating in Python have already been reported by the Interpreter as // Untranslated developer intended messages (i.e. to the Report View) // Example of exception carrying a static string with a pair in the "Notifications" context - Gui::NotifyUserError(obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); @@ -525,9 +578,10 @@ bool addConstraintSafely(SketchObject * obj, std::function constraintadd return false; } catch (const Base::Exception& e) { - Gui::TranslatedUserError(obj, - QObject::tr("Error"), - QObject::tr("Unexpected error. More information may be available in the Report View.")); + Gui::TranslatedUserError( + obj, + QObject::tr("Error"), + QObject::tr("Unexpected error. More information may be available in the Report View.")); Gui::Command::abortCommand(); @@ -538,22 +592,27 @@ bool addConstraintSafely(SketchObject * obj, std::function constraintadd return true; } -namespace SketcherGui { +namespace SketcherGui +{ -struct SelIdPair{ +struct SelIdPair +{ int GeoId; Sketcher::PointPos PosId; }; -struct SketchSelection{ - enum GeoType { +struct SketchSelection +{ + enum GeoType + { Point, Line, Circle, Arc }; int setUp(); - struct SketchSelectionItem { + struct SketchSelectionItem + { GeoType type; int GeoId; bool Extern; @@ -566,47 +625,52 @@ int SketchSelection::setUp() { std::vector selection = Gui::Selection().getSelectionEx(); - Sketcher::SketchObject *SketchObj=nullptr; + Sketcher::SketchObject* SketchObj = nullptr; std::vector SketchSubNames; std::vector SupportSubNames; // only one sketch with its subelements are allowed to be selected if (selection.size() == 1) { // if one selectetd, only sketch allowed. should be done by activity of command - if(!selection[0].getObject()->getTypeId().isDerivedFrom(Sketcher::SketchObject::getClassTypeId())) - { + if (!selection[0].getObject()->getTypeId().isDerivedFrom( + Sketcher::SketchObject::getClassTypeId())) { ErrorMsg = QObject::tr("Only sketch and its support are allowed to be selected."); return -1; } SketchObj = static_cast(selection[0].getObject()); SketchSubNames = selection[0].getSubNames(); - } else if(selection.size() == 2) { - if(selection[0].getObject()->getTypeId().isDerivedFrom(Sketcher::SketchObject::getClassTypeId())){ + } + else if (selection.size() == 2) { + if (selection[0].getObject()->getTypeId().isDerivedFrom( + Sketcher::SketchObject::getClassTypeId())) { SketchObj = static_cast(selection[0].getObject()); // check if the none sketch object is the support of the sketch - if(selection[1].getObject() != SketchObj->Support.getValue()){ - ErrorMsg = QObject::tr("Only sketch and its support are allowed to be selected."); - return-1; - } - // assume always a Part::Feature derived object as support - assert(selection[1].getObject()->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())); - SketchSubNames = selection[0].getSubNames(); - SupportSubNames = selection[1].getSubNames(); - - } else if (selection[1].getObject()->getTypeId().isDerivedFrom(Sketcher::SketchObject::getClassTypeId())) { - SketchObj = static_cast(selection[1].getObject()); - // check if the none sketch object is the support of the sketch - if(selection[0].getObject() != SketchObj->Support.getValue()){ + if (selection[1].getObject() != SketchObj->Support.getValue()) { ErrorMsg = QObject::tr("Only sketch and its support are allowed to be selected."); return -1; } // assume always a Part::Feature derived object as support - assert(selection[0].getObject()->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())); - SketchSubNames = selection[1].getSubNames(); + assert(selection[1].getObject()->getTypeId().isDerivedFrom( + Part::Feature::getClassTypeId())); + SketchSubNames = selection[0].getSubNames(); + SupportSubNames = selection[1].getSubNames(); + } + else if (selection[1].getObject()->getTypeId().isDerivedFrom( + Sketcher::SketchObject::getClassTypeId())) { + SketchObj = static_cast(selection[1].getObject()); + // check if the none sketch object is the support of the sketch + if (selection[0].getObject() != SketchObj->Support.getValue()) { + ErrorMsg = QObject::tr("Only sketch and its support are allowed to be selected."); + return -1; + } + // assume always a Part::Feature derived object as support + assert(selection[0].getObject()->getTypeId().isDerivedFrom( + Part::Feature::getClassTypeId())); + SketchSubNames = selection[1].getSubNames(); SupportSubNames = selection[0].getSubNames(); - - } else { + } + else { ErrorMsg = QObject::tr("One of the selected has to be on the sketch."); return -1; } @@ -615,88 +679,99 @@ int SketchSelection::setUp() return Items.size(); } -} // namespace SketcherGui +}// namespace SketcherGui /* Constrain commands =======================================================*/ -namespace SketcherGui { - /** - * @brief The SelType enum - * Types of sketch elements that can be (pre)selected. The root/origin and the - * axes are put up separately so that they can be specifically disallowed, for - * example, when in lock, horizontal, or vertical constraint modes. - */ - enum SelType { - SelUnknown = 0, - SelVertex = 1, - SelVertexOrRoot = 64, - SelRoot = 2, - SelEdge = 4, - SelEdgeOrAxis = 128, - SelHAxis = 8, - SelVAxis = 16, - SelExternalEdge = 32 - }; +namespace SketcherGui +{ +/** + * @brief The SelType enum + * Types of sketch elements that can be (pre)selected. The root/origin and the + * axes are put up separately so that they can be specifically disallowed, for + * example, when in lock, horizontal, or vertical constraint modes. + */ +enum SelType +{ + SelUnknown = 0, + SelVertex = 1, + SelVertexOrRoot = 64, + SelRoot = 2, + SelEdge = 4, + SelEdgeOrAxis = 128, + SelHAxis = 8, + SelVAxis = 16, + SelExternalEdge = 32 +}; - /** - * @brief The GenericConstraintSelection class - * SelectionFilterGate with changeable filters. In a constraint creation mode - * like point on object, if the first selection object can be a point, the next - * has to be a curve for the constraint to make sense. Thus filters are - * changeable so that same filter can be kept on while in one mode. - */ - class GenericConstraintSelection : public Gui::SelectionFilterGate +/** + * @brief The GenericConstraintSelection class + * SelectionFilterGate with changeable filters. In a constraint creation mode + * like point on object, if the first selection object can be a point, the next + * has to be a curve for the constraint to make sense. Thus filters are + * changeable so that same filter can be kept on while in one mode. + */ +class GenericConstraintSelection: public Gui::SelectionFilterGate +{ + App::DocumentObject* object; + +public: + explicit GenericConstraintSelection(App::DocumentObject* obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) + , allowedSelTypes(0) + {} + + bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) override { - App::DocumentObject* object; - public: - explicit GenericConstraintSelection(App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()) - , object(obj), allowedSelTypes(0) - {} - - bool allow(App::Document *, App::DocumentObject *pObj, const char *sSubName) override - { - if (pObj != this->object) - return false; - if (!sSubName || sSubName[0] == '\0') - return false; - std::string element(sSubName); - if ( (allowedSelTypes & (SelRoot | SelVertexOrRoot) && element.substr(0,9) == "RootPoint") || - (allowedSelTypes & (SelVertex | SelVertexOrRoot) && element.substr(0,6) == "Vertex") || - (allowedSelTypes & (SelEdge | SelEdgeOrAxis) && element.substr(0,4) == "Edge") || - (allowedSelTypes & (SelHAxis | SelEdgeOrAxis) && element.substr(0,6) == "H_Axis") || - (allowedSelTypes & (SelVAxis | SelEdgeOrAxis) && element.substr(0,6) == "V_Axis") || - (allowedSelTypes & SelExternalEdge && element.substr(0,12) == "ExternalEdge")) - return true; - + if (pObj != this->object) return false; - } + if (!sSubName || sSubName[0] == '\0') + return false; + std::string element(sSubName); + if ((allowedSelTypes & (SelRoot | SelVertexOrRoot) && element.substr(0, 9) == "RootPoint") + || (allowedSelTypes & (SelVertex | SelVertexOrRoot) && element.substr(0, 6) == "Vertex") + || (allowedSelTypes & (SelEdge | SelEdgeOrAxis) && element.substr(0, 4) == "Edge") + || (allowedSelTypes & (SelHAxis | SelEdgeOrAxis) && element.substr(0, 6) == "H_Axis") + || (allowedSelTypes & (SelVAxis | SelEdgeOrAxis) && element.substr(0, 6) == "V_Axis") + || (allowedSelTypes & SelExternalEdge && element.substr(0, 12) == "ExternalEdge")) + return true; - void setAllowedSelTypes(unsigned int types) { - if (types < 256) allowedSelTypes = types; - } + return false; + } - protected: - int allowedSelTypes; - }; -} + void setAllowedSelTypes(unsigned int types) + { + if (types < 256) + allowedSelTypes = types; + } + +protected: + int allowedSelTypes; +}; +}// namespace SketcherGui /** * @brief The CmdSketcherConstraint class * Superclass for all sketcher constraints to ease generation of constraint * creation modes. */ -class CmdSketcherConstraint : public Gui::Command +class CmdSketcherConstraint: public Gui::Command { friend class DrawSketchHandlerGenConstraint; + public: explicit CmdSketcherConstraint(const char* name) - : Command(name) {} + : Command(name) + {} - ~CmdSketcherConstraint() override{} + ~CmdSketcherConstraint() override + {} const char* className() const override - { return "CmdSketcherConstraint"; } + { + return "CmdSketcherConstraint"; + } protected: /** @@ -713,25 +788,31 @@ protected: * * TODO: Introduce structs to allow keeping first selection */ - std::vector > allowedSelSequences; + std::vector> allowedSelSequences; - virtual void applyConstraint(std::vector &, int) {} + virtual void applyConstraint(std::vector&, int) + {} void activated(int /*iMsg*/) override; bool isActive() override - { return isCommandActive(getActiveGuiDocument()); } + { + return isCommandActive(getActiveGuiDocument()); + } }; class DrawSketchHandlerGenConstraint: public DrawSketchHandler { public: - explicit DrawSketchHandlerGenConstraint(CmdSketcherConstraint *_cmd) - : cmd(_cmd), seqIndex(0) {} + explicit DrawSketchHandlerGenConstraint(CmdSketcherConstraint* _cmd) + : cmd(_cmd) + , seqIndex(0) + {} ~DrawSketchHandlerGenConstraint() override { Gui::Selection().rmvSelectionGate(); } - void mouseMove(Base::Vector2d /*onSketchPos*/) override {} + void mouseMove(Base::Vector2d /*onSketchPos*/) override + {} bool pressButton(Base::Vector2d /*onSketchPos*/) override { @@ -746,7 +827,7 @@ public: std::stringstream ss; SelType newSelType = SelUnknown; - //For each SelType allowed, check if button is released there and assign it to selIdPair + // For each SelType allowed, check if button is released there and assign it to selIdPair int VtId = getPreselectPoint(); int CrvId = getPreselectCurve(); int CrsId = getPreselectCross(); @@ -757,9 +838,7 @@ public: ss << "RootPoint"; } else if (allowedSelTypes & (SelVertex | SelVertexOrRoot) && VtId >= 0) { - sketchgui->getSketchObject()->getGeoVertexIndex(VtId, - selIdPair.GeoId, - selIdPair.PosId); + sketchgui->getSketchObject()->getGeoVertexIndex(VtId, selIdPair.GeoId, selIdPair.PosId); newSelType = (allowedSelTypes & SelVertex) ? SelVertex : SelVertexOrRoot; ss << "Vertex" << VtId + 1; } @@ -779,7 +858,7 @@ public: ss << "V_Axis"; } else if (allowedSelTypes & SelExternalEdge && CrvId <= Sketcher::GeoEnum::RefExt) { - //TODO: Figure out how this works + // TODO: Figure out how this works selIdPair.GeoId = CrvId; newSelType = SelExternalEdge; ss << "ExternalEdge" << Sketcher::GeoEnum::RefExt + 1 - CrvId; @@ -803,11 +882,12 @@ public: _tempOnSequences.clear(); allowedSelTypes = 0; for (std::set::iterator token = ongoingSequences.begin(); - token != ongoingSequences.end(); ++token) { + token != ongoingSequences.end(); + ++token) { if ((cmd->allowedSelSequences).at(*token).at(seqIndex) == newSelType) { - if (seqIndex == (cmd->allowedSelSequences).at(*token).size()-1) { + if (seqIndex == (cmd->allowedSelSequences).at(*token).size() - 1) { // One of the sequences is completed. Pass to cmd->applyConstraint - cmd->applyConstraint(selSeq, *token); // replace arg 2 by ongoingToken + cmd->applyConstraint(selSeq, *token);// replace arg 2 by ongoingToken selSeq.clear(); resetOngoingSequences(); @@ -815,7 +895,8 @@ public: return true; } _tempOnSequences.insert(*token); - allowedSelTypes = allowedSelTypes | (cmd->allowedSelSequences).at(*token).at(seqIndex+1); + allowedSelTypes = + allowedSelTypes | (cmd->allowedSelSequences).at(*token).at(seqIndex + 1); } } @@ -849,8 +930,10 @@ private: qreal fullIconWidth = 32 * pixelRatio; qreal iconWidth = 16 * pixelRatio; - QPixmap cursorPixmap = Gui::BitmapFactory().pixmapFromSvg("Sketcher_Crosshair", QSizeF(fullIconWidth, fullIconWidth), colorMapping), - icon = Gui::BitmapFactory().pixmapFromSvg(cmd->getPixmap(), QSizeF(iconWidth, iconWidth)); + QPixmap cursorPixmap = Gui::BitmapFactory().pixmapFromSvg( + "Sketcher_Crosshair", QSizeF(fullIconWidth, fullIconWidth), colorMapping), + icon = Gui::BitmapFactory().pixmapFromSvg(cmd->getPixmap(), + QSizeF(iconWidth, iconWidth)); QPainter cursorPainter; cursorPainter.begin(&cursorPixmap); cursorPainter.drawPixmap(16 * pixelRatio, 16 * pixelRatio, icon); @@ -879,7 +962,8 @@ protected: /// Index within the selection sequences active unsigned int seqIndex; - void resetOngoingSequences() { + void resetOngoingSequences() + { ongoingSequences.clear(); for (unsigned int i = 0; i < cmd->allowedSelSequences.size(); i++) { ongoingSequences.insert(i); @@ -888,8 +972,10 @@ protected: // Estimate allowed selections from the first types in allowedSelTypes allowedSelTypes = 0; - for (std::vector< std::vector< SelType > >::const_iterator it = cmd->allowedSelSequences.begin(); - it != cmd->allowedSelSequences.end(); ++it) { + for (std::vector>::const_iterator it = + cmd->allowedSelSequences.begin(); + it != cmd->allowedSelSequences.end(); + ++it) { allowedSelTypes = allowedSelTypes | (*it).at(seqIndex); } selFilterGate->setAllowedSelTypes(allowedSelTypes); @@ -900,38 +986,40 @@ protected: void CmdSketcherConstraint::activated(int /*iMsg*/) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); } // ============================================================================ -class CmdSketcherConstrainHorizontal : public CmdSketcherConstraint +class CmdSketcherConstrainHorizontal: public CmdSketcherConstraint { public: CmdSketcherConstrainHorizontal(); - ~CmdSketcherConstrainHorizontal() override{} + ~CmdSketcherConstrainHorizontal() override + {} const char* className() const override - { return "CmdSketcherConstrainHorizontal"; } + { + return "CmdSketcherConstrainHorizontal"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; - + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainHorizontal::CmdSketcherConstrainHorizontal() - :CmdSketcherConstraint("Sketcher_ConstrainHorizontal") + : CmdSketcherConstraint("Sketcher_ConstrainHorizontal") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain horizontally"); - sToolTipText = QT_TR_NOOP("Create a horizontal constraint on the selected item"); - sWhatsThis = "Sketcher_ConstrainHorizontal"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Horizontal"; - sAccel = "H"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain horizontally"); + sToolTipText = QT_TR_NOOP("Create a horizontal constraint on the selected item"); + sWhatsThis = "Sketcher_ConstrainHorizontal"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Horizontal"; + sAccel = "H"; + eType = ForEdit; allowedSelSequences = {{SelEdge}, {SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}}; } @@ -944,26 +1032,28 @@ void CmdSketcherConstrainHorizontal::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), - QObject::tr("Select an edge from the sketch.")); + QObject::tr("Select an edge from the sketch.")); } return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + const std::vector& vals = Obj->Constraints.getValues(); std::vector edgegeoids; std::vector pointgeoids; @@ -971,42 +1061,58 @@ void CmdSketcherConstrainHorizontal::activated(int iMsg) int fixedpoints = 0; // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoId; Sketcher::PointPos PosId; getIdsFromName((*it), Obj, GeoId, PosId); - if (isEdge(GeoId,PosId)) {// it is an edge - const Part::Geometry *geo = Obj->getGeometry(GeoId); + if (isEdge(GeoId, PosId)) {// it is an edge + const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge is not a line segment.")); + Gui::TranslatedUserWarning(Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge is not a line segment.")); return; } // check if the edge already has a Horizontal/Vertical/Block constraint - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if ((*it)->Type == Sketcher::Horizontal && (*it)->First == GeoId && (*it)->FirstPos == Sketcher::PointPos::none){ - Gui::TranslatedUserWarning(Obj, QObject::tr("Double constraint"), QObject::tr("The selected edge already has a horizontal constraint!")); + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::Horizontal && (*it)->First == GeoId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Double constraint"), + QObject::tr("The selected edge already has a horizontal constraint!")); return; } - if ((*it)->Type == Sketcher::Vertical && (*it)->First == GeoId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge already has a vertical constraint!")); + if ((*it)->Type == Sketcher::Vertical && (*it)->First == GeoId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a vertical constraint!")); return; } // check if the edge already has a Block constraint - if ((*it)->Type == Sketcher::Block && (*it)->First == GeoId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge already has a Block constraint!")); + if ((*it)->Type == Sketcher::Block && (*it)->First == GeoId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a Block constraint!")); return; } } edgegeoids.push_back(GeoId); } - else if(isVertex(GeoId,PosId)) { + else if (isVertex(GeoId, PosId)) { // can be a point, a construction point, an external point or root - if(isPointOrSegmentFixed(Obj, GeoId)) + if (isPointOrSegmentFixed(Obj, GeoId)) fixedpoints++; pointgeoids.push_back(GeoId); @@ -1015,7 +1121,10 @@ void CmdSketcherConstrainHorizontal::activated(int iMsg) } if (edgegeoids.empty() && pointgeoids.empty()) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected item(s) can't accept a horizontal constraint!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected item(s) can't accept a horizontal constraint!")); return; } @@ -1023,26 +1132,35 @@ void CmdSketcherConstrainHorizontal::activated(int iMsg) if (!edgegeoids.empty()) { // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add horizontal constraint")); - for (std::vector::iterator it=edgegeoids.begin(); it != edgegeoids.end(); it++) { + for (std::vector::iterator it = edgegeoids.begin(); it != edgegeoids.end(); it++) { // issue the actual commands to create the constraint Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Horizontal',%d))", *it); + "addConstraint(Sketcher.Constraint('Horizontal',%d))", + *it); } } - else if (fixedpoints <= 1) { // pointgeoids + else if (fixedpoints <= 1) {// pointgeoids // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add horizontal alignment")); std::vector::iterator it; std::vector::iterator itp; - for (it=pointgeoids.begin(), itp=pointpos.begin(); it != std::prev(pointgeoids.end()) && itp != std::prev(pointpos.end()); it++,itp++) { + for (it = pointgeoids.begin(), itp = pointpos.begin(); + it != std::prev(pointgeoids.end()) && itp != std::prev(pointpos.end()); + it++, itp++) { // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(selection[0].getObject() - ,"addConstraint(Sketcher.Constraint('Horizontal',%d,%d,%d,%d))" - ,*it,static_cast(*itp),*std::next(it),static_cast(*std::next(itp))); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Horizontal',%d,%d,%d,%d))", + *it, + static_cast(*itp), + *std::next(it), + static_cast(*std::next(itp))); } } - else { // vertex mode, fixedpoints > 1 - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("There are more than one fixed points selected. Select a maximum of one fixed point!")); + else {// vertex mode, fixedpoints > 1 + Gui::TranslatedUserWarning(Obj, + QObject::tr("Impossible constraint"), + QObject::tr("There are more than one fixed points selected. " + "Select a maximum of one fixed point!")); return; } // finish the transaction and update @@ -1054,47 +1172,67 @@ void CmdSketcherConstrainHorizontal::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainHorizontal::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainHorizontal::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); switch (seqIndex) { - case 0: // {Edge} + case 0:// {Edge} { // create the constraint - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + const std::vector& vals = Obj->Constraints.getValues(); int CrvId = selSeq.front().GeoId; if (CrvId != -1) { - const Part::Geometry *geo = Obj->getGeometry(CrvId); + const Part::Geometry* geo = Obj->getGeometry(CrvId); if (geo->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge is not a line segment.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge is not a line segment.")); return; } // check if the edge already has a Horizontal/Vertical/Block constraint - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if ((*it)->Type == Sketcher::Horizontal && (*it)->First == CrvId && (*it)->FirstPos == Sketcher::PointPos::none){ - Gui::TranslatedUserWarning(Obj, QObject::tr("Double constraint"), QObject::tr("The selected edge already has a horizontal constraint!")); + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::Horizontal && (*it)->First == CrvId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Double constraint"), + QObject::tr("The selected edge already has a horizontal constraint!")); return; } - if ((*it)->Type == Sketcher::Vertical && (*it)->First == CrvId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge already has a vertical constraint!")); + if ((*it)->Type == Sketcher::Vertical && (*it)->First == CrvId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a vertical constraint!")); return; } // check if the edge already has a Block constraint - if ((*it)->Type == Sketcher::Block && (*it)->First == CrvId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge already has a Block constraint!")); + if ((*it)->Type == Sketcher::Block && (*it)->First == CrvId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a Block constraint!")); return; } } // undo command open - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add horizontal constraint")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add horizontal constraint")); // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Horizontal',%d))", CrvId); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Horizontal',%d))", + CrvId); // finish the transaction and update Gui::Command::commitCommand(); @@ -1104,15 +1242,17 @@ void CmdSketcherConstrainHorizontal::applyConstraint(std::vector &sel break; } - case 1 : // {SelVertex, SelVertexOrRoot} - case 2 : // {SelRoot, SelVertex} + case 1:// {SelVertex, SelVertexOrRoot} + case 2:// {SelRoot, SelVertex} { int GeoId1, GeoId2; Sketcher::PointPos PosId1, PosId2; - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; - if ( areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) ) { + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { showNoConstraintBetweenFixedGeometry(Obj); return; } @@ -1120,47 +1260,52 @@ void CmdSketcherConstrainHorizontal::applyConstraint(std::vector &sel // undo command open Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add horizontal alignment")); // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(sketchgui->getObject() - ,"addConstraint(Sketcher.Constraint('Horizontal',%d,%d,%d,%d))" - ,GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Horizontal',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); // finish the transaction and update Gui::Command::commitCommand(); tryAutoRecompute(Obj); break; - } } } // ================================================================================ -class CmdSketcherConstrainVertical : public CmdSketcherConstraint +class CmdSketcherConstrainVertical: public CmdSketcherConstraint { public: CmdSketcherConstrainVertical(); - ~CmdSketcherConstrainVertical() override{} + ~CmdSketcherConstrainVertical() override + {} const char* className() const override - { return "CmdSketcherConstrainVertical"; } + { + return "CmdSketcherConstrainVertical"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; - + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainVertical::CmdSketcherConstrainVertical() - :CmdSketcherConstraint("Sketcher_ConstrainVertical") + : CmdSketcherConstraint("Sketcher_ConstrainVertical") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain vertically"); - sToolTipText = QT_TR_NOOP("Create a vertical constraint on the selected item"); - sWhatsThis = "Sketcher_ConstrainVertical"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Vertical"; - sAccel = "V"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain vertically"); + sToolTipText = QT_TR_NOOP("Create a vertical constraint on the selected item"); + sWhatsThis = "Sketcher_ConstrainVertical"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Vertical"; + sAccel = "V"; + eType = ForEdit; allowedSelSequences = {{SelEdge}, {SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}}; } @@ -1173,15 +1318,17 @@ void CmdSketcherConstrainVertical::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), QObject::tr("Select an edge from the sketch.")); @@ -1190,9 +1337,9 @@ void CmdSketcherConstrainVertical::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + const std::vector& vals = Obj->Constraints.getValues(); std::vector edgegeoids; std::vector pointgeoids; @@ -1200,49 +1347,57 @@ void CmdSketcherConstrainVertical::activated(int iMsg) int fixedpoints = 0; // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoId; Sketcher::PointPos PosId; getIdsFromName((*it), Obj, GeoId, PosId); - if (isEdge(GeoId,PosId)) {// it is an edge - const Part::Geometry *geo = Obj->getGeometry(GeoId); + if (isEdge(GeoId, PosId)) {// it is an edge + const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Impossible constraint"), - QObject::tr("The selected edge is not a line segment.")); + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge is not a line segment.")); return; } // check if the edge already has a Horizontal/Vertical/Block constraint - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if ((*it)->Type == Sketcher::Vertical && (*it)->First == GeoId && (*it)->FirstPos == Sketcher::PointPos::none){ - Gui::TranslatedUserWarning(Obj, - QObject::tr("Double constraint"), - QObject::tr("The selected edge already has a horizontal constraint!")); + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::Vertical && (*it)->First == GeoId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Double constraint"), + QObject::tr("The selected edge already has a horizontal constraint!")); return; } - if ((*it)->Type == Sketcher::Horizontal && (*it)->First == GeoId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Impossible constraint"), - QObject::tr("The selected edge already has a horizontal constraint!")); + if ((*it)->Type == Sketcher::Horizontal && (*it)->First == GeoId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a horizontal constraint!")); return; } // check if the edge already has a Block constraint - if ((*it)->Type == Sketcher::Block && (*it)->First == GeoId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Impossible constraint"), - QObject::tr("The selected edge already has a Block constraint!")); + if ((*it)->Type == Sketcher::Block && (*it)->First == GeoId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a Block constraint!")); return; } } edgegeoids.push_back(GeoId); } - else if(isVertex(GeoId,PosId)) { + else if (isVertex(GeoId, PosId)) { // can be a point, a construction point, an external point, root or a blocked geometry - if(isPointOrSegmentFixed(Obj, GeoId)) + if (isPointOrSegmentFixed(Obj, GeoId)) fixedpoints++; pointgeoids.push_back(GeoId); @@ -1251,9 +1406,10 @@ void CmdSketcherConstrainVertical::activated(int iMsg) } if (edgegeoids.empty() && pointgeoids.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Impossible constraint"), - QObject::tr("The selected item(s) can't accept a vertical constraint!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected item(s) can't accept a vertical constraint!")); return; } @@ -1261,26 +1417,34 @@ void CmdSketcherConstrainVertical::activated(int iMsg) if (!edgegeoids.empty()) { // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add vertical constraint")); - for (std::vector::iterator it=edgegeoids.begin(); it != edgegeoids.end(); it++) { + for (std::vector::iterator it = edgegeoids.begin(); it != edgegeoids.end(); it++) { // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('Vertical',%d))", *it); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "addConstraint(Sketcher.Constraint('Vertical',%d))", *it); } } - else if (fixedpoints <= 1) { // vertex mode, maximum one fixed point + else if (fixedpoints <= 1) {// vertex mode, maximum one fixed point // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add vertical alignment")); std::vector::iterator it; std::vector::iterator itp; - for (it=pointgeoids.begin(), itp=pointpos.begin(); it != std::prev(pointgeoids.end()) && itp != std::prev(pointpos.end()); it++,itp++) { + for (it = pointgeoids.begin(), itp = pointpos.begin(); + it != std::prev(pointgeoids.end()) && itp != std::prev(pointpos.end()); + it++, itp++) { // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Vertical',%d,%d,%d,%d))" - ,*it,static_cast(*itp),*std::next(it),static_cast(*std::next(itp))); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Vertical',%d,%d,%d,%d))", + *it, + static_cast(*itp), + *std::next(it), + static_cast(*std::next(itp))); } } - else { // vertex mode, fixedpoints > 1 + else {// vertex mode, fixedpoints > 1 Gui::TranslatedUserWarning(Obj, - QObject::tr("Impossible constraint"), - QObject::tr("There are more than one fixed points selected. Select a maximum of one fixed point!")); + QObject::tr("Impossible constraint"), + QObject::tr("There are more than one fixed points selected. " + "Select a maximum of one fixed point!")); return; } @@ -1293,113 +1457,141 @@ void CmdSketcherConstrainVertical::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainVertical::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainVertical::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); switch (seqIndex) { - case 0: // {Edge} - { - // create the constraint - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + case 0:// {Edge} + { + // create the constraint + const std::vector& vals = Obj->Constraints.getValues(); - int CrvId = selSeq.front().GeoId; - if (CrvId != -1) { - const Part::Geometry *geo = Obj->getGeometry(CrvId); - if (geo->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge is not a line segment.")); + int CrvId = selSeq.front().GeoId; + if (CrvId != -1) { + const Part::Geometry* geo = Obj->getGeometry(CrvId); + if (geo->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge is not a line segment.")); + return; + } + + // check if the edge already has a Horizontal or Vertical constraint + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it) { + if ((*it)->Type == Sketcher::Horizontal && (*it)->First == CrvId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a horizontal constraint!")); + return; + } + if ((*it)->Type == Sketcher::Vertical && (*it)->First == CrvId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Double constraint"), + QObject::tr("The selected edge already has a vertical constraint!")); + return; + } + // check if the edge already has a Block constraint + if ((*it)->Type == Sketcher::Block && (*it)->First == CrvId + && (*it)->FirstPos == Sketcher::PointPos::none) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Impossible constraint"), + QObject::tr("The selected edge already has a Block constraint!")); + return; + } + } + + // undo command open + Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add vertical constraint")); + // issue the actual commands to create the constraint + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Vertical',%d))", + CrvId); + // finish the transaction and update + Gui::Command::commitCommand(); + tryAutoRecompute(Obj); + } + + break; + } + + case 1:// {SelVertex, SelVertexOrRoot} + case 2:// {SelRoot, SelVertex} + { + int GeoId1, GeoId2; + Sketcher::PointPos PosId1, PosId2; + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; + + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); return; } - // check if the edge already has a Horizontal or Vertical constraint - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it) { - if ((*it)->Type == Sketcher::Horizontal && (*it)->First == CrvId && (*it)->FirstPos == Sketcher::PointPos::none){ - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge already has a horizontal constraint!")); - return; - } - if ((*it)->Type == Sketcher::Vertical && (*it)->First == CrvId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Double constraint"), QObject::tr("The selected edge already has a vertical constraint!")); - return; - } - // check if the edge already has a Block constraint - if ((*it)->Type == Sketcher::Block && (*it)->First == CrvId && (*it)->FirstPos == Sketcher::PointPos::none) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Impossible constraint"), QObject::tr("The selected edge already has a Block constraint!")); - return; - } - } - // undo command open - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add vertical constraint")); + Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add horizontal alignment")); // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Vertical',%d))", CrvId); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Vertical',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); // finish the transaction and update Gui::Command::commitCommand(); + tryAutoRecompute(Obj); + + break; } - - break; - } - - case 1 : // {SelVertex, SelVertexOrRoot} - case 2 : // {SelRoot, SelVertex} - { - int GeoId1, GeoId2; - Sketcher::PointPos PosId1, PosId2; - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; - - if ( areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } - - // undo command open - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add horizontal alignment")); - // issue the actual commands to create the constraint - Gui::cmdAppObjectArgs(sketchgui->getObject() - ,"addConstraint(Sketcher.Constraint('Vertical',%d,%d,%d,%d))" - ,GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); - // finish the transaction and update - Gui::Command::commitCommand(); - - tryAutoRecompute(Obj); - - break; - } } } // ====================================================================================== -class CmdSketcherConstrainLock : public CmdSketcherConstraint +class CmdSketcherConstrainLock: public CmdSketcherConstraint { public: CmdSketcherConstrainLock(); - ~CmdSketcherConstrainLock() override{} + ~CmdSketcherConstrainLock() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainLock"; } + { + return "CmdSketcherConstrainLock"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainLock::CmdSketcherConstrainLock() - :CmdSketcherConstraint("Sketcher_ConstrainLock") + : CmdSketcherConstraint("Sketcher_ConstrainLock") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain lock"); - sToolTipText = QT_TR_NOOP("Create both a horizontal " - "and a vertical distance constraint\n" - "on the selected vertex"); - sWhatsThis = "Sketcher_ConstrainLock"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Lock"; - sAccel = "K, L"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain lock"); + sToolTipText = QT_TR_NOOP("Create both a horizontal " + "and a vertical distance constraint\n" + "on the selected vertex"); + sWhatsThis = "Sketcher_ConstrainLock"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Lock"; + sAccel = "K, L"; + eType = ForEdit; allowedSelSequences = {{SelVertex}}; } @@ -1412,15 +1604,17 @@ void CmdSketcherConstrainLock::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), QObject::tr("Select vertices from the sketch.")); @@ -1429,30 +1623,34 @@ void CmdSketcherConstrainLock::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); std::vector GeoId; std::vector PosId; - for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoIdt; Sketcher::PointPos PosIdt; getIdsFromName((*it), Obj, GeoIdt, PosIdt); GeoId.push_back(GeoIdt); PosId.push_back(PosIdt); - if ((it != std::prev(SubNames.end()) && (isEdge(GeoIdt,PosIdt) || (GeoIdt < 0 && GeoIdt >= Sketcher::GeoEnum::VAxis))) || - (it == std::prev(SubNames.end()) && isEdge(GeoIdt,PosIdt)) ) { - if(selection.size() == 1) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one vertex from the sketch other than the origin.")); + if ((it != std::prev(SubNames.end()) + && (isEdge(GeoIdt, PosIdt) || (GeoIdt < 0 && GeoIdt >= Sketcher::GeoEnum::VAxis))) + || (it == std::prev(SubNames.end()) && isEdge(GeoIdt, PosIdt))) { + if (selection.size() == 1) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one vertex from the sketch other than the origin.")); } else { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select only vertices from the sketch. The last selected vertex may be the origin.")); + QObject::tr("Wrong selection"), + QObject::tr("Select only vertices from the sketch. The " + "last selected vertex may be the origin.")); } // clear the selection (convenience) getSelection().clearSelection(); @@ -1460,76 +1658,95 @@ void CmdSketcherConstrainLock::activated(int iMsg) } } - int lastconstraintindex = Obj->Constraints.getSize()-1; + int lastconstraintindex = Obj->Constraints.getSize() - 1; - if( GeoId.size() == 1 ) { // absolute mode + if (GeoId.size() == 1) {// absolute mode // check if the edge already has a Block constraint bool edgeisblocked = false; - if ( isPointOrSegmentFixed(Obj, GeoId[0])) { + if (isPointOrSegmentFixed(Obj, GeoId[0])) { edgeisblocked = true; } - Base::Vector3d pnt = Obj->getPoint(GeoId[0],PosId[0]); + Base::Vector3d pnt = Obj->getPoint(GeoId[0], PosId[0]); // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add 'Lock' constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%f))", - GeoId[0],static_cast(PosId[0]),pnt.x); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%f))", - GeoId[0],static_cast(PosId[0]),pnt.y); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%f))", + GeoId[0], + static_cast(PosId[0]), + pnt.x); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%f))", + GeoId[0], + static_cast(PosId[0]), + pnt.y); - lastconstraintindex+=2; + lastconstraintindex += 2; - if (edgeisblocked - || GeoId[0] <= Sketcher::GeoEnum::RefExt - || constraintCreationMode==Reference) { + if (edgeisblocked || GeoId[0] <= Sketcher::GeoEnum::RefExt + || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - lastconstraintindex-1,"False"); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", lastconstraintindex - 1, "False"); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - lastconstraintindex,"False"); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", lastconstraintindex, "False"); } } else { std::vector::const_iterator itg; std::vector::const_iterator itp; - Base::Vector3d pntr = Obj->getPoint(GeoId.back(),PosId.back()); + Base::Vector3d pntr = Obj->getPoint(GeoId.back(), PosId.back()); // check if the edge already has a Block constraint bool refpointfixed = false; - if ( isPointOrSegmentFixed(Obj, GeoId.back())) + if (isPointOrSegmentFixed(Obj, GeoId.back())) refpointfixed = true; - for (itg = GeoId.begin(), itp = PosId.begin(); itg != std::prev(GeoId.end()) && itp != std::prev(PosId.end()); ++itp, ++itg) { + for (itg = GeoId.begin(), itp = PosId.begin(); + itg != std::prev(GeoId.end()) && itp != std::prev(PosId.end()); + ++itp, ++itg) { bool pointfixed = false; - if ( isPointOrSegmentFixed(Obj, *itg)) + if (isPointOrSegmentFixed(Obj, *itg)) pointfixed = true; - Base::Vector3d pnt = Obj->getPoint(*itg,*itp); + Base::Vector3d pnt = Obj->getPoint(*itg, *itp); // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add relative 'Lock' constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", - *itg,static_cast(*itp),GeoId.back(),static_cast(PosId.back()),pntr.x-pnt.x); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", + *itg, + static_cast(*itp), + GeoId.back(), + static_cast(PosId.back()), + pntr.x - pnt.x); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", - *itg,static_cast(*itp),GeoId.back(),static_cast(PosId.back()),pntr.y-pnt.y); - lastconstraintindex+=2; + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", + *itg, + static_cast(*itp), + GeoId.back(), + static_cast(PosId.back()), + pntr.y - pnt.y); + lastconstraintindex += 2; - if ( (refpointfixed && pointfixed) || constraintCreationMode==Reference) { + if ((refpointfixed && pointfixed) || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - lastconstraintindex-1,"False"); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "setDriving(%d,%s)", + lastconstraintindex - 1, + "False"); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - lastconstraintindex,"False"); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", lastconstraintindex, "False"); } } } @@ -1542,90 +1759,104 @@ void CmdSketcherConstrainLock::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainLock::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainLock::applyConstraint(std::vector& selSeq, int seqIndex) { switch (seqIndex) { - case 0: // {Vertex} - // Create the constraints - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); - Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); + case 0:// {Vertex} + // Create the constraints + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); + Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); - // check if the edge already has a Block constraint - bool pointfixed = false; + // check if the edge already has a Block constraint + bool pointfixed = false; - if ( isPointOrSegmentFixed(Obj, selSeq.front().GeoId)) - pointfixed = true; + if (isPointOrSegmentFixed(Obj, selSeq.front().GeoId)) + pointfixed = true; - Base::Vector3d pnt = Obj->getPoint(selSeq.front().GeoId, selSeq.front().PosId); + Base::Vector3d pnt = Obj->getPoint(selSeq.front().GeoId, selSeq.front().PosId); - // undo command open - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add fixed constraint")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('DistanceX', %d, %d, %f))", - selSeq.front().GeoId, static_cast(selSeq.front().PosId), pnt.x); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('DistanceY', %d, %d, %f))", - selSeq.front().GeoId, static_cast(selSeq.front().PosId), pnt.y); + // undo command open + Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add fixed constraint")); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('DistanceX', %d, %d, %f))", + selSeq.front().GeoId, + static_cast(selSeq.front().PosId), + pnt.x); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('DistanceY', %d, %d, %f))", + selSeq.front().GeoId, + static_cast(selSeq.front().PosId), + pnt.y); - if (pointfixed || constraintCreationMode==Reference) { - // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (pointfixed || constraintCreationMode == Reference) { + // it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "setDriving(%d, %s)", ConStr.size()-2, "False"); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "setDriving(%d, %s)", ConStr.size() - 2, "False"); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "setDriving(%d, %s)", ConStr.size()-1, "False"); - } + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "setDriving(%d, %s)", ConStr.size() - 1, "False"); + } - // finish the transaction and update - Gui::Command::commitCommand(); + // finish the transaction and update + Gui::Command::commitCommand(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool autoRecompute = hGrp->GetBool("AutoRecompute", false); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool autoRecompute = hGrp->GetBool("AutoRecompute", false); - if(autoRecompute) - Gui::Command::updateActive(); - break; + if (autoRecompute) + Gui::Command::updateActive(); + break; } } void CmdSketcherConstrainLock::updateAction(int mode) { switch (mode) { - case Reference: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Lock_Driven")); - break; - case Driving: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Lock")); - break; + case Reference: + if (getAction()) + getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Lock_Driven")); + break; + case Driving: + if (getAction()) + getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Lock")); + break; } } // ====================================================================================== -class CmdSketcherConstrainBlock : public CmdSketcherConstraint +class CmdSketcherConstrainBlock: public CmdSketcherConstraint { public: CmdSketcherConstrainBlock(); - ~CmdSketcherConstrainBlock() override{} + ~CmdSketcherConstrainBlock() override + {} const char* className() const override - { return "CmdSketcherConstrainBlock"; } + { + return "CmdSketcherConstrainBlock"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainBlock::CmdSketcherConstrainBlock() -:CmdSketcherConstraint("Sketcher_ConstrainBlock") + : CmdSketcherConstraint("Sketcher_ConstrainBlock") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain block"); - sToolTipText = QT_TR_NOOP("Block the selected edge from moving"); - sWhatsThis = "Sketcher_ConstrainBlock"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Block"; - sAccel = "K, B"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain block"); + sToolTipText = QT_TR_NOOP("Block the selected edge from moving"); + sWhatsThis = "Sketcher_ConstrainBlock"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Block"; + sAccel = "K, B"; + eType = ForEdit; allowedSelSequences = {{SelEdge}}; } @@ -1638,15 +1869,17 @@ void CmdSketcherConstrainBlock::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), QObject::tr("Select vertices from the sketch.")); @@ -1655,38 +1888,40 @@ void CmdSketcherConstrainBlock::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); // Check that the solver does not report redundant/conflicting constraints - if(Obj->getLastSolverStatus()!=GCS::Success || Obj->getLastHasConflicts() || Obj->getLastHasRedundancies()) { + if (Obj->getLastSolverStatus() != GCS::Success || Obj->getLastHasConflicts() + || Obj->getLastHasRedundancies()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong solver status"), - QObject::tr("A Block constraint cannot be added " - "if the sketch is unsolved " - "or there are redundant and " - "conflicting constraints.")); - return; + QObject::tr("Wrong solver status"), + QObject::tr("A Block constraint cannot be added " + "if the sketch is unsolved " + "or there are redundant and " + "conflicting constraints.")); + return; } std::vector GeoId; - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + const std::vector& vals = Obj->Constraints.getValues(); - for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoIdt; Sketcher::PointPos PosIdt; getIdsFromName((*it), Obj, GeoIdt, PosIdt); - if ( isVertex(GeoIdt,PosIdt) || GeoIdt < 0 ) { - if(selection.size() == 1) { + if (isVertex(GeoIdt, PosIdt) || GeoIdt < 0) { + if (selection.size() == 1) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one edge from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select one edge from the sketch.")); } else { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select only edges from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select only edges from the sketch.")); } // clear the selection getSelection().clearSelection(); @@ -1694,10 +1929,11 @@ void CmdSketcherConstrainBlock::activated(int iMsg) } // check if the edge already has a Block constraint - if ( checkConstraint(vals, Sketcher::Block, GeoIdt, Sketcher::PointPos::none)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Double constraint"), - QObject::tr("The selected edge already has a Block constraint!")); + if (checkConstraint(vals, Sketcher::Block, GeoIdt, Sketcher::PointPos::none)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Double constraint"), + QObject::tr("The selected edge already has a Block constraint!")); return; } @@ -1708,11 +1944,11 @@ void CmdSketcherConstrainBlock::activated(int iMsg) // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add 'Block' constraint")); - bool safe = addConstraintSafely(Obj, [&](){ + bool safe = addConstraintSafely(Obj, [&]() { Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Block',%d))", (*itg)); }); - if(!safe) + if (!safe) return; else { commitCommand(); @@ -1724,42 +1960,47 @@ void CmdSketcherConstrainBlock::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainBlock::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainBlock::applyConstraint(std::vector& selSeq, int seqIndex) { switch (seqIndex) { - case 0: // {Edge} + case 0:// {Edge} { // Create the constraints - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); - auto Obj = static_cast(sketchgui->getObject()); + auto Obj = static_cast(sketchgui->getObject()); // check if the edge already has a Block constraint - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + const std::vector& vals = Obj->Constraints.getValues(); - if ( checkConstraint(vals, Sketcher::Block, selSeq.front().GeoId, Sketcher::PointPos::none)) { - Gui::TranslatedUserWarning(Obj, QObject::tr("Double constraint"), QObject::tr("The selected edge already has a Block constraint!")); + if (checkConstraint( + vals, Sketcher::Block, selSeq.front().GeoId, Sketcher::PointPos::none)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Double constraint"), + QObject::tr("The selected edge already has a Block constraint!")); return; } // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add block constraint")); - bool safe = addConstraintSafely(Obj, [&](){ - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Block',%d))", + bool safe = addConstraintSafely(Obj, [&]() { + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Block',%d))", selSeq.front().GeoId); }); - if(!safe) + if (!safe) return; else { commitCommand(); tryAutoRecompute(Obj); } - } - break; - default: - break; + } break; + default: + break; } } @@ -1767,43 +2008,42 @@ void CmdSketcherConstrainBlock::applyConstraint(std::vector &selSeq, // ====================================================================================== /* XPM */ -static const char *cursor_createcoincident[]={ -"32 32 3 1", -"+ c white", -"# c red", -". c None", -"......+.........................", -"......+.........................", -"......+.........................", -"......+.........................", -"......+.........................", -"................................", -"+++++...+++++...................", -"................................", -"......+.........................", -"......+.........................", -"......+.........................", -"......+.........................", -"......+.........................", -"................................", -"................................", -"................................", -".................####...........", -"................######..........", -"...............########.........", -"...............########.........", -"...............########.........", -"...............########.........", -"................######..........", -".................####...........", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................"}; +static const char* cursor_createcoincident[] = {"32 32 3 1", + "+ c white", + "# c red", + ". c None", + "......+.........................", + "......+.........................", + "......+.........................", + "......+.........................", + "......+.........................", + "................................", + "+++++...+++++...................", + "................................", + "......+.........................", + "......+.........................", + "......+.........................", + "......+.........................", + "......+.........................", + "................................", + "................................", + "................................", + ".................####...........", + "................######..........", + "...............########.........", + "...............########.........", + "...............########.........", + "...............########.........", + "................######..........", + ".................####...........", + "................................", + "................................", + "................................", + "................................", + "................................", + "................................", + "................................", + "................................"}; class DrawSketchHandlerCoincident: public DrawSketchHandler { @@ -1818,7 +2058,10 @@ public: Gui::Selection().rmvSelectionGate(); } - void mouseMove(Base::Vector2d onSketchPos) override {Q_UNUSED(onSketchPos);} + void mouseMove(Base::Vector2d onSketchPos) override + { + Q_UNUSED(onSketchPos); + } bool pressButton(Base::Vector2d onSketchPos) override { @@ -1835,10 +2078,10 @@ public: Sketcher::PointPos PosId_temp; if (VtId != -1) { - sketchgui->getSketchObject()->getGeoVertexIndex(VtId,GeoId_temp,PosId_temp); + sketchgui->getSketchObject()->getGeoVertexIndex(VtId, GeoId_temp, PosId_temp); ss << "Vertex" << VtId + 1; } - else if (CrsId == 0){ + else if (CrsId == 0) { GeoId_temp = Sketcher::GeoEnum::RtPnt; PosId_temp = Sketcher::PointPos::start; ss << "RootPoint"; @@ -1867,16 +2110,22 @@ public: PosId2 = PosId_temp; // Apply the constraint - Sketcher::SketchObject* Obj = static_cast(sketchgui->getObject()); + Sketcher::SketchObject* Obj = + static_cast(sketchgui->getObject()); // undo command open Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add coincident constraint")); // check if this coincidence is already enforced (even indirectly) - bool constraintExists = Obj->arePointsCoincident(GeoId1,PosId1,GeoId2,PosId2); + bool constraintExists = Obj->arePointsCoincident(GeoId1, PosId1, GeoId2, PosId2); if (!constraintExists && (GeoId1 != GeoId2)) { - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); Gui::Command::commitCommand(); } else { @@ -1886,12 +2135,14 @@ public: return true; } + private: void activated() override { Gui::Selection().rmvSelectionGate(); - GenericConstraintSelection* selFilterGate = new GenericConstraintSelection(sketchgui->getObject()); - selFilterGate->setAllowedSelTypes(SelVertex|SelRoot); + GenericConstraintSelection* selFilterGate = + new GenericConstraintSelection(sketchgui->getObject()); + selFilterGate->setAllowedSelTypes(SelVertex | SelRoot); Gui::Selection().addSelectionGate(selFilterGate); int hotX = 8; int hotY = 8; @@ -1903,68 +2154,79 @@ protected: Sketcher::PointPos PosId1, PosId2; }; -class CmdSketcherConstrainCoincident : public CmdSketcherConstraint +class CmdSketcherConstrainCoincident: public CmdSketcherConstraint { public: CmdSketcherConstrainCoincident(); - ~CmdSketcherConstrainCoincident() override{} + ~CmdSketcherConstrainCoincident() override + {} const char* className() const override - { return "CmdSketcherConstrainCoincident"; } + { + return "CmdSketcherConstrainCoincident"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; // returns true if a substitution took place - static bool substituteConstraintCombinations(SketchObject * Obj, - int GeoId1, PointPos PosId1, - int GeoId2, PointPos PosId2); + static bool substituteConstraintCombinations(SketchObject* Obj, int GeoId1, PointPos PosId1, + int GeoId2, PointPos PosId2); }; CmdSketcherConstrainCoincident::CmdSketcherConstrainCoincident() - :CmdSketcherConstraint("Sketcher_ConstrainCoincident") + : CmdSketcherConstraint("Sketcher_ConstrainCoincident") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain coincident"); - sToolTipText = QT_TR_NOOP("Create a coincident constraint between points, or a concentric constraint between circles, arcs, and ellipses"); - sWhatsThis = "Sketcher_ConstrainCoincident"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_PointOnPoint"; - sAccel = "C"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain coincident"); + sToolTipText = QT_TR_NOOP("Create a coincident constraint between points, or a concentric " + "constraint between circles, arcs, and ellipses"); + sWhatsThis = "Sketcher_ConstrainCoincident"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_PointOnPoint"; + sAccel = "C"; + eType = ForEdit; - allowedSelSequences = { {SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}, {SelEdge, SelEdge}, {SelEdge, SelExternalEdge}, {SelExternalEdge, SelEdge} }; + allowedSelSequences = {{SelVertex, SelVertexOrRoot}, + {SelRoot, SelVertex}, + {SelEdge, SelEdge}, + {SelEdge, SelExternalEdge}, + {SelExternalEdge, SelEdge}}; } -bool CmdSketcherConstrainCoincident::substituteConstraintCombinations(SketchObject * Obj, - int GeoId1, PointPos PosId1, - int GeoId2, PointPos PosId2) +bool CmdSketcherConstrainCoincident::substituteConstraintCombinations(SketchObject* Obj, int GeoId1, + PointPos PosId1, int GeoId2, + PointPos PosId2) { // checks for direct and indirect coincidence constraints - bool constraintExists = Obj->arePointsCoincident(GeoId1,PosId1,GeoId2,PosId2); + bool constraintExists = Obj->arePointsCoincident(GeoId1, PosId1, GeoId2, PosId2); - const std::vector< Constraint * > &cvals = Obj->Constraints.getValues(); + const std::vector& cvals = Obj->Constraints.getValues(); // NOTE: This function does not either open or commit a command as it is used for group addition // it relies on such infrastructure being provided by the caller. - int j=0; - for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); ++it,++j) { - if ((*it)->Type == Sketcher::Tangent && - (*it)->Third == GeoEnum::GeoUndef && - (((*it)->First == GeoId1 && (*it)->Second == GeoId2) || - ((*it)->Second == GeoId1 && (*it)->First == GeoId2))) { - if ((*it)->FirstPos == Sketcher::PointPos::none && (*it)->SecondPos == Sketcher::PointPos::none) { + int j = 0; + for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); + ++it, ++j) { + if ((*it)->Type == Sketcher::Tangent && (*it)->Third == GeoEnum::GeoUndef + && (((*it)->First == GeoId1 && (*it)->Second == GeoId2) + || ((*it)->Second == GeoId1 && (*it)->First == GeoId2))) { + if ((*it)->FirstPos == Sketcher::PointPos::none + && (*it)->SecondPos == Sketcher::PointPos::none) { - if( constraintExists ) { + if (constraintExists) { // try to remove any pre-existing direct coincident constraints - Gui::cmdAppObjectArgs(Obj, "delConstraintOnPoint(%d,%d)", GeoId1, static_cast(PosId1)); + Gui::cmdAppObjectArgs( + Obj, "delConstraintOnPoint(%d,%d)", GeoId1, static_cast(PosId1)); } Gui::cmdAppObjectArgs(Obj, "delConstraint(%d)", j); doEndpointTangency(Obj, GeoId1, GeoId2, PosId1, PosId2); - notifyConstraintSubstitutions(QObject::tr("Endpoint to endpoint tangency was applied instead.")); + notifyConstraintSubstitutions( + QObject::tr("Endpoint to endpoint tangency was applied instead.")); getSelection().clearSelection(); return true; @@ -1973,8 +2235,8 @@ bool CmdSketcherConstrainCoincident::substituteConstraintCombinations(SketchObje // Replace with knot-to-endpoint tangency if (isBsplineKnot(Obj, GeoId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } // if a similar tangency already exists this must result in bad constraints @@ -1983,7 +2245,8 @@ bool CmdSketcherConstrainCoincident::substituteConstraintCombinations(SketchObje doEndpointTangency(Obj, GeoId1, GeoId2, PosId1, PosId2); - notifyConstraintSubstitutions(QObject::tr("B-spline knot to endpoint tangency was applied instead.")); + notifyConstraintSubstitutions( + QObject::tr("B-spline knot to endpoint tangency was applied instead.")); getSelection().clearSelection(); return true; @@ -2004,15 +2267,17 @@ void CmdSketcherConstrainCoincident::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -2022,19 +2287,21 @@ void CmdSketcherConstrainCoincident::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.size() < 2) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two or more vertices from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select two or more vertices from the sketch.")); return; } - bool allConicsEdges = true; //If user selects only conics (circle, ellipse, arc, arcOfEllipse) then we make concentric constraint. + bool allConicsEdges = true;// If user selects only conics (circle, ellipse, arc, arcOfEllipse) + // then we make concentric constraint. bool atLeastOneEdge = false; - for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoId; Sketcher::PointPos PosId; getIdsFromName(*it, Obj, GeoId, PosId); @@ -2044,12 +2311,16 @@ void CmdSketcherConstrainCoincident::activated(int iMsg) allConicsEdges = false; } else - allConicsEdges = false; //at least one point is selected, so concentric can't be applied. + allConicsEdges = false;// at least one point is selected, so concentric can't be + // applied. if (atLeastOneEdge && !allConicsEdges) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two or more vertices from the sketch for a coincident constraint, or two or more circles, ellipses, arcs or arcs of ellipse for a concentric constraint.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select two or more vertices from the sketch for a coincident " + "constraint, or two or more circles, ellipses, arcs or arcs of ellipse " + "for a concentric constraint.")); return; } } @@ -2063,13 +2334,13 @@ void CmdSketcherConstrainCoincident::activated(int iMsg) // undo command open bool constraintsAdded = false; openCommand(QT_TRANSLATE_NOOP("Command", "Add coincident constraint")); - for (std::size_t i=1; iarePointsCoincident(GeoId1,PosId1,GeoId2,PosId2); + bool constraintExists = Obj->arePointsCoincident(GeoId1, PosId1, GeoId2, PosId2); if (!constraintExists) { constraintsAdded = true; - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); } } @@ -2105,32 +2380,37 @@ void CmdSketcherConstrainCoincident::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainCoincident::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainCoincident::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = selSeq.at(0).GeoId, GeoId2 = selSeq.at(1).GeoId; Sketcher::PointPos PosId1 = selSeq.at(0).PosId, PosId2 = selSeq.at(1).PosId; switch (seqIndex) { - case 0: // {SelVertex, SelVertexOrRoot} - case 1: // {SelRoot, SelVertex} - //Nothing specific. - break; - case 2: // {SelEdge, SelEdge} - case 3: // {SelEdge, SelExternalEdge} - case 4: // {SelExternalEdge, SelEdge} - //Concentric for circles, ellipse, arc, arcofEllipse only. - if (!isGeoConcentricCompatible(Obj->getGeometry(GeoId1)) || !isGeoConcentricCompatible(Obj->getGeometry(GeoId2))) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two vertices from the sketch for a coincident constraint, or two circles, ellipses, arcs or arcs of ellipse for a concentric constraint.")); - return; - } - PosId1 = Sketcher::PointPos::mid; - PosId2 = Sketcher::PointPos::mid; - break; + case 0:// {SelVertex, SelVertexOrRoot} + case 1:// {SelRoot, SelVertex} + // Nothing specific. + break; + case 2:// {SelEdge, SelEdge} + case 3:// {SelEdge, SelExternalEdge} + case 4:// {SelExternalEdge, SelEdge} + // Concentric for circles, ellipse, arc, arcofEllipse only. + if (!isGeoConcentricCompatible(Obj->getGeometry(GeoId1)) + || !isGeoConcentricCompatible(Obj->getGeometry(GeoId2))) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "Select two vertices from the sketch for a coincident constraint, or two " + "circles, ellipses, arcs or arcs of ellipse for a concentric constraint.")); + return; + } + PosId1 = Sketcher::PointPos::mid; + PosId2 = Sketcher::PointPos::mid; + break; } // check if the edge already has a Block constraint @@ -2144,11 +2424,14 @@ void CmdSketcherConstrainCoincident::applyConstraint(std::vector &sel // check if this coincidence is already enforced (even indirectly) bool constraintExists = Obj->arePointsCoincident(GeoId1, PosId1, GeoId2, PosId2); - if (substituteConstraintCombinations(Obj, GeoId1, PosId1, GeoId2, PosId2)) { - } + if (substituteConstraintCombinations(Obj, GeoId1, PosId1, GeoId2, PosId2)) {} else if (!constraintExists && (GeoId1 != GeoId2)) { - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Coincident', %d, %d, %d, %d))", - GeoId1, static_cast(PosId1), GeoId2, static_cast(PosId2)); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Coincident', %d, %d, %d, %d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); } else { Gui::Command::abortCommand(); @@ -2160,36 +2443,45 @@ void CmdSketcherConstrainCoincident::applyConstraint(std::vector &sel // ====================================================================================== -class CmdSketcherConstrainDistance : public CmdSketcherConstraint +class CmdSketcherConstrainDistance: public CmdSketcherConstraint { public: CmdSketcherConstrainDistance(); - ~CmdSketcherConstrainDistance() override{} + ~CmdSketcherConstrainDistance() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainDistance"; } + { + return "CmdSketcherConstrainDistance"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainDistance::CmdSketcherConstrainDistance() - :CmdSketcherConstraint("Sketcher_ConstrainDistance") + : CmdSketcherConstraint("Sketcher_ConstrainDistance") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain distance"); - sToolTipText = QT_TR_NOOP("Fix a length of a line or the distance between a line and a vertex or between two circles"); - sWhatsThis = "Sketcher_ConstrainDistance"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Length"; - sAccel = "K, D"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain distance"); + sToolTipText = QT_TR_NOOP("Fix a length of a line or the distance between a line and a vertex " + "or between two circles"); + sWhatsThis = "Sketcher_ConstrainDistance"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Length"; + sAccel = "K, D"; + eType = ForEdit; - allowedSelSequences = {{SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}, - {SelEdge}, {SelExternalEdge}, - {SelVertex, SelEdgeOrAxis}, {SelRoot, SelEdge}, - {SelVertex, SelExternalEdge}, {SelRoot, SelExternalEdge}, + allowedSelSequences = {{SelVertex, SelVertexOrRoot}, + {SelRoot, SelVertex}, + {SelEdge}, + {SelExternalEdge}, + {SelVertex, SelEdgeOrAxis}, + {SelRoot, SelEdge}, + {SelVertex, SelExternalEdge}, + {SelRoot, SelExternalEdge}, {SelEdge, SelEdge}}; } @@ -2200,13 +2492,14 @@ void CmdSketcherConstrainDistance::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); } @@ -2219,112 +2512,134 @@ void CmdSketcherConstrainDistance::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.empty() || SubNames.size() > 2) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or one point and one line or two points from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or one point and one line " + "or two points from the sketch.")); return; } - int GeoId1, GeoId2=GeoEnum::GeoUndef; - Sketcher::PointPos PosId1, PosId2=Sketcher::PointPos::none; + int GeoId1, GeoId2 = GeoEnum::GeoUndef; + Sketcher::PointPos PosId1, PosId2 = Sketcher::PointPos::none; getIdsFromName(SubNames[0], Obj, GeoId1, PosId1); if (SubNames.size() == 2) getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); - bool arebothpointsorsegmentsfixed=areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2); + bool arebothpointsorsegmentsfixed = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); - if (isVertex(GeoId1,PosId1) && (GeoId2 == Sketcher::GeoEnum::VAxis || GeoId2 == Sketcher::GeoEnum::HAxis)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + if (isVertex(GeoId1, PosId1) + && (GeoId2 == Sketcher::GeoEnum::VAxis || GeoId2 == Sketcher::GeoEnum::HAxis)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - if ((isVertex(GeoId1,PosId1) || GeoId1 == Sketcher::GeoEnum::VAxis || GeoId1 == Sketcher::GeoEnum::HAxis) && - isVertex(GeoId2,PosId2)) { // point to point distance + if ((isVertex(GeoId1, PosId1) || GeoId1 == Sketcher::GeoEnum::VAxis + || GeoId1 == Sketcher::GeoEnum::HAxis) + && isVertex(GeoId2, PosId2)) {// point to point distance - Base::Vector3d pnt2 = Obj->getPoint(GeoId2,PosId2); + Base::Vector3d pnt2 = Obj->getPoint(GeoId2, PosId2); if (GeoId1 == Sketcher::GeoEnum::HAxis && PosId1 == Sketcher::PointPos::none) { PosId1 = Sketcher::PointPos::start; - openCommand(QT_TRANSLATE_NOOP("Command", "Add distance from horizontal axis constraint")); + openCommand( + QT_TRANSLATE_NOOP("Command", "Add distance from horizontal axis constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),pnt2.y); + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + pnt2.y); } else if (GeoId1 == Sketcher::GeoEnum::VAxis && PosId1 == Sketcher::PointPos::none) { PosId1 = Sketcher::PointPos::start; openCommand(QT_TRANSLATE_NOOP("Command", "Add distance from vertical axis constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),pnt2.x); + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + pnt2.x); } else { - Base::Vector3d pnt1 = Obj->getPoint(GeoId1,PosId1); + Base::Vector3d pnt1 = Obj->getPoint(GeoId1, PosId1); openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point distance constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),(pnt2-pnt1).Length()); + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + (pnt2 - pnt1).Length()); } - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { + if (arebothpointsorsegmentsfixed || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), - "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } - else if ((isVertex(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) || - (isEdge(GeoId1,PosId1) && isVertex(GeoId2,PosId2))) { // point to line distance - if (isVertex(GeoId2,PosId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + else if ((isVertex(GeoId1, PosId1) && isEdge(GeoId2, PosId2)) + || (isEdge(GeoId1, PosId1) && isVertex(GeoId2, PosId2))) {// point to line distance + if (isVertex(GeoId2, PosId2)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - Base::Vector3d pnt = Obj->getPoint(GeoId1,PosId1); - const Part::Geometry *geom = Obj->getGeometry(GeoId2); + Base::Vector3d pnt = Obj->getPoint(GeoId1, PosId1); + const Part::Geometry* geom = Obj->getGeometry(GeoId2); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg; + const Part::GeomLineSegment* lineSeg; lineSeg = static_cast(geom); Base::Vector3d pnt1 = lineSeg->getStartPoint(); Base::Vector3d pnt2 = lineSeg->getEndPoint(); - Base::Vector3d d = pnt2-pnt1; - double ActDist = std::abs(-pnt.x*d.y+pnt.y*d.x+pnt1.x*pnt2.y-pnt2.x*pnt1.y) / d.Length(); + Base::Vector3d d = pnt2 - pnt1; + double ActDist = + std::abs(-pnt.x * d.y + pnt.y * d.x + pnt1.x * pnt2.y - pnt2.x * pnt1.y) + / d.Length(); openCommand(QT_TRANSLATE_NOOP("Command", "Add point to line Distance constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,ActDist); + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + ActDist); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (arebothpointsorsegmentsfixed + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), - "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } } - else if (isEdge(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) { - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); + else if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2)) { + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); if (geom1->getTypeId() == Part::GeomCircle::getClassTypeId() - && geom2->getTypeId() == Part::GeomCircle::getClassTypeId() ) { // circle to circle distance + && geom2->getTypeId() + == Part::GeomCircle::getClassTypeId()) {// circle to circle distance auto circleSeg1 = static_cast(geom1); double radius1 = circleSeg1->getRadius(); Base::Vector3d center1 = circleSeg1->getCenter(); @@ -2338,42 +2653,46 @@ void CmdSketcherConstrainDistance::activated(int iMsg) Base::Vector3d intercenter = center1 - center2; double intercenterdistance = intercenter.Length(); - if( intercenterdistance >= radius1 && - intercenterdistance >= radius2 ) { + if (intercenterdistance >= radius1 && intercenterdistance >= radius2) { ActDist = intercenterdistance - radius1 - radius2; } else { - double bigradius = std::max(radius1,radius2); - double smallradius = std::min(radius1,radius2); + double bigradius = std::max(radius1, radius2); + double smallradius = std::min(radius1, radius2); ActDist = bigradius - smallradius - intercenterdistance; } openCommand(QT_TRANSLATE_NOOP("Command", "Add circle to circle distance constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%f))", - GeoId1,GeoId2,ActDist); + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%f))", + GeoId1, + GeoId2, + ActDist); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (arebothpointsorsegmentsfixed + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), - "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; - } else if ((geom1->getTypeId() == Part::GeomCircle::getClassTypeId() - && geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) - || (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() - && geom2->getTypeId() == Part::GeomCircle::getClassTypeId()) ) { // circle to line distance + } + else if ((geom1->getTypeId() == Part::GeomCircle::getClassTypeId() + && geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) + || (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geom2->getTypeId() + == Part::GeomCircle::getClassTypeId())) {// circle to line distance - if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId()){ - std::swap(geom1, geom2); //Assume circle is first + if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + std::swap(geom1, geom2);// Assume circle is first std::swap(GeoId1, GeoId2); } @@ -2381,337 +2700,391 @@ void CmdSketcherConstrainDistance::activated(int iMsg) double radius = circleSeg->getRadius(); Base::Vector3d center = circleSeg->getCenter(); - auto lineSeg= static_cast(geom2); + auto lineSeg = static_cast(geom2); Base::Vector3d pnt1 = lineSeg->getStartPoint(); Base::Vector3d pnt2 = lineSeg->getEndPoint(); Base::Vector3d d = pnt2 - pnt1; - double ActDist = std::abs(-center.x*d.y+center.y*d.x+pnt1.x*pnt2.y-pnt2.x*pnt1.y) / d.Length() - radius; + double ActDist = + std::abs(-center.x * d.y + center.y * d.x + pnt1.x * pnt2.y - pnt2.x * pnt1.y) + / d.Length() + - radius; openCommand(QT_TRANSLATE_NOOP("Command", "Add circle to line distance constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%f)) ", - GeoId1,GeoId2,ActDist); + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%f)) ", + GeoId1, + GeoId2, + ActDist); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (arebothpointsorsegmentsfixed + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), - "setDriving(%i,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%i,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } } - else if (isEdge(GeoId1,PosId1)) { // line length + else if (isEdge(GeoId1, PosId1)) {// line length if (GeoId1 < 0 && GeoId1 >= Sketcher::GeoEnum::VAxis) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a length constraint on an axis!")); + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a length constraint on an axis!")); return; } - arebothpointsorsegmentsfixed=isPointOrSegmentFixed(Obj,GeoId1); + arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj, GeoId1); - const Part::Geometry *geom = Obj->getGeometry(GeoId1); + const Part::Geometry* geom = Obj->getGeometry(GeoId1); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg; + const Part::GeomLineSegment* lineSeg; lineSeg = static_cast(geom); - double ActLength = (lineSeg->getEndPoint()-lineSeg->getStartPoint()).Length(); + double ActLength = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Length(); openCommand(QT_TRANSLATE_NOOP("Command", "Add length constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Distance',%d,%f))", - GeoId1,ActLength); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Distance',%d,%f))", + GeoId1, + ActLength); // it is a constraint on a external line, make it non-driving - if (arebothpointsorsegmentsfixed || GeoId1 <= Sketcher::GeoEnum::RefExt || - constraintCreationMode==Reference) { - const std::vector &ConStr = Obj->Constraints.getValues(); + if (arebothpointsorsegmentsfixed || GeoId1 <= Sketcher::GeoEnum::RefExt + || constraintCreationMode == Reference) { + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } } Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or one point and one line or two points or two circles from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or one point and one line or " + "two points or two circles from the sketch.")); return; } -void CmdSketcherConstrainDistance::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainDistance::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef; Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none; - bool arebothpointsorsegmentsfixed=areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2); + bool arebothpointsorsegmentsfixed = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); switch (seqIndex) { - case 0: // {SelVertex, SelVertexOrRoot} - case 1: // {SelRoot, SelVertex} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; + case 0:// {SelVertex, SelVertexOrRoot} + case 1:// {SelRoot, SelVertex} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; - Base::Vector3d pnt2 = Obj->getPoint(GeoId2,PosId2); + Base::Vector3d pnt2 = Obj->getPoint(GeoId2, PosId2); - if (GeoId1 == Sketcher::GeoEnum::HAxis && PosId1 == Sketcher::PointPos::none) { - PosId1 = Sketcher::PointPos::start; + if (GeoId1 == Sketcher::GeoEnum::HAxis && PosId1 == Sketcher::PointPos::none) { + PosId1 = Sketcher::PointPos::start; - openCommand(QT_TRANSLATE_NOOP("Command", "Add distance from horizontal axis constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),pnt2.y); - } - else if (GeoId1 == Sketcher::GeoEnum::VAxis && PosId1 == Sketcher::PointPos::none) { - PosId1 = Sketcher::PointPos::start; - - openCommand(QT_TRANSLATE_NOOP("Command", "Add distance from vertical axis constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),pnt2.x); - } - else { - Base::Vector3d pnt1 = Obj->getPoint(GeoId1,PosId1); - - openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point distance constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),(pnt2-pnt1).Length()); - } - - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { - // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); - } - else - finishDatumConstraint (this, Obj, true); - - return; - } - case 2: // {SelEdge} - case 3: // {SelExternalEdge} - { - GeoId1 = GeoId2 = selSeq.at(0).GeoId; - PosId1 = Sketcher::PointPos::start; PosId2 = Sketcher::PointPos::end; - - arebothpointsorsegmentsfixed=isPointOrSegmentFixed(Obj,GeoId1); - - const Part::Geometry *geom = Obj->getGeometry(GeoId1); - if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg; - lineSeg = static_cast(geom); - double ActLength = (lineSeg->getEndPoint()-lineSeg->getStartPoint()).Length(); - - openCommand(QT_TRANSLATE_NOOP("Command", "Add length constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('Distance',%d,%f))", - GeoId1,ActLength); - - if (arebothpointsorsegmentsfixed - || GeoId1 <= Sketcher::GeoEnum::RefExt - || constraintCreationMode==Reference) { - // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + openCommand( + QT_TRANSLATE_NOOP("Command", "Add distance from horizontal axis constraint")); + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + pnt2.y); } - else - finishDatumConstraint (this, Obj, true); - } - else if (geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - // allow this selection but do nothing as it needs 2 circles or 1 circle and 1 line - } - else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("This constraint does not make sense for non-linear curves.")); - } + else if (GeoId1 == Sketcher::GeoEnum::VAxis && PosId1 == Sketcher::PointPos::none) { + PosId1 = Sketcher::PointPos::start; - return; - } - case 4: // {SelVertex, SelEdgeOrAxis} - case 5: // {SelRoot, SelEdge} - case 6: // {SelVertex, SelExternalEdge} - case 7: // {SelRoot, SelExternalEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; - - Base::Vector3d pnt = Obj->getPoint(GeoId1,PosId1); - const Part::Geometry *geom = Obj->getGeometry(GeoId2); - if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg; - lineSeg = static_cast(geom); - Base::Vector3d pnt1 = lineSeg->getStartPoint(); - Base::Vector3d pnt2 = lineSeg->getEndPoint(); - Base::Vector3d d = pnt2-pnt1; - double ActDist = std::abs(-pnt.x*d.y+pnt.y*d.x+pnt1.x*pnt2.y-pnt2.x*pnt1.y) / d.Length(); - - openCommand(QT_TRANSLATE_NOOP("Command", "Add point to line Distance constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,ActDist); - - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { - // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); - } - else - finishDatumConstraint (this, Obj, true); - } - - return; - } - case 8: // {SelEdge, SelEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - if (geom1->getTypeId() == Part::GeomCircle::getClassTypeId() - && geom2->getTypeId() == Part::GeomCircle::getClassTypeId() ) { // circle to circle distance - auto circleSeg1 = static_cast(geom1); - double radius1 = circleSeg1->getRadius(); - Base::Vector3d center1 = circleSeg1->getCenter(); - - auto circleSeg2 = static_cast(geom2); - double radius2 = circleSeg2->getRadius(); - Base::Vector3d center2 = circleSeg2->getCenter(); - - double ActDist = 0.; - - Base::Vector3d intercenter = center1 - center2; - double intercenterdistance = intercenter.Length(); - - if( intercenterdistance >= radius1 && - intercenterdistance >= radius2 ) { - - ActDist = intercenterdistance - radius1 - radius2; + openCommand( + QT_TRANSLATE_NOOP("Command", "Add distance from vertical axis constraint")); + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + pnt2.x); } else { - double bigradius = std::max(radius1,radius2); - double smallradius = std::min(radius1,radius2); + Base::Vector3d pnt1 = Obj->getPoint(GeoId1, PosId1); - ActDist = bigradius - smallradius - intercenterdistance; + openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point distance constraint")); + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + (pnt2 - pnt1).Length()); } - openCommand(QT_TRANSLATE_NOOP("Command", "Add circle to circle distance constraint")); - Gui::cmdAppObjectArgs(Obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%f))", - GeoId1,GeoId2,ActDist); + if (arebothpointsorsegmentsfixed || constraintCreationMode == Reference) { + // it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; - } else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or one point and one line or two points or two circles from the sketch.")); - } - } - default: - break; + case 2:// {SelEdge} + case 3:// {SelExternalEdge} + { + GeoId1 = GeoId2 = selSeq.at(0).GeoId; + PosId1 = Sketcher::PointPos::start; + PosId2 = Sketcher::PointPos::end; + + arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj, GeoId1); + + const Part::Geometry* geom = Obj->getGeometry(GeoId1); + if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg; + lineSeg = static_cast(geom); + double ActLength = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Length(); + + openCommand(QT_TRANSLATE_NOOP("Command", "Add length constraint")); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Distance',%d,%f))", GeoId1, ActLength); + + if (arebothpointsorsegmentsfixed || GeoId1 <= Sketcher::GeoEnum::RefExt + || constraintCreationMode == Reference) { + // it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); + + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); + } + else + finishDatumConstraint(this, Obj, true); + } + else if (geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { + // allow this selection but do nothing as it needs 2 circles or 1 circle and 1 line + } + else { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("This constraint does not make sense for non-linear curves.")); + } + + return; + } + case 4:// {SelVertex, SelEdgeOrAxis} + case 5:// {SelRoot, SelEdge} + case 6:// {SelVertex, SelExternalEdge} + case 7:// {SelRoot, SelExternalEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; + + Base::Vector3d pnt = Obj->getPoint(GeoId1, PosId1); + const Part::Geometry* geom = Obj->getGeometry(GeoId2); + if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg; + lineSeg = static_cast(geom); + Base::Vector3d pnt1 = lineSeg->getStartPoint(); + Base::Vector3d pnt2 = lineSeg->getEndPoint(); + Base::Vector3d d = pnt2 - pnt1; + double ActDist = + std::abs(-pnt.x * d.y + pnt.y * d.x + pnt1.x * pnt2.y - pnt2.x * pnt1.y) + / d.Length(); + + openCommand(QT_TRANSLATE_NOOP("Command", "Add point to line Distance constraint")); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + ActDist); + + if (arebothpointsorsegmentsfixed || constraintCreationMode == Reference) { + // it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); + + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); + } + else + finishDatumConstraint(this, Obj, true); + } + + return; + } + case 8:// {SelEdge, SelEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); + if (geom1->getTypeId() == Part::GeomCircle::getClassTypeId() + && geom2->getTypeId() + == Part::GeomCircle::getClassTypeId()) {// circle to circle distance + auto circleSeg1 = static_cast(geom1); + double radius1 = circleSeg1->getRadius(); + Base::Vector3d center1 = circleSeg1->getCenter(); + + auto circleSeg2 = static_cast(geom2); + double radius2 = circleSeg2->getRadius(); + Base::Vector3d center2 = circleSeg2->getCenter(); + + double ActDist = 0.; + + Base::Vector3d intercenter = center1 - center2; + double intercenterdistance = intercenter.Length(); + + if (intercenterdistance >= radius1 && intercenterdistance >= radius2) { + + ActDist = intercenterdistance - radius1 - radius2; + } + else { + double bigradius = std::max(radius1, radius2); + double smallradius = std::min(radius1, radius2); + + ActDist = bigradius - smallradius - intercenterdistance; + } + + openCommand( + QT_TRANSLATE_NOOP("Command", "Add circle to circle distance constraint")); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%f))", + GeoId1, + GeoId2, + ActDist); + + if (arebothpointsorsegmentsfixed + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); + + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); + } + else + finishDatumConstraint(this, Obj, true); + + return; + } + else { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or one point and one line or two points " + "or two circles from the sketch.")); + } + } + default: + break; } } void CmdSketcherConstrainDistance::updateAction(int mode) { switch (mode) { - case Reference: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Length_Driven")); - break; - case Driving: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Length")); - break; + case Reference: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_Length_Driven")); + break; + case Driving: + if (getAction()) + getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Length")); + break; } } // ====================================================================================== -class CmdSketcherConstrainPointOnObject : public CmdSketcherConstraint +class CmdSketcherConstrainPointOnObject: public CmdSketcherConstraint { public: CmdSketcherConstrainPointOnObject(); - ~CmdSketcherConstrainPointOnObject() override{} + ~CmdSketcherConstrainPointOnObject() override + {} const char* className() const override - { return "CmdSketcherConstrainPointOnObject"; } + { + return "CmdSketcherConstrainPointOnObject"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; // returns true if a substitution took place - static bool substituteConstraintCombinations(SketchObject * Obj, - int GeoId1, PointPos PosId1, int GeoId2); + static bool substituteConstraintCombinations(SketchObject* Obj, int GeoId1, PointPos PosId1, + int GeoId2); }; CmdSketcherConstrainPointOnObject::CmdSketcherConstrainPointOnObject() - :CmdSketcherConstraint("Sketcher_ConstrainPointOnObject") + : CmdSketcherConstraint("Sketcher_ConstrainPointOnObject") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain point onto object"); - sToolTipText = QT_TR_NOOP("Fix a point onto an object"); - sWhatsThis = "Sketcher_ConstrainPointOnObject"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_PointOnObject"; - sAccel = "O"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain point onto object"); + sToolTipText = QT_TR_NOOP("Fix a point onto an object"); + sWhatsThis = "Sketcher_ConstrainPointOnObject"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_PointOnObject"; + sAccel = "O"; + eType = ForEdit; - allowedSelSequences = {{SelVertex, SelEdgeOrAxis}, {SelRoot, SelEdge}, + allowedSelSequences = {{SelVertex, SelEdgeOrAxis}, + {SelRoot, SelEdge}, {SelVertex, SelExternalEdge}, - {SelEdge, SelVertexOrRoot}, {SelEdgeOrAxis, SelVertex}, + {SelEdge, SelVertexOrRoot}, + {SelEdgeOrAxis, SelVertex}, {SelExternalEdge, SelVertex}}; - } -bool CmdSketcherConstrainPointOnObject::substituteConstraintCombinations( SketchObject * Obj, - int GeoId1, PointPos PosId1, int GeoId2) +bool CmdSketcherConstrainPointOnObject::substituteConstraintCombinations(SketchObject* Obj, + int GeoId1, + PointPos PosId1, + int GeoId2) { - const std::vector< Constraint * > &cvals = Obj->Constraints.getValues(); + const std::vector& cvals = Obj->Constraints.getValues(); int cid = 0; - for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); ++it, ++cid) { - if( (*it)->Type == Sketcher::Tangent && - (*it)->FirstPos == Sketcher::PointPos::none && (*it)->SecondPos == Sketcher::PointPos::none && - (*it)->Third == GeoEnum::GeoUndef && - (((*it)->First == GeoId1 && (*it)->Second == GeoId2) || - ((*it)->Second == GeoId1 && (*it)->First == GeoId2)) ) { + for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); + ++it, ++cid) { + if ((*it)->Type == Sketcher::Tangent && (*it)->FirstPos == Sketcher::PointPos::none + && (*it)->SecondPos == Sketcher::PointPos::none && (*it)->Third == GeoEnum::GeoUndef + && (((*it)->First == GeoId1 && (*it)->Second == GeoId2) + || ((*it)->Second == GeoId1 && (*it)->First == GeoId2))) { - // NOTE: This function does not either open or commit a command as it is used for group addition - // it relies on such infrastructure being provided by the caller. + // NOTE: This function does not either open or commit a command as it is used for group + // addition it relies on such infrastructure being provided by the caller. Gui::cmdAppObjectArgs(Obj, "delConstraint(%d)", cid); doEndpointToEdgeTangency(Obj, GeoId1, PosId1, GeoId2); - notifyConstraintSubstitutions(QObject::tr("Endpoint to edge tangency was applied instead.")); + notifyConstraintSubstitutions( + QObject::tr("Endpoint to edge tangency was applied instead.")); getSelection().clearSelection(); return true; @@ -2728,214 +3101,14 @@ void CmdSketcherConstrainPointOnObject::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); - getSelection().clearSelection(); - } else { - // TODO: Get the exact message from git history and put it here - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select the right things from the sketch.")); - } - return; - } - - // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); - Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - - //count curves and points - std::vector points; - std::vector curves; - for (std::size_t i = 0 ; i < SubNames.size() ; i++){ - SelIdPair id; - getIdsFromName(SubNames[i], Obj, id.GeoId, id.PosId); - if (isEdge(id.GeoId, id.PosId)) - curves.push_back(id); - if (isVertex(id.GeoId, id.PosId)) - points.push_back(id); - } - - if ((points.size() == 1 && !curves.empty()) || - (!points.empty() && curves.size() == 1)) { - - openCommand(QT_TRANSLATE_NOOP("Command", "Add point on object constraint")); - int cnt = 0; - for (std::size_t iPnt = 0; iPnt < points.size(); iPnt++) { - for (std::size_t iCrv = 0; iCrv < curves.size(); iCrv++) { - if (areBothPointsOrSegmentsFixed(Obj, points[iPnt].GeoId, curves[iCrv].GeoId)){ - showNoConstraintBetweenFixedGeometry(Obj); - continue; - } - if (points[iPnt].GeoId == curves[iCrv].GeoId) - continue; //constraining a point of an element onto the element is a bad idea... - - const Part::Geometry *geom = Obj->getGeometry(curves[iCrv].GeoId); - - if( geom && isBsplinePole(geom)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); - abortCommand(); - - continue; - } - - if(substituteConstraintCombinations(Obj, points[iPnt].GeoId, points[iPnt].PosId, curves[iCrv].GeoId)) { - cnt++; - continue; - } - - cnt++; - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - points[iPnt].GeoId, static_cast(points[iPnt].PosId), curves[iCrv].GeoId); - } - } - if (cnt) { - commitCommand(); - getSelection().clearSelection(); - } else { - abortCommand(); - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("None of the selected points were constrained " - "onto the respective curves, " - "because they are parts " - "of the same element, " - "because they are both external geometry, " - "or because the edge is not eligible.")); - } - return; - } - - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select either one point and several curves, " - "or one curve and several points.")); - return; -} - -void CmdSketcherConstrainPointOnObject::applyConstraint(std::vector &selSeq, int seqIndex) -{ - int GeoIdVt, GeoIdCrv; - Sketcher::PointPos PosIdVt; - - switch (seqIndex) { - case 0: // {SelVertex, SelEdgeOrAxis} - case 1: // {SelRoot, SelEdge} - case 2: // {SelVertex, SelExternalEdge} - GeoIdVt = selSeq.at(0).GeoId; GeoIdCrv = selSeq.at(1).GeoId; - PosIdVt = selSeq.at(0).PosId; - - break; - case 3: // {SelEdge, SelVertexOrRoot} - case 4: // {SelEdgeOrAxis, SelVertex} - case 5: // {SelExternalEdge, SelVertex} - GeoIdVt = selSeq.at(1).GeoId; GeoIdCrv = selSeq.at(0).GeoId; - PosIdVt = selSeq.at(1).PosId; - - break; - default: - return; - } - - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); - Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); - - openCommand(QT_TRANSLATE_NOOP("Command", "Add point on object constraint")); - bool allOK = true; - - if (areBothPointsOrSegmentsFixed(Obj, GeoIdVt, GeoIdCrv)){ - showNoConstraintBetweenFixedGeometry(Obj); - allOK = false; - } - if (GeoIdVt == GeoIdCrv) - allOK = false; //constraining a point of an element onto the element is a bad idea... - - const Part::Geometry *geom = Obj->getGeometry(GeoIdCrv); - - if( geom && isBsplinePole(geom)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); - abortCommand(); - - return; - } - - if (allOK) { - if (!substituteConstraintCombinations(Obj, GeoIdVt, PosIdVt, GeoIdCrv)) - Gui::cmdAppObjectArgs( sketchgui->getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdVt, static_cast(PosIdVt), GeoIdCrv); - - commitCommand(); - tryAutoRecompute(Obj); - } - else { - abortCommand(); - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("None of the selected points " - "were constrained onto the respective curves, " - "either because they are parts of the same element, " - "or because they are both external geometry.")); - } - return; -} - -// ====================================================================================== - -class CmdSketcherConstrainDistanceX : public CmdSketcherConstraint -{ -public: - CmdSketcherConstrainDistanceX(); - ~CmdSketcherConstrainDistanceX() override{} - void updateAction(int mode) override; - const char* className() const override - { return "CmdSketcherConstrainDistanceX"; } -protected: - void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; -}; - -CmdSketcherConstrainDistanceX::CmdSketcherConstrainDistanceX() - :CmdSketcherConstraint("Sketcher_ConstrainDistanceX") -{ - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain horizontal distance"); - sToolTipText = QT_TR_NOOP("Fix the horizontal distance " - "between two points or line ends"); - sWhatsThis = "Sketcher_ConstrainDistanceX"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_HorizontalDistance"; - sAccel = "L"; - eType = ForEdit; - - // Can't do single vertex because its a prefix for 2 vertices - allowedSelSequences = {{SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}, - {SelEdge}, {SelExternalEdge}}; -} - -void CmdSketcherConstrainDistanceX::activated(int iMsg) -{ - Q_UNUSED(iMsg); - // get the selection - std::vector selection = getSelection().getSelectionEx(); - - // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); - - if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); } else { @@ -2948,27 +3121,248 @@ void CmdSketcherConstrainDistanceX::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - if (SubNames.empty() || SubNames.size() > 2) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or up to two points from the sketch.")); + // count curves and points + std::vector points; + std::vector curves; + for (std::size_t i = 0; i < SubNames.size(); i++) { + SelIdPair id; + getIdsFromName(SubNames[i], Obj, id.GeoId, id.PosId); + if (isEdge(id.GeoId, id.PosId)) + curves.push_back(id); + if (isVertex(id.GeoId, id.PosId)) + points.push_back(id); + } + + if ((points.size() == 1 && !curves.empty()) || (!points.empty() && curves.size() == 1)) { + + openCommand(QT_TRANSLATE_NOOP("Command", "Add point on object constraint")); + int cnt = 0; + for (std::size_t iPnt = 0; iPnt < points.size(); iPnt++) { + for (std::size_t iCrv = 0; iCrv < curves.size(); iCrv++) { + if (areBothPointsOrSegmentsFixed(Obj, points[iPnt].GeoId, curves[iCrv].GeoId)) { + showNoConstraintBetweenFixedGeometry(Obj); + continue; + } + if (points[iPnt].GeoId == curves[iCrv].GeoId) + continue;// constraining a point of an element onto the element is a bad idea... + + const Part::Geometry* geom = Obj->getGeometry(curves[iCrv].GeoId); + + if (geom && isBsplinePole(geom)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); + abortCommand(); + + continue; + } + + if (substituteConstraintCombinations( + Obj, points[iPnt].GeoId, points[iPnt].PosId, curves[iCrv].GeoId)) { + cnt++; + continue; + } + + cnt++; + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + points[iPnt].GeoId, + static_cast(points[iPnt].PosId), + curves[iCrv].GeoId); + } + } + if (cnt) { + commitCommand(); + getSelection().clearSelection(); + } + else { + abortCommand(); + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("None of the selected points were constrained " + "onto the respective curves, " + "because they are parts " + "of the same element, " + "because they are both external geometry, " + "or because the edge is not eligible.")); + } return; } - int GeoId1, GeoId2=GeoEnum::GeoUndef; - Sketcher::PointPos PosId1, PosId2=Sketcher::PointPos::none; + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select either one point and several curves, " + "or one curve and several points.")); + return; +} + +void CmdSketcherConstrainPointOnObject::applyConstraint(std::vector& selSeq, + int seqIndex) +{ + int GeoIdVt, GeoIdCrv; + Sketcher::PointPos PosIdVt; + + switch (seqIndex) { + case 0:// {SelVertex, SelEdgeOrAxis} + case 1:// {SelRoot, SelEdge} + case 2:// {SelVertex, SelExternalEdge} + GeoIdVt = selSeq.at(0).GeoId; + GeoIdCrv = selSeq.at(1).GeoId; + PosIdVt = selSeq.at(0).PosId; + + break; + case 3:// {SelEdge, SelVertexOrRoot} + case 4:// {SelEdgeOrAxis, SelVertex} + case 5:// {SelExternalEdge, SelVertex} + GeoIdVt = selSeq.at(1).GeoId; + GeoIdCrv = selSeq.at(0).GeoId; + PosIdVt = selSeq.at(1).PosId; + + break; + default: + return; + } + + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); + Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); + + openCommand(QT_TRANSLATE_NOOP("Command", "Add point on object constraint")); + bool allOK = true; + + if (areBothPointsOrSegmentsFixed(Obj, GeoIdVt, GeoIdCrv)) { + showNoConstraintBetweenFixedGeometry(Obj); + allOK = false; + } + if (GeoIdVt == GeoIdCrv) + allOK = false;// constraining a point of an element onto the element is a bad idea... + + const Part::Geometry* geom = Obj->getGeometry(GeoIdCrv); + + if (geom && isBsplinePole(geom)) { + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); + abortCommand(); + + return; + } + + if (allOK) { + if (!substituteConstraintCombinations(Obj, GeoIdVt, PosIdVt, GeoIdCrv)) + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdVt, + static_cast(PosIdVt), + GeoIdCrv); + + commitCommand(); + tryAutoRecompute(Obj); + } + else { + abortCommand(); + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("None of the selected points " + "were constrained onto the respective curves, " + "either because they are parts of the same element, " + "or because they are both external geometry.")); + } + return; +} + +// ====================================================================================== + +class CmdSketcherConstrainDistanceX: public CmdSketcherConstraint +{ +public: + CmdSketcherConstrainDistanceX(); + ~CmdSketcherConstrainDistanceX() override + {} + void updateAction(int mode) override; + const char* className() const override + { + return "CmdSketcherConstrainDistanceX"; + } + +protected: + void activated(int iMsg) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; +}; + +CmdSketcherConstrainDistanceX::CmdSketcherConstrainDistanceX() + : CmdSketcherConstraint("Sketcher_ConstrainDistanceX") +{ + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain horizontal distance"); + sToolTipText = QT_TR_NOOP("Fix the horizontal distance " + "between two points or line ends"); + sWhatsThis = "Sketcher_ConstrainDistanceX"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_HorizontalDistance"; + sAccel = "L"; + eType = ForEdit; + + // Can't do single vertex because its a prefix for 2 vertices + allowedSelSequences = { + {SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}, {SelEdge}, {SelExternalEdge}}; +} + +void CmdSketcherConstrainDistanceX::activated(int iMsg) +{ + Q_UNUSED(iMsg); + // get the selection + std::vector selection = getSelection().getSelectionEx(); + + // only one sketch with its subelements are allowed to be selected + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); + + if (constraintMode) { + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); + getSelection().clearSelection(); + } + else { + // TODO: Get the exact message from git history and put it here + Gui::TranslatedUserWarning(getActiveGuiDocument(), + QObject::tr("Wrong selection"), + QObject::tr("Select the right things from the sketch.")); + } + return; + } + + // get the needed lists and objects + const std::vector& SubNames = selection[0].getSubNames(); + Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); + + if (SubNames.empty() || SubNames.size() > 2) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or up to two points from the sketch.")); + return; + } + + int GeoId1, GeoId2 = GeoEnum::GeoUndef; + Sketcher::PointPos PosId1, PosId2 = Sketcher::PointPos::none; getIdsFromName(SubNames[0], Obj, GeoId1, PosId1); if (SubNames.size() == 2) getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); - bool arebothpointsorsegmentsfixed=areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2); + bool arebothpointsorsegmentsfixed = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); if (GeoId2 == Sketcher::GeoEnum::HAxis || GeoId2 == Sketcher::GeoEnum::VAxis) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } if (GeoId1 == Sketcher::GeoEnum::HAxis && PosId1 == Sketcher::PointPos::none) @@ -2979,207 +3373,235 @@ void CmdSketcherConstrainDistanceX::activated(int iMsg) PosId1 = Sketcher::PointPos::start; } - if (isEdge(GeoId1,PosId1) && GeoId2 == GeoEnum::GeoUndef) { + if (isEdge(GeoId1, PosId1) && GeoId2 == GeoEnum::GeoUndef) { // horizontal length of a line if (GeoId1 < 0 && GeoId1 >= Sketcher::GeoEnum::VAxis) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a horizontal length constraint on an axis!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a horizontal length constraint on an axis!")); return; } - arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj,GeoId1); + arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj, GeoId1); - const Part::Geometry *geom = Obj->getGeometry(GeoId1); + const Part::Geometry* geom = Obj->getGeometry(GeoId1); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - //convert to as if two endpoints of the line have been selected + // convert to as if two endpoints of the line have been selected PosId1 = Sketcher::PointPos::start; GeoId2 = GeoId1; PosId2 = Sketcher::PointPos::end; } } - if (isVertex(GeoId1,PosId1) && isVertex(GeoId2,PosId2)) { + if (isVertex(GeoId1, PosId1) && isVertex(GeoId2, PosId2)) { // point to point horizontal distance - Base::Vector3d pnt1 = Obj->getPoint(GeoId1,PosId1); - Base::Vector3d pnt2 = Obj->getPoint(GeoId2,PosId2); - double ActLength = pnt2.x-pnt1.x; + Base::Vector3d pnt1 = Obj->getPoint(GeoId1, PosId1); + Base::Vector3d pnt2 = Obj->getPoint(GeoId2, PosId2); + double ActLength = pnt2.x - pnt1.x; - //negative sign avoidance: swap the points to make value positive + // negative sign avoidance: swap the points to make value positive if (ActLength < -Precision::Confusion()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); std::swap(pnt1, pnt2); ActLength = -ActLength; } - openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point horizontal distance constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),ActLength); + openCommand( + QT_TRANSLATE_NOOP("Command", "Add point to point horizontal distance constraint")); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + ActLength); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { + if (arebothpointsorsegmentsfixed || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } - else if (isVertex(GeoId1,PosId1) && GeoId2 == GeoEnum::GeoUndef) { + else if (isVertex(GeoId1, PosId1) && GeoId2 == GeoEnum::GeoUndef) { // point on fixed x-coordinate if (GeoId1 < 0 && GeoId1 >= Sketcher::GeoEnum::VAxis) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a fixed x-coordinate constraint on the origin point!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a fixed x-coordinate constraint on the origin point!")); return; } - Base::Vector3d pnt = Obj->getPoint(GeoId1,PosId1); + Base::Vector3d pnt = Obj->getPoint(GeoId1, PosId1); double ActX = pnt.x; - arebothpointsorsegmentsfixed=isPointOrSegmentFixed(Obj,GeoId1); + arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj, GeoId1); openCommand(QT_TRANSLATE_NOOP("Command", "Add fixed x-coordinate constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%f))", - GeoId1,static_cast(PosId1),ActX); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%f))", + GeoId1, + static_cast(PosId1), + ActX); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { + if (arebothpointsorsegmentsfixed || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(),"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or up to two points from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or up to two points from the sketch.")); return; } -void CmdSketcherConstrainDistanceX::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainDistanceX::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef; Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none; switch (seqIndex) { - case 0: // {SelVertex, SelVertexOrRoot} - case 1: // {SelRoot, SelVertex} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; - break; - } - case 2: // {SelEdge} - case 3: // {SelExternalEdge} - { - GeoId1 = GeoId2 = selSeq.at(0).GeoId; - PosId1 = Sketcher::PointPos::start; PosId2 = Sketcher::PointPos::end; - - const Part::Geometry *geom = Obj->getGeometry(GeoId1); - if (geom->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("This constraint only makes sense on a line segment or a pair of points.")); - return; + case 0:// {SelVertex, SelVertexOrRoot} + case 1:// {SelRoot, SelVertex} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; + break; } + case 2:// {SelEdge} + case 3:// {SelExternalEdge} + { + GeoId1 = GeoId2 = selSeq.at(0).GeoId; + PosId1 = Sketcher::PointPos::start; + PosId2 = Sketcher::PointPos::end; - break; - } - default: - break; + const Part::Geometry* geom = Obj->getGeometry(GeoId1); + if (geom->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "This constraint only makes sense on a line segment or a pair of points.")); + return; + } + + break; + } + default: + break; } - Base::Vector3d pnt1 = Obj->getPoint(GeoId1,PosId1); - Base::Vector3d pnt2 = Obj->getPoint(GeoId2,PosId2); - double ActLength = pnt2.x-pnt1.x; + Base::Vector3d pnt1 = Obj->getPoint(GeoId1, PosId1); + Base::Vector3d pnt2 = Obj->getPoint(GeoId2, PosId2); + double ActLength = pnt2.x - pnt1.x; - //negative sign avoidance: swap the points to make value positive + // negative sign avoidance: swap the points to make value positive if (ActLength < -Precision::Confusion()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); std::swap(pnt1, pnt2); ActLength = -ActLength; } openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point horizontal distance constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),ActLength); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + ActLength); - if (areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2) || constraintCreationMode==Reference) { + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); } void CmdSketcherConstrainDistanceX::updateAction(int mode) { switch (mode) { - case Reference: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance_Driven")); - break; - case Driving: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance")); - break; + case Reference: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance_Driven")); + break; + case Driving: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance")); + break; } } // ====================================================================================== -class CmdSketcherConstrainDistanceY : public CmdSketcherConstraint +class CmdSketcherConstrainDistanceY: public CmdSketcherConstraint { public: CmdSketcherConstrainDistanceY(); - ~CmdSketcherConstrainDistanceY() override{} + ~CmdSketcherConstrainDistanceY() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainDistanceY"; } + { + return "CmdSketcherConstrainDistanceY"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainDistanceY::CmdSketcherConstrainDistanceY() - :CmdSketcherConstraint("Sketcher_ConstrainDistanceY") + : CmdSketcherConstraint("Sketcher_ConstrainDistanceY") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain vertical distance"); - sToolTipText = QT_TR_NOOP("Fix the vertical distance between two points or line ends"); - sWhatsThis = "Sketcher_ConstrainDistanceY"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_VerticalDistance"; - sAccel = "I"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain vertical distance"); + sToolTipText = QT_TR_NOOP("Fix the vertical distance between two points or line ends"); + sWhatsThis = "Sketcher_ConstrainDistanceY"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_VerticalDistance"; + sAccel = "I"; + eType = ForEdit; // Can't do single vertex because its a prefix for 2 vertices - allowedSelSequences = {{SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}, - {SelEdge}, {SelExternalEdge}}; + allowedSelSequences = { + {SelVertex, SelVertexOrRoot}, {SelRoot, SelVertex}, {SelEdge}, {SelExternalEdge}}; } void CmdSketcherConstrainDistanceY::activated(int iMsg) @@ -3189,15 +3611,17 @@ void CmdSketcherConstrainDistanceY::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -3207,231 +3631,264 @@ void CmdSketcherConstrainDistanceY::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.empty() || SubNames.size() > 2) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or up to two points from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or up to two points from the sketch.")); return; } - int GeoId1, GeoId2=GeoEnum::GeoUndef; - Sketcher::PointPos PosId1, PosId2=Sketcher::PointPos::none; + int GeoId1, GeoId2 = GeoEnum::GeoUndef; + Sketcher::PointPos PosId1, PosId2 = Sketcher::PointPos::none; getIdsFromName(SubNames[0], Obj, GeoId1, PosId1); if (SubNames.size() == 2) getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); - bool arebothpointsorsegmentsfixed=areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2); + bool arebothpointsorsegmentsfixed = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); if (GeoId2 == Sketcher::GeoEnum::HAxis || GeoId2 == Sketcher::GeoEnum::VAxis) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - if (GeoId1 == Sketcher::GeoEnum::VAxis && PosId1 == Sketcher::PointPos::none) // reject vertical axis from selection + if (GeoId1 == Sketcher::GeoEnum::VAxis + && PosId1 == Sketcher::PointPos::none)// reject vertical axis from selection GeoId1 = GeoEnum::GeoUndef; else if (GeoId1 == Sketcher::GeoEnum::HAxis && PosId1 == Sketcher::PointPos::none) PosId1 = Sketcher::PointPos::start; - if (isEdge(GeoId1,PosId1) && GeoId2 == GeoEnum::GeoUndef) { // vertical length of a line + if (isEdge(GeoId1, PosId1) && GeoId2 == GeoEnum::GeoUndef) {// vertical length of a line if (GeoId1 < 0 && GeoId1 >= Sketcher::GeoEnum::VAxis) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a vertical length constraint on an axis!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a vertical length constraint on an axis!")); return; } - arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj,GeoId1); + arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj, GeoId1); - const Part::Geometry *geom = Obj->getGeometry(GeoId1); + const Part::Geometry* geom = Obj->getGeometry(GeoId1); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - //convert to as if two endpoints of the line have been selected + // convert to as if two endpoints of the line have been selected PosId1 = Sketcher::PointPos::start; GeoId2 = GeoId1; PosId2 = Sketcher::PointPos::end; } } - if (isVertex(GeoId1,PosId1) && isVertex(GeoId2,PosId2)) { + if (isVertex(GeoId1, PosId1) && isVertex(GeoId2, PosId2)) { // point to point vertical distance - Base::Vector3d pnt1 = Obj->getPoint(GeoId1,PosId1); - Base::Vector3d pnt2 = Obj->getPoint(GeoId2,PosId2); - double ActLength = pnt2.y-pnt1.y; + Base::Vector3d pnt1 = Obj->getPoint(GeoId1, PosId1); + Base::Vector3d pnt2 = Obj->getPoint(GeoId2, PosId2); + double ActLength = pnt2.y - pnt1.y; - //negative sign avoidance: swap the points to make value positive + // negative sign avoidance: swap the points to make value positive if (ActLength < -Precision::Confusion()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); std::swap(pnt1, pnt2); ActLength = -ActLength; } - openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point vertical distance constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),ActLength); + openCommand( + QT_TRANSLATE_NOOP("Command", "Add point to point vertical distance constraint")); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + ActLength); - if (arebothpointsorsegmentsfixed || constraintCreationMode==Reference) { + if (arebothpointsorsegmentsfixed || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } - else if (isVertex(GeoId1,PosId1) && GeoId2 == GeoEnum::GeoUndef) { + else if (isVertex(GeoId1, PosId1) && GeoId2 == GeoEnum::GeoUndef) { // point on fixed y-coordinate if (GeoId1 < 0 && GeoId1 >= Sketcher::GeoEnum::VAxis) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a fixed y-coordinate constraint on the origin point!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a fixed y-coordinate constraint on the origin point!")); return; } - Base::Vector3d pnt = Obj->getPoint(GeoId1,PosId1); + Base::Vector3d pnt = Obj->getPoint(GeoId1, PosId1); double ActY = pnt.y; - arebothpointsorsegmentsfixed=isPointOrSegmentFixed(Obj,GeoId1); + arebothpointsorsegmentsfixed = isPointOrSegmentFixed(Obj, GeoId1); openCommand(QT_TRANSLATE_NOOP("Command", "Add fixed y-coordinate constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%f))", - GeoId1,static_cast(PosId1),ActY); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%f))", + GeoId1, + static_cast(PosId1), + ActY); - if (GeoId1 <= Sketcher::GeoEnum::RefExt - || constraintCreationMode==Reference) { + if (GeoId1 <= Sketcher::GeoEnum::RefExt || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select exactly one line or up to two points from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select exactly one line or up to two points from the sketch.")); return; } -void CmdSketcherConstrainDistanceY::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainDistanceY::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef; Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none; switch (seqIndex) { - case 0: // {SelVertex, SelVertexOrRoot} - case 1: // {SelRoot, SelVertex} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; - break; - } - case 2: // {SelEdge} - case 3: // {SelExternalEdge} - { - GeoId1 = GeoId2 = selSeq.at(0).GeoId; - PosId1 = Sketcher::PointPos::start; PosId2 = Sketcher::PointPos::end; - - const Part::Geometry *geom = Obj->getGeometry(GeoId1); - if (geom->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("This constraint only makes sense on a line segment or a pair of points.")); - return; + case 0:// {SelVertex, SelVertexOrRoot} + case 1:// {SelRoot, SelVertex} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; + break; } + case 2:// {SelEdge} + case 3:// {SelExternalEdge} + { + GeoId1 = GeoId2 = selSeq.at(0).GeoId; + PosId1 = Sketcher::PointPos::start; + PosId2 = Sketcher::PointPos::end; - break; - } - default: - break; + const Part::Geometry* geom = Obj->getGeometry(GeoId1); + if (geom->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "This constraint only makes sense on a line segment or a pair of points.")); + return; + } + + break; + } + default: + break; } - Base::Vector3d pnt1 = Obj->getPoint(GeoId1,PosId1); - Base::Vector3d pnt2 = Obj->getPoint(GeoId2,PosId2); - double ActLength = pnt2.y-pnt1.y; + Base::Vector3d pnt1 = Obj->getPoint(GeoId1, PosId1); + Base::Vector3d pnt2 = Obj->getPoint(GeoId2, PosId2); + double ActLength = pnt2.y - pnt1.y; - //negative sign avoidance: swap the points to make value positive + // negative sign avoidance: swap the points to make value positive if (ActLength < -Precision::Confusion()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); std::swap(pnt1, pnt2); ActLength = -ActLength; } openCommand(QT_TRANSLATE_NOOP("Command", "Add point to point vertical distance constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),ActLength); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + ActLength); - if (areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2) || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); } void CmdSketcherConstrainDistanceY::updateAction(int mode) { switch (mode) { - case Reference: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance_Driven")); - break; - case Driving: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance")); - break; + case Reference: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance_Driven")); + break; + case Driving: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance")); + break; } } //================================================================================= -class CmdSketcherConstrainParallel : public CmdSketcherConstraint +class CmdSketcherConstrainParallel: public CmdSketcherConstraint { public: CmdSketcherConstrainParallel(); - ~CmdSketcherConstrainParallel() override{} + ~CmdSketcherConstrainParallel() override + {} const char* className() const override - { return "CmdSketcherConstrainParallel"; } + { + return "CmdSketcherConstrainParallel"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainParallel::CmdSketcherConstrainParallel() - :CmdSketcherConstraint("Sketcher_ConstrainParallel") + : CmdSketcherConstraint("Sketcher_ConstrainParallel") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain parallel"); - sToolTipText = QT_TR_NOOP("Create a parallel constraint between two lines"); - sWhatsThis = "Sketcher_ConstrainParallel"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Parallel"; - sAccel = "P"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain parallel"); + sToolTipText = QT_TR_NOOP("Create a parallel constraint between two lines"); + sWhatsThis = "Sketcher_ConstrainParallel"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Parallel"; + sAccel = "P"; + eType = ForEdit; // TODO: Also needed: ExternalEdges - allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, {SelEdgeOrAxis, SelEdge}, - {SelEdge, SelExternalEdge}, {SelExternalEdge, SelEdge}}; + allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, + {SelEdgeOrAxis, SelEdge}, + {SelEdge, SelExternalEdge}, + {SelExternalEdge, SelEdge}}; } void CmdSketcherConstrainParallel::activated(int iMsg) @@ -3441,15 +3898,17 @@ void CmdSketcherConstrainParallel::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -3459,33 +3918,33 @@ void CmdSketcherConstrainParallel::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); // go through the selected subelements if (SubNames.size() < 2) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select at least two lines from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select at least two lines from the sketch.")); return; } std::vector ids; - bool hasAlreadyExternal=false; - for (std::vector::const_iterator it=SubNames.begin();it!=SubNames.end();++it) { + bool hasAlreadyExternal = false; + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoId; Sketcher::PointPos PosId; getIdsFromName(*it, Obj, GeoId, PosId); - if (!isEdge(GeoId,PosId)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select a valid line.")); + if (!isEdge(GeoId, PosId)) { + Gui::TranslatedUserWarning( + Obj, QObject::tr("Wrong selection"), QObject::tr("Select a valid line.")); return; } - else if (isPointOrSegmentFixed(Obj,GeoId)) { + else if (isPointOrSegmentFixed(Obj, GeoId)) { if (hasAlreadyExternal) { showNoConstraintBetweenFixedGeometry(Obj); return; @@ -3495,11 +3954,11 @@ void CmdSketcherConstrainParallel::activated(int iMsg) } // Check that the curve is a line segment - const Part::Geometry *geo = Obj->getGeometry(GeoId); + const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("The selected edge is not a valid line.")); + QObject::tr("Wrong selection"), + QObject::tr("The selected edge is not a valid line.")); return; } @@ -3508,9 +3967,11 @@ void CmdSketcherConstrainParallel::activated(int iMsg) // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add parallel constraint")); - for (int i=0; i < int(ids.size()-1); i++) { - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Parallel',%d,%d))", - ids[i],ids[i+1]); + for (int i = 0; i < int(ids.size() - 1); i++) { + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Parallel',%d,%d))", + ids[i], + ids[i + 1]); } // finish the transaction and update commitCommand(); @@ -3521,73 +3982,83 @@ void CmdSketcherConstrainParallel::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainParallel::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainParallel::applyConstraint(std::vector& selSeq, int seqIndex) { switch (seqIndex) { - case 0: // {SelEdge, SelEdgeOrAxis} - case 1: // {SelEdgeOrAxis, SelEdge} - case 2: // {SelEdge, SelExternalEdge} - case 3: // {SelExternalEdge, SelEdge} - // create the constraint - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); - Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); + case 0:// {SelEdge, SelEdgeOrAxis} + case 1:// {SelEdgeOrAxis, SelEdge} + case 2:// {SelEdge, SelExternalEdge} + case 3:// {SelExternalEdge, SelEdge} + // create the constraint + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); + Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); - int GeoId1 = selSeq.at(0).GeoId, GeoId2 = selSeq.at(1).GeoId; + int GeoId1 = selSeq.at(0).GeoId, GeoId2 = selSeq.at(1).GeoId; - // Check that the curves are line segments - if ( Obj->getGeometry(GeoId1)->getTypeId() != Part::GeomLineSegment::getClassTypeId() || - Obj->getGeometry(GeoId2)->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("The selected edge is not a valid line.")); - return; - } + // Check that the curves are line segments + if (Obj->getGeometry(GeoId1)->getTypeId() != Part::GeomLineSegment::getClassTypeId() + || Obj->getGeometry(GeoId2)->getTypeId() + != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("The selected edge is not a valid line.")); + return; + } - if( areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2)) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; + } - // undo command open - openCommand(QT_TRANSLATE_NOOP("Command", "Add parallel constraint")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Parallel',%d,%d))", - GeoId1, GeoId2); - // finish the transaction and update - commitCommand(); - tryAutoRecompute(Obj); + // undo command open + openCommand(QT_TRANSLATE_NOOP("Command", "Add parallel constraint")); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Parallel',%d,%d))", + GeoId1, + GeoId2); + // finish the transaction and update + commitCommand(); + tryAutoRecompute(Obj); } } // ====================================================================================== -class CmdSketcherConstrainPerpendicular : public CmdSketcherConstraint +class CmdSketcherConstrainPerpendicular: public CmdSketcherConstraint { public: CmdSketcherConstrainPerpendicular(); - ~CmdSketcherConstrainPerpendicular() override{} + ~CmdSketcherConstrainPerpendicular() override + {} const char* className() const override - { return "CmdSketcherConstrainPerpendicular"; } + { + return "CmdSketcherConstrainPerpendicular"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainPerpendicular::CmdSketcherConstrainPerpendicular() - :CmdSketcherConstraint("Sketcher_ConstrainPerpendicular") + : CmdSketcherConstraint("Sketcher_ConstrainPerpendicular") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain perpendicular"); - sToolTipText = QT_TR_NOOP("Create a perpendicular constraint between two lines"); - sWhatsThis = "Sketcher_ConstrainPerpendicular"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Perpendicular"; - sAccel = "N"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain perpendicular"); + sToolTipText = QT_TR_NOOP("Create a perpendicular constraint between two lines"); + sWhatsThis = "Sketcher_ConstrainPerpendicular"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Perpendicular"; + sAccel = "N"; + eType = ForEdit; // TODO: there are two more combos: endpoint then curve and endpoint then endpoint - allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, {SelEdgeOrAxis, SelEdge}, - {SelEdge, SelExternalEdge}, {SelExternalEdge, SelEdge}, + allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, + {SelEdgeOrAxis, SelEdge}, + {SelEdge, SelExternalEdge}, + {SelExternalEdge, SelEdge}, {SelVertexOrRoot, SelEdge, SelEdgeOrAxis}, {SelVertexOrRoot, SelEdgeOrAxis, SelEdge}, {SelVertexOrRoot, SelEdge, SelExternalEdge}, @@ -3596,7 +4067,7 @@ CmdSketcherConstrainPerpendicular::CmdSketcherConstrainPerpendicular() {SelEdgeOrAxis, SelVertexOrRoot, SelEdge}, {SelEdge, SelVertexOrRoot, SelExternalEdge}, {SelExternalEdge, SelVertexOrRoot, SelEdge}}; -; + ; } void CmdSketcherConstrainPerpendicular::activated(int iMsg) @@ -3607,39 +4078,40 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here QString strBasicHelp = - QObject::tr( - "There is a number of ways this constraint can be applied.\n\n" - "Accepted combinations: two curves; an endpoint and a curve; two endpoints; two curves and a point.", - /*disambig.:*/ "perpendicular constraint"); - QString strError = QObject::tr("Select some geometry from the sketch.", "perpendicular constraint"); + QObject::tr("There is a number of ways this constraint can be applied.\n\n" + "Accepted combinations: two curves; an endpoint and a curve; two " + "endpoints; two curves and a point.", + /*disambig.:*/ "perpendicular constraint"); + QString strError = + QObject::tr("Select some geometry from the sketch.", "perpendicular constraint"); strError.append(QString::fromLatin1("\n\n")); strError.append(strBasicHelp); - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - std::move(strError)); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), QObject::tr("Wrong selection"), std::move(strError)); } return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = dynamic_cast(selection[0].getObject()); if (!Obj || (SubNames.size() != 2 && SubNames.size() != 3)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Wrong number of selected objects!")); + Gui::TranslatedUserWarning( + Obj, QObject::tr("Wrong selection"), QObject::tr("Wrong number of selected objects!")); return; } @@ -3648,56 +4120,80 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) getIdsFromName(SubNames[0], Obj, GeoId1, PosId1); getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); - if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { //checkBothExternal displays error message + if (areBothPointsOrSegmentsFixed( + Obj, GeoId1, GeoId2)) {// checkBothExternal displays error message showNoConstraintBetweenFixedGeometry(Obj); return; } - if (SubNames.size() == 3) { //perpendicular via point + if (SubNames.size() == 3) {// perpendicular via point getIdsFromName(SubNames[2], Obj, GeoId3, PosId3); - //let's sink the point to be GeoId3. We want to keep the order the two curves have been selected in. - if ( isVertex(GeoId1, PosId1) ){ - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + // let's sink the point to be GeoId3. We want to keep the order the two curves have been + // selected in. + if (isVertex(GeoId1, PosId1)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); }; - if ( isVertex(GeoId2, PosId2) ){ - std::swap(GeoId2,GeoId3); - std::swap(PosId2,PosId3); + if (isVertex(GeoId2, PosId2)) { + std::swap(GeoId2, GeoId3); + std::swap(PosId2, PosId3); }; if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { - if(isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); - bool safe = addConstraintSafely(Obj, [&](){ - //add missing point-on-object constraints - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + bool safe = addConstraintSafely(Obj, [&]() { + // add missing point-on-object constraints + if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - if(! IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId2); + if (!IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId2); }; - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){//FIXME: it's a good idea to add a check if the sketch is solved - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + if (!IsPointAlreadyOnCurve( + GeoId1, + GeoId3, + PosId3, + Obj)) {// FIXME: it's a good idea to add a check if the sketch is solved + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", - GeoId1,GeoId2,GeoId3,static_cast(PosId3)); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", + GeoId1, + GeoId2, + GeoId3, + static_cast(PosId3)); }); - if(!safe) + if (!safe) return; else { commitCommand(); @@ -3707,123 +4203,139 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) getSelection().clearSelection(); return; - }; - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("With 3 objects, there must be 2 curves and 1 point.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("With 3 objects, there must be 2 curves and 1 point.")); + } + else if (SubNames.size() == 2) { + if (isVertex(GeoId1, PosId1) + && isVertex(GeoId2, PosId2)) {// endpoint-to-endpoint perpendicularity - } else if (SubNames.size() == 2) { - - if (isVertex(GeoId1,PosId1) && isVertex(GeoId2,PosId2)) { //endpoint-to-endpoint perpendicularity - - if (isSimpleVertex(Obj, GeoId1, PosId1) || - isSimpleVertex(Obj, GeoId2, PosId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a perpendicularity constraint at an unconnected point!")); + if (isSimpleVertex(Obj, GeoId1, PosId1) || isSimpleVertex(Obj, GeoId2, PosId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "Cannot add a perpendicularity constraint at an unconnected point!")); return; } // This code supports simple B-spline endpoint perp to any other geometric curve - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() )){ + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { - if(geom1->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + if (geom1->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } // GeoId1 is the B-spline now - } // end of code supports simple B-spline endpoint tangency + }// end of code supports simple B-spline endpoint tangency openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); commitCommand(); tryAutoRecompute(Obj); getSelection().clearSelection(); return; } - else if ((isVertex(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) || - (isEdge(GeoId1,PosId1) && isVertex(GeoId2,PosId2))) { // endpoint-to-curve - if (isVertex(GeoId2,PosId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + else if ((isVertex(GeoId1, PosId1) && isEdge(GeoId2, PosId2)) + || (isEdge(GeoId1, PosId1) && isVertex(GeoId2, PosId2))) {// endpoint-to-curve + if (isVertex(GeoId2, PosId2)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } if (isSimpleVertex(Obj, GeoId1, PosId1)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a perpendicularity constraint at an unconnected point!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "Cannot add a perpendicularity constraint at an unconnected point!")); return; } - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); - if( geom2 && geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() ){ + if (geom2 && geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // unsupported until normal to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Perpendicular to B-spline edge currently unsupported.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Perpendicular to B-spline edge currently unsupported.")); return; } - if(isBsplinePole(geom2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(geom2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicularity constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2); commitCommand(); tryAutoRecompute(Obj); getSelection().clearSelection(); return; } - else if (isEdge(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) { // simple perpendicularity between GeoId1 and GeoId2 + else if (isEdge(GeoId1, PosId1) + && isEdge(GeoId2, PosId2)) {// simple perpendicularity between GeoId1 and GeoId2 - const Part::Geometry *geo1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geo2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geo1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geo2 = Obj->getGeometry(GeoId2); if (!geo1 || !geo2) { return; } - if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("One of the selected edges should be a line.")); + if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("One of the selected edges should be a line.")); return; } - if (geo1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geo2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ + if (geo1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geo2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // unsupported until tangent to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Perpendicular to B-spline edge currently unsupported.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Perpendicular to B-spline edge currently unsupported.")); return; } if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) - std::swap(GeoId1,GeoId2); + std::swap(GeoId1, GeoId2); - if(isBsplinePole(Obj, GeoId1)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } @@ -3831,10 +4343,10 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) geo1 = Obj->getGeometry(GeoId1); geo2 = Obj->getGeometry(GeoId2); - if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { Base::Vector3d center; Base::Vector3d majdir; @@ -3843,89 +4355,110 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) double minord = 0; double phi = 0; - if( geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() ){ - const Part::GeomEllipse *ellipse = static_cast(geo1); + if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = static_cast(geo1); - center=ellipse->getCenter(); - majord=ellipse->getMajorRadius(); - minord=ellipse->getMinorRadius(); - majdir=ellipse->getMajorAxisDir(); - phi=atan2(majdir.y, majdir.x); + center = ellipse->getCenter(); + majord = ellipse->getMajorRadius(); + minord = ellipse->getMinorRadius(); + majdir = ellipse->getMajorAxisDir(); + phi = atan2(majdir.y, majdir.x); } - else if( geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() ){ - const Part::GeomArcOfEllipse *aoe = static_cast(geo1); + else if (geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoe = + static_cast(geo1); - center=aoe->getCenter(); - majord=aoe->getMajorRadius(); - minord=aoe->getMinorRadius(); - majdir=aoe->getMajorAxisDir(); - phi=atan2(majdir.y, majdir.x); + center = aoe->getCenter(); + majord = aoe->getMajorRadius(); + minord = aoe->getMinorRadius(); + majdir = aoe->getMajorAxisDir(); + phi = atan2(majdir.y, majdir.x); } - else if( geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ){ - const Part::GeomArcOfHyperbola *aoh = static_cast(geo1); + else if (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = + static_cast(geo1); - center=aoh->getCenter(); - majord=aoh->getMajorRadius(); - minord=aoh->getMinorRadius(); - majdir=aoh->getMajorAxisDir(); - phi=atan2(majdir.y, majdir.x); + center = aoh->getCenter(); + majord = aoh->getMajorRadius(); + minord = aoh->getMinorRadius(); + majdir = aoh->getMajorAxisDir(); + phi = atan2(majdir.y, majdir.x); } - else if( geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ){ - const Part::GeomArcOfParabola *aop = static_cast(geo1); + else if (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = + static_cast(geo1); - center=aop->getCenter(); - focus=aop->getFocus(); + center = aop->getCenter(); + focus = aop->getFocus(); } - const Part::GeomLineSegment *line = static_cast(geo2); + const Part::GeomLineSegment* line = static_cast(geo2); - Base::Vector3d point1=line->getStartPoint(); + Base::Vector3d point1 = line->getStartPoint(); Base::Vector3d PoO; - if( geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ) { - double df=sqrt(majord*majord+minord*minord); - Base::Vector3d direction=point1-(center+majdir*df); // towards the focus - double tapprox=atan2(direction.y,direction.x)-phi; + if (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + double df = sqrt(majord * majord + minord * minord); + Base::Vector3d direction = point1 - (center + majdir * df);// towards the focus + double tapprox = atan2(direction.y, direction.x) - phi; - PoO = Base::Vector3d(center.x+majord*cosh(tapprox)*cos(phi)-minord*sinh(tapprox)*sin(phi), - center.y+majord*cosh(tapprox)*sin(phi)+minord*sinh(tapprox)*cos(phi), 0); + PoO = Base::Vector3d(center.x + majord * cosh(tapprox) * cos(phi) + - minord * sinh(tapprox) * sin(phi), + center.y + majord * cosh(tapprox) * sin(phi) + + minord * sinh(tapprox) * cos(phi), + 0); } - else if( geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Base::Vector3d direction=point1-focus; // towards the focus + else if (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Base::Vector3d direction = point1 - focus;// towards the focus PoO = point1 + direction / 2; } else { - Base::Vector3d direction=point1-center; - double tapprox=atan2(direction.y,direction.x)-phi; // we approximate the eccentric anomaly by the polar + Base::Vector3d direction = point1 - center; + double tapprox = atan2(direction.y, direction.x) + - phi;// we approximate the eccentric anomaly by the polar - PoO = Base::Vector3d(center.x+majord*cos(tapprox)*cos(phi)-minord*sin(tapprox)*sin(phi), - center.y+majord*cos(tapprox)*sin(phi)+minord*sin(tapprox)*cos(phi), 0); + PoO = Base::Vector3d(center.x + majord * cos(tapprox) * cos(phi) + - minord * sin(tapprox) * sin(phi), + center.y + majord * cos(tapprox) * sin(phi) + + minord * sin(tapprox) * cos(phi), + 0); } openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); try { // Add a point - Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - PoO.x,PoO.y); + Gui::cmdAppObjectArgs( + Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", PoO.x, PoO.y); int GeoIdPoint = Obj->getHighestCurveIndex(); // Point on first object (ellipse, arc of ellipse) - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),GeoId1); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + GeoId1); // Point on second object - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),GeoId2); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + GeoId2); // add constraint: Perpendicular-via-point - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", - GeoId1, GeoId2 ,GeoIdPoint, static_cast(Sketcher::PointPos::start)); - + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", + GeoId1, + GeoId2, + GeoIdPoint, + static_cast(Sketcher::PointPos::start)); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); tryAutoRecompute(Obj); @@ -3937,12 +4470,13 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) getSelection().clearSelection(); return; - } openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d))", - GeoId1,GeoId2); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d))", + GeoId1, + GeoId2); commitCommand(); tryAutoRecompute(Obj); @@ -3954,248 +4488,302 @@ void CmdSketcherConstrainPerpendicular::activated(int iMsg) return; } -void CmdSketcherConstrainPerpendicular::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainPerpendicular::applyConstraint(std::vector& selSeq, + int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; - Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; + Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, + PosId3 = Sketcher::PointPos::none; switch (seqIndex) { - case 0: // {SelEdge, SelEdgeOrAxis} - case 1: // {SelEdgeOrAxis, SelEdge} - case 2: // {SelEdge, SelExternalEdge} - case 3: // {SelExternalEdge, SelEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; + case 0:// {SelEdge, SelEdgeOrAxis} + case 1:// {SelEdgeOrAxis, SelEdge} + case 2:// {SelEdge, SelExternalEdge} + case 3:// {SelExternalEdge, SelEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; - // check if the edge already has a Block constraint - if ( areBothPointsOrSegmentsFixed(Obj,GeoId1,GeoId2) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } - - const Part::Geometry *geo1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geo2 = Obj->getGeometry(GeoId2); - if (!geo1 || !geo2) { - return; - } - - if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("One of the selected edges should be a line.")); - return; - } - - if (geo1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geo2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ - - // unsupported until tangent to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Perpendicular to B-spline edge currently unsupported.")); - - return; - } - - if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) - std::swap(GeoId1,GeoId2); - - if(isBsplinePole(Obj, GeoId1)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); - return; - } - - // GeoId2 is the line - geo1 = Obj->getGeometry(GeoId1); - geo2 = Obj->getGeometry(GeoId2); - - if( geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - - Base::Vector3d center; - Base::Vector3d majdir; - Base::Vector3d focus; - double majord = 0; - double minord = 0; - double phi = 0; - - if( geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() ){ - const Part::GeomEllipse *ellipse = static_cast(geo1); - - center=ellipse->getCenter(); - majord=ellipse->getMajorRadius(); - minord=ellipse->getMinorRadius(); - majdir=ellipse->getMajorAxisDir(); - phi=atan2(majdir.y, majdir.x); - } - else if( geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() ){ - const Part::GeomArcOfEllipse *aoe = static_cast(geo1); - - center=aoe->getCenter(); - majord=aoe->getMajorRadius(); - minord=aoe->getMinorRadius(); - majdir=aoe->getMajorAxisDir(); - phi=atan2(majdir.y, majdir.x); - } - else if( geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ){ - const Part::GeomArcOfHyperbola *aoh = static_cast(geo1); - - center=aoh->getCenter(); - majord=aoh->getMajorRadius(); - minord=aoh->getMinorRadius(); - majdir=aoh->getMajorAxisDir(); - phi=atan2(majdir.y, majdir.x); - } - else if( geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ){ - const Part::GeomArcOfParabola *aop = static_cast(geo1); - - center=aop->getCenter(); - focus=aop->getFocus(); + // check if the edge already has a Block constraint + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; } - const Part::GeomLineSegment *line = static_cast(geo2); - - Base::Vector3d point1=line->getStartPoint(); - Base::Vector3d PoO; - - if( geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ) { - double df=sqrt(majord*majord+minord*minord); - Base::Vector3d direction=point1-(center+majdir*df); // towards the focus - double tapprox=atan2(direction.y,direction.x)-phi; - - PoO = Base::Vector3d(center.x+majord*cosh(tapprox)*cos(phi)-minord*sinh(tapprox)*sin(phi), - center.y+majord*cosh(tapprox)*sin(phi)+minord*sinh(tapprox)*cos(phi), 0); + const Part::Geometry* geo1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geo2 = Obj->getGeometry(GeoId2); + if (!geo1 || !geo2) { + return; } - else if( geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Base::Vector3d direction=point1-focus; // towards the focus - PoO = point1 + direction / 2; + if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("One of the selected edges should be a line.")); + return; } - else { - Base::Vector3d direction=point1-center; - double tapprox=atan2(direction.y,direction.x)-phi; // we approximate the eccentric anomaly by the polar - PoO = Base::Vector3d(center.x+majord*cos(tapprox)*cos(phi)-minord*sin(tapprox)*sin(phi), - center.y+majord*cos(tapprox)*sin(phi)+minord*sin(tapprox)*cos(phi), 0); + if (geo1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geo2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + + // unsupported until tangent to B-spline at any point implemented. + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Perpendicular to B-spline edge currently unsupported.")); + + return; } + + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) + std::swap(GeoId1, GeoId2); + + if (isBsplinePole(Obj, GeoId1)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); + return; + } + + // GeoId2 is the line + geo1 = Obj->getGeometry(GeoId1); + geo2 = Obj->getGeometry(GeoId2); + + if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + + Base::Vector3d center; + Base::Vector3d majdir; + Base::Vector3d focus; + double majord = 0; + double minord = 0; + double phi = 0; + + if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = static_cast(geo1); + + center = ellipse->getCenter(); + majord = ellipse->getMajorRadius(); + minord = ellipse->getMinorRadius(); + majdir = ellipse->getMajorAxisDir(); + phi = atan2(majdir.y, majdir.x); + } + else if (geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoe = + static_cast(geo1); + + center = aoe->getCenter(); + majord = aoe->getMajorRadius(); + minord = aoe->getMinorRadius(); + majdir = aoe->getMajorAxisDir(); + phi = atan2(majdir.y, majdir.x); + } + else if (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = + static_cast(geo1); + + center = aoh->getCenter(); + majord = aoh->getMajorRadius(); + minord = aoh->getMinorRadius(); + majdir = aoh->getMajorAxisDir(); + phi = atan2(majdir.y, majdir.x); + } + else if (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = + static_cast(geo1); + + center = aop->getCenter(); + focus = aop->getFocus(); + } + + const Part::GeomLineSegment* line = static_cast(geo2); + + Base::Vector3d point1 = line->getStartPoint(); + Base::Vector3d PoO; + + if (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + double df = sqrt(majord * majord + minord * minord); + Base::Vector3d direction = point1 - (center + majdir * df);// towards the focus + double tapprox = atan2(direction.y, direction.x) - phi; + + PoO = Base::Vector3d(center.x + majord * cosh(tapprox) * cos(phi) + - minord * sinh(tapprox) * sin(phi), + center.y + majord * cosh(tapprox) * sin(phi) + + minord * sinh(tapprox) * cos(phi), + 0); + } + else if (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Base::Vector3d direction = point1 - focus;// towards the focus + + PoO = point1 + direction / 2; + } + else { + Base::Vector3d direction = point1 - center; + double tapprox = atan2(direction.y, direction.x) + - phi;// we approximate the eccentric anomaly by the polar + + PoO = Base::Vector3d(center.x + majord * cos(tapprox) * cos(phi) + - minord * sin(tapprox) * sin(phi), + center.y + majord * cos(tapprox) * sin(phi) + + minord * sin(tapprox) * cos(phi), + 0); + } + openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); + + try { + // Add a point + Gui::cmdAppObjectArgs( + Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", PoO.x, PoO.y); + int GeoIdPoint = Obj->getHighestCurveIndex(); + + // Point on first object (ellipse, arc of ellipse) + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + GeoId1); + // Point on second object + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoIdPoint, + static_cast(Sketcher::PointPos::start), + GeoId2); + + // add constraint: Perpendicular-via-point + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", + GeoId1, + GeoId2, + GeoIdPoint, + static_cast(Sketcher::PointPos::start)); + + commitCommand(); + } + catch (const Base::Exception& e) { + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); + Gui::Command::abortCommand(); + } + + + tryAutoRecompute(Obj); + + getSelection().clearSelection(); + return; + } + openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); - - try { - // Add a point - Gui::cmdAppObjectArgs(Obj, "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - PoO.x,PoO.y); - int GeoIdPoint = Obj->getHighestCurveIndex(); - - // Point on first object (ellipse, arc of ellipse) - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),GeoId1); - // Point on second object - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoIdPoint,static_cast(Sketcher::PointPos::start),GeoId2); - - // add constraint: Perpendicular-via-point - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", - GeoId1, GeoId2 ,GeoIdPoint, static_cast(Sketcher::PointPos::start)); - - commitCommand(); - } - catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); - Gui::Command::abortCommand(); - } - + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d))", GeoId1, GeoId2); + commitCommand(); tryAutoRecompute(Obj); - - getSelection().clearSelection(); return; - } + case 4:// {SelVertexOrRoot, SelEdge, SelEdgeOrAxis} + case 5:// {SelVertexOrRoot, SelEdgeOrAxis, SelEdge} + case 6:// {SelVertexOrRoot, SelEdge, SelExternalEdge} + case 7:// {SelVertexOrRoot, SelExternalEdge, SelEdge} + { + // let's sink the point to be GeoId3. + GeoId1 = selSeq.at(1).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(0).GeoId; + PosId3 = selSeq.at(0).PosId; - openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d))", - GeoId1,GeoId2); - commitCommand(); + break; + } + case 8: // {SelEdge, SelVertexOrRoot, SelEdgeOrAxis} + case 9: // {SelEdgeOrAxis, SelVertexOrRoot, SelEdge} + case 10:// {SelEdge, SelVertexOrRoot, SelExternalEdge} + case 11:// {SelExternalEdge, SelVertexOrRoot, SelEdge} + { + // let's sink the point to be GeoId3. + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(1).GeoId; + PosId3 = selSeq.at(1).PosId; - tryAutoRecompute(Obj); - return; - } - case 4: // {SelVertexOrRoot, SelEdge, SelEdgeOrAxis} - case 5: // {SelVertexOrRoot, SelEdgeOrAxis, SelEdge} - case 6: // {SelVertexOrRoot, SelEdge, SelExternalEdge} - case 7: // {SelVertexOrRoot, SelExternalEdge, SelEdge} - { - //let's sink the point to be GeoId3. - GeoId1 = selSeq.at(1).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(0).GeoId; - PosId3 = selSeq.at(0).PosId; - - break; - } - case 8: // {SelEdge, SelVertexOrRoot, SelEdgeOrAxis} - case 9: // {SelEdgeOrAxis, SelVertexOrRoot, SelEdge} - case 10: // {SelEdge, SelVertexOrRoot, SelExternalEdge} - case 11: // {SelExternalEdge, SelVertexOrRoot, SelEdge} - { - //let's sink the point to be GeoId3. - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(1).GeoId; - PosId3 = selSeq.at(1).PosId; - - break; - } - default: - return; + break; + } + default: + return; } if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { // check if the edge already has a Block constraint - if ( areBothPointsOrSegmentsFixed(Obj,GeoId1,GeoId2) ) { + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { showNoConstraintBetweenFixedGeometry(Obj); return; } - if(isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Add perpendicular constraint")); - bool safe = addConstraintSafely(Obj, [&](){ - //add missing point-on-object constraints - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + bool safe = addConstraintSafely(Obj, [&]() { + // add missing point-on-object constraints + if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - if(! IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId2); + if (!IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId2); }; - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){//FIXME: it's a good idea to add a check if the sketch is solved - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + if (!IsPointAlreadyOnCurve( + GeoId1, + GeoId3, + PosId3, + Obj)) {// FIXME: it's a good idea to add a check if the sketch is solved + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", - GeoId1,GeoId2,GeoId3,static_cast(PosId3)); + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PerpendicularViaPoint',%d,%d,%d,%d))", + GeoId1, + GeoId2, + GeoId3, + static_cast(PosId3)); }); - if(!safe) + if (!safe) return; else { commitCommand(); @@ -4205,99 +4793,114 @@ void CmdSketcherConstrainPerpendicular::applyConstraint(std::vector & getSelection().clearSelection(); return; - }; } // ====================================================================================== -class CmdSketcherConstrainTangent : public CmdSketcherConstraint +class CmdSketcherConstrainTangent: public CmdSketcherConstraint { public: CmdSketcherConstrainTangent(); - ~CmdSketcherConstrainTangent() override{} + ~CmdSketcherConstrainTangent() override + {} const char* className() const override - { return "CmdSketcherConstrainTangent"; } + { + return "CmdSketcherConstrainTangent"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; // returns true if a substitution took place - static bool substituteConstraintCombinations(SketchObject * Obj, int GeoId1, int GeoId2); + static bool substituteConstraintCombinations(SketchObject* Obj, int GeoId1, int GeoId2); }; CmdSketcherConstrainTangent::CmdSketcherConstrainTangent() - :CmdSketcherConstraint("Sketcher_ConstrainTangent") + : CmdSketcherConstraint("Sketcher_ConstrainTangent") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain tangent"); - sToolTipText = QT_TR_NOOP("Create a tangent constraint between two entities"); - sWhatsThis = "Sketcher_ConstrainTangent"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Tangent"; - sAccel = "T"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain tangent"); + sToolTipText = QT_TR_NOOP("Create a tangent constraint between two entities"); + sWhatsThis = "Sketcher_ConstrainTangent"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Tangent"; + sAccel = "T"; + eType = ForEdit; - allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, {SelEdgeOrAxis, SelEdge}, - {SelEdge, SelExternalEdge}, {SelExternalEdge, SelEdge},/* Two Curves */ - {SelVertexOrRoot, SelEdge, SelEdgeOrAxis}, - {SelVertexOrRoot, SelEdgeOrAxis, SelEdge}, - {SelVertexOrRoot, SelEdge, SelExternalEdge}, - {SelVertexOrRoot, SelExternalEdge, SelEdge}, - {SelEdge, SelVertexOrRoot, SelEdgeOrAxis}, - {SelEdgeOrAxis, SelVertexOrRoot, SelEdge}, - {SelEdge, SelVertexOrRoot, SelExternalEdge}, - {SelExternalEdge, SelVertexOrRoot, SelEdge}, /* Two Curves and a Point */ - {SelVertexOrRoot, SelVertex} /*Two Endpoints*/ /*No Place for One Endpoint and One Curve*/}; + allowedSelSequences = { + {SelEdge, SelEdgeOrAxis}, + {SelEdgeOrAxis, SelEdge}, + {SelEdge, SelExternalEdge}, + {SelExternalEdge, SelEdge}, /* Two Curves */ + {SelVertexOrRoot, SelEdge, SelEdgeOrAxis}, + {SelVertexOrRoot, SelEdgeOrAxis, SelEdge}, + {SelVertexOrRoot, SelEdge, SelExternalEdge}, + {SelVertexOrRoot, SelExternalEdge, SelEdge}, + {SelEdge, SelVertexOrRoot, SelEdgeOrAxis}, + {SelEdgeOrAxis, SelVertexOrRoot, SelEdge}, + {SelEdge, SelVertexOrRoot, SelExternalEdge}, + {SelExternalEdge, SelVertexOrRoot, SelEdge}, /* Two Curves and a Point */ + {SelVertexOrRoot, SelVertex} /*Two Endpoints*/ /*No Place for One Endpoint and One Curve*/}; } -bool CmdSketcherConstrainTangent::substituteConstraintCombinations(SketchObject * Obj, int GeoId1, int GeoId2) +bool CmdSketcherConstrainTangent::substituteConstraintCombinations(SketchObject* Obj, int GeoId1, + int GeoId2) { - const std::vector< Constraint * > &cvals = Obj->Constraints.getValues(); + const std::vector& cvals = Obj->Constraints.getValues(); int cid = 0; - for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); ++it, ++cid) { - if( (*it)->Type == Sketcher::Coincident && - (((*it)->First == GeoId1 && (*it)->Second == GeoId2) || - ((*it)->Second == GeoId1 && (*it)->First == GeoId2)) ) { + for (std::vector::const_iterator it = cvals.begin(); it != cvals.end(); + ++it, ++cid) { + if ((*it)->Type == Sketcher::Coincident + && (((*it)->First == GeoId1 && (*it)->Second == GeoId2) + || ((*it)->Second == GeoId1 && (*it)->First == GeoId2))) { // save values because 'doEndpointTangency' changes the // constraint property and thus invalidates this iterator int first = (*it)->First; int firstpos = static_cast((*it)->FirstPos); - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Swap coincident+tangency with ptp tangency")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Swap coincident+tangency with ptp tangency")); doEndpointTangency(Obj, (*it)->First, (*it)->Second, (*it)->FirstPos, (*it)->SecondPos); Gui::cmdAppObjectArgs(Obj, "delConstraintOnPoint(%d,%d)", first, firstpos); commitCommand(); - Obj->solve(); // The substitution requires a solve() so that the autoremove redundants works when Autorecompute not active. + Obj->solve();// The substitution requires a solve() so that the autoremove redundants + // works when Autorecompute not active. tryAutoRecomputeIfNotSolve(Obj); - notifyConstraintSubstitutions(QObject::tr("Endpoint to endpoint tangency was applied. The coincident constraint was deleted.")); + notifyConstraintSubstitutions(QObject::tr("Endpoint to endpoint tangency was applied. " + "The coincident constraint was deleted.")); getSelection().clearSelection(); return true; } - else if( (*it)->Type == Sketcher::PointOnObject && - (((*it)->First == GeoId1 && (*it)->Second == GeoId2) || - ((*it)->Second == GeoId1 && (*it)->First == GeoId2)) ) { + else if ((*it)->Type == Sketcher::PointOnObject + && (((*it)->First == GeoId1 && (*it)->Second == GeoId2) + || ((*it)->Second == GeoId1 && (*it)->First == GeoId2))) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Swap PointOnObject+tangency with point to curve tangency")); + Gui::Command::openCommand(QT_TRANSLATE_NOOP( + "Command", "Swap PointOnObject+tangency with point to curve tangency")); doEndpointToEdgeTangency(Obj, (*it)->First, (*it)->FirstPos, (*it)->Second); - Gui::cmdAppObjectArgs(Obj, "delConstraint(%d)", cid); // remove the preexisting point on object constraint. + Gui::cmdAppObjectArgs( + Obj, "delConstraint(%d)", cid);// remove the preexisting point on object constraint. commitCommand(); - // A substitution requires a solve() so that the autoremove redundants works when Autorecompute not active. However, - // delConstraint includes such solve() internally. So at this point it is already solved. + // A substitution requires a solve() so that the autoremove redundants works when + // Autorecompute not active. However, delConstraint includes such solve() internally. So + // at this point it is already solved. tryAutoRecomputeIfNotSolve(Obj); - notifyConstraintSubstitutions(QObject::tr("Endpoint to edge tangency was applied. The point on object constraint was deleted.")); + notifyConstraintSubstitutions(QObject::tr("Endpoint to edge tangency was applied. The " + "point on object constraint was deleted.")); getSelection().clearSelection(); return true; @@ -4315,41 +4918,41 @@ void CmdSketcherConstrainTangent::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { QString strBasicHelp = - QObject::tr( - "There are a number of ways this constraint can be applied.\n\n" - "Accepted combinations: two curves; an endpoint and a curve; two endpoints; two curves and a point.", - /*disambig.:*/ "tangent constraint"); - QString strError = QObject::tr("Select some geometry from the sketch.", "tangent constraint"); + QObject::tr("There are a number of ways this constraint can be applied.\n\n" + "Accepted combinations: two curves; an endpoint and a curve; two " + "endpoints; two curves and a point.", + /*disambig.:*/ "tangent constraint"); + QString strError = + QObject::tr("Select some geometry from the sketch.", "tangent constraint"); strError.append(QString::fromLatin1("\n\n")); strError.append(strBasicHelp); - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - std::move(strError)); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), QObject::tr("Wrong selection"), std::move(strError)); } return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - if (SubNames.size() != 2 && SubNames.size() != 3){ - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Wrong number of selected objects!")); + if (SubNames.size() != 2 && SubNames.size() != 3) { + Gui::TranslatedUserWarning( + Obj, QObject::tr("Wrong selection"), QObject::tr("Wrong number of selected objects!")); return; - } int GeoId1, GeoId2, GeoId3; @@ -4357,56 +4960,80 @@ void CmdSketcherConstrainTangent::activated(int iMsg) getIdsFromName(SubNames[0], Obj, GeoId1, PosId1); getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); - if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)){ //checkBothExternal displays error message + if (areBothPointsOrSegmentsFixed( + Obj, GeoId1, GeoId2)) {// checkBothExternal displays error message showNoConstraintBetweenFixedGeometry(Obj); return; } - if (SubNames.size() == 3) { //tangent via point + if (SubNames.size() == 3) {// tangent via point getIdsFromName(SubNames[2], Obj, GeoId3, PosId3); - //let's sink the point to be GeoId3. We want to keep the order the two curves have been selected in. - if ( isVertex(GeoId1, PosId1) ){ - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + // let's sink the point to be GeoId3. We want to keep the order the two curves have been + // selected in. + if (isVertex(GeoId1, PosId1)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); }; - if ( isVertex(GeoId2, PosId2) ){ - std::swap(GeoId2,GeoId3); - std::swap(PosId2,PosId3); + if (isVertex(GeoId2, PosId2)) { + std::swap(GeoId2, GeoId3); + std::swap(PosId2, PosId3); }; if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { - if(isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); - bool safe = addConstraintSafely(Obj, [&](){ - //add missing point-on-object constraints - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + bool safe = addConstraintSafely(Obj, [&]() { + // add missing point-on-object constraints + if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - if(! IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId2); + if (!IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId2); }; - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){//FIXME: it's a good idea to add a check if the sketch is solved - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + if (!IsPointAlreadyOnCurve( + GeoId1, + GeoId3, + PosId3, + Obj)) {// FIXME: it's a good idea to add a check if the sketch is solved + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", - GeoId1,GeoId2,GeoId3,static_cast(PosId3)); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", + GeoId1, + GeoId2, + GeoId3, + static_cast(PosId3)); }); - if(!safe) + if (!safe) return; else { commitCommand(); @@ -4416,40 +5043,41 @@ void CmdSketcherConstrainTangent::activated(int iMsg) getSelection().clearSelection(); return; - }; - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("With 3 objects, there must be 2 curves and 1 point.")); - + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("With 3 objects, there must be 2 curves and 1 point.")); } else if (SubNames.size() == 2) { - if (isVertex(GeoId1,PosId1) && isVertex(GeoId2,PosId2)) { // endpoint-to-endpoint tangency + if (isVertex(GeoId1, PosId1) && isVertex(GeoId2, PosId2)) {// endpoint-to-endpoint tangency if (isBsplineKnot(Obj, GeoId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - if (isSimpleVertex(Obj, GeoId1, PosId1) || - isSimpleVertex(Obj, GeoId2, PosId2)) { + if (isSimpleVertex(Obj, GeoId1, PosId1) || isSimpleVertex(Obj, GeoId2, PosId2)) { if (isBsplineKnot(Obj, GeoId1)) { - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - if (!geom2 || geom2->getTypeId() !=Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Tangent constraint at B-spline knot is only supported with lines!")); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); + if (!geom2 || geom2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Tangent constraint at B-spline knot is only supported " + "with lines!")); return; } } else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a tangency constraint at an unconnected point!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a tangency constraint at an unconnected point!")); return; } @@ -4463,217 +5091,261 @@ void CmdSketcherConstrainTangent::activated(int iMsg) getSelection().clearSelection(); return; } - else if ((isVertex(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) || - (isEdge(GeoId1,PosId1) && isVertex(GeoId2,PosId2))) { // endpoint-to-curve/knot-to-curve tangency - if (isVertex(GeoId2,PosId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + else if ((isVertex(GeoId1, PosId1) && isEdge(GeoId2, PosId2)) + || (isEdge(GeoId1, PosId1) + && isVertex(GeoId2, PosId2))) {// endpoint-to-curve/knot-to-curve tangency + if (isVertex(GeoId2, PosId2)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } if (isSimpleVertex(Obj, GeoId1, PosId1)) { if (isBsplineKnot(Obj, GeoId1)) { - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - if (!geom2 || geom2->getTypeId() !=Part::GeomLineSegment::getClassTypeId()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Tangent constraint at B-spline knot is only supported with lines!")); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); + if (!geom2 || geom2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Tangent constraint at B-spline knot is only supported " + "with lines!")); return; } } else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a tangency constraint at an unconnected point!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a tangency constraint at an unconnected point!")); return; } } - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); - if( geom2 && geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() ){ + if (geom2 && geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // unsupported until tangent to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Tangency to B-spline edge currently unsupported.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Tangency to B-spline edge currently unsupported.")); return; } - if(isBsplinePole(geom2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(geom2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2); commitCommand(); tryAutoRecompute(Obj); getSelection().clearSelection(); return; } - else if (isEdge(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) { // simple tangency between GeoId1 and GeoId2 + else if (isEdge(GeoId1, PosId1) + && isEdge(GeoId2, PosId2)) {// simple tangency between GeoId1 and GeoId2 - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() )){ + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { // unsupported until tangent to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Tangency to B-spline edge currently unsupported.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Tangency to B-spline edge currently unsupported.")); return; } - if(isBsplinePole(geom1) || isBsplinePole(geom2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(geom1) || isBsplinePole(geom2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } - // check if as a consequence of this command undesirable combinations of constraints would - // arise and substitute them with more appropriate counterparts, examples: + // check if as a consequence of this command undesirable combinations of constraints + // would arise and substitute them with more appropriate counterparts, examples: // - coincidence + tangency on edge // - point on object + tangency on edge - if(substituteConstraintCombinations(Obj, GeoId1, GeoId2)) + if (substituteConstraintCombinations(Obj, GeoId1, GeoId2)) return; - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() )){ + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomEllipse::getClassTypeId())) { - if(geom1->getTypeId() != Part::GeomEllipse::getClassTypeId()) - std::swap(GeoId1,GeoId2); + if (geom1->getTypeId() != Part::GeomEllipse::getClassTypeId()) + std::swap(GeoId1, GeoId2); // GeoId1 is the ellipse geom1 = Obj->getGeometry(GeoId1); geom2 = Obj->getGeometry(GeoId2); - if( geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() ) { + if (geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToEllipseviaNewPoint(Obj,static_cast(geom1), geom2, - GeoId1, GeoId2); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToEllipseviaNewPoint( + Obj, static_cast(geom1), geom2, GeoId1, GeoId2); getSelection().clearSelection(); return; } - else if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfHyperbolaviaNewPoint(Obj, static_cast(geom2), - geom1, GeoId2, GeoId1); + else if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfHyperbolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); getSelection().clearSelection(); return; } - else if( geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj,static_cast(geom2), - geom1, GeoId2, GeoId1); + else if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); getSelection().clearSelection(); return; } } - else if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() )){ + else if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId())) { - if(geom1->getTypeId() != Part::GeomArcOfEllipse::getClassTypeId()) - std::swap(GeoId1,GeoId2); + if (geom1->getTypeId() != Part::GeomArcOfEllipse::getClassTypeId()) + std::swap(GeoId1, GeoId2); // GeoId1 is the arc of ellipse geom1 = Obj->getGeometry(GeoId1); geom2 = Obj->getGeometry(GeoId2); - if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { + if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfEllipseviaNewPoint(Obj, - static_cast(geom1), geom2, GeoId1, GeoId2); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfEllipseviaNewPoint( + Obj, + static_cast(geom1), + geom2, + GeoId1, + GeoId2); getSelection().clearSelection(); return; } - else if( geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj, - static_cast(geom2), - geom1, GeoId2, GeoId1); + else if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); getSelection().clearSelection(); return; } } - else if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() )){ + else if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId())) { - if(geom1->getTypeId() != Part::GeomArcOfHyperbola::getClassTypeId()) - std::swap(GeoId1,GeoId2); + if (geom1->getTypeId() != Part::GeomArcOfHyperbola::getClassTypeId()) + std::swap(GeoId1, GeoId2); // GeoId1 is the arc of hyperbola geom1 = Obj->getGeometry(GeoId1); geom2 = Obj->getGeometry(GeoId2); - if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { + if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfHyperbolaviaNewPoint(Obj, - static_cast(geom1), - geom2, GeoId1, GeoId2); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfHyperbolaviaNewPoint( + Obj, + static_cast(geom1), + geom2, + GeoId1, + GeoId2); getSelection().clearSelection(); return; } - else if( geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj, - static_cast(geom2), - geom1, GeoId2, GeoId1); + else if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); getSelection().clearSelection(); return; } - } - else if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() )){ + else if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId())) { - if(geom1->getTypeId() != Part::GeomArcOfParabola::getClassTypeId()) - std::swap(GeoId1,GeoId2); + if (geom1->getTypeId() != Part::GeomArcOfParabola::getClassTypeId()) + std::swap(GeoId1, GeoId2); // GeoId1 is the arc of hyperbola geom1 = Obj->getGeometry(GeoId1); geom2 = Obj->getGeometry(GeoId2); - if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { + if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj, static_cast(geom1), - geom2, GeoId1, GeoId2); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom1), + geom2, + GeoId1, + GeoId2); getSelection().clearSelection(); return; } @@ -4681,286 +5353,348 @@ void CmdSketcherConstrainTangent::activated(int iMsg) openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Tangent',%d,%d))", - GeoId1,GeoId2); + "addConstraint(Sketcher.Constraint('Tangent',%d,%d))", + GeoId1, + GeoId2); commitCommand(); tryAutoRecompute(Obj); getSelection().clearSelection(); return; } - } return; } -void CmdSketcherConstrainTangent::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainTangent::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; - Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; + Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, + PosId3 = Sketcher::PointPos::none; switch (seqIndex) { - case 0: // {SelEdge, SelEdgeOrAxis} - case 1: // {SelEdgeOrAxis, SelEdge} - case 2: // {SelEdge, SelExternalEdge} - case 3: // {SelExternalEdge, SelEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; + case 0:// {SelEdge, SelEdgeOrAxis} + case 1:// {SelEdgeOrAxis, SelEdge} + case 2:// {SelEdge, SelExternalEdge} + case 3:// {SelExternalEdge, SelEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; - // check if the edge already has a Block constraint - if ( areBothPointsOrSegmentsFixed(Obj,GeoId1,GeoId2) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } - - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() )){ - - // unsupported until tangent to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Tangency to B-spline edge currently unsupported.")); - - return; - } - - if(isBsplinePole(geom1) || isBsplinePole(geom2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); - - return; - } - - // check if as a consequence of this command undesirable combinations of constraints would - // arise and substitute them with more appropriate counterparts, examples: - // - coincidence + tangency on edge - // - point on object + tangency on edge - if(substituteConstraintCombinations(Obj, GeoId1, GeoId2)) - return; - - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() )){ - - if(geom1->getTypeId() != Part::GeomEllipse::getClassTypeId()) - std::swap(GeoId1,GeoId2); - - // GeoId1 is the ellipse - geom1 = Obj->getGeometry(GeoId1); - geom2 = Obj->getGeometry(GeoId2); - - if( geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() ) { - - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToEllipseviaNewPoint(Obj, static_cast(geom1), - geom2, GeoId1, GeoId2); - getSelection().clearSelection(); - return; - } - else if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfHyperbolaviaNewPoint(Obj, static_cast(geom2), - geom1, GeoId2, GeoId1); - getSelection().clearSelection(); - return; - } - else if( geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj, static_cast(geom2), - geom1, GeoId2, GeoId1); - getSelection().clearSelection(); - return; - } - } - else if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() )){ - - if(geom1->getTypeId() != Part::GeomArcOfHyperbola::getClassTypeId()) - std::swap(GeoId1,GeoId2); - - // GeoId1 is the arc of hyperbola - geom1 = Obj->getGeometry(GeoId1); - geom2 = Obj->getGeometry(GeoId2); - - if( geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { - - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfHyperbolaviaNewPoint(Obj, static_cast(geom1), - geom2, GeoId1, GeoId2); - getSelection().clearSelection(); - return; - } - else if( geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() ) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj, static_cast(geom2), - geom1, GeoId2, GeoId1); - getSelection().clearSelection(); + // check if the edge already has a Block constraint + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); return; } - } - else if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() )){ + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); - if(geom1->getTypeId() != Part::GeomArcOfParabola::getClassTypeId()) - std::swap(GeoId1,GeoId2); + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { - // GeoId1 is the arc of hyperbola - geom1 = Obj->getGeometry(GeoId1); - geom2 = Obj->getGeometry(GeoId2); + // unsupported until tangent to B-spline at any point implemented. + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Tangency to B-spline edge currently unsupported.")); - if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId() ) { - - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); - makeTangentToArcOfParabolaviaNewPoint(Obj, static_cast(geom1), - geom2, GeoId1, GeoId2); - getSelection().clearSelection(); return; } - } - openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Tangent',%d,%d))", - GeoId1,GeoId2); - commitCommand(); - tryAutoRecompute(Obj); + if (isBsplinePole(geom1) || isBsplinePole(geom2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); - return; - } - case 4: // {SelVertexOrRoot, SelEdge, SelEdgeOrAxis} - case 5: // {SelVertexOrRoot, SelEdgeOrAxis, SelEdge} - case 6: // {SelVertexOrRoot, SelEdge, SelExternalEdge} - case 7: // {SelVertexOrRoot, SelExternalEdge, SelEdge} - { - //let's sink the point to be GeoId3. - GeoId1 = selSeq.at(1).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(0).GeoId; - PosId3 = selSeq.at(0).PosId; - - break; - } - case 8: // {SelEdge, SelVertexOrRoot, SelEdgeOrAxis} - case 9: // {SelEdgeOrAxis, SelVertexOrRoot, SelEdge} - case 10: // {SelEdge, SelVertexOrRoot, SelExternalEdge} - case 11: // {SelExternalEdge, SelVertexOrRoot, SelEdge} - { - //let's sink the point to be GeoId3. - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(1).GeoId; - PosId3 = selSeq.at(1).PosId; - - break; - } - case 12: // {SelVertexOrRoot, SelVertex} - { - // Different notation than the previous places - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; - - // check if the edge already has a Block constraint - if ( areBothPointsOrSegmentsFixed(Obj,GeoId1,GeoId2) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } - - if (isSimpleVertex(Obj, GeoId1, PosId1) || - isSimpleVertex(Obj, GeoId2, PosId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a tangency constraint at an unconnected point!")); - - return; - } - - // This code supports simple B-spline endpoint tangency to any other geometric curve - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() || - geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() )){ - - if(geom1->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + return; } - // GeoId1 is the B-spline now - } // end of code supports simple B-spline endpoint tangency - openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); - commitCommand(); - tryAutoRecompute(Obj); + // check if as a consequence of this command undesirable combinations of constraints + // would arise and substitute them with more appropriate counterparts, examples: + // - coincidence + tangency on edge + // - point on object + tangency on edge + if (substituteConstraintCombinations(Obj, GeoId1, GeoId2)) + return; - getSelection().clearSelection(); - return; - } - default: - return; + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomEllipse::getClassTypeId())) { + + if (geom1->getTypeId() != Part::GeomEllipse::getClassTypeId()) + std::swap(GeoId1, GeoId2); + + // GeoId1 is the ellipse + geom1 = Obj->getGeometry(GeoId1); + geom2 = Obj->getGeometry(GeoId2); + + if (geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToEllipseviaNewPoint( + Obj, static_cast(geom1), geom2, GeoId1, GeoId2); + getSelection().clearSelection(); + return; + } + else if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfHyperbolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); + getSelection().clearSelection(); + return; + } + else if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); + getSelection().clearSelection(); + return; + } + } + else if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId())) { + + if (geom1->getTypeId() != Part::GeomArcOfHyperbola::getClassTypeId()) + std::swap(GeoId1, GeoId2); + + // GeoId1 is the arc of hyperbola + geom1 = Obj->getGeometry(GeoId1); + geom2 = Obj->getGeometry(GeoId2); + + if (geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfHyperbolaviaNewPoint( + Obj, + static_cast(geom1), + geom2, + GeoId1, + GeoId2); + getSelection().clearSelection(); + return; + } + else if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom2), + geom1, + GeoId2, + GeoId1); + getSelection().clearSelection(); + return; + } + } + else if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId())) { + + if (geom1->getTypeId() != Part::GeomArcOfParabola::getClassTypeId()) + std::swap(GeoId1, GeoId2); + + // GeoId1 is the arc of hyperbola + geom1 = Obj->getGeometry(GeoId1); + geom2 = Obj->getGeometry(GeoId2); + + if (geom2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add tangent constraint point")); + makeTangentToArcOfParabolaviaNewPoint( + Obj, + static_cast(geom1), + geom2, + GeoId1, + GeoId2); + getSelection().clearSelection(); + return; + } + } + + openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Tangent',%d,%d))", GeoId1, GeoId2); + commitCommand(); + tryAutoRecompute(Obj); + + return; + } + case 4:// {SelVertexOrRoot, SelEdge, SelEdgeOrAxis} + case 5:// {SelVertexOrRoot, SelEdgeOrAxis, SelEdge} + case 6:// {SelVertexOrRoot, SelEdge, SelExternalEdge} + case 7:// {SelVertexOrRoot, SelExternalEdge, SelEdge} + { + // let's sink the point to be GeoId3. + GeoId1 = selSeq.at(1).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(0).GeoId; + PosId3 = selSeq.at(0).PosId; + + break; + } + case 8: // {SelEdge, SelVertexOrRoot, SelEdgeOrAxis} + case 9: // {SelEdgeOrAxis, SelVertexOrRoot, SelEdge} + case 10:// {SelEdge, SelVertexOrRoot, SelExternalEdge} + case 11:// {SelExternalEdge, SelVertexOrRoot, SelEdge} + { + // let's sink the point to be GeoId3. + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(1).GeoId; + PosId3 = selSeq.at(1).PosId; + + break; + } + case 12:// {SelVertexOrRoot, SelVertex} + { + // Different notation than the previous places + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; + + // check if the edge already has a Block constraint + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; + } + + if (isSimpleVertex(Obj, GeoId1, PosId1) || isSimpleVertex(Obj, GeoId2, PosId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a tangency constraint at an unconnected point!")); + + return; + } + + // This code supports simple B-spline endpoint tangency to any other geometric curve + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); + + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() + || geom2->getTypeId() == Part::GeomBSplineCurve::getClassTypeId())) { + + if (geom1->getTypeId() != Part::GeomBSplineCurve::getClassTypeId()) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); + } + // GeoId1 is the B-spline now + }// end of code supports simple B-spline endpoint tangency + + openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Tangent',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); + commitCommand(); + tryAutoRecompute(Obj); + + getSelection().clearSelection(); + return; + } + default: + return; } if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { // check if the edge already has a Block constraint - if ( areBothPointsOrSegmentsFixed(Obj,GeoId1,GeoId2) ) { + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { showNoConstraintBetweenFixedGeometry(Obj); return; } - if(isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Add tangent constraint")); - bool safe = addConstraintSafely(Obj, [&](){ - //add missing point-on-object constraints - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + bool safe = addConstraintSafely(Obj, [&]() { + // add missing point-on-object constraints + if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - if(! IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId2); + if (!IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId2); }; - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){//FIXME: it's a good idea to add a check if the sketch is solved - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + if (!IsPointAlreadyOnCurve( + GeoId1, + GeoId3, + PosId3, + Obj)) {// FIXME: it's a good idea to add a check if the sketch is solved + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); }; - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", - GeoId1,GeoId2,GeoId3,static_cast(PosId3)); + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('TangentViaPoint',%d,%d,%d,%d))", + GeoId1, + GeoId2, + GeoId3, + static_cast(PosId3)); }); - if(!safe) + if (!safe) return; else { commitCommand(); @@ -4975,31 +5709,36 @@ void CmdSketcherConstrainTangent::applyConstraint(std::vector &selSeq // ====================================================================================== -class CmdSketcherConstrainRadius : public CmdSketcherConstraint +class CmdSketcherConstrainRadius: public CmdSketcherConstraint { public: CmdSketcherConstrainRadius(); - ~CmdSketcherConstrainRadius() override{} + ~CmdSketcherConstrainRadius() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainRadius"; } + { + return "CmdSketcherConstrainRadius"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainRadius::CmdSketcherConstrainRadius() - :CmdSketcherConstraint("Sketcher_ConstrainRadius") + : CmdSketcherConstraint("Sketcher_ConstrainRadius") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain radius or weight"); - sToolTipText = QT_TR_NOOP("Fix the radius of a circle or an arc or fix the weight of a pole of a B-Spline"); - sWhatsThis = "Sketcher_ConstrainRadius"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Radius"; - sAccel = "K, R"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain radius or weight"); + sToolTipText = QT_TR_NOOP( + "Fix the radius of a circle or an arc or fix the weight of a pole of a B-Spline"); + sWhatsThis = "Sketcher_ConstrainRadius"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Radius"; + sAccel = "K, R"; + eType = ForEdit; allowedSelSequences = {{SelEdge}, {SelExternalEdge}}; } @@ -5011,15 +5750,17 @@ void CmdSketcherConstrainRadius::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -5029,45 +5770,47 @@ void CmdSketcherConstrainRadius::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or more arcs or circles from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or more arcs or circles from the sketch.")); return; } // check for which selected geometry the constraint can be applied - std::vector< std::pair > geoIdRadiusMap; - std::vector< std::pair > externalGeoIdRadiusMap; + std::vector> geoIdRadiusMap; + std::vector> externalGeoIdRadiusMap; bool poles = false; bool nonpoles = false; - for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { bool issegmentfixed = false; int GeoId; - if (it->size() > 4 && it->substr(0,4) == "Edge") { - GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; - issegmentfixed = isPointOrSegmentFixed(Obj,GeoId); + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; + issegmentfixed = isPointOrSegmentFixed(Obj, GeoId); } - else if (it->size() > 4 && it->substr(0,12) == "ExternalEdge") { - GeoId = -std::atoi(it->substr(12,4000).c_str()) - 2; + else if (it->size() > 4 && it->substr(0, 12) == "ExternalEdge") { + GeoId = -std::atoi(it->substr(12, 4000).c_str()) - 2; issegmentfixed = true; } else continue; - const Part::Geometry *geom = Obj->getGeometry(GeoId); + const Part::Geometry* geom = Obj->getGeometry(GeoId); if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); + const Part::GeomArcOfCircle* arc = static_cast(geom); double radius = arc->getRadius(); - if(issegmentfixed) { + if (issegmentfixed) { externalGeoIdRadiusMap.emplace_back(GeoId, radius); } else { @@ -5077,17 +5820,17 @@ void CmdSketcherConstrainRadius::activated(int iMsg) nonpoles = true; } else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geom); + const Part::GeomCircle* circle = static_cast(geom); double radius = circle->getRadius(); - if(issegmentfixed) { + if (issegmentfixed) { externalGeoIdRadiusMap.emplace_back(GeoId, radius); } else { geoIdRadiusMap.emplace_back(GeoId, radius); } - if(isBsplinePole(geom)) + if (isBsplinePole(geom)) poles = true; else nonpoles = true; @@ -5095,219 +5838,250 @@ void CmdSketcherConstrainRadius::activated(int iMsg) } if (geoIdRadiusMap.empty() && externalGeoIdRadiusMap.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or more arcs or circles from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or more arcs or circles from the sketch.")); return; } - if(poles && nonpoles) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select either only one or more B-Spline poles or only one or more arcs or circles from the sketch, but not mixed.")); + if (poles && nonpoles) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select either only one or more B-Spline poles or only one or more arcs or " + "circles from the sketch, but not mixed.")); return; } - bool commitNeeded=false; - bool updateNeeded=false; - bool commandopened=false; + bool commitNeeded = false; + bool updateNeeded = false; + bool commandopened = false; - if(!externalGeoIdRadiusMap.empty()) { + if (!externalGeoIdRadiusMap.empty()) { // Create the non-driving radius constraints now openCommand(QT_TRANSLATE_NOOP("Command", "Add radius constraint")); - commandopened=true; + commandopened = true; unsigned int constrSize = 0; - for (std::vector< std::pair >::iterator it = externalGeoIdRadiusMap.begin(); it != externalGeoIdRadiusMap.end(); ++it) { + for (std::vector>::iterator it = externalGeoIdRadiusMap.begin(); + it != externalGeoIdRadiusMap.end(); + ++it) { - if(nonpoles) - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('Radius',%d,%f))", - it->first,it->second); + if (nonpoles) + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Radius',%d,%f))", + it->first, + it->second); else - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('Weight',%d,%f))", - it->first,it->second); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Weight',%d,%f))", + it->first, + it->second); - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - constrSize=ConStr.size(); + constrSize = ConStr.size(); - Gui::cmdAppObjectArgs(selection[0].getObject(),"setDriving(%d,%s)", constrSize-1,"False"); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", constrSize - 1, "False"); } - finishDatumConstraint (this, Obj, false, externalGeoIdRadiusMap.size()); + finishDatumConstraint(this, Obj, false, externalGeoIdRadiusMap.size()); - commitNeeded=true; - updateNeeded=true; + commitNeeded = true; + updateNeeded = true; } - if(!geoIdRadiusMap.empty()) - { - if (geoIdRadiusMap.size() > 1 && constraintCreationMode==Driving) { + if (!geoIdRadiusMap.empty()) { + if (geoIdRadiusMap.size() > 1 && constraintCreationMode == Driving) { int refGeoId = geoIdRadiusMap.front().first; double radius = geoIdRadiusMap.front().second; - if(!commandopened) + if (!commandopened) openCommand(QT_TRANSLATE_NOOP("Command", "Add radius constraint")); // Add the equality constraints - for (std::vector< std::pair >::iterator it = geoIdRadiusMap.begin()+1; it != geoIdRadiusMap.end(); ++it) { + for (std::vector>::iterator it = geoIdRadiusMap.begin() + 1; + it != geoIdRadiusMap.end(); + ++it) { Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Equal',%d,%d))", - refGeoId,it->first); + "addConstraint(Sketcher.Constraint('Equal',%d,%d))", + refGeoId, + it->first); } - if(nonpoles) - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Radius',%d,%f))", - refGeoId,radius); + if (nonpoles) + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Radius',%d,%f))", + refGeoId, + radius); else - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Weight',%d,%f))", - refGeoId,radius); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Weight',%d,%f))", + refGeoId, + radius); } else { // Create the radius constraints now - if(!commandopened) + if (!commandopened) openCommand(QT_TRANSLATE_NOOP("Command", "Add radius constraint")); - for (std::vector< std::pair >::iterator it = geoIdRadiusMap.begin(); it != geoIdRadiusMap.end(); ++it) { - if(nonpoles) - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Radius',%d,%f))", - it->first,it->second); + for (std::vector>::iterator it = geoIdRadiusMap.begin(); + it != geoIdRadiusMap.end(); + ++it) { + if (nonpoles) + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Radius',%d,%f))", + it->first, + it->second); else - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Weight',%d,%f))", - it->first,it->second); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Weight',%d,%f))", + it->first, + it->second); - if (constraintCreationMode==Reference) { - const std::vector &ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", ConStr.size()-1,"False"); + if (constraintCreationMode == Reference) { + const std::vector& ConStr = Obj->Constraints.getValues(); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); } } } - finishDatumConstraint (this, Obj, constraintCreationMode==Driving); + finishDatumConstraint(this, Obj, constraintCreationMode == Driving); - //updateActive(); + // updateActive(); getSelection().clearSelection(); } if (commitNeeded) commitCommand(); - if(updateNeeded) { - tryAutoRecomputeIfNotSolve(Obj); // we have to update the solver after this aborted addition. + if (updateNeeded) { + tryAutoRecomputeIfNotSolve(Obj);// we have to update the solver after this aborted addition. } } -void CmdSketcherConstrainRadius::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainRadius::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId = selSeq.at(0).GeoId; double radius = 0.0; - bool updateNeeded=false; + bool updateNeeded = false; switch (seqIndex) { - case 0: // {SelEdge} - case 1: // {SelExternalEdge} - { - const Part::Geometry *geom = Obj->getGeometry(GeoId); - if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); - radius = arc->getRadius(); + case 0:// {SelEdge} + case 1:// {SelExternalEdge} + { + const Part::Geometry* geom = Obj->getGeometry(GeoId); + if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = static_cast(geom); + radius = arc->getRadius(); + } + else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = static_cast(geom); + radius = circle->getRadius(); + } + else { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Constraint only applies to arcs or circles.")); + + return; + } + + // Create the radius constraint now + openCommand(QT_TRANSLATE_NOOP("Command", "Add radius constraint")); + + bool ispole = isBsplinePole(geom); + + if (ispole) + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", GeoId, radius); + else + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", GeoId, radius); + + const std::vector& ConStr = Obj->Constraints.getValues(); + + bool fixed = isPointOrSegmentFixed(Obj, GeoId); + if (fixed || constraintCreationMode == Reference) { + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + + updateNeeded = true;// We do need to update the solver DoF after setting the + // constraint driving. + } + + finishDatumConstraint(this, Obj, constraintCreationMode == Driving && !fixed); + + // updateActive(); + getSelection().clearSelection(); + + commitCommand(); + + if (updateNeeded) { + tryAutoRecomputeIfNotSolve( + Obj);// we have to update the solver after this aborted addition. + } } - else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geom); - radius = circle->getRadius(); - } - else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Constraint only applies to arcs or circles.")); - - return; - } - - // Create the radius constraint now - openCommand(QT_TRANSLATE_NOOP("Command", "Add radius constraint")); - - bool ispole = isBsplinePole(geom); - - if(ispole) - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", - GeoId, radius); - else - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", - GeoId, radius); - - const std::vector &ConStr = Obj->Constraints.getValues(); - - bool fixed = isPointOrSegmentFixed(Obj,GeoId); - if(fixed || constraintCreationMode==Reference) { - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", - ConStr.size()-1, "False"); - - updateNeeded=true; // We do need to update the solver DoF after setting the constraint driving. - } - - finishDatumConstraint (this, Obj, constraintCreationMode==Driving && !fixed); - - //updateActive(); - getSelection().clearSelection(); - - commitCommand(); - - if(updateNeeded) { - tryAutoRecomputeIfNotSolve(Obj); // we have to update the solver after this aborted addition. - } - } } } void CmdSketcherConstrainRadius::updateAction(int mode) { switch (mode) { - case Reference: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Radius_Driven")); - break; - case Driving: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Radius")); - break; + case Reference: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_Radius_Driven")); + break; + case Driving: + if (getAction()) + getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Radius")); + break; } } // ====================================================================================== -class CmdSketcherConstrainDiameter : public CmdSketcherConstraint +class CmdSketcherConstrainDiameter: public CmdSketcherConstraint { public: CmdSketcherConstrainDiameter(); - ~CmdSketcherConstrainDiameter() override{} + ~CmdSketcherConstrainDiameter() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainDiameter"; } + { + return "CmdSketcherConstrainDiameter"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainDiameter::CmdSketcherConstrainDiameter() -:CmdSketcherConstraint("Sketcher_ConstrainDiameter") + : CmdSketcherConstraint("Sketcher_ConstrainDiameter") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain diameter"); - sToolTipText = QT_TR_NOOP("Fix the diameter of a circle or an arc"); - sWhatsThis = "Sketcher_ConstrainDiameter"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Diameter"; - sAccel = "K, O"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain diameter"); + sToolTipText = QT_TR_NOOP("Fix the diameter of a circle or an arc"); + sWhatsThis = "Sketcher_ConstrainDiameter"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Diameter"; + sAccel = "K, O"; + eType = ForEdit; allowedSelSequences = {{SelEdge}, {SelExternalEdge}}; } @@ -5319,15 +6093,17 @@ void CmdSketcherConstrainDiameter::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -5337,216 +6113,233 @@ void CmdSketcherConstrainDiameter::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or more arcs or circles from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or more arcs or circles from the sketch.")); return; } // check for which selected geometry the constraint can be applied - std::vector< std::pair > geoIdDiameterMap; - std::vector< std::pair > externalGeoIdDiameterMap; + std::vector> geoIdDiameterMap; + std::vector> externalGeoIdDiameterMap; - for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { bool issegmentfixed = false; int GeoId; - if (it->size() > 4 && it->substr(0,4) == "Edge") { - GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; - issegmentfixed = isPointOrSegmentFixed(Obj,GeoId); + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; + issegmentfixed = isPointOrSegmentFixed(Obj, GeoId); } - else if (it->size() > 4 && it->substr(0,12) == "ExternalEdge") { - GeoId = -std::atoi(it->substr(12,4000).c_str()) - 2; + else if (it->size() > 4 && it->substr(0, 12) == "ExternalEdge") { + GeoId = -std::atoi(it->substr(12, 4000).c_str()) - 2; issegmentfixed = true; } else continue; - const Part::Geometry *geom = Obj->getGeometry(GeoId); + const Part::Geometry* geom = Obj->getGeometry(GeoId); if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); + const Part::GeomArcOfCircle* arc = static_cast(geom); double radius = arc->getRadius(); - if(issegmentfixed) { - externalGeoIdDiameterMap.emplace_back(GeoId, 2*radius); + if (issegmentfixed) { + externalGeoIdDiameterMap.emplace_back(GeoId, 2 * radius); } else { - geoIdDiameterMap.emplace_back(GeoId, 2*radius); + geoIdDiameterMap.emplace_back(GeoId, 2 * radius); } } else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geom); + const Part::GeomCircle* circle = static_cast(geom); double radius = circle->getRadius(); - if(isBsplinePole(geom)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(geom)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); continue; } - if(issegmentfixed) { - externalGeoIdDiameterMap.emplace_back(GeoId, 2*radius); + if (issegmentfixed) { + externalGeoIdDiameterMap.emplace_back(GeoId, 2 * radius); } else { - geoIdDiameterMap.emplace_back(GeoId, 2*radius); + geoIdDiameterMap.emplace_back(GeoId, 2 * radius); } } } if (geoIdDiameterMap.empty() && externalGeoIdDiameterMap.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or more arcs or circles from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or more arcs or circles from the sketch.")); return; } - bool commitNeeded=false; - bool updateNeeded=false; - bool commandopened=false; + bool commitNeeded = false; + bool updateNeeded = false; + bool commandopened = false; - if(!externalGeoIdDiameterMap.empty()) { + if (!externalGeoIdDiameterMap.empty()) { // Create the non-driving radius constraints now openCommand(QT_TRANSLATE_NOOP("Command", "Add diameter constraint")); - commandopened=true; + commandopened = true; unsigned int constrSize = 0; - for (std::vector< std::pair >::iterator it = externalGeoIdDiameterMap.begin(); it != externalGeoIdDiameterMap.end(); ++it) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", it->first,it->second); + for (std::vector>::iterator it = externalGeoIdDiameterMap.begin(); + it != externalGeoIdDiameterMap.end(); + ++it) { + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", it->first, it->second); - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - constrSize=ConStr.size(); + constrSize = ConStr.size(); - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)",constrSize-1,"False"); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", constrSize - 1, "False"); } - finishDatumConstraint (this, Obj, false, externalGeoIdDiameterMap.size()); + finishDatumConstraint(this, Obj, false, externalGeoIdDiameterMap.size()); - commitNeeded=true; - updateNeeded=true; + commitNeeded = true; + updateNeeded = true; } - if(!geoIdDiameterMap.empty()) - { - if (geoIdDiameterMap.size() > 1 && constraintCreationMode==Driving) { + if (!geoIdDiameterMap.empty()) { + if (geoIdDiameterMap.size() > 1 && constraintCreationMode == Driving) { int refGeoId = geoIdDiameterMap.front().first; double diameter = geoIdDiameterMap.front().second; - if(!commandopened) + if (!commandopened) openCommand(QT_TRANSLATE_NOOP("Command", "Add diameter constraint")); // Add the equality constraints - for (std::vector< std::pair >::iterator it = geoIdDiameterMap.begin()+1; it != geoIdDiameterMap.end(); ++it) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Equal',%d,%d))", refGeoId,it->first); + for (std::vector>::iterator it = geoIdDiameterMap.begin() + 1; + it != geoIdDiameterMap.end(); + ++it) { + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Equal',%d,%d))", refGeoId, it->first); } - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", refGeoId,diameter); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", refGeoId, diameter); } else { // Create the diameter constraints now - if(!commandopened) + if (!commandopened) openCommand(QT_TRANSLATE_NOOP("Command", "Add diameter constraint")); - for (std::vector< std::pair >::iterator it = geoIdDiameterMap.begin(); it != geoIdDiameterMap.end(); ++it) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", - it->first,it->second); + for (std::vector>::iterator it = geoIdDiameterMap.begin(); + it != geoIdDiameterMap.end(); + ++it) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", + it->first, + it->second); - if(constraintCreationMode==Reference) { + if (constraintCreationMode == Reference) { - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size()-1,"False"); + const std::vector& ConStr = Obj->Constraints.getValues(); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); } - } } - finishDatumConstraint (this, Obj, constraintCreationMode==Driving); + finishDatumConstraint(this, Obj, constraintCreationMode == Driving); - //updateActive(); + // updateActive(); getSelection().clearSelection(); } if (commitNeeded) commitCommand(); - if(updateNeeded) { - tryAutoRecomputeIfNotSolve(Obj); // we have to update the solver after this aborted addition. + if (updateNeeded) { + tryAutoRecomputeIfNotSolve(Obj);// we have to update the solver after this aborted addition. } } -void CmdSketcherConstrainDiameter::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainDiameter::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId = selSeq.at(0).GeoId; double diameter = 0.0; - bool updateNeeded=false; + bool updateNeeded = false; switch (seqIndex) { - case 0: // {SelEdge} - case 1: // {SelExternalEdge} + case 0:// {SelEdge} + case 1:// {SelExternalEdge} { - const Part::Geometry *geom = Obj->getGeometry(GeoId); + const Part::Geometry* geom = Obj->getGeometry(GeoId); if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); - diameter = 2*arc->getRadius(); + const Part::GeomArcOfCircle* arc = static_cast(geom); + diameter = 2 * arc->getRadius(); } else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geom); - diameter = 2*circle->getRadius(); + const Part::GeomCircle* circle = static_cast(geom); + diameter = 2 * circle->getRadius(); } else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Constraint only applies to arcs or circles.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Constraint only applies to arcs or circles.")); return; } - if(isBsplinePole(geom)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(geom)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } // Create the diameter constraint now openCommand(QT_TRANSLATE_NOOP("Command", "Add diameter constraint")); - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", - GeoId, diameter); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", GeoId, diameter); - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - bool fixed = isPointOrSegmentFixed(Obj,GeoId); - if(fixed || constraintCreationMode==Reference) { - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size()-1, "False"); - updateNeeded=true; // We do need to update the solver DoF after setting the constraint driving. + bool fixed = isPointOrSegmentFixed(Obj, GeoId); + if (fixed || constraintCreationMode == Reference) { + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + updateNeeded = true;// We do need to update the solver DoF after setting the + // constraint driving. } - finishDatumConstraint (this, Obj, constraintCreationMode==Driving && !fixed); + finishDatumConstraint(this, Obj, constraintCreationMode == Driving && !fixed); - //updateActive(); + // updateActive(); getSelection().clearSelection(); commitCommand(); - if(updateNeeded) { - tryAutoRecomputeIfNotSolve(Obj); // we have to update the solver after this aborted addition. + if (updateNeeded) { + tryAutoRecomputeIfNotSolve( + Obj);// we have to update the solver after this aborted addition. } } } @@ -5557,7 +6350,8 @@ void CmdSketcherConstrainDiameter::updateAction(int mode) switch (mode) { case Reference: if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Diameter_Driven")); + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_Diameter_Driven")); break; case Driving: if (getAction()) @@ -5568,31 +6362,36 @@ void CmdSketcherConstrainDiameter::updateAction(int mode) // ====================================================================================== -class CmdSketcherConstrainRadiam : public CmdSketcherConstraint +class CmdSketcherConstrainRadiam: public CmdSketcherConstraint { public: CmdSketcherConstrainRadiam(); - ~CmdSketcherConstrainRadiam() override{} + ~CmdSketcherConstrainRadiam() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainRadiam"; } + { + return "CmdSketcherConstrainRadiam"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainRadiam::CmdSketcherConstrainRadiam() -:CmdSketcherConstraint("Sketcher_ConstrainRadiam") + : CmdSketcherConstraint("Sketcher_ConstrainRadiam") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain auto radius/diameter"); - sToolTipText = QT_TR_NOOP("Fix the diameter if a circle is chosen, or the radius if an arc/spline pole is chosen"); - sWhatsThis = "Sketcher_ConstrainRadiam"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Radiam"; - sAccel = "K, S"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain auto radius/diameter"); + sToolTipText = QT_TR_NOOP( + "Fix the diameter if a circle is chosen, or the radius if an arc/spline pole is chosen"); + sWhatsThis = "Sketcher_ConstrainRadiam"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Radiam"; + sAccel = "K, S"; + eType = ForEdit; allowedSelSequences = {{SelEdge}, {SelExternalEdge}}; } @@ -5604,15 +6403,17 @@ void CmdSketcherConstrainRadiam::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -5622,51 +6423,53 @@ void CmdSketcherConstrainRadiam::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or more arcs or circles from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or more arcs or circles from the sketch.")); return; } // check for which selected geometry the constraint can be applied - std::vector< std::pair > geoIdRadiamMap; - std::vector< std::pair > externalGeoIdRadiamMap; + std::vector> geoIdRadiamMap; + std::vector> externalGeoIdRadiamMap; bool poles = false; bool nonpoles = false; - for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { bool issegmentfixed = false; int GeoId; - if (it->size() > 4 && it->substr(0,4) == "Edge") { - GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; - issegmentfixed = isPointOrSegmentFixed(Obj,GeoId); + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; + issegmentfixed = isPointOrSegmentFixed(Obj, GeoId); } - else if (it->size() > 4 && it->substr(0,12) == "ExternalEdge") { - GeoId = -std::atoi(it->substr(12,4000).c_str()) - 2; + else if (it->size() > 4 && it->substr(0, 12) == "ExternalEdge") { + GeoId = -std::atoi(it->substr(12, 4000).c_str()) - 2; issegmentfixed = true; } else continue; - const Part::Geometry *geom = Obj->getGeometry(GeoId); + const Part::Geometry* geom = Obj->getGeometry(GeoId); double radius; if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arcir = static_cast(geom); + const Part::GeomArcOfCircle* arcir = static_cast(geom); radius = arcir->getRadius(); nonpoles = true; } else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *arcir = static_cast(geom); + const Part::GeomCircle* arcir = static_cast(geom); radius = arcir->getRadius(); - if(isBsplinePole(geom)) + if (isBsplinePole(geom)) poles = true; else nonpoles = true; @@ -5674,7 +6477,7 @@ void CmdSketcherConstrainRadiam::activated(int iMsg) else continue; - if(issegmentfixed) { + if (issegmentfixed) { externalGeoIdRadiamMap.emplace_back(GeoId, radius); } else { @@ -5683,158 +6486,190 @@ void CmdSketcherConstrainRadiam::activated(int iMsg) } if (geoIdRadiamMap.empty() && externalGeoIdRadiamMap.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or more arcs or circles from the sketch.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or more arcs or circles from the sketch.")); return; } - if(poles && nonpoles) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select either only one or more B-Spline poles or only one or more arcs or circles from the sketch, but not mixed.")); + if (poles && nonpoles) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select either only one or more B-Spline poles or only one or more arcs or " + "circles from the sketch, but not mixed.")); return; } - bool commitNeeded=false; - bool updateNeeded=false; - bool commandopened=false; + bool commitNeeded = false; + bool updateNeeded = false; + bool commandopened = false; - if(!externalGeoIdRadiamMap.empty()) { + if (!externalGeoIdRadiamMap.empty()) { // Create the non-driving radiam constraints now openCommand(QT_TRANSLATE_NOOP("Command", "Add radiam constraint")); - commandopened=true; + commandopened = true; unsigned int constrSize = 0; - for (std::vector< std::pair >::iterator it = externalGeoIdRadiamMap.begin(); it != externalGeoIdRadiamMap.end(); ++it) { - if (Obj->getGeometry(it->first)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - if(nonpoles) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", it->first, it->second); + for (std::vector>::iterator it = externalGeoIdRadiamMap.begin(); + it != externalGeoIdRadiamMap.end(); + ++it) { + if (Obj->getGeometry(it->first)->getTypeId() + == Part::GeomArcOfCircle::getClassTypeId()) { + if (nonpoles) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f))", + it->first, + it->second); } else { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", it->first, it->second); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Weight',%d,%f))", + it->first, + it->second); } } - else - { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", it->first, it->second*2); + else { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", + it->first, + it->second * 2); } - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - constrSize=ConStr.size(); + constrSize = ConStr.size(); - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)",constrSize-1,"False"); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", constrSize - 1, "False"); } - finishDatumConstraint (this, Obj, false, externalGeoIdRadiamMap.size()); + finishDatumConstraint(this, Obj, false, externalGeoIdRadiamMap.size()); - commitNeeded=true; - updateNeeded=true; + commitNeeded = true; + updateNeeded = true; } - if(!geoIdRadiamMap.empty()) - { - if (geoIdRadiamMap.size() > 1 && constraintCreationMode==Driving) { + if (!geoIdRadiamMap.empty()) { + if (geoIdRadiamMap.size() > 1 && constraintCreationMode == Driving) { int refGeoId = geoIdRadiamMap.front().first; double radiam = geoIdRadiamMap.front().second; - if(!commandopened) + if (!commandopened) openCommand(QT_TRANSLATE_NOOP("Command", "Add radiam constraint")); // Add the equality constraints - for (std::vector< std::pair >::iterator it = geoIdRadiamMap.begin()+1; it != geoIdRadiamMap.end(); ++it) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Equal',%d,%d))", refGeoId,it->first); + for (std::vector>::iterator it = geoIdRadiamMap.begin() + 1; + it != geoIdRadiamMap.end(); + ++it) { + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Equal',%d,%d))", refGeoId, it->first); } - if(poles) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", refGeoId, radiam); + if (poles) { + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", refGeoId, radiam); } - else if (Obj->getGeometry(refGeoId)->getTypeId() == Part::GeomCircle::getClassTypeId()) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", refGeoId, radiam*2); + else if (Obj->getGeometry(refGeoId)->getTypeId() + == Part::GeomCircle::getClassTypeId()) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", + refGeoId, + radiam * 2); } - else - { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", refGeoId, radiam); + else { + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", refGeoId, radiam); } } else { // Create the radiam constraints now - if(!commandopened) + if (!commandopened) openCommand(QT_TRANSLATE_NOOP("Command", "Add radiam constraint")); - for (std::vector< std::pair >::iterator it = geoIdRadiamMap.begin(); it != geoIdRadiamMap.end(); ++it) { - if(poles) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", it->first, it->second); + for (std::vector>::iterator it = geoIdRadiamMap.begin(); + it != geoIdRadiamMap.end(); + ++it) { + if (poles) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Weight',%d,%f))", + it->first, + it->second); } - else if (Obj->getGeometry(it->first)->getTypeId() == Part::GeomCircle::getClassTypeId()) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", it->first, it->second*2); + else if (Obj->getGeometry(it->first)->getTypeId() + == Part::GeomCircle::getClassTypeId()) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", + it->first, + it->second * 2); } - else - { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", it->first, it->second); + else { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f))", + it->first, + it->second); } - if(constraintCreationMode==Reference) { + if (constraintCreationMode == Reference) { - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size()-1,"False"); + const std::vector& ConStr = Obj->Constraints.getValues(); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); } - } } - finishDatumConstraint (this, Obj, constraintCreationMode==Driving); + finishDatumConstraint(this, Obj, constraintCreationMode == Driving); - //updateActive(); + // updateActive(); getSelection().clearSelection(); } if (commitNeeded) commitCommand(); - if(updateNeeded) { - tryAutoRecomputeIfNotSolve(Obj); // we have to update the solver after this aborted addition. + if (updateNeeded) { + tryAutoRecomputeIfNotSolve(Obj);// we have to update the solver after this aborted addition. } } -void CmdSketcherConstrainRadiam::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainRadiam::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId = selSeq.at(0).GeoId; double radiam = 0.0; - bool updateNeeded=false; + bool updateNeeded = false; bool isCircle = false; bool isPole = false; switch (seqIndex) { - case 0: // {SelEdge} - case 1: // {SelExternalEdge} + case 0:// {SelEdge} + case 1:// {SelExternalEdge} { - const Part::Geometry *geom = Obj->getGeometry(GeoId); + const Part::Geometry* geom = Obj->getGeometry(GeoId); if (geom && geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); + const Part::GeomArcOfCircle* arc = static_cast(geom); radiam = arc->getRadius(); } else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geom); + const Part::GeomCircle* circle = static_cast(geom); radiam = circle->getRadius(); isCircle = true; if (isBsplinePole(geom)) isPole = true; } else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Constraint only applies to arcs or circles.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Constraint only applies to arcs or circles.")); return; } @@ -5843,32 +6678,37 @@ void CmdSketcherConstrainRadiam::applyConstraint(std::vector &selSeq, openCommand(QT_TRANSLATE_NOOP("Command", "Add radiam constraint")); if (isPole) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", GeoId, radiam); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Weight',%d,%f))", GeoId, radiam); } else if (isCircle) { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", GeoId, radiam*2); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Diameter',%d,%f))", GeoId, radiam * 2); } else { - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", GeoId, radiam); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Radius',%d,%f))", GeoId, radiam); } - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - bool fixed = isPointOrSegmentFixed(Obj,GeoId); - if(fixed || constraintCreationMode==Reference) { - Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size()-1, "False"); - updateNeeded=true; // We do need to update the solver DoF after setting the constraint driving. + bool fixed = isPointOrSegmentFixed(Obj, GeoId); + if (fixed || constraintCreationMode == Reference) { + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + updateNeeded = true;// We do need to update the solver DoF after setting the + // constraint driving. } - finishDatumConstraint (this, Obj, constraintCreationMode==Driving && !fixed); + finishDatumConstraint(this, Obj, constraintCreationMode == Driving && !fixed); - //updateActive(); + // updateActive(); getSelection().clearSelection(); commitCommand(); - if(updateNeeded) { - tryAutoRecomputeIfNotSolve(Obj); // we have to update the solver after this aborted addition. + if (updateNeeded) { + tryAutoRecomputeIfNotSolve( + Obj);// we have to update the solver after this aborted addition. } } } @@ -5879,7 +6719,8 @@ void CmdSketcherConstrainRadiam::updateAction(int mode) switch (mode) { case Reference: if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_Radiam_Driven")); + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_Radiam_Driven")); break; case Driving: if (getAction()) @@ -5893,35 +6734,36 @@ void CmdSketcherConstrainRadiam::updateAction(int mode) DEF_STD_CMD_ACLU(CmdSketcherCompConstrainRadDia) CmdSketcherCompConstrainRadDia::CmdSketcherCompConstrainRadDia() -: Command("Sketcher_CompConstrainRadDia") + : Command("Sketcher_CompConstrainRadDia") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain arc or circle"); - sToolTipText = QT_TR_NOOP("Constrain an arc or a circle"); - sWhatsThis = "Sketcher_CompConstrainRadDia"; - sStatusTip = sToolTipText; - sAccel = "R"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain arc or circle"); + sToolTipText = QT_TR_NOOP("Constrain an arc or a circle"); + sWhatsThis = "Sketcher_CompConstrainRadDia"; + sStatusTip = sToolTipText; + sAccel = "R"; + eType = ForEdit; } void CmdSketcherCompConstrainRadDia::activated(int iMsg) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); - if (iMsg==0) { + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); + if (iMsg == 0) { rcCmdMgr.runCommandByName("Sketcher_ConstrainRadius"); } - else if (iMsg==1) { + else if (iMsg == 1) { rcCmdMgr.runCommandByName("Sketcher_ConstrainDiameter"); } - else if (iMsg==2) { + else if (iMsg == 2) { rcCmdMgr.runCommandByName("Sketcher_ConstrainRadiam"); } else return; - //Save new choice as default - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + // Save new choice as default + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); hGrp->SetInt("CurRadDiaCons", iMsg); // Since the default icon is reset when enabling/disabling the command we have @@ -5933,7 +6775,7 @@ void CmdSketcherCompConstrainRadDia::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompConstrainRadDia::createAction() +Gui::Action* CmdSketcherCompConstrainRadDia::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -5949,7 +6791,8 @@ Gui::Action * CmdSketcherCompConstrainRadDia::createAction() _pcAction = pcAction; languageChange(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); int curRadDiaCons = hGrp->GetInt("CurRadDiaCons", 2); switch (curRadDiaCons) { @@ -6004,16 +6847,23 @@ void CmdSketcherCompConstrainRadDia::languageChange() QAction* arc1 = a[0]; arc1->setText(QApplication::translate("CmdSketcherCompConstrainRadDia", "Constrain radius")); - arc1->setToolTip(QApplication::translate("Sketcher_ConstrainRadius", "Fix the radius of a circle or an arc")); - arc1->setStatusTip(QApplication::translate("Sketcher_ConstrainRadius", "Fix the radius of a circle or an arc")); + arc1->setToolTip(QApplication::translate("Sketcher_ConstrainRadius", + "Fix the radius of a circle or an arc")); + arc1->setStatusTip(QApplication::translate("Sketcher_ConstrainRadius", + "Fix the radius of a circle or an arc")); QAction* arc2 = a[1]; arc2->setText(QApplication::translate("CmdSketcherCompConstrainRadDia", "Constrain diameter")); - arc2->setToolTip(QApplication::translate("Sketcher_ConstrainDiameter", "Fix the diameter of a circle or an arc")); - arc2->setStatusTip(QApplication::translate("Sketcher_ConstrainDiameter", "Fix the diameter of a circle or an arc")); + arc2->setToolTip(QApplication::translate("Sketcher_ConstrainDiameter", + "Fix the diameter of a circle or an arc")); + arc2->setStatusTip(QApplication::translate("Sketcher_ConstrainDiameter", + "Fix the diameter of a circle or an arc")); QAction* arc3 = a[2]; - arc3->setText(QApplication::translate("CmdSketcherCompConstrainRadDia", "Constrain auto radius/diameter")); - arc3->setToolTip(QApplication::translate("Sketcher_ConstraintRadiam", "Fix the radius/diameter of a circle or an arc")); - arc3->setStatusTip(QApplication::translate("Sketcher_ConstrainRadiam", "Fix the radius/diameter of a circle or an arc")); + arc3->setText(QApplication::translate("CmdSketcherCompConstrainRadDia", + "Constrain auto radius/diameter")); + arc3->setToolTip(QApplication::translate("Sketcher_ConstraintRadiam", + "Fix the radius/diameter of a circle or an arc")); + arc3->setStatusTip(QApplication::translate("Sketcher_ConstrainRadiam", + "Fix the radius/diameter of a circle or an arc")); } bool CmdSketcherCompConstrainRadDia::isActive() @@ -6023,34 +6873,40 @@ bool CmdSketcherCompConstrainRadDia::isActive() // ====================================================================================== -class CmdSketcherConstrainAngle : public CmdSketcherConstraint +class CmdSketcherConstrainAngle: public CmdSketcherConstraint { public: CmdSketcherConstrainAngle(); - ~CmdSketcherConstrainAngle() override{} + ~CmdSketcherConstrainAngle() override + {} void updateAction(int mode) override; const char* className() const override - { return "CmdSketcherConstrainAngle"; } + { + return "CmdSketcherConstrainAngle"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainAngle::CmdSketcherConstrainAngle() - :CmdSketcherConstraint("Sketcher_ConstrainAngle") + : CmdSketcherConstraint("Sketcher_ConstrainAngle") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain angle"); - sToolTipText = QT_TR_NOOP("Fix the angle of a line or the angle between two lines"); - sWhatsThis = "Sketcher_ConstrainAngle"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_InternalAngle"; - sAccel = "K, A"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain angle"); + sToolTipText = QT_TR_NOOP("Fix the angle of a line or the angle between two lines"); + sWhatsThis = "Sketcher_ConstrainAngle"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_InternalAngle"; + sAccel = "K, A"; + eType = ForEdit; - allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, {SelEdgeOrAxis, SelEdge}, - {SelEdge, SelExternalEdge}, {SelExternalEdge, SelEdge}, + allowedSelSequences = {{SelEdge, SelEdgeOrAxis}, + {SelEdgeOrAxis, SelEdge}, + {SelEdge, SelExternalEdge}, + {SelExternalEdge, SelEdge}, {SelExternalEdge, SelExternalEdge}, {SelEdge, SelVertexOrRoot, SelEdgeOrAxis}, {SelEdgeOrAxis, SelVertexOrRoot, SelEdge}, @@ -6067,20 +6923,22 @@ CmdSketcherConstrainAngle::CmdSketcherConstrainAngle() void CmdSketcherConstrainAngle::activated(int iMsg) { Q_UNUSED(iMsg); - //TODO: comprehensive messages, like in CmdSketcherConstrainTangent - // get the selection + // TODO: comprehensive messages, like in CmdSketcherConstrainTangent + // get the selection std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { // TODO: Get the exact message from git history and put it here Gui::TranslatedUserWarning(getActiveGuiDocument(), QObject::tr("Wrong selection"), @@ -6090,46 +6948,50 @@ void CmdSketcherConstrainAngle::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.empty() || SubNames.size() > 3) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or two lines from the sketch. Or select two edges and a point.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "Select one or two lines from the sketch. Or select two edges and a point.")); return; } - int GeoId1, GeoId2=GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; - Sketcher::PointPos PosId1, PosId2=Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; + int GeoId1, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; + Sketcher::PointPos PosId1, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; getIdsFromName(SubNames[0], Obj, GeoId1, PosId1); if (SubNames.size() > 1) getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); if (SubNames.size() > 2) getIdsFromName(SubNames[2], Obj, GeoId3, PosId3); - if (SubNames.size() == 3){//standalone implementation of angle-via-point + if (SubNames.size() == 3) {// standalone implementation of angle-via-point - //let's sink the point to be GeoId3. We want to keep the order the two curves have been selected in. - if ( isVertex(GeoId1, PosId1) ){ - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + // let's sink the point to be GeoId3. We want to keep the order the two curves have been + // selected in. + if (isVertex(GeoId1, PosId1)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); }; - if ( isVertex(GeoId2, PosId2) ){ - std::swap(GeoId2,GeoId3); - std::swap(PosId2,PosId3); + if (isVertex(GeoId2, PosId2)) { + std::swap(GeoId2, GeoId3); + std::swap(PosId2, PosId3); }; - bool bothexternal=areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); + bool bothexternal = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { - if(isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } @@ -6137,74 +6999,102 @@ void CmdSketcherConstrainAngle::activated(int iMsg) openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); - //add missing point-on-object constraints + // add missing point-on-object constraints if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); } if (!IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)) { - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId2); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId2); } - if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) {//FIXME: it's a good idea to add a check if the sketch is solved - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + if (!IsPointAlreadyOnCurve( + GeoId1, + GeoId3, + PosId3, + Obj)) {// FIXME: it's a good idea to add a check if the sketch is solved + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); } - //assuming point-on-curves have been solved, calculate the angle. - //DeepSOIC: this may be slow, but I wanted to reuse the conversion - //from Geometry to GCS shapes that is done in Sketch - Base::Vector3d p = Obj->getPoint(GeoId3, PosId3 ); - ActAngle = Obj->calculateAngleViaPoint(GeoId1,GeoId2,p.x,p.y); + // assuming point-on-curves have been solved, calculate the angle. + // DeepSOIC: this may be slow, but I wanted to reuse the conversion + // from Geometry to GCS shapes that is done in Sketch + Base::Vector3d p = Obj->getPoint(GeoId3, PosId3); + ActAngle = Obj->calculateAngleViaPoint(GeoId1, GeoId2, p.x, p.y); - //negative constraint value avoidance - if (ActAngle < -Precision::Angular()){ + // negative constraint value avoidance + if (ActAngle < -Precision::Angular()) { std::swap(GeoId1, GeoId2); std::swap(PosId1, PosId2); ActAngle = -ActAngle; } - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('AngleViaPoint',%d,%d,%d,%d,%f))", - GeoId1,GeoId2,GeoId3,static_cast(PosId3),ActAngle); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('AngleViaPoint',%d,%d,%d,%d,%f))", + GeoId1, + GeoId2, + GeoId3, + static_cast(PosId3), + ActAngle); - if (bothexternal || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (bothexternal + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(),"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; }; - - } else if (SubNames.size() < 3) { + } + else if (SubNames.size() < 3) { bool bothexternal = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); - if (isVertex(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + if (isVertex(GeoId1, PosId1) && isEdge(GeoId2, PosId2)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - if(isBsplinePole(Obj, GeoId1) || (GeoId2 != GeoEnum::GeoUndef && isBsplinePole(Obj, GeoId2))) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) + || (GeoId2 != GeoEnum::GeoUndef && isBsplinePole(Obj, GeoId2))) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } - if (isEdge(GeoId2,PosId2)) { // line to line angle + if (isEdge(GeoId2, PosId2)) {// line to line angle - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geom1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geom2); + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); + if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = + static_cast(geom1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geom2); // find the two closest line ends Sketcher::PointPos PosId1 = Sketcher::PointPos::none; @@ -6216,11 +7106,14 @@ void CmdSketcherConstrainAngle::activated(int iMsg) p2[1] = lineSeg2->getEndPoint(); // Get the intersection point in 2d of the two lines if possible - Base::Line2d line1(Base::Vector2d(p1[0].x, p1[0].y), Base::Vector2d(p1[1].x, p1[1].y)); - Base::Line2d line2(Base::Vector2d(p2[0].x, p2[0].y), Base::Vector2d(p2[1].x, p2[1].y)); + Base::Line2d line1(Base::Vector2d(p1[0].x, p1[0].y), + Base::Vector2d(p1[1].x, p1[1].y)); + Base::Line2d line2(Base::Vector2d(p2[0].x, p2[0].y), + Base::Vector2d(p2[1].x, p2[1].y)); Base::Vector2d s; if (line1.Intersect(line2, s)) { - // get the end points of the line segments that are closest to the intersection point + // get the end points of the line segments that are closest to the intersection + // point Base::Vector3d s3d(s.x, s.y, p1[0].z); if (Base::DistanceP2(s3d, p1[0]) < Base::DistanceP2(s3d, p1[1])) PosId1 = Sketcher::PointPos::start; @@ -6234,8 +7127,8 @@ void CmdSketcherConstrainAngle::activated(int iMsg) else { // if all points are collinear double length = DBL_MAX; - for (int i=0; i <= 1; i++) { - for (int j=0; j <= 1; j++) { + for (int i = 0; i <= 1; i++) { + for (int j = 0; j <= 1; j++) { double tmp = Base::DistanceP2(p2[j], p1[i]); if (tmp < length) { length = tmp; @@ -6246,255 +7139,291 @@ void CmdSketcherConstrainAngle::activated(int iMsg) } } - Base::Vector3d dir1 = ((PosId1 == Sketcher::PointPos::start) ? 1. : -1.) * - (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); - Base::Vector3d dir2 = ((PosId2 == Sketcher::PointPos::start) ? 1. : -1.) * - (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); + Base::Vector3d dir1 = ((PosId1 == Sketcher::PointPos::start) ? 1. : -1.) + * (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()); + Base::Vector3d dir2 = ((PosId2 == Sketcher::PointPos::start) ? 1. : -1.) + * (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()); // check if the two lines are parallel, in this case an angle is not possible Base::Vector3d dir3 = dir1 % dir2; if (dir3.Length() < Precision::Intersection()) { Base::Vector3d dist = (p1[0] - p2[0]) % dir1; if (dist.Sqr() > Precision::Intersection()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Parallel lines"), - QObject::tr("An angle constraint cannot be set for two parallel lines.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Parallel lines"), + QObject::tr( + "An angle constraint cannot be set for two parallel lines.")); return; } } - double ActAngle = atan2(dir1.x*dir2.y-dir1.y*dir2.x, - dir1.y*dir2.y+dir1.x*dir2.x); + double ActAngle = + atan2(dir1.x * dir2.y - dir1.y * dir2.x, dir1.y * dir2.y + dir1.x * dir2.x); if (ActAngle < 0) { ActAngle *= -1; - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),ActAngle); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + ActAngle); - if (bothexternal || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + if (bothexternal + || constraintCreationMode + == Reference) {// it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(),"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } - } else if (isEdge(GeoId1,PosId1)) { // line angle + } + else if (isEdge(GeoId1, PosId1)) {// line angle if (GeoId1 < 0 && GeoId1 >= Sketcher::GeoEnum::VAxis) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add an angle constraint on an axis!")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add an angle constraint on an axis!")); return; } - const Part::Geometry *geom = Obj->getGeometry(GeoId1); + const Part::Geometry* geom = Obj->getGeometry(GeoId1); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg; + const Part::GeomLineSegment* lineSeg; lineSeg = static_cast(geom); - Base::Vector3d dir = lineSeg->getEndPoint()-lineSeg->getStartPoint(); - double ActAngle = atan2(dir.y,dir.x); + Base::Vector3d dir = lineSeg->getEndPoint() - lineSeg->getStartPoint(); + double ActAngle = atan2(dir.y, dir.x); openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(),"addConstraint(Sketcher.Constraint('Angle',%d,%f))", - GeoId1,ActAngle); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Angle',%d,%f))", + GeoId1, + ActAngle); - if (GeoId1 <= Sketcher::GeoEnum::RefExt || constraintCreationMode==Reference) { + if (GeoId1 <= Sketcher::GeoEnum::RefExt || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc; + const Part::GeomArcOfCircle* arc; arc = static_cast(geom); double startangle, endangle; arc->getRange(startangle, endangle, /*EmulateCCWXY=*/true); double angle = endangle - startangle; openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Angle',%d,%f))", - GeoId1,angle); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Angle',%d,%f))", + GeoId1, + angle); - if (GeoId1 <= Sketcher::GeoEnum::RefExt || constraintCreationMode==Reference) { + if (GeoId1 <= Sketcher::GeoEnum::RefExt || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(selection[0].getObject(), "setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; } } }; - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select one or two lines from the sketch. Or select two edges and a point.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select one or two lines from the sketch. Or select two edges and a point.")); return; } -void CmdSketcherConstrainAngle::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainAngle::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; - Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; + Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, + PosId3 = Sketcher::PointPos::none; switch (seqIndex) { - case 0: // {SelEdge, SelEdgeOrAxis} - case 1: // {SelEdgeOrAxis, SelEdge} - case 2: // {SelEdge, SelExternalEdge} - case 3: // {SelExternalEdge, SelEdge} - case 4: // {SelExternalEdge, SelExternalEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; + case 0:// {SelEdge, SelEdgeOrAxis} + case 1:// {SelEdgeOrAxis, SelEdge} + case 2:// {SelEdge, SelExternalEdge} + case 3:// {SelExternalEdge, SelEdge} + case 4:// {SelExternalEdge, SelExternalEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; - const Part::Geometry *geom1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geom2 = Obj->getGeometry(GeoId2); - if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geom1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geom2); + const Part::Geometry* geom1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geom2 = Obj->getGeometry(GeoId2); + if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = + static_cast(geom1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geom2); - // find the two closest line ends - Sketcher::PointPos PosId1 = Sketcher::PointPos::none; - Sketcher::PointPos PosId2 = Sketcher::PointPos::none; - Base::Vector3d p1[2], p2[2]; - p1[0] = lineSeg1->getStartPoint(); - p1[1] = lineSeg1->getEndPoint(); - p2[0] = lineSeg2->getStartPoint(); - p2[1] = lineSeg2->getEndPoint(); + // find the two closest line ends + Sketcher::PointPos PosId1 = Sketcher::PointPos::none; + Sketcher::PointPos PosId2 = Sketcher::PointPos::none; + Base::Vector3d p1[2], p2[2]; + p1[0] = lineSeg1->getStartPoint(); + p1[1] = lineSeg1->getEndPoint(); + p2[0] = lineSeg2->getStartPoint(); + p2[1] = lineSeg2->getEndPoint(); - // Get the intersection point in 2d of the two lines if possible - Base::Line2d line1(Base::Vector2d(p1[0].x, p1[0].y), Base::Vector2d(p1[1].x, p1[1].y)); - Base::Line2d line2(Base::Vector2d(p2[0].x, p2[0].y), Base::Vector2d(p2[1].x, p2[1].y)); - Base::Vector2d s; - if (line1.Intersect(line2, s)) { - // get the end points of the line segments that are closest to the intersection point - Base::Vector3d s3d(s.x, s.y, p1[0].z); - if (Base::DistanceP2(s3d, p1[0]) < Base::DistanceP2(s3d, p1[1])) - PosId1 = Sketcher::PointPos::start; - else - PosId1 = Sketcher::PointPos::end; - if (Base::DistanceP2(s3d, p2[0]) < Base::DistanceP2(s3d, p2[1])) - PosId2 = Sketcher::PointPos::start; - else - PosId2 = Sketcher::PointPos::end; - } - else { - // if all points are collinear - double length = DBL_MAX; - for (int i=0; i <= 1; i++) { - for (int j=0; j <= 1; j++) { - double tmp = Base::DistanceP2(p2[j], p1[i]); - if (tmp < length) { - length = tmp; - PosId1 = i ? Sketcher::PointPos::end : Sketcher::PointPos::start; - PosId2 = j ? Sketcher::PointPos::end : Sketcher::PointPos::start; + // Get the intersection point in 2d of the two lines if possible + Base::Line2d line1(Base::Vector2d(p1[0].x, p1[0].y), + Base::Vector2d(p1[1].x, p1[1].y)); + Base::Line2d line2(Base::Vector2d(p2[0].x, p2[0].y), + Base::Vector2d(p2[1].x, p2[1].y)); + Base::Vector2d s; + if (line1.Intersect(line2, s)) { + // get the end points of the line segments that are closest to the intersection + // point + Base::Vector3d s3d(s.x, s.y, p1[0].z); + if (Base::DistanceP2(s3d, p1[0]) < Base::DistanceP2(s3d, p1[1])) + PosId1 = Sketcher::PointPos::start; + else + PosId1 = Sketcher::PointPos::end; + if (Base::DistanceP2(s3d, p2[0]) < Base::DistanceP2(s3d, p2[1])) + PosId2 = Sketcher::PointPos::start; + else + PosId2 = Sketcher::PointPos::end; + } + else { + // if all points are collinear + double length = DBL_MAX; + for (int i = 0; i <= 1; i++) { + for (int j = 0; j <= 1; j++) { + double tmp = Base::DistanceP2(p2[j], p1[i]); + if (tmp < length) { + length = tmp; + PosId1 = i ? Sketcher::PointPos::end : Sketcher::PointPos::start; + PosId2 = j ? Sketcher::PointPos::end : Sketcher::PointPos::start; + } } } } - } - Base::Vector3d dir1 = ((PosId1 == Sketcher::PointPos::start) ? 1. : -1.) * - (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); - Base::Vector3d dir2 = ((PosId2 == Sketcher::PointPos::start) ? 1. : -1.) * - (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); + Base::Vector3d dir1 = ((PosId1 == Sketcher::PointPos::start) ? 1. : -1.) + * (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()); + Base::Vector3d dir2 = ((PosId2 == Sketcher::PointPos::start) ? 1. : -1.) + * (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()); - // check if the two lines are parallel, in this case an angle is not possible - Base::Vector3d dir3 = dir1 % dir2; - if (dir3.Length() < Precision::Intersection()) { - Base::Vector3d dist = (p1[0] - p2[0]) % dir1; - if (dist.Sqr() > Precision::Intersection()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Parallel lines"), - QObject::tr("An angle constraint cannot be set for two parallel lines.")); + // check if the two lines are parallel, in this case an angle is not possible + Base::Vector3d dir3 = dir1 % dir2; + if (dir3.Length() < Precision::Intersection()) { + Base::Vector3d dist = (p1[0] - p2[0]) % dir1; + if (dist.Sqr() > Precision::Intersection()) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Parallel lines"), + QObject::tr( + "An angle constraint cannot be set for two parallel lines.")); - return; + return; + } } + + double ActAngle = + atan2(dir1.x * dir2.y - dir1.y * dir2.x, dir1.y * dir2.y + dir1.x * dir2.x); + if (ActAngle < 0) { + ActAngle *= -1; + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); + } + + openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + ActAngle); + + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) + || constraintCreationMode == Reference) { + // it is a constraint on a external line, make it non-driving + const std::vector& ConStr = Obj->Constraints.getValues(); + + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); + } + else + finishDatumConstraint(this, Obj, true); + + return; } - - double ActAngle = atan2(dir1.x*dir2.y-dir1.y*dir2.x, - dir1.y*dir2.y+dir1.x*dir2.x); - if (ActAngle < 0) { - ActAngle *= -1; - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); - } - - openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),ActAngle); - - if (areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2) || constraintCreationMode==Reference) { - // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); - - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); - } - else - finishDatumConstraint (this, Obj, true); - return; } - return; - } - case 5: // {SelEdge, SelVertexOrRoot, SelEdgeOrAxis} - case 6: // {SelEdgeOrAxis, SelVertexOrRoot, SelEdge} - case 7: // {SelEdge, SelVertexOrRoot, SelExternalEdge} - case 8: // {SelExternalEdge, SelVertexOrRoot, SelEdge} - case 9: // {SelExternalEdge, SelVertexOrRoot, SelExternalEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(1).GeoId; - PosId3 = selSeq.at(1).PosId; - break; - } - case 10: // {SelVertexOrRoot, SelEdge, SelEdgeOrAxis} - case 11: // {SelVertexOrRoot, SelEdgeOrAxis, SelEdge} - case 12: // {SelVertexOrRoot, SelEdge, SelExternalEdge} - case 13: // {SelVertexOrRoot, SelExternalEdge, SelEdge} - case 14: // {SelVertexOrRoot, SelExternalEdge, SelExternalEdge} - { - GeoId1 = selSeq.at(1).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(0).GeoId; - PosId3 = selSeq.at(0).PosId; - break; - } + case 5:// {SelEdge, SelVertexOrRoot, SelEdgeOrAxis} + case 6:// {SelEdgeOrAxis, SelVertexOrRoot, SelEdge} + case 7:// {SelEdge, SelVertexOrRoot, SelExternalEdge} + case 8:// {SelExternalEdge, SelVertexOrRoot, SelEdge} + case 9:// {SelExternalEdge, SelVertexOrRoot, SelExternalEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(1).GeoId; + PosId3 = selSeq.at(1).PosId; + break; + } + case 10:// {SelVertexOrRoot, SelEdge, SelEdgeOrAxis} + case 11:// {SelVertexOrRoot, SelEdgeOrAxis, SelEdge} + case 12:// {SelVertexOrRoot, SelEdge, SelExternalEdge} + case 13:// {SelVertexOrRoot, SelExternalEdge, SelEdge} + case 14:// {SelVertexOrRoot, SelExternalEdge, SelExternalEdge} + { + GeoId1 = selSeq.at(1).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(0).GeoId; + PosId3 = selSeq.at(0).PosId; + break; + } } - bool bothexternal=areBothPointsOrSegmentsFixed(Obj,GeoId1, GeoId2); + bool bothexternal = areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2); if (isEdge(GeoId1, PosId1) && isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { - if(isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + if (isBsplinePole(Obj, GeoId1) || isBsplinePole(Obj, GeoId2)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } @@ -6503,96 +7432,116 @@ void CmdSketcherConstrainAngle::applyConstraint(std::vector &selSeq, openCommand(QT_TRANSLATE_NOOP("Command", "Add angle constraint")); - //add missing point-on-object constraints - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + // add missing point-on-object constraints + if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); } - if(! IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)){ - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId2); + if (!IsPointAlreadyOnCurve(GeoId2, GeoId3, PosId3, Obj)) { + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId2); } - if(! IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)){ - //FIXME: it's a good idea to add a check if the sketch is solved - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId3,static_cast(PosId3),GeoId1); + if (!IsPointAlreadyOnCurve(GeoId1, GeoId3, PosId3, Obj)) { + // FIXME: it's a good idea to add a check if the sketch is solved + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId3, + static_cast(PosId3), + GeoId1); } - //assuming point-on-curves have been solved, calculate the angle. - //DeepSOIC: this may be slow, but I wanted to reuse the conversion - //from Geometry to GCS shapes that is done in Sketch - Base::Vector3d p = Obj->getPoint(GeoId3, PosId3 ); - ActAngle = Obj->calculateAngleViaPoint(GeoId1,GeoId2,p.x,p.y); + // assuming point-on-curves have been solved, calculate the angle. + // DeepSOIC: this may be slow, but I wanted to reuse the conversion + // from Geometry to GCS shapes that is done in Sketch + Base::Vector3d p = Obj->getPoint(GeoId3, PosId3); + ActAngle = Obj->calculateAngleViaPoint(GeoId1, GeoId2, p.x, p.y); - //negative constraint value avoidance - if (ActAngle < -Precision::Angular()){ + // negative constraint value avoidance + if (ActAngle < -Precision::Angular()) { std::swap(GeoId1, GeoId2); std::swap(PosId1, PosId2); ActAngle = -ActAngle; } - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('AngleViaPoint',%d,%d,%d,%d,%f))", - GeoId1,GeoId2,GeoId3,static_cast(PosId3),ActAngle); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('AngleViaPoint',%d,%d,%d,%d,%f))", + GeoId1, + GeoId2, + GeoId3, + static_cast(PosId3), + ActAngle); - if (bothexternal || constraintCreationMode==Reference) { + if (bothexternal || constraintCreationMode == Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + const std::vector& ConStr = Obj->Constraints.getValues(); - Gui::cmdAppObjectArgs(Obj,"setDriving(%d,%s)", - ConStr.size()-1,"False"); - finishDatumConstraint (this, Obj, false); + Gui::cmdAppObjectArgs(Obj, "setDriving(%d,%s)", ConStr.size() - 1, "False"); + finishDatumConstraint(this, Obj, false); } else - finishDatumConstraint (this, Obj, true); + finishDatumConstraint(this, Obj, true); return; }; - } void CmdSketcherConstrainAngle::updateAction(int mode) { switch (mode) { - case Reference: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle_Driven")); - break; - case Driving: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle")); - break; + case Reference: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle_Driven")); + break; + case Driving: + if (getAction()) + getAction()->setIcon( + Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle")); + break; } } // ====================================================================================== -class CmdSketcherConstrainEqual : public CmdSketcherConstraint +class CmdSketcherConstrainEqual: public CmdSketcherConstraint { public: CmdSketcherConstrainEqual(); - ~CmdSketcherConstrainEqual() override{} + ~CmdSketcherConstrainEqual() override + {} const char* className() const override - { return "CmdSketcherConstrainEqual"; } + { + return "CmdSketcherConstrainEqual"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainEqual::CmdSketcherConstrainEqual() - :CmdSketcherConstraint("Sketcher_ConstrainEqual") + : CmdSketcherConstraint("Sketcher_ConstrainEqual") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain equal"); - sToolTipText = QT_TR_NOOP("Create an equality constraint between two lines or between circles and arcs"); - sWhatsThis = "Sketcher_ConstrainEqual"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_EqualLength"; - sAccel = "E"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain equal"); + sToolTipText = + QT_TR_NOOP("Create an equality constraint between two lines or between circles and arcs"); + sWhatsThis = "Sketcher_ConstrainEqual"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_EqualLength"; + sAccel = "E"; + eType = ForEdit; - allowedSelSequences = {{SelEdge, SelEdge}, {SelEdge, SelExternalEdge}, - {SelExternalEdge, SelEdge}}; // Only option for equal constraint + allowedSelSequences = {{SelEdge, SelEdge}, + {SelEdge, SelExternalEdge}, + {SelExternalEdge, SelEdge}};// Only option for equal constraint } void CmdSketcherConstrainEqual::activated(int iMsg) @@ -6602,15 +7551,17 @@ void CmdSketcherConstrainEqual::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { + } + else { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), QObject::tr("Wrong selection"), QObject::tr("Select two edges from the sketch.")); @@ -6619,44 +7570,47 @@ void CmdSketcherConstrainEqual::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); // go through the selected subelements if (SubNames.size() < 2) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select at least two lines from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select at least two lines from the sketch.")); return; } std::vector ids; - bool lineSel = false, arcSel = false, circSel = false, ellipsSel = false, arcEllipsSel=false, hasAlreadyExternal = false; - bool hyperbSel = false, parabSel=false, weightSel=false; + bool lineSel = false, arcSel = false, circSel = false, ellipsSel = false, arcEllipsSel = false, + hasAlreadyExternal = false; + bool hyperbSel = false, parabSel = false, weightSel = false; - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { int GeoId; Sketcher::PointPos PosId; getIdsFromName(*it, Obj, GeoId, PosId); - if (!isEdge(GeoId,PosId)) { + if (!isEdge(GeoId, PosId)) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two or more compatible edges.")); + QObject::tr("Wrong selection"), + QObject::tr("Select two or more compatible edges.")); return; } else if (GeoId == Sketcher::GeoEnum::HAxis || GeoId == Sketcher::GeoEnum::VAxis) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Sketch axes cannot be used in equality constraints.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Sketch axes cannot be used in equality constraints.")); return; } - else if (isPointOrSegmentFixed(Obj,GeoId)) { + else if (isPointOrSegmentFixed(Obj, GeoId)) { if (hasAlreadyExternal) { showNoConstraintBetweenFixedGeometry(Obj); @@ -6667,13 +7621,14 @@ void CmdSketcherConstrainEqual::activated(int iMsg) } } - const Part::Geometry *geo = Obj->getGeometry(GeoId); + const Part::Geometry* geo = Obj->getGeometry(GeoId); - if(geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // unsupported as they are generally hereogeneus shapes - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Equality for B-spline edge currently unsupported.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Equality for B-spline edge currently unsupported.")); return; } @@ -6685,7 +7640,7 @@ void CmdSketcherConstrainEqual::activated(int iMsg) arcSel = true; } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - if(isBsplinePole(geo)) + if (isBsplinePole(geo)) weightSel = true; else circSel = true; @@ -6704,8 +7659,8 @@ void CmdSketcherConstrainEqual::activated(int iMsg) } else { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two or more edges of similar type.")); + QObject::tr("Wrong selection"), + QObject::tr("Select two or more edges of similar type.")); return; } @@ -6714,24 +7669,28 @@ void CmdSketcherConstrainEqual::activated(int iMsg) } // Check for heterogeneous groups in selection - if ( (lineSel && ((arcSel || circSel) || (ellipsSel || arcEllipsSel) || hyperbSel || parabSel || weightSel) ) || - ((arcSel || circSel) && ((ellipsSel || arcEllipsSel) || hyperbSel || parabSel || weightSel)) || - ((ellipsSel || arcEllipsSel) && (hyperbSel || parabSel || weightSel)) || - ( hyperbSel && (parabSel || weightSel)) || - ( parabSel && weightSel)) { + if ((lineSel + && ((arcSel || circSel) || (ellipsSel || arcEllipsSel) || hyperbSel || parabSel + || weightSel)) + || ((arcSel || circSel) + && ((ellipsSel || arcEllipsSel) || hyperbSel || parabSel || weightSel)) + || ((ellipsSel || arcEllipsSel) && (hyperbSel || parabSel || weightSel)) + || (hyperbSel && (parabSel || weightSel)) || (parabSel && weightSel)) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two or more edges of similar type.")); + QObject::tr("Wrong selection"), + QObject::tr("Select two or more edges of similar type.")); return; } // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add equality constraint")); - for (int i=0; i < int(ids.size()-1); i++) { - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('Equal',%d,%d))", - ids[i],ids[i+1]); + for (int i = 0; i < int(ids.size() - 1); i++) { + Gui::cmdAppObjectArgs(selection[0].getObject(), + "addConstraint(Sketcher.Constraint('Equal',%d,%d))", + ids[i], + ids[i + 1]); } // finish the transaction and update commitCommand(); @@ -6741,88 +7700,102 @@ void CmdSketcherConstrainEqual::activated(int iMsg) getSelection().clearSelection(); } -void CmdSketcherConstrainEqual::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainEqual::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef; switch (seqIndex) { - case 0: // {SelEdge, SelEdge} - case 1: // {SelEdge, SelExternalEdge} - case 2: // {SelExternalEdge, SelEdge} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; + case 0:// {SelEdge, SelEdge} + case 1:// {SelEdge, SelExternalEdge} + case 2:// {SelExternalEdge, SelEdge} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; - // check if the edge already has a Block constraint - if ( areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } + // check if the edge already has a Block constraint + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; + } - const Part::Geometry *geo1 = Obj->getGeometry(GeoId1); - const Part::Geometry *geo2 = Obj->getGeometry(GeoId2); + const Part::Geometry* geo1 = Obj->getGeometry(GeoId1); + const Part::Geometry* geo2 = Obj->getGeometry(GeoId2); - if ( (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) || - (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() && geo2->getTypeId() != Part::GeomArcOfHyperbola::getClassTypeId()) || - (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() && geo2->getTypeId() != Part::GeomArcOfParabola::getClassTypeId()) || - (isBsplinePole(geo1) && !isBsplinePole(geo2)) || - ( (geo1->getTypeId() == Part::GeomCircle::getClassTypeId() || geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) && - !(geo2->getTypeId() == Part::GeomCircle::getClassTypeId() || geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId())) || - ( (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) && - !(geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId())) ){ + if ((geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) + || (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + && geo2->getTypeId() != Part::GeomArcOfHyperbola::getClassTypeId()) + || (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + && geo2->getTypeId() != Part::GeomArcOfParabola::getClassTypeId()) + || (isBsplinePole(geo1) && !isBsplinePole(geo2)) + || ((geo1->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + && !(geo2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId())) + || ((geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) + && !(geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()))) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two or more edges of similar type.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select two or more edges of similar type.")); + + return; + } + + // undo command open + openCommand(QT_TRANSLATE_NOOP("Command", "Add equality constraint")); + Gui::cmdAppObjectArgs( + Obj, "addConstraint(Sketcher.Constraint('Equal',%d,%d))", GeoId1, GeoId2); + // finish the transaction and update + commitCommand(); + tryAutoRecompute(Obj); return; } - - // undo command open - openCommand(QT_TRANSLATE_NOOP("Command", "Add equality constraint")); - Gui::cmdAppObjectArgs(Obj, "addConstraint(Sketcher.Constraint('Equal',%d,%d))", - GeoId1, GeoId2); - // finish the transaction and update - commitCommand(); - tryAutoRecompute(Obj); - - return; - } - default: - break; + default: + break; } } // ====================================================================================== -class CmdSketcherConstrainSymmetric : public CmdSketcherConstraint +class CmdSketcherConstrainSymmetric: public CmdSketcherConstraint { public: CmdSketcherConstrainSymmetric(); - ~CmdSketcherConstrainSymmetric() override{} + ~CmdSketcherConstrainSymmetric() override + {} const char* className() const override - { return "CmdSketcherConstrainSymmetric"; } + { + return "CmdSketcherConstrainSymmetric"; + } + protected: void activated(int iMsg) override; - void applyConstraint(std::vector &selSeq, int seqIndex) override; + void applyConstraint(std::vector& selSeq, int seqIndex) override; }; CmdSketcherConstrainSymmetric::CmdSketcherConstrainSymmetric() - :CmdSketcherConstraint("Sketcher_ConstrainSymmetric") + : CmdSketcherConstraint("Sketcher_ConstrainSymmetric") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain symmetrical"); - sToolTipText = QT_TR_NOOP("Create a symmetry constraint " - "between two points\n" - "with respect to a line or a third point"); - sWhatsThis = "Sketcher_ConstrainSymmetric"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_Symmetric"; - sAccel = "S"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain symmetrical"); + sToolTipText = QT_TR_NOOP("Create a symmetry constraint " + "between two points\n" + "with respect to a line or a third point"); + sWhatsThis = "Sketcher_ConstrainSymmetric"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_Symmetric"; + sAccel = "S"; + eType = ForEdit; allowedSelSequences = {{SelEdge, SelVertexOrRoot}, {SelExternalEdge, SelVertex}, @@ -6831,7 +7804,7 @@ CmdSketcherConstrainSymmetric::CmdSketcherConstrainSymmetric() {SelVertex, SelExternalEdge, SelVertexOrRoot}, {SelRoot, SelExternalEdge, SelVertex}, {SelVertex, SelEdgeOrAxis, SelVertex}, - {SelVertex, SelVertexOrRoot,SelEdge}, + {SelVertex, SelVertexOrRoot, SelEdge}, {SelRoot, SelVertex, SelEdge}, {SelVertex, SelVertexOrRoot, SelExternalEdge}, {SelRoot, SelVertex, SelExternalEdge}, @@ -6848,34 +7821,37 @@ void CmdSketcherConstrainSymmetric::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool constraintMode = hGrp->GetBool("ContinuousConstraintMode", true); if (constraintMode) { - ActivateHandler(getActiveGuiDocument(), - new DrawSketchHandlerGenConstraint(this)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerGenConstraint(this)); getSelection().clearSelection(); - } else { - Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select two points and a symmetry line, " - "two points and a symmetry point " - "or a line and a symmetry point from the sketch.")); + } + else { + Gui::TranslatedUserWarning( + getActiveGuiDocument()->getDocument(), + QObject::tr("Wrong selection"), + QObject::tr("Select two points and a symmetry line, " + "two points and a symmetry point " + "or a line and a symmetry point from the sketch.")); } return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); if (SubNames.size() != 3 && SubNames.size() != 2) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two points and a symmetry line, " - "two points and a symmetry point " - "or a line and a symmetry point from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select two points and a symmetry line, " + "two points and a symmetry point " + "or a line and a symmetry point from the sketch.")); return; } @@ -6886,31 +7862,37 @@ void CmdSketcherConstrainSymmetric::activated(int iMsg) getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); if (SubNames.size() == 2) { - if ( areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) ) { + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { showNoConstraintBetweenFixedGeometry(Obj); return; } - if (isVertex(GeoId1,PosId1) && isEdge(GeoId2,PosId2)) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + if (isVertex(GeoId1, PosId1) && isEdge(GeoId2, PosId2)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - if (isEdge(GeoId1,PosId1) && isVertex(GeoId2,PosId2)) { - const Part::Geometry *geom = Obj->getGeometry(GeoId1); + if (isEdge(GeoId1, PosId1) && isVertex(GeoId2, PosId2)) { + const Part::Geometry* geom = Obj->getGeometry(GeoId1); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { if (GeoId1 == GeoId2) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a symmetry constraint " - "between a line and its end points.")); + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a symmetry constraint " + "between a line and its end points.")); return; } // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add symmetric constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), + Gui::cmdAppObjectArgs( + selection[0].getObject(), "addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d,%d))", - GeoId1,static_cast(Sketcher::PointPos::start),GeoId1,static_cast(Sketcher::PointPos::end),GeoId2,static_cast(PosId2)); + GeoId1, + static_cast(Sketcher::PointPos::start), + GeoId1, + static_cast(Sketcher::PointPos::end), + GeoId2, + static_cast(PosId2)); // finish the transaction and update commitCommand(); @@ -6923,50 +7905,54 @@ void CmdSketcherConstrainSymmetric::activated(int iMsg) } Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two points and a symmetry line, " - "two points and a symmetry point " - "or a line and a symmetry point from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select two points and a symmetry line, " + "two points and a symmetry point " + "or a line and a symmetry point from the sketch.")); return; } getIdsFromName(SubNames[2], Obj, GeoId3, PosId3); - if (isEdge(GeoId1,PosId1) && isVertex(GeoId3,PosId3)) { - std::swap(GeoId1,GeoId3); - std::swap(PosId1,PosId3); + if (isEdge(GeoId1, PosId1) && isVertex(GeoId3, PosId3)) { + std::swap(GeoId1, GeoId3); + std::swap(PosId1, PosId3); } - else if (isEdge(GeoId2,PosId2) && isVertex(GeoId3,PosId3)) { - std::swap(GeoId2,GeoId3); - std::swap(PosId2,PosId3); + else if (isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { + std::swap(GeoId2, GeoId3); + std::swap(PosId2, PosId3); } - if ( areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; + if (areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; } - if (isVertex(GeoId1,PosId1) && - isVertex(GeoId2,PosId2)) { + if (isVertex(GeoId1, PosId1) && isVertex(GeoId2, PosId2)) { - if (isEdge(GeoId3,PosId3)) { - const Part::Geometry *geom = Obj->getGeometry(GeoId3); + if (isEdge(GeoId3, PosId3)) { + const Part::Geometry* geom = Obj->getGeometry(GeoId3); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { if (GeoId1 == GeoId2 && GeoId2 == GeoId3) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a symmetry constraint " - "between a line and its end points!")); + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a symmetry constraint " + "between a line and its end points!")); return; } // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add symmetric constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), + Gui::cmdAppObjectArgs( + selection[0].getObject(), "addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),GeoId3); + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + GeoId3); // finish the transaction and update commitCommand(); @@ -6977,12 +7963,18 @@ void CmdSketcherConstrainSymmetric::activated(int iMsg) return; } } - else if (isVertex(GeoId3,PosId3)) { + else if (isVertex(GeoId3, PosId3)) { // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add symmetric constraint")); - Gui::cmdAppObjectArgs(selection[0].getObject(), + Gui::cmdAppObjectArgs( + selection[0].getObject(), "addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),GeoId3,static_cast(PosId3)); + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + GeoId3, + static_cast(PosId3)); // finish the transaction and update commitCommand(); @@ -6995,122 +7987,148 @@ void CmdSketcherConstrainSymmetric::activated(int iMsg) } Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two points and a symmetry line, " - "two points and a symmetry point " - "or a line and a symmetry point from the sketch.")); - + QObject::tr("Wrong selection"), + QObject::tr("Select two points and a symmetry line, " + "two points and a symmetry point " + "or a line and a symmetry point from the sketch.")); } -void CmdSketcherConstrainSymmetric::applyConstraint(std::vector &selSeq, int seqIndex) +void CmdSketcherConstrainSymmetric::applyConstraint(std::vector& selSeq, int seqIndex) { - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; - Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; + Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, + PosId3 = Sketcher::PointPos::none; switch (seqIndex) { - case 0: // {SelEdge, SelVertexOrRoot} - case 1: // {SelExternalEdge, SelVertex} - { - GeoId1 = GeoId2 = selSeq.at(0).GeoId; GeoId3 = selSeq.at(1).GeoId; - PosId1 = Sketcher::PointPos::start; PosId2 = Sketcher::PointPos::end; PosId3 = selSeq.at(1).PosId; + case 0:// {SelEdge, SelVertexOrRoot} + case 1:// {SelExternalEdge, SelVertex} + { + GeoId1 = GeoId2 = selSeq.at(0).GeoId; + GeoId3 = selSeq.at(1).GeoId; + PosId1 = Sketcher::PointPos::start; + PosId2 = Sketcher::PointPos::end; + PosId3 = selSeq.at(1).PosId; - if (GeoId1 == GeoId3) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a symmetry constraint between a line and its end points!")); - - return; - } - - if ( areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } - break; - } - case 2: // {SelVertex, SelEdge, SelVertexOrRoot} - case 3: // {SelRoot, SelEdge, SelVertex} - case 4: // {SelVertex, SelExternalEdge, SelVertexOrRoot} - case 5: // {SelRoot, SelExternalEdge, SelVertex} - case 6: // {SelVertex, SelEdgeOrAxis, SelVertex} - case 7: // {SelVertex, SelVertexOrRoot,SelEdge} - case 8: // {SelRoot, SelVertex, SelEdge} - case 9: // {SelVertex, SelVertexOrRoot, SelExternalEdge} - case 10: // {SelRoot, SelVertex, SelExternalEdge} - case 11: // {SelVertex, SelVertex, SelEdgeOrAxis} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(2).GeoId; GeoId3 = selSeq.at(1).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(2).PosId; PosId3 = selSeq.at(1).PosId; - - if (isEdge(GeoId1,PosId1) && isVertex(GeoId3,PosId3)) { - std::swap(GeoId1,GeoId3); - std::swap(PosId1,PosId3); - } - else if (isEdge(GeoId2,PosId2) && isVertex(GeoId3,PosId3)) { - std::swap(GeoId2,GeoId3); - std::swap(PosId2,PosId3); - } - - if ( areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3) ) { - showNoConstraintBetweenFixedGeometry(Obj); - return; - } - - const Part::Geometry *geom = Obj->getGeometry(GeoId3); - if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - if (GeoId1 == GeoId2 && GeoId2 == GeoId3) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot add a symmetry constraint " - "between a line and its end points.")); + if (GeoId1 == GeoId3) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "Cannot add a symmetry constraint between a line and its end points!")); return; } - // undo command open - openCommand(QT_TRANSLATE_NOOP("Command", "Add symmetric constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),GeoId3); - - // finish the transaction and update - commitCommand(); - tryAutoRecompute(Obj); + if (areBothPointsOrSegmentsFixed(Obj, GeoId1, GeoId2)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; + } + break; } - else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select two points and a symmetry line, " - "two points and a symmetry point " - "or a line and a symmetry point from the sketch.")); + case 2: // {SelVertex, SelEdge, SelVertexOrRoot} + case 3: // {SelRoot, SelEdge, SelVertex} + case 4: // {SelVertex, SelExternalEdge, SelVertexOrRoot} + case 5: // {SelRoot, SelExternalEdge, SelVertex} + case 6: // {SelVertex, SelEdgeOrAxis, SelVertex} + case 7: // {SelVertex, SelVertexOrRoot,SelEdge} + case 8: // {SelRoot, SelVertex, SelEdge} + case 9: // {SelVertex, SelVertexOrRoot, SelExternalEdge} + case 10:// {SelRoot, SelVertex, SelExternalEdge} + case 11:// {SelVertex, SelVertex, SelEdgeOrAxis} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(2).GeoId; + GeoId3 = selSeq.at(1).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(2).PosId; + PosId3 = selSeq.at(1).PosId; - } + if (isEdge(GeoId1, PosId1) && isVertex(GeoId3, PosId3)) { + std::swap(GeoId1, GeoId3); + std::swap(PosId1, PosId3); + } + else if (isEdge(GeoId2, PosId2) && isVertex(GeoId3, PosId3)) { + std::swap(GeoId2, GeoId3); + std::swap(PosId2, PosId3); + } - return; - } - case 12: // {SelVertex, SelVertexOrRoot, SelVertex} - case 13: // {SelVertex, SelVertex, SelVertexOrRoot} - case 14: // {SelVertexOrRoot, SelVertex, SelVertex} - { - GeoId1 = selSeq.at(0).GeoId; GeoId2 = selSeq.at(1).GeoId; GeoId3 = selSeq.at(2).GeoId; - PosId1 = selSeq.at(0).PosId; PosId2 = selSeq.at(1).PosId; PosId3 = selSeq.at(2).PosId; + if (areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; + } + + const Part::Geometry* geom = Obj->getGeometry(GeoId3); + if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + if (GeoId1 == GeoId2 && GeoId2 == GeoId3) { + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot add a symmetry constraint " + "between a line and its end points.")); + + return; + } + + // undo command open + openCommand(QT_TRANSLATE_NOOP("Command", "Add symmetric constraint")); + Gui::cmdAppObjectArgs( + Obj, + "addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + GeoId3); + + // finish the transaction and update + commitCommand(); + tryAutoRecompute(Obj); + } + else { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select two points and a symmetry line, " + "two points and a symmetry point " + "or a line and a symmetry point from the sketch.")); + } - if ( areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3) ) { - showNoConstraintBetweenFixedGeometry(Obj); return; } - break; - } - default: - break; + case 12:// {SelVertex, SelVertexOrRoot, SelVertex} + case 13:// {SelVertex, SelVertex, SelVertexOrRoot} + case 14:// {SelVertexOrRoot, SelVertex, SelVertex} + { + GeoId1 = selSeq.at(0).GeoId; + GeoId2 = selSeq.at(1).GeoId; + GeoId3 = selSeq.at(2).GeoId; + PosId1 = selSeq.at(0).PosId; + PosId2 = selSeq.at(1).PosId; + PosId3 = selSeq.at(2).PosId; + + if (areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3)) { + showNoConstraintBetweenFixedGeometry(Obj); + return; + } + break; + } + default: + break; } // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Add symmetric constraint")); - Gui::cmdAppObjectArgs(Obj,"addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),GeoId3,static_cast(PosId3)); + Gui::cmdAppObjectArgs(Obj, + "addConstraint(Sketcher.Constraint('Symmetric',%d,%d,%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + GeoId3, + static_cast(PosId3)); // finish the transaction and update commitCommand(); @@ -7127,19 +8145,19 @@ void CmdSketcherConstrainSymmetric::applyConstraint(std::vector &selS DEF_STD_CMD_A(CmdSketcherConstrainSnellsLaw) CmdSketcherConstrainSnellsLaw::CmdSketcherConstrainSnellsLaw() - :Command("Sketcher_ConstrainSnellsLaw") + : Command("Sketcher_ConstrainSnellsLaw") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Constrain refraction (Snell's law)"); - sToolTipText = QT_TR_NOOP("Create a refraction law (Snell's law)" - "constraint between two endpoints of rays\n" - "and an edge as an interface."); - sWhatsThis = "Sketcher_ConstrainSnellsLaw"; - sStatusTip = sToolTipText; - sPixmap = "Constraint_SnellsLaw"; - sAccel = "K, W"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Constrain refraction (Snell's law)"); + sToolTipText = QT_TR_NOOP("Create a refraction law (Snell's law)" + "constraint between two endpoints of rays\n" + "and an edge as an interface."); + sWhatsThis = "Sketcher_ConstrainSnellsLaw"; + sStatusTip = sToolTipText; + sPixmap = "Constraint_SnellsLaw"; + sAccel = "K, W"; + eType = ForEdit; } void CmdSketcherConstrainSnellsLaw::activated(int iMsg) @@ -7151,18 +8169,20 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { QString strHelp = QObject::tr("Select two endpoints of lines to act as rays, " - "and an edge representing a boundary. " - "The first selected point corresponds " - "to index n1, second to n2, " - "and datum value sets the ratio n2/n1.", - "Constraint_SnellsLaw"); + "and an edge representing a boundary. " + "The first selected point corresponds " + "to index n1, second to n2, " + "and datum value sets the ratio n2/n1.", + "Constraint_SnellsLaw"); const char dmbg[] = "Constraint_SnellsLaw"; QString strError = QObject::tr("Selected objects are not just geometry " - "from one sketch.", dmbg); + "from one sketch.", + dmbg); strError.append(strHelp); Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), @@ -7172,12 +8192,12 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) // get the needed lists and objects Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.size() != 3) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Number of selected objects is not 3")); + QObject::tr("Wrong selection"), + QObject::tr("Number of selected objects is not 3")); return; } @@ -7188,59 +8208,60 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) getIdsFromName(SubNames[1], Obj, GeoId2, PosId2); getIdsFromName(SubNames[2], Obj, GeoId3, PosId3); - //sink the edge to be the last item - if (isEdge(GeoId1,PosId1) ) { - std::swap(GeoId1,GeoId2); - std::swap(PosId1,PosId2); + // sink the edge to be the last item + if (isEdge(GeoId1, PosId1)) { + std::swap(GeoId1, GeoId2); + std::swap(PosId1, PosId2); } - if (isEdge(GeoId2,PosId2) ) { - std::swap(GeoId2,GeoId3); - std::swap(PosId2,PosId3); + if (isEdge(GeoId2, PosId2)) { + std::swap(GeoId2, GeoId3); + std::swap(PosId2, PosId3); } - //a bunch of validity checks - if (areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3) ) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Cannot create constraint with external geometry only.")); + // a bunch of validity checks + if (areAllPointsOrSegmentsFixed(Obj, GeoId1, GeoId2, GeoId3)) { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Cannot create constraint with external geometry only.")); return; } - if (!(isVertex(GeoId1,PosId1) && !isSimpleVertex(Obj, GeoId1, PosId1) && - isVertex(GeoId2,PosId2) && !isSimpleVertex(Obj, GeoId2, PosId2) && - isEdge(GeoId3,PosId3) )) { + if (!(isVertex(GeoId1, PosId1) && !isSimpleVertex(Obj, GeoId1, PosId1) + && isVertex(GeoId2, PosId2) && !isSimpleVertex(Obj, GeoId2, PosId2) + && isEdge(GeoId3, PosId3))) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Incompatible geometry is selected.")); + Gui::TranslatedUserWarning( + Obj, QObject::tr("Wrong selection"), QObject::tr("Incompatible geometry is selected.")); return; }; - const Part::Geometry *geo = Obj->getGeometry(GeoId3); + const Part::Geometry* geo = Obj->getGeometry(GeoId3); - if( geo && geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() ){ + if (geo && geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // unsupported until normal to B-spline at any point implemented. - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("SnellsLaw on B-spline edge is currently unsupported.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("SnellsLaw on B-spline edge is currently unsupported.")); return; } - if(isBsplinePole(geo)) { + if (isBsplinePole(geo)) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select an edge that is not a B-spline weight.")); + QObject::tr("Wrong selection"), + QObject::tr("Select an edge that is not a B-spline weight.")); return; } - double n2divn1=0; + double n2divn1 = 0; - //the essence. - //Unlike other constraints, we'll ask for a value immediately. + // the essence. + // Unlike other constraints, we'll ask for a value immediately. QDialog dlg(Gui::getMainWindow()); Ui::InsertDatum ui_Datum; ui_Datum.setupUi(&dlg); @@ -7251,7 +8272,8 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) init_val.setValue(0.0); ui_Datum.labelEdit->setValue(init_val); - ui_Datum.labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherRefrIndexRatio")); + ui_Datum.labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherRefrIndexRatio")); ui_Datum.labelEdit->setEntryName(QByteArray("DatumValue")); ui_Datum.labelEdit->setToLastUsedValue(); ui_Datum.labelEdit->selectNumber(); @@ -7265,32 +8287,45 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) Base::Quantity newQuant = ui_Datum.labelEdit->value(); n2divn1 = newQuant.getValue(); - //add constraint + // add constraint openCommand(QT_TRANSLATE_NOOP("Command", "Add Snell's law constraint")); - bool safe = addConstraintSafely(Obj, [&](){ - if (! IsPointAlreadyOnCurve(GeoId2,GeoId1,PosId1,Obj)) + bool safe = addConstraintSafely(Obj, [&]() { + if (!IsPointAlreadyOnCurve(GeoId2, GeoId1, PosId1, Obj)) Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2)); + "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2)); - if (! IsPointAlreadyOnCurve(GeoId3,GeoId1,PosId1,Obj)) + if (!IsPointAlreadyOnCurve(GeoId3, GeoId1, PosId1, Obj)) Gui::cmdAppObjectArgs(selection[0].getObject(), - "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", - GeoId1,static_cast(PosId1),GeoId3); + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d))", + GeoId1, + static_cast(PosId1), + GeoId3); - Gui::cmdAppObjectArgs(selection[0].getObject(), "addConstraint(Sketcher.Constraint('SnellsLaw',%d,%d,%d,%d,%d,%.12f))", - GeoId1,static_cast(PosId1),GeoId2,static_cast(PosId2),GeoId3,n2divn1); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "addConstraint(Sketcher.Constraint('SnellsLaw',%d,%d,%d,%d,%d,%.12f))", + GeoId1, + static_cast(PosId1), + GeoId2, + static_cast(PosId2), + GeoId3, + n2divn1); - /*if (allexternal || constraintCreationMode==Reference) { // it is a constraint on a external line, make it non-driving - const std::vector &ConStr = Obj->Constraints.getValues(); + /*if (allexternal || constraintCreationMode==Reference) { // it is a constraint on a + external line, make it non-driving const std::vector &ConStr = + Obj->Constraints.getValues(); Gui::cmdAppObjectArgs(selection[0].getObject(),"setDriving(%i,%s)", ConStr.size()-1,"False"); }*/ }); - if(!safe) + if (!safe) return; else { commitCommand(); @@ -7299,12 +8334,11 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) // clear the selection (convenience) getSelection().clearSelection(); - } bool CmdSketcherConstrainSnellsLaw::isActive() { - return isCreateConstraintActive( getActiveGuiDocument() ); + return isCreateConstraintActive(getActiveGuiDocument()); } // ====================================================================================== @@ -7312,22 +8346,22 @@ bool CmdSketcherConstrainSnellsLaw::isActive() DEF_STD_CMD_A(CmdSketcherToggleDrivingConstraint) CmdSketcherToggleDrivingConstraint::CmdSketcherToggleDrivingConstraint() - :Command("Sketcher_ToggleDrivingConstraint") + : Command("Sketcher_ToggleDrivingConstraint") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Toggle driving/reference constraint"); - sToolTipText = QT_TR_NOOP("Set the toolbar, " - "or the selected constraints,\n" - "into driving or reference mode"); - sWhatsThis = "Sketcher_ToggleDrivingConstraint"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_ToggleConstraint"; - sAccel = "K, X"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Toggle driving/reference constraint"); + sToolTipText = QT_TR_NOOP("Set the toolbar, " + "or the selected constraints,\n" + "into driving or reference mode"); + sWhatsThis = "Sketcher_ToggleDrivingConstraint"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_ToggleConstraint"; + sAccel = "K, X"; + eType = ForEdit; // list of toggle driving constraint commands - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainLock"); rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainDistance"); rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainDistanceX"); @@ -7337,52 +8371,55 @@ CmdSketcherToggleDrivingConstraint::CmdSketcherToggleDrivingConstraint() rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainRadiam"); rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainAngle"); rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_CompConstrainRadDia"); - //rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainSnellsLaw"); + // rcCmdMgr.addCommandMode("ToggleDrivingConstraint", "Sketcher_ConstrainSnellsLaw"); } void CmdSketcherToggleDrivingConstraint::activated(int iMsg) { Q_UNUSED(iMsg); - bool modeChange=true; + bool modeChange = true; std::vector selection; - if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0){ + if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) { // Now we check whether we have a constraint selected or not. // get the selection selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), QObject::tr("Wrong selection"), QObject::tr("Select constraints from the sketch.")); return; } - Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); + Sketcher::SketchObject* Obj = + static_cast(selection[0].getObject()); // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select constraints from the sketch.")); return; } - for (std::vector::const_iterator it=SubNames.begin();it!=SubNames.end();++it){ + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { // see if we have constraints, if we do it is not a mode change, but a toggle. - if (it->size() > 10 && it->substr(0,10) == "Constraint") - modeChange=false; + if (it->size() > 10 && it->substr(0, 10) == "Constraint") + modeChange = false; } } if (modeChange) { // Here starts the code for mode change - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); if (constraintCreationMode == Driving) { constraintCreationMode = Reference; @@ -7391,18 +8428,20 @@ void CmdSketcherToggleDrivingConstraint::activated(int iMsg) constraintCreationMode = Driving; } - rcCmdMgr.updateCommands("ToggleDrivingConstraint", static_cast(constraintCreationMode)); + rcCmdMgr.updateCommands("ToggleDrivingConstraint", + static_cast(constraintCreationMode)); } - else // toggle the selected constraint(s) + else// toggle the selected constraint(s) { - Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); + Sketcher::SketchObject* Obj = + static_cast(selection[0].getObject()); // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select constraints from the sketch.")); return; } @@ -7410,17 +8449,18 @@ void CmdSketcherToggleDrivingConstraint::activated(int iMsg) // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Toggle constraint to driving/reference")); - int successful=SubNames.size(); + int successful = SubNames.size(); // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin();it!=SubNames.end();++it){ + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { // only handle constraints - if (it->size() > 10 && it->substr(0,10) == "Constraint") { + if (it->size() > 10 && it->substr(0, 10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); try { // issue the actual commands to toggle Gui::cmdAppObjectArgs(selection[0].getObject(), "toggleDriving(%d)", ConstrId); } - catch(const Base::Exception&) { + catch (const Base::Exception&) { successful--; } } @@ -7440,24 +8480,24 @@ void CmdSketcherToggleDrivingConstraint::activated(int iMsg) bool CmdSketcherToggleDrivingConstraint::isActive() { - return isCommandActive( getActiveGuiDocument() ); + return isCommandActive(getActiveGuiDocument()); } DEF_STD_CMD_A(CmdSketcherToggleActiveConstraint) CmdSketcherToggleActiveConstraint::CmdSketcherToggleActiveConstraint() -:Command("Sketcher_ToggleActiveConstraint") + : Command("Sketcher_ToggleActiveConstraint") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Activate/deactivate constraint"); - sToolTipText = QT_TR_NOOP("Activates or deactivates " - "the selected constraints"); - sWhatsThis = "Sketcher_ToggleActiveConstraint"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_ToggleActiveConstraint"; - sAccel = "K, Z"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Activate/deactivate constraint"); + sToolTipText = QT_TR_NOOP("Activates or deactivates " + "the selected constraints"); + sWhatsThis = "Sketcher_ToggleActiveConstraint"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_ToggleActiveConstraint"; + sAccel = "K, Z"; + eType = ForEdit; } void CmdSketcherToggleActiveConstraint::activated(int iMsg) @@ -7466,28 +8506,30 @@ void CmdSketcherToggleActiveConstraint::activated(int iMsg) std::vector selection; - if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0){ + if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) { // Now we check whether we have a constraint selected or not. // get the selection selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select constraints from the sketch.")); return; } - Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); + Sketcher::SketchObject* Obj = + static_cast(selection[0].getObject()); // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { - Gui::TranslatedUserWarning( Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + Gui::TranslatedUserWarning(Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select constraints from the sketch.")); return; } @@ -7495,17 +8537,18 @@ void CmdSketcherToggleActiveConstraint::activated(int iMsg) // undo command open openCommand(QT_TRANSLATE_NOOP("Command", "Activate/Deactivate constraint")); - int successful=SubNames.size(); + int successful = SubNames.size(); - for (std::vector::const_iterator it=SubNames.begin();it!=SubNames.end();++it){ + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { - if (it->size() > 10 && it->substr(0,10) == "Constraint") { + if (it->size() > 10 && it->substr(0, 10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); try { // issue the actual commands to toggle - Gui::cmdAppObjectArgs(selection[0].getObject(), "toggleActive(%d)",ConstrId); + Gui::cmdAppObjectArgs(selection[0].getObject(), "toggleActive(%d)", ConstrId); } - catch(const Base::Exception&) { + catch (const Base::Exception&) { successful--; } } @@ -7525,13 +8568,13 @@ void CmdSketcherToggleActiveConstraint::activated(int iMsg) bool CmdSketcherToggleActiveConstraint::isActive() { - return isCreateConstraintActive( getActiveGuiDocument() ); + return isCreateConstraintActive(getActiveGuiDocument()); } void CreateSketcherCommandsConstraints() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherConstrainHorizontal()); rcCmdMgr.addCommand(new CmdSketcherConstrainVertical()); diff --git a/src/Mod/Sketcher/Gui/CommandConstraints.h b/src/Mod/Sketcher/Gui/CommandConstraints.h index 554e8bf40f..d1435459ca 100644 --- a/src/Mod/Sketcher/Gui/CommandConstraints.h +++ b/src/Mod/Sketcher/Gui/CommandConstraints.h @@ -24,12 +24,11 @@ #ifndef SKETCHERGUI_CommandConstraints_H #define SKETCHERGUI_CommandConstraints_H -#include #include +#include -namespace SketcherGui { - - +namespace SketcherGui +{ // These functions are declared here to promote code reuse from other modules @@ -42,12 +41,8 @@ namespace SketcherGui { /// NOTE: A command must be opened before calling this function, which this function /// commits or aborts as appropriate. The reason is for compatibility reasons with /// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp -void makeTangentToEllipseviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomEllipse *ellipse, - const Part::Geometry *geom2, - int geoId1, - int geoId2 - ); +void makeTangentToEllipseviaNewPoint(Sketcher::SketchObject* Obj, const Part::GeomEllipse* ellipse, + const Part::Geometry* geom2, int geoId1, int geoId2); /// Makes a tangency constraint using external construction line between /// aoe => an arc of ellipse /// geom2 => any of an arc of ellipse, a circle, or an arc (of circle) @@ -57,11 +52,8 @@ void makeTangentToEllipseviaNewPoint(Sketcher::SketchObject* Obj, /// commits or aborts as appropriate. The reason is for compatibility reasons with /// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp void makeTangentToArcOfEllipseviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfEllipse *aoe, - const Part::Geometry *geom2, - int geoId1, - int geoId2 - ); + const Part::GeomArcOfEllipse* aoe, + const Part::Geometry* geom2, int geoId1, int geoId2); /// Makes a tangency constraint using external construction line between /// aoh => an arc of hyperbola @@ -72,36 +64,34 @@ void makeTangentToArcOfEllipseviaNewPoint(Sketcher::SketchObject* Obj, /// commits or aborts as appropriate. The reason is for compatibility reasons with /// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp void makeTangentToArcOfHyperbolaviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfHyperbola *aoh, - const Part::Geometry *geom2, - int geoId1, - int geoId2 - ); + const Part::GeomArcOfHyperbola* aoh, + const Part::Geometry* geom2, int geoId1, int geoId2); /// Makes a simple tangency constraint using extra point + tangent via point /// aop => an arc of parabola -/// geom2 => any of an arc of parabola, an arc of hyperbola an arc of ellipse, a circle, or an arc (of circle) +/// geom2 => any of an arc of parabola, an arc of hyperbola an arc of ellipse, a circle, or an arc +/// (of circle) /// geoId1 => geoid of the arc of parabola /// geoId2 => geoid of geom2 -/// NOTE: A command must be opened before calling this function, which this function -/// commits or aborts as appropriate. The reason is for compatibility reasons with -/// other code e.g. "Autoconstraints" in DrawSketchHandler.cpp +/// NOTE: A command must +/// be opened before calling this function, which this function commits or aborts as appropriate. +/// The reason is for compatibility reasons with other code e.g. "Autoconstraints" in +/// DrawSketchHandler.cpp void makeTangentToArcOfParabolaviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfParabola *aop, - const Part::Geometry *geom2, - int geoId1, - int geoId2 - ); + const Part::GeomArcOfParabola* aop, + const Part::Geometry* geom2, int geoId1, int geoId2); /// Does an endpoint-to-endpoint tangency -void doEndpointTangency(Sketcher::SketchObject* Obj, int GeoId1, int GeoId2, Sketcher::PointPos PosId1, Sketcher::PointPos PosId2); +void doEndpointTangency(Sketcher::SketchObject* Obj, int GeoId1, int GeoId2, + Sketcher::PointPos PosId1, Sketcher::PointPos PosId2); /// Does an endpoint-edge tangency -void doEndpointToEdgeTangency( Sketcher::SketchObject* Obj, int GeoId1, Sketcher::PointPos PosId1, int GeoId2); +void doEndpointToEdgeTangency(Sketcher::SketchObject* Obj, int GeoId1, Sketcher::PointPos PosId1, + int GeoId2); -/// shows constraint substitution information dialog box, enabling the user to forgo further notifications -void notifyConstraintSubstitutions(const QString & message); - -} -#endif // SKETCHERGUI_CommandConstraints_H +/// shows constraint substitution information dialog box, enabling the user to forgo further +/// notifications +void notifyConstraintSubstitutions(const QString& message); +}// namespace SketcherGui +#endif// SKETCHERGUI_CommandConstraints_H diff --git a/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp b/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp index 850db37cfc..c1d5ba1fce 100644 --- a/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp +++ b/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp @@ -22,11 +22,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include +#include +#include -# include -# include +#include +#include #endif #include @@ -75,25 +75,27 @@ using namespace std; using namespace SketcherGui; -#define CONSTRUCTION_UPDATE_ACTION(CLASS, ICON) \ - /* This macro creates an updateAction() function that will toggle between normal & construction icon */ \ - void CLASS::updateAction(int mode) \ - { \ - auto act = getAction(); \ - if (act) { \ - switch (mode) { \ - case Normal: \ - act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON)); \ - break; \ - case Construction: \ - act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON "_Constr")); \ - break; \ - } \ - } \ +#define CONSTRUCTION_UPDATE_ACTION(CLASS, ICON) \ + /* This macro creates an updateAction() function that will toggle between normal & \ + * construction icon */ \ + void CLASS::updateAction(int mode) \ + { \ + auto act = getAction(); \ + if (act) { \ + switch (mode) { \ + case Normal: \ + act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON)); \ + break; \ + case Construction: \ + act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON "_Constr")); \ + break; \ + } \ + } \ } -namespace SketcherGui { -GeometryCreationMode geometryCreationMode=Normal; +namespace SketcherGui +{ +GeometryCreationMode geometryCreationMode = Normal; } /* Sketch commands =======================================================*/ @@ -101,25 +103,25 @@ GeometryCreationMode geometryCreationMode=Normal; DEF_STD_CMD_AU(CmdSketcherCreateLine) CmdSketcherCreateLine::CmdSketcherCreateLine() - : Command("Sketcher_CreateLine") + : Command("Sketcher_CreateLine") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create line"); - sToolTipText = QT_TR_NOOP("Create a line in the sketch"); - sWhatsThis = "Sketcher_CreateLine"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateLine"; - sAccel = "G, L"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create line"); + sToolTipText = QT_TR_NOOP("Create a line in the sketch"); + sWhatsThis = "Sketcher_CreateLine"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateLine"; + sAccel = "G, L"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateLine,"Sketcher_CreateLine") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateLine, "Sketcher_CreateLine") void CmdSketcherCreateLine::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerLine() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerLine()); } bool CmdSketcherCreateLine::isActive() @@ -133,25 +135,26 @@ bool CmdSketcherCreateLine::isActive() DEF_STD_CMD_AU(CmdSketcherCreateRectangle) CmdSketcherCreateRectangle::CmdSketcherCreateRectangle() - : Command("Sketcher_CreateRectangle") + : Command("Sketcher_CreateRectangle") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create rectangle"); - sToolTipText = QT_TR_NOOP("Create a rectangle in the sketch"); - sWhatsThis = "Sketcher_CreateRectangle"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateRectangle"; - sAccel = "G, R"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create rectangle"); + sToolTipText = QT_TR_NOOP("Create a rectangle in the sketch"); + sWhatsThis = "Sketcher_CreateRectangle"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateRectangle"; + sAccel = "G, R"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangle,"Sketcher_CreateRectangle") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangle, "Sketcher_CreateRectangle") void CmdSketcherCreateRectangle::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBox(DrawSketchHandlerBox::Diagonal) ); + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerBox(DrawSketchHandlerBox::Diagonal)); } bool CmdSketcherCreateRectangle::isActive() @@ -162,25 +165,26 @@ bool CmdSketcherCreateRectangle::isActive() DEF_STD_CMD_AU(CmdSketcherCreateRectangleCenter) CmdSketcherCreateRectangleCenter::CmdSketcherCreateRectangleCenter() - : Command("Sketcher_CreateRectangle_Center") + : Command("Sketcher_CreateRectangle_Center") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create centered rectangle"); - sToolTipText = QT_TR_NOOP("Create a centered rectangle in the sketch"); - sWhatsThis = "Sketcher_CreateRectangle_Center"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateRectangle_Center"; - sAccel = "G, V"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create centered rectangle"); + sToolTipText = QT_TR_NOOP("Create a centered rectangle in the sketch"); + sWhatsThis = "Sketcher_CreateRectangle_Center"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateRectangle_Center"; + sAccel = "G, V"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangleCenter,"Sketcher_CreateRectangle_Center") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangleCenter, "Sketcher_CreateRectangle_Center") void CmdSketcherCreateRectangleCenter::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBox(DrawSketchHandlerBox::CenterAndCorner) ); + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerBox(DrawSketchHandlerBox::CenterAndCorner)); } bool CmdSketcherCreateRectangleCenter::isActive() @@ -207,7 +211,7 @@ CmdSketcherCreateOblong::CmdSketcherCreateOblong() eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOblong,"Sketcher_CreateOblong") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOblong, "Sketcher_CreateOblong") void CmdSketcherCreateOblong::activated(int iMsg) { @@ -239,9 +243,11 @@ CmdSketcherCompCreateRectangles::CmdSketcherCompCreateRectangles() void CmdSketcherCompCreateRectangles::activated(int iMsg) { if (iMsg == 0) - ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerBox(DrawSketchHandlerBox::Diagonal)); + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerBox(DrawSketchHandlerBox::Diagonal)); else if (iMsg == 1) - ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerBox(DrawSketchHandlerBox::CenterAndCorner)); + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerBox(DrawSketchHandlerBox::CenterAndCorner)); else if (iMsg == 2) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerOblong()); else @@ -288,18 +294,19 @@ void CmdSketcherCompCreateRectangles::updateAction(int mode) QList a = pcAction->actions(); int index = pcAction->property("defaultAction").toInt(); switch (mode) { - case Normal: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong")); - getAction()->setIcon(a[index]->icon()); - break; - case Construction: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong_Constr")); - getAction()->setIcon(a[index]->icon()); - break; + case Normal: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center")); + a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong")); + getAction()->setIcon(a[index]->icon()); + break; + case Construction: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr")); + a[1]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr")); + a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong_Constr")); + getAction()->setIcon(a[index]->icon()); + break; } } @@ -314,15 +321,20 @@ void CmdSketcherCompCreateRectangles::languageChange() QAction* rectangle1 = a[0]; rectangle1->setText(QApplication::translate("CmdSketcherCompCreateRectangles", "Rectangle")); - rectangle1->setToolTip(QApplication::translate("Sketcher_CreateRectangle", "Create a rectangle")); + rectangle1->setToolTip( + QApplication::translate("Sketcher_CreateRectangle", "Create a rectangle")); rectangle1->setStatusTip(rectangle1->toolTip()); QAction* rectangle2 = a[1]; - rectangle2->setText(QApplication::translate("CmdSketcherCompCreateRectangles", "Centered rectangle")); - rectangle2->setToolTip(QApplication::translate("Sketcher_CreateRectangle_Center", "Create a centered rectangle")); + rectangle2->setText( + QApplication::translate("CmdSketcherCompCreateRectangles", "Centered rectangle")); + rectangle2->setToolTip( + QApplication::translate("Sketcher_CreateRectangle_Center", "Create a centered rectangle")); rectangle2->setStatusTip(rectangle2->toolTip()); QAction* rectangle3 = a[2]; - rectangle3->setText(QApplication::translate("CmdSketcherCompCreateRectangles", "Rounded rectangle")); - rectangle3->setToolTip(QApplication::translate("Sketcher_CreateOblong", "Create a rounded rectangle")); + rectangle3->setText( + QApplication::translate("CmdSketcherCompCreateRectangles", "Rounded rectangle")); + rectangle3->setToolTip( + QApplication::translate("Sketcher_CreateOblong", "Create a rounded rectangle")); rectangle3->setStatusTip(rectangle3->toolTip()); } @@ -336,25 +348,25 @@ bool CmdSketcherCompCreateRectangles::isActive() DEF_STD_CMD_AU(CmdSketcherCreatePolyline) CmdSketcherCreatePolyline::CmdSketcherCreatePolyline() - : Command("Sketcher_CreatePolyline") + : Command("Sketcher_CreatePolyline") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create polyline"); - sToolTipText = QT_TR_NOOP("Create a polyline in the sketch. 'M' Key cycles behaviour"); - sWhatsThis = "Sketcher_CreatePolyline"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreatePolyline"; - sAccel = "G, M"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create polyline"); + sToolTipText = QT_TR_NOOP("Create a polyline in the sketch. 'M' Key cycles behaviour"); + sWhatsThis = "Sketcher_CreatePolyline"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreatePolyline"; + sAccel = "G, M"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePolyline,"Sketcher_CreatePolyline") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePolyline, "Sketcher_CreatePolyline") void CmdSketcherCreatePolyline::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerLineSet() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerLineSet()); } bool CmdSketcherCreatePolyline::isActive() @@ -368,25 +380,25 @@ bool CmdSketcherCreatePolyline::isActive() DEF_STD_CMD_AU(CmdSketcherCreateArc) CmdSketcherCreateArc::CmdSketcherCreateArc() - : Command("Sketcher_CreateArc") + : Command("Sketcher_CreateArc") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create arc by center"); - sToolTipText = QT_TR_NOOP("Create an arc by its center and by its end points"); - sWhatsThis = "Sketcher_CreateArc"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateArc"; - sAccel = "G, A"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create arc by center"); + sToolTipText = QT_TR_NOOP("Create an arc by its center and by its end points"); + sWhatsThis = "Sketcher_CreateArc"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateArc"; + sAccel = "G, A"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArc,"Sketcher_CreateArc") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArc, "Sketcher_CreateArc") void CmdSketcherCreateArc::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArc() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArc()); } bool CmdSketcherCreateArc::isActive() @@ -400,25 +412,25 @@ bool CmdSketcherCreateArc::isActive() DEF_STD_CMD_AU(CmdSketcherCreate3PointArc) CmdSketcherCreate3PointArc::CmdSketcherCreate3PointArc() - : Command("Sketcher_Create3PointArc") + : Command("Sketcher_Create3PointArc") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create arc by three points"); - sToolTipText = QT_TR_NOOP("Create an arc by its end points and a point along the arc"); - sWhatsThis = "Sketcher_Create3PointArc"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Create3PointArc"; - sAccel = "G, 3, A"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create arc by three points"); + sToolTipText = QT_TR_NOOP("Create an arc by its end points and a point along the arc"); + sWhatsThis = "Sketcher_Create3PointArc"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Create3PointArc"; + sAccel = "G, 3, A"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointArc,"Sketcher_Create3PointArc") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointArc, "Sketcher_Create3PointArc") void CmdSketcherCreate3PointArc::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandler3PointArc() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandler3PointArc()); } bool CmdSketcherCreate3PointArc::isActive() @@ -430,23 +442,23 @@ bool CmdSketcherCreate3PointArc::isActive() DEF_STD_CMD_ACLU(CmdSketcherCompCreateArc) CmdSketcherCompCreateArc::CmdSketcherCompCreateArc() - : Command("Sketcher_CompCreateArc") + : Command("Sketcher_CompCreateArc") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create arc"); - sToolTipText = QT_TR_NOOP("Create an arc in the sketcher"); - sWhatsThis = "Sketcher_CompCreateArc"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create arc"); + sToolTipText = QT_TR_NOOP("Create an arc in the sketcher"); + sWhatsThis = "Sketcher_CompCreateArc"; + sStatusTip = sToolTipText; + eType = ForEdit; } void CmdSketcherCompCreateArc::activated(int iMsg) { - if (iMsg==0) - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArc()); - else if (iMsg==1) - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandler3PointArc()); + if (iMsg == 0) + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArc()); + else if (iMsg == 1) + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandler3PointArc()); else return; @@ -459,7 +471,7 @@ void CmdSketcherCompCreateArc::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateArc::createAction() +Gui::Action* CmdSketcherCompCreateArc::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -489,16 +501,16 @@ void CmdSketcherCompCreateArc::updateAction(int mode) QList a = pcAction->actions(); int index = pcAction->property("defaultAction").toInt(); switch (mode) { - case Normal: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc")); - getAction()->setIcon(a[index]->icon()); - break; - case Construction: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc_Constr")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc_Constr")); - getAction()->setIcon(a[index]->icon()); - break; + case Normal: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc")); + getAction()->setIcon(a[index]->icon()); + break; + case Construction: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc_Constr")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc_Constr")); + getAction()->setIcon(a[index]->icon()); + break; } } @@ -512,13 +524,17 @@ void CmdSketcherCompCreateArc::languageChange() QList a = pcAction->actions(); QAction* arc1 = a[0]; - arc1->setText(QApplication::translate("CmdSketcherCompCreateArc","Center and end points")); - arc1->setToolTip(QApplication::translate("Sketcher_CreateArc","Create an arc by its center and by its end points")); - arc1->setStatusTip(QApplication::translate("Sketcher_CreateArc","Create an arc by its center and by its end points")); + arc1->setText(QApplication::translate("CmdSketcherCompCreateArc", "Center and end points")); + arc1->setToolTip(QApplication::translate("Sketcher_CreateArc", + "Create an arc by its center and by its end points")); + arc1->setStatusTip(QApplication::translate( + "Sketcher_CreateArc", "Create an arc by its center and by its end points")); QAction* arc2 = a[1]; - arc2->setText(QApplication::translate("CmdSketcherCompCreateArc","End points and rim point")); - arc2->setToolTip(QApplication::translate("Sketcher_Create3PointArc","Create an arc by its end points and a point along the arc")); - arc2->setStatusTip(QApplication::translate("Sketcher_Create3PointArc","Create an arc by its end points and a point along the arc")); + arc2->setText(QApplication::translate("CmdSketcherCompCreateArc", "End points and rim point")); + arc2->setToolTip(QApplication::translate( + "Sketcher_Create3PointArc", "Create an arc by its end points and a point along the arc")); + arc2->setStatusTip(QApplication::translate( + "Sketcher_Create3PointArc", "Create an arc by its end points and a point along the arc")); } bool CmdSketcherCompCreateArc::isActive() @@ -533,25 +549,25 @@ bool CmdSketcherCompCreateArc::isActive() DEF_STD_CMD_AU(CmdSketcherCreateCircle) CmdSketcherCreateCircle::CmdSketcherCreateCircle() - : Command("Sketcher_CreateCircle") + : Command("Sketcher_CreateCircle") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create circle"); - sToolTipText = QT_TR_NOOP("Create a circle in the sketch"); - sWhatsThis = "Sketcher_CreateCircle"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateCircle"; - sAccel = "G, C"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create circle"); + sToolTipText = QT_TR_NOOP("Create a circle in the sketch"); + sWhatsThis = "Sketcher_CreateCircle"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateCircle"; + sAccel = "G, C"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateCircle,"Sketcher_CreateCircle") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateCircle, "Sketcher_CreateCircle") void CmdSketcherCreateCircle::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerCircle() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerCircle()); } bool CmdSketcherCreateCircle::isActive() @@ -567,17 +583,17 @@ DEF_STD_CMD_AU(CmdSketcherCreateEllipseByCenter) * @brief ctor */ CmdSketcherCreateEllipseByCenter::CmdSketcherCreateEllipseByCenter() - : Command("Sketcher_CreateEllipseByCenter") + : Command("Sketcher_CreateEllipseByCenter") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create ellipse by center"); - sToolTipText = QT_TR_NOOP("Create an ellipse by center in the sketch"); - sWhatsThis = "Sketcher_CreateEllipseByCenter"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateEllipseByCenter"; - sAccel = "G, E, E"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create ellipse by center"); + sToolTipText = QT_TR_NOOP("Create an ellipse by center in the sketch"); + sWhatsThis = "Sketcher_CreateEllipseByCenter"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateEllipseByCenter"; + sAccel = "G, E, E"; + eType = ForEdit; } CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseByCenter, "Sketcher_CreateEllipseByCenter") @@ -585,7 +601,7 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseByCenter, "Sketcher_CreateEll void CmdSketcherCreateEllipseByCenter::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerEllipse(0) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerEllipse(0)); } bool CmdSketcherCreateEllipseByCenter::isActive() @@ -600,25 +616,25 @@ DEF_STD_CMD_AU(CmdSketcherCreateEllipseBy3Points) * @brief ctor */ CmdSketcherCreateEllipseBy3Points::CmdSketcherCreateEllipseBy3Points() - : Command("Sketcher_CreateEllipseBy3Points") + : Command("Sketcher_CreateEllipseBy3Points") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create ellipse by 3 points"); - sToolTipText = QT_TR_NOOP("Create an ellipse by 3 points in the sketch"); - sWhatsThis = "Sketcher_CreateEllipseBy3Points"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateEllipse_3points"; - sAccel = "G, 3, E"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create ellipse by 3 points"); + sToolTipText = QT_TR_NOOP("Create an ellipse by 3 points in the sketch"); + sWhatsThis = "Sketcher_CreateEllipseBy3Points"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateEllipse_3points"; + sAccel = "G, 3, E"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseBy3Points,"Sketcher_CreateEllipse_3points") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseBy3Points, "Sketcher_CreateEllipse_3points") void CmdSketcherCreateEllipseBy3Points::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerEllipse(1) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerEllipse(1)); } bool CmdSketcherCreateEllipseBy3Points::isActive() @@ -629,25 +645,25 @@ bool CmdSketcherCreateEllipseBy3Points::isActive() DEF_STD_CMD_AU(CmdSketcherCreateArcOfEllipse) CmdSketcherCreateArcOfEllipse::CmdSketcherCreateArcOfEllipse() - : Command("Sketcher_CreateArcOfEllipse") + : Command("Sketcher_CreateArcOfEllipse") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create an arc of ellipse"); - sToolTipText = QT_TR_NOOP("Create an arc of ellipse in the sketch"); - sWhatsThis = "Sketcher_CreateArcOfEllipse"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateElliptical_Arc"; - sAccel = "G, E, A"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create an arc of ellipse"); + sToolTipText = QT_TR_NOOP("Create an arc of ellipse in the sketch"); + sWhatsThis = "Sketcher_CreateArcOfEllipse"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateElliptical_Arc"; + sAccel = "G, E, A"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfEllipse,"Sketcher_CreateElliptical_Arc") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfEllipse, "Sketcher_CreateElliptical_Arc") void CmdSketcherCreateArcOfEllipse::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArcOfEllipse() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArcOfEllipse()); } bool CmdSketcherCreateArcOfEllipse::isActive() @@ -658,24 +674,24 @@ bool CmdSketcherCreateArcOfEllipse::isActive() DEF_STD_CMD_AU(CmdSketcherCreateArcOfHyperbola) CmdSketcherCreateArcOfHyperbola::CmdSketcherCreateArcOfHyperbola() - : Command("Sketcher_CreateArcOfHyperbola") + : Command("Sketcher_CreateArcOfHyperbola") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create an arc of hyperbola"); - sToolTipText = QT_TR_NOOP("Create an arc of hyperbola in the sketch"); - sWhatsThis = "Sketcher_CreateArcOfHyperbola"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateHyperbolic_Arc"; - sAccel = "G, H"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create an arc of hyperbola"); + sToolTipText = QT_TR_NOOP("Create an arc of hyperbola in the sketch"); + sWhatsThis = "Sketcher_CreateArcOfHyperbola"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateHyperbolic_Arc"; + sAccel = "G, H"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfHyperbola,"Sketcher_CreateHyperbolic_Arc") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfHyperbola, "Sketcher_CreateHyperbolic_Arc") void CmdSketcherCreateArcOfHyperbola::activated(int /*iMsg*/) { - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArcOfHyperbola() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArcOfHyperbola()); } bool CmdSketcherCreateArcOfHyperbola::isActive() @@ -686,24 +702,24 @@ bool CmdSketcherCreateArcOfHyperbola::isActive() DEF_STD_CMD_AU(CmdSketcherCreateArcOfParabola) CmdSketcherCreateArcOfParabola::CmdSketcherCreateArcOfParabola() - : Command("Sketcher_CreateArcOfParabola") + : Command("Sketcher_CreateArcOfParabola") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create an arc of parabola"); - sToolTipText = QT_TR_NOOP("Create an arc of parabola in the sketch"); - sWhatsThis = "Sketcher_CreateArcOfParabola"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateParabolic_Arc"; - sAccel = "G, J"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create an arc of parabola"); + sToolTipText = QT_TR_NOOP("Create an arc of parabola in the sketch"); + sWhatsThis = "Sketcher_CreateArcOfParabola"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateParabolic_Arc"; + sAccel = "G, J"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfParabola,"Sketcher_CreateParabolic_Arc") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfParabola, "Sketcher_CreateParabolic_Arc") void CmdSketcherCreateArcOfParabola::activated(int /*iMsg*/) { - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArcOfParabola() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArcOfParabola()); } bool CmdSketcherCreateArcOfParabola::isActive() @@ -712,8 +728,6 @@ bool CmdSketcherCreateArcOfParabola::isActive() } - - /// @brief Macro that declares a new sketcher command class 'CmdSketcherCompCreateEllipse' DEF_STD_CMD_ACLU(CmdSketcherCompCreateConic) @@ -721,15 +735,15 @@ DEF_STD_CMD_ACLU(CmdSketcherCompCreateConic) * @brief ctor */ CmdSketcherCompCreateConic::CmdSketcherCompCreateConic() - : Command("Sketcher_CompCreateConic") + : Command("Sketcher_CompCreateConic") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create a conic"); - sToolTipText = QT_TR_NOOP("Create a conic in the sketch"); - sWhatsThis = "Sketcher_CompCreateConic"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create a conic"); + sToolTipText = QT_TR_NOOP("Create a conic in the sketch"); + sWhatsThis = "Sketcher_CompCreateConic"; + sStatusTip = sToolTipText; + eType = ForEdit; } /** @@ -740,15 +754,20 @@ void CmdSketcherCompCreateConic::activated(int iMsg) { if (iMsg == 0) { ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerEllipse(iMsg)); - } else if (iMsg == 1) { + } + else if (iMsg == 1) { ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerEllipse(iMsg)); - } else if (iMsg == 2) { + } + else if (iMsg == 2) { ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArcOfEllipse()); - } else if (iMsg == 3) { + } + else if (iMsg == 3) { ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArcOfHyperbola()); - } else if (iMsg == 4) { + } + else if (iMsg == 4) { ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerArcOfParabola()); - } else { + } + else { return; } @@ -761,7 +780,7 @@ void CmdSketcherCompCreateConic::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateConic::createAction() +Gui::Action* CmdSketcherCompCreateConic::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -801,22 +820,27 @@ void CmdSketcherCompCreateConic::updateAction(int mode) QList a = pcAction->actions(); int index = pcAction->property("defaultAction").toInt(); switch (mode) { - case Normal: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc")); - a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc")); - a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateParabolic_Arc")); - getAction()->setIcon(a[index]->icon()); - break; - case Construction: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc_Constr")); - a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc_Constr")); - a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateParabolic_Arc_Constr")); - getAction()->setIcon(a[index]->icon()); - break; + case Normal: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); + a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc")); + a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc")); + a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateParabolic_Arc")); + getAction()->setIcon(a[index]->icon()); + break; + case Construction: + a[0]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr")); + a[1]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr")); + a[2]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc_Constr")); + a[3]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc_Constr")); + a[4]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateParabolic_Arc_Constr")); + getAction()->setIcon(a[index]->icon()); + break; } } @@ -830,25 +854,48 @@ void CmdSketcherCompCreateConic::languageChange() QList a = pcAction->actions(); QAction* ellipseByCenter = a[0]; - ellipseByCenter->setText(QApplication::translate("CmdSketcherCompCreateConic","Ellipse by center, major radius, point")); - ellipseByCenter->setToolTip(QApplication::translate("Sketcher_CreateEllipseByCenter","Create an ellipse by center, major radius and point")); - ellipseByCenter->setStatusTip(QApplication::translate("Sketcher_CreateEllipseByCenter","Create an ellipse by center, major radius and point")); + ellipseByCenter->setText(QApplication::translate("CmdSketcherCompCreateConic", + "Ellipse by center, major radius, point")); + ellipseByCenter->setToolTip(QApplication::translate( + "Sketcher_CreateEllipseByCenter", "Create an ellipse by center, major radius and point")); + ellipseByCenter->setStatusTip(QApplication::translate( + "Sketcher_CreateEllipseByCenter", "Create an ellipse by center, major radius and point")); QAction* ellipseBy3Points = a[1]; - ellipseBy3Points->setText(QApplication::translate("CmdSketcherCompCreateConic","Ellipse by periapsis, apoapsis, minor radius")); - ellipseBy3Points->setToolTip(QApplication::translate("Sketcher_CreateEllipseBy3Points","Create a ellipse by periapsis, apoapsis, and minor radius")); - ellipseBy3Points->setStatusTip(QApplication::translate("Sketcher_CreateEllipseBy3Points","Create a ellipse by periapsis, apoapsis, and minor radius")); + ellipseBy3Points->setText(QApplication::translate( + "CmdSketcherCompCreateConic", "Ellipse by periapsis, apoapsis, minor radius")); + ellipseBy3Points->setToolTip( + QApplication::translate("Sketcher_CreateEllipseBy3Points", + "Create a ellipse by periapsis, apoapsis, and minor radius")); + ellipseBy3Points->setStatusTip( + QApplication::translate("Sketcher_CreateEllipseBy3Points", + "Create a ellipse by periapsis, apoapsis, and minor radius")); QAction* arcofellipse = a[2]; - arcofellipse->setText(QApplication::translate("CmdSketcherCompCreateConic","Arc of ellipse by center, major radius, endpoints")); - arcofellipse->setToolTip(QApplication::translate("Sketcher_CreateArcOfEllipse","Create an arc of ellipse by its center, major radius, and endpoints")); - arcofellipse->setStatusTip(QApplication::translate("Sketcher_CreateArcOfEllipse","Create an arc of ellipse by its center, major radius, and endpoints")); + arcofellipse->setText(QApplication::translate( + "CmdSketcherCompCreateConic", "Arc of ellipse by center, major radius, endpoints")); + arcofellipse->setToolTip(QApplication::translate( + "Sketcher_CreateArcOfEllipse", + "Create an arc of ellipse by its center, major radius, and endpoints")); + arcofellipse->setStatusTip(QApplication::translate( + "Sketcher_CreateArcOfEllipse", + "Create an arc of ellipse by its center, major radius, and endpoints")); QAction* arcofhyperbola = a[3]; - arcofhyperbola->setText(QApplication::translate("CmdSketcherCompCreateConic","Arc of hyperbola by center, major radius, endpoints")); - arcofhyperbola->setToolTip(QApplication::translate("Sketcher_CreateArcOfHyperbola","Create an arc of hyperbola by its center, major radius, and endpoints")); - arcofhyperbola->setStatusTip(QApplication::translate("Sketcher_CreateArcOfHyperbola","Create an arc of hyperbola by its center, major radius, and endpoints")); + arcofhyperbola->setText(QApplication::translate( + "CmdSketcherCompCreateConic", "Arc of hyperbola by center, major radius, endpoints")); + arcofhyperbola->setToolTip(QApplication::translate( + "Sketcher_CreateArcOfHyperbola", + "Create an arc of hyperbola by its center, major radius, and endpoints")); + arcofhyperbola->setStatusTip(QApplication::translate( + "Sketcher_CreateArcOfHyperbola", + "Create an arc of hyperbola by its center, major radius, and endpoints")); QAction* arcofparabola = a[4]; - arcofparabola->setText(QApplication::translate("CmdSketcherCompCreateConic","Arc of parabola by focus, vertex, endpoints")); - arcofparabola->setToolTip(QApplication::translate("Sketcher_CreateArcOfParabola","Create an arc of parabola by its focus, vertex, and endpoints")); - arcofparabola->setStatusTip(QApplication::translate("Sketcher_CreateArcOfParabola","Create an arc of parabola by its focus, vertex, and endpoints")); + arcofparabola->setText(QApplication::translate("CmdSketcherCompCreateConic", + "Arc of parabola by focus, vertex, endpoints")); + arcofparabola->setToolTip( + QApplication::translate("Sketcher_CreateArcOfParabola", + "Create an arc of parabola by its focus, vertex, and endpoints")); + arcofparabola->setStatusTip( + QApplication::translate("Sketcher_CreateArcOfParabola", + "Create an arc of parabola by its focus, vertex, and endpoints")); } bool CmdSketcherCompCreateConic::isActive() @@ -861,25 +908,25 @@ bool CmdSketcherCompCreateConic::isActive() DEF_STD_CMD_AU(CmdSketcherCreateBSpline) CmdSketcherCreateBSpline::CmdSketcherCreateBSpline() - : Command("Sketcher_CreateBSpline") + : Command("Sketcher_CreateBSpline") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create B-spline"); - sToolTipText = QT_TR_NOOP("Create a B-spline via control points in the sketch."); - sWhatsThis = "Sketcher_CreateBSpline"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateBSpline"; - sAccel = "G, B, B"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create B-spline"); + sToolTipText = QT_TR_NOOP("Create a B-spline via control points in the sketch."); + sWhatsThis = "Sketcher_CreateBSpline"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateBSpline"; + sAccel = "G, B, B"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSpline,"Sketcher_CreateBSpline") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSpline, "Sketcher_CreateBSpline") void CmdSketcherCreateBSpline::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBSpline(0) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerBSpline(0)); } bool CmdSketcherCreateBSpline::isActive() @@ -894,25 +941,25 @@ DEF_STD_CMD_AU(CmdSketcherCreatePeriodicBSpline) * @brief ctor */ CmdSketcherCreatePeriodicBSpline::CmdSketcherCreatePeriodicBSpline() -: Command("Sketcher_CreatePeriodicBSpline") + : Command("Sketcher_CreatePeriodicBSpline") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create periodic B-spline"); - sToolTipText = QT_TR_NOOP("Create a periodic B-spline via control points in the sketch."); - sWhatsThis = "Sketcher_CreatePeriodicBSpline"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Create_Periodic_BSpline"; - sAccel = "G, B, P"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create periodic B-spline"); + sToolTipText = QT_TR_NOOP("Create a periodic B-spline via control points in the sketch."); + sWhatsThis = "Sketcher_CreatePeriodicBSpline"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Create_Periodic_BSpline"; + sAccel = "G, B, P"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSpline,"Sketcher_Create_Periodic_BSpline") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSpline, "Sketcher_Create_Periodic_BSpline") void CmdSketcherCreatePeriodicBSpline::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBSpline(1) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerBSpline(1)); } bool CmdSketcherCreatePeriodicBSpline::isActive() @@ -920,29 +967,31 @@ bool CmdSketcherCreatePeriodicBSpline::isActive() return isCommandActive(getActiveGuiDocument()); } -/// @brief Macro that declares a new sketcher command class 'CmdSketcherCreateBSplineByInterpolation' +/// @brief Macro that declares a new sketcher command class +/// 'CmdSketcherCreateBSplineByInterpolation' DEF_STD_CMD_AU(CmdSketcherCreateBSplineByInterpolation) CmdSketcherCreateBSplineByInterpolation::CmdSketcherCreateBSplineByInterpolation() -: Command("Sketcher_CreateBSplineByInterpolation") + : Command("Sketcher_CreateBSplineByInterpolation") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Interpolate B-spline"); - sToolTipText = QT_TR_NOOP("Create a B-spline by interpolation, i.e. via knots in the sketch."); - sWhatsThis = "Sketcher_CreateBSplineByInterpolation"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateBSplineByInterpolation"; - sAccel = "G, B, I"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Interpolate B-spline"); + sToolTipText = QT_TR_NOOP("Create a B-spline by interpolation, i.e. via knots in the sketch."); + sWhatsThis = "Sketcher_CreateBSplineByInterpolation"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateBSplineByInterpolation"; + sAccel = "G, B, I"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSplineByInterpolation,"Sketcher_CreateBSplineByInterpolation") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSplineByInterpolation, + "Sketcher_CreateBSplineByInterpolation") void CmdSketcherCreateBSplineByInterpolation::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBSplineByInterpolation(0) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerBSplineByInterpolation(0)); } bool CmdSketcherCreateBSplineByInterpolation::isActive() @@ -950,29 +999,32 @@ bool CmdSketcherCreateBSplineByInterpolation::isActive() return isCommandActive(getActiveGuiDocument()); } -/// @brief Macro that declares a new sketcher command class 'CmdSketcherCreatePeriodicBSplineByInterpolation' +/// @brief Macro that declares a new sketcher command class +/// 'CmdSketcherCreatePeriodicBSplineByInterpolation' DEF_STD_CMD_AU(CmdSketcherCreatePeriodicBSplineByInterpolation) CmdSketcherCreatePeriodicBSplineByInterpolation::CmdSketcherCreatePeriodicBSplineByInterpolation() -: Command("Sketcher_CreatePeriodicBSplineByInterpolation") + : Command("Sketcher_CreatePeriodicBSplineByInterpolation") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Interpolate periodic B-spline"); - sToolTipText = QT_TR_NOOP("Create a periodic B-spline by interpolation, i.e. via knots in the sketch."); - sWhatsThis = "Sketcher_Create_Periodic_BSplineByInterpolation"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Create_Periodic_BSplineByInterpolation"; - sAccel = "G, B, O"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Interpolate periodic B-spline"); + sToolTipText = + QT_TR_NOOP("Create a periodic B-spline by interpolation, i.e. via knots in the sketch."); + sWhatsThis = "Sketcher_Create_Periodic_BSplineByInterpolation"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Create_Periodic_BSplineByInterpolation"; + sAccel = "G, B, O"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSplineByInterpolation,"Sketcher_CreatePeriodicBSplineByInterpolation") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSplineByInterpolation, + "Sketcher_CreatePeriodicBSplineByInterpolation") void CmdSketcherCreatePeriodicBSplineByInterpolation::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBSplineByInterpolation(1) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerBSplineByInterpolation(1)); } bool CmdSketcherCreatePeriodicBSplineByInterpolation::isActive() @@ -988,15 +1040,15 @@ DEF_STD_CMD_ACLU(CmdSketcherCompCreateBSpline) * @brief ctor */ CmdSketcherCompCreateBSpline::CmdSketcherCompCreateBSpline() -: Command("Sketcher_CompCreateBSpline") + : Command("Sketcher_CompCreateBSpline") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create a B-spline"); - sToolTipText = QT_TR_NOOP("Create a B-spline in the sketch"); - sWhatsThis = "Sketcher_CompCreateBSpline"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create a B-spline"); + sToolTipText = QT_TR_NOOP("Create a B-spline in the sketch"); + sWhatsThis = "Sketcher_CompCreateBSpline"; + sStatusTip = sToolTipText; + eType = ForEdit; } /** @@ -1030,7 +1082,7 @@ void CmdSketcherCompCreateBSpline::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateBSpline::createAction() +Gui::Action* CmdSketcherCompCreateBSpline::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1040,13 +1092,16 @@ Gui::Action * CmdSketcherCompCreateBSpline::createAction() bspline->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline")); QAction* periodicbspline = pcAction->addAction(QString()); - periodicbspline->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline")); + periodicbspline->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline")); QAction* bsplinebyknot = pcAction->addAction(QString()); - bsplinebyknot->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation")); + bsplinebyknot->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation")); QAction* periodicbsplinebyknot = pcAction->addAction(QString()); - periodicbsplinebyknot->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSplineByInterpolation")); + periodicbsplinebyknot->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSplineByInterpolation")); _pcAction = pcAction; languageChange(); @@ -1071,15 +1126,20 @@ void CmdSketcherCompCreateBSpline::updateAction(int mode) case Normal: a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline")); a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation")); - a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSplineByInterpolation")); + a[2]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation")); + a[3]->setIcon(Gui::BitmapFactory().iconFromTheme( + "Sketcher_Create_Periodic_BSplineByInterpolation")); getAction()->setIcon(a[index]->icon()); break; case Construction: a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline_Constr")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline_Constr")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation_Constr")); - a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSplineByInterpolation_Constr")); + a[1]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline_Constr")); + a[2]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation_Constr")); + a[3]->setIcon(Gui::BitmapFactory().iconFromTheme( + "Sketcher_Create_Periodic_BSplineByInterpolation_Constr")); getAction()->setIcon(a[index]->icon()); break; } @@ -1095,21 +1155,33 @@ void CmdSketcherCompCreateBSpline::languageChange() QList a = pcAction->actions(); QAction* bspline = a[0]; - bspline->setText(QApplication::translate("Sketcher_CreateBSpline","B-spline by control points")); - bspline->setToolTip(QApplication::translate("Sketcher_CreateBSpline","Create a B-spline by control points")); - bspline->setStatusTip(QApplication::translate("Sketcher_CreateBSpline","Create a B-spline by control points")); + bspline->setText( + QApplication::translate("Sketcher_CreateBSpline", "B-spline by control points")); + bspline->setToolTip( + QApplication::translate("Sketcher_CreateBSpline", "Create a B-spline by control points")); + bspline->setStatusTip( + QApplication::translate("Sketcher_CreateBSpline", "Create a B-spline by control points")); QAction* periodicbspline = a[1]; - periodicbspline->setText(QApplication::translate("Sketcher_Create_Periodic_BSpline","Periodic B-spline by control points")); - periodicbspline->setToolTip(QApplication::translate("Sketcher_Create_Periodic_BSpline","Create a periodic B-spline by control points")); - periodicbspline->setStatusTip(QApplication::translate("Sketcher_Create_Periodic_BSpline","Create a periodic B-spline by control points")); + periodicbspline->setText(QApplication::translate("Sketcher_Create_Periodic_BSpline", + "Periodic B-spline by control points")); + periodicbspline->setToolTip(QApplication::translate( + "Sketcher_Create_Periodic_BSpline", "Create a periodic B-spline by control points")); + periodicbspline->setStatusTip(QApplication::translate( + "Sketcher_Create_Periodic_BSpline", "Create a periodic B-spline by control points")); QAction* bsplinebyknot = a[2]; - bsplinebyknot->setText(QApplication::translate("Sketcher_CreateBSplineByInterpolation","B-spline by knots")); - bsplinebyknot->setToolTip(QApplication::translate("Sketcher_CreateBSplineByInterpolation","Create a B-spline by knots")); - bsplinebyknot->setStatusTip(QApplication::translate("Sketcher_CreateBSplineByInterpolation","Create a B-spline by knots")); + bsplinebyknot->setText( + QApplication::translate("Sketcher_CreateBSplineByInterpolation", "B-spline by knots")); + bsplinebyknot->setToolTip(QApplication::translate("Sketcher_CreateBSplineByInterpolation", + "Create a B-spline by knots")); + bsplinebyknot->setStatusTip(QApplication::translate("Sketcher_CreateBSplineByInterpolation", + "Create a B-spline by knots")); QAction* periodicbsplinebyknot = a[3]; - periodicbsplinebyknot->setText(QApplication::translate("Sketcher_Create_Periodic_BSplineByInterpolation","Periodic B-spline by knots")); - periodicbsplinebyknot->setToolTip(QApplication::translate("Sketcher_Create_Periodic_BSplineByInterpolation","Create a periodic B-spline by knots")); - periodicbsplinebyknot->setStatusTip(QApplication::translate("Sketcher_Create_Periodic_BSplineByInterpolation","Create a periodic B-spline by knots")); + periodicbsplinebyknot->setText(QApplication::translate( + "Sketcher_Create_Periodic_BSplineByInterpolation", "Periodic B-spline by knots")); + periodicbsplinebyknot->setToolTip(QApplication::translate( + "Sketcher_Create_Periodic_BSplineByInterpolation", "Create a periodic B-spline by knots")); + periodicbsplinebyknot->setStatusTip(QApplication::translate( + "Sketcher_Create_Periodic_BSplineByInterpolation", "Create a periodic B-spline by knots")); } bool CmdSketcherCompCreateBSpline::isActive() @@ -1123,25 +1195,25 @@ bool CmdSketcherCompCreateBSpline::isActive() DEF_STD_CMD_AU(CmdSketcherCreate3PointCircle) CmdSketcherCreate3PointCircle::CmdSketcherCreate3PointCircle() - : Command("Sketcher_Create3PointCircle") + : Command("Sketcher_Create3PointCircle") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create circle by three points"); - sToolTipText = QT_TR_NOOP("Create a circle by 3 perimeter points"); - sWhatsThis = "Sketcher_Create3PointCircle"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Create3PointCircle"; - sAccel = "G, 3, C"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create circle by three points"); + sToolTipText = QT_TR_NOOP("Create a circle by 3 perimeter points"); + sWhatsThis = "Sketcher_Create3PointCircle"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Create3PointCircle"; + sAccel = "G, 3, C"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointCircle,"Sketcher_Create3PointCircle") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointCircle, "Sketcher_Create3PointCircle") void CmdSketcherCreate3PointCircle::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandler3PointCircle() ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandler3PointCircle()); } bool CmdSketcherCreate3PointCircle::isActive() @@ -1153,23 +1225,23 @@ bool CmdSketcherCreate3PointCircle::isActive() DEF_STD_CMD_ACLU(CmdSketcherCompCreateCircle) CmdSketcherCompCreateCircle::CmdSketcherCompCreateCircle() - : Command("Sketcher_CompCreateCircle") + : Command("Sketcher_CompCreateCircle") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create circle"); - sToolTipText = QT_TR_NOOP("Create a circle in the sketcher"); - sWhatsThis = "Sketcher_CompCreateCircle"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create circle"); + sToolTipText = QT_TR_NOOP("Create a circle in the sketcher"); + sWhatsThis = "Sketcher_CompCreateCircle"; + sStatusTip = sToolTipText; + eType = ForEdit; } void CmdSketcherCompCreateCircle::activated(int iMsg) { - if (iMsg==0) - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerCircle()); - else if (iMsg==1) - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandler3PointCircle()); + if (iMsg == 0) + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerCircle()); + else if (iMsg == 1) + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandler3PointCircle()); else return; @@ -1182,7 +1254,7 @@ void CmdSketcherCompCreateCircle::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateCircle::createAction() +Gui::Action* CmdSketcherCompCreateCircle::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1212,16 +1284,16 @@ void CmdSketcherCompCreateCircle::updateAction(int mode) QList a = pcAction->actions(); int index = pcAction->property("defaultAction").toInt(); switch (mode) { - case Normal: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle")); - getAction()->setIcon(a[index]->icon()); - break; - case Construction: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle_Constr")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle_Constr")); - getAction()->setIcon(a[index]->icon()); - break; + case Normal: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle")); + getAction()->setIcon(a[index]->icon()); + break; + case Construction: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle_Constr")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle_Constr")); + getAction()->setIcon(a[index]->icon()); + break; } } @@ -1236,12 +1308,16 @@ void CmdSketcherCompCreateCircle::languageChange() QAction* arc1 = a[0]; arc1->setText(QApplication::translate("CmdSketcherCompCreateCircle", "Center and rim point")); - arc1->setToolTip(QApplication::translate("Sketcher_CreateCircle", "Create a circle by its center and by a rim point")); - arc1->setStatusTip(QApplication::translate("Sketcher_CreateCircle", "Create a circle by its center and by a rim point")); + arc1->setToolTip(QApplication::translate("Sketcher_CreateCircle", + "Create a circle by its center and by a rim point")); + arc1->setStatusTip(QApplication::translate("Sketcher_CreateCircle", + "Create a circle by its center and by a rim point")); QAction* arc2 = a[1]; arc2->setText(QApplication::translate("CmdSketcherCompCreateCircle", "3 rim points")); - arc2->setToolTip(QApplication::translate("Sketcher_Create3PointCircle", "Create a circle by 3 rim points")); - arc2->setStatusTip(QApplication::translate("Sketcher_Create3PointCircle", "Create a circle by 3 rim points")); + arc2->setToolTip( + QApplication::translate("Sketcher_Create3PointCircle", "Create a circle by 3 rim points")); + arc2->setStatusTip( + QApplication::translate("Sketcher_Create3PointCircle", "Create a circle by 3 rim points")); } bool CmdSketcherCompCreateCircle::isActive() @@ -1256,17 +1332,17 @@ bool CmdSketcherCompCreateCircle::isActive() DEF_STD_CMD_A(CmdSketcherCreatePoint) CmdSketcherCreatePoint::CmdSketcherCreatePoint() - : Command("Sketcher_CreatePoint") + : Command("Sketcher_CreatePoint") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create point"); - sToolTipText = QT_TR_NOOP("Create a point in the sketch"); - sWhatsThis = "Sketcher_CreatePoint"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreatePoint"; - sAccel = "G, Y"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create point"); + sToolTipText = QT_TR_NOOP("Create a point in the sketch"); + sWhatsThis = "Sketcher_CreatePoint"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreatePoint"; + sAccel = "G, Y"; + eType = ForEdit; } void CmdSketcherCreatePoint::activated(int iMsg) @@ -1285,23 +1361,24 @@ bool CmdSketcherCreatePoint::isActive() DEF_STD_CMD_A(CmdSketcherCreateFillet) CmdSketcherCreateFillet::CmdSketcherCreateFillet() - : Command("Sketcher_CreateFillet") + : Command("Sketcher_CreateFillet") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create fillet"); - sToolTipText = QT_TR_NOOP("Create a fillet between two lines or at a coincident point"); - sWhatsThis = "Sketcher_CreateFillet"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateFillet"; - sAccel = "G, F, F"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create fillet"); + sToolTipText = QT_TR_NOOP("Create a fillet between two lines or at a coincident point"); + sWhatsThis = "Sketcher_CreateFillet"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateFillet"; + sAccel = "G, F, F"; + eType = ForEdit; } void CmdSketcherCreateFillet::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerFillet(DrawSketchHandlerFillet::SimpleFillet)); + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerFillet(DrawSketchHandlerFillet::SimpleFillet)); } bool CmdSketcherCreateFillet::isActive() @@ -1314,23 +1391,25 @@ bool CmdSketcherCreateFillet::isActive() DEF_STD_CMD_A(CmdSketcherCreatePointFillet) CmdSketcherCreatePointFillet::CmdSketcherCreatePointFillet() - : Command("Sketcher_CreatePointFillet") + : Command("Sketcher_CreatePointFillet") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create corner-preserving fillet"); - sToolTipText = QT_TR_NOOP("Fillet that preserves intersection point and most constraints"); - sWhatsThis = "Sketcher_CreatePointFillet"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreatePointFillet"; - sAccel = "G, F, P"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create corner-preserving fillet"); + sToolTipText = QT_TR_NOOP("Fillet that preserves intersection point and most constraints"); + sWhatsThis = "Sketcher_CreatePointFillet"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreatePointFillet"; + sAccel = "G, F, P"; + eType = ForEdit; } void CmdSketcherCreatePointFillet::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerFillet(DrawSketchHandlerFillet::ConstraintPreservingFillet)); + ActivateHandler( + getActiveGuiDocument(), + new DrawSketchHandlerFillet(DrawSketchHandlerFillet::ConstraintPreservingFillet)); } bool CmdSketcherCreatePointFillet::isActive() @@ -1345,15 +1424,15 @@ DEF_STD_CMD_ACLU(CmdSketcherCompCreateFillets) * @brief ctor */ CmdSketcherCompCreateFillets::CmdSketcherCompCreateFillets() - : Command("Sketcher_CompCreateFillets") + : Command("Sketcher_CompCreateFillets") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Fillets"); - sToolTipText = QT_TR_NOOP("Create a fillet between two lines"); - sWhatsThis = "Sketcher_CompCreateFillets"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Fillets"); + sToolTipText = QT_TR_NOOP("Create a fillet between two lines"); + sWhatsThis = "Sketcher_CompCreateFillets"; + sStatusTip = sToolTipText; + eType = ForEdit; } /** @@ -1363,10 +1442,15 @@ CmdSketcherCompCreateFillets::CmdSketcherCompCreateFillets() void CmdSketcherCompCreateFillets::activated(int iMsg) { if (iMsg == 0) { - ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerFillet(DrawSketchHandlerFillet::SimpleFillet)); - } else if (iMsg == 1) { - ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerFillet(DrawSketchHandlerFillet::ConstraintPreservingFillet)); - } else { + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerFillet(DrawSketchHandlerFillet::SimpleFillet)); + } + else if (iMsg == 1) { + ActivateHandler( + getActiveGuiDocument(), + new DrawSketchHandlerFillet(DrawSketchHandlerFillet::ConstraintPreservingFillet)); + } + else { return; } @@ -1379,7 +1463,7 @@ void CmdSketcherCompCreateFillets::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateFillets::createAction() +Gui::Action* CmdSketcherCompCreateFillets::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1425,13 +1509,18 @@ void CmdSketcherCompCreateFillets::languageChange() QList a = pcAction->actions(); QAction* oldFillet = a[0]; - oldFillet->setText(QApplication::translate("CmdSketcherCompCreateFillets","Sketch fillet")); - oldFillet->setToolTip(QApplication::translate("Sketcher_CreateFillet","Creates a radius between two lines")); - oldFillet->setStatusTip(QApplication::translate("Sketcher_CreateFillet","Creates a radius between two lines")); + oldFillet->setText(QApplication::translate("CmdSketcherCompCreateFillets", "Sketch fillet")); + oldFillet->setToolTip( + QApplication::translate("Sketcher_CreateFillet", "Creates a radius between two lines")); + oldFillet->setStatusTip( + QApplication::translate("Sketcher_CreateFillet", "Creates a radius between two lines")); QAction* pointFillet = a[1]; - pointFillet->setText(QApplication::translate("CmdSketcherCompCreateFillets","Constraint-preserving sketch fillet")); - pointFillet->setToolTip(QApplication::translate("Sketcher_CreatePointFillet","Fillet that preserves constraints and intersection point")); - pointFillet->setStatusTip(QApplication::translate("Sketcher_CreatePointFillet","Fillet that preserves constraints and intersection point")); + pointFillet->setText(QApplication::translate("CmdSketcherCompCreateFillets", + "Constraint-preserving sketch fillet")); + pointFillet->setToolTip(QApplication::translate( + "Sketcher_CreatePointFillet", "Fillet that preserves constraints and intersection point")); + pointFillet->setStatusTip(QApplication::translate( + "Sketcher_CreatePointFillet", "Fillet that preserves constraints and intersection point")); } bool CmdSketcherCompCreateFillets::isActive() @@ -1444,17 +1533,17 @@ bool CmdSketcherCompCreateFillets::isActive() DEF_STD_CMD_A(CmdSketcherTrimming) CmdSketcherTrimming::CmdSketcherTrimming() - : Command("Sketcher_Trimming") + : Command("Sketcher_Trimming") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Trim edge"); - sToolTipText = QT_TR_NOOP("Trim an edge with respect to the picked position"); - sWhatsThis = "Sketcher_Trimming"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Trimming"; - sAccel = "G, T"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Trim edge"); + sToolTipText = QT_TR_NOOP("Trim an edge with respect to the picked position"); + sWhatsThis = "Sketcher_Trimming"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Trimming"; + sAccel = "G, T"; + eType = ForEdit; } void CmdSketcherTrimming::activated(int iMsg) @@ -1473,19 +1562,19 @@ bool CmdSketcherTrimming::isActive() DEF_STD_CMD_A(CmdSketcherExtend) -//TODO: fix the translations for this +// TODO: fix the translations for this CmdSketcherExtend::CmdSketcherExtend() - : Command("Sketcher_Extend") + : Command("Sketcher_Extend") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Extend edge"); - sToolTipText = QT_TR_NOOP("Extend an edge with respect to the picked position"); - sWhatsThis = "Sketcher_Extend"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Extend"; - sAccel = "G, Q"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Extend edge"); + sToolTipText = QT_TR_NOOP("Extend an edge with respect to the picked position"); + sWhatsThis = "Sketcher_Extend"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Extend"; + sAccel = "G, Q"; + eType = ForEdit; } void CmdSketcherExtend::activated(int iMsg) @@ -1504,19 +1593,19 @@ bool CmdSketcherExtend::isActive() DEF_STD_CMD_A(CmdSketcherSplit) -//TODO: fix the translations for this +// TODO: fix the translations for this CmdSketcherSplit::CmdSketcherSplit() - : Command("Sketcher_Split") + : Command("Sketcher_Split") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Split edge"); - sToolTipText = QT_TR_NOOP("Splits an edge into two while preserving constraints"); - sWhatsThis = "Sketcher_Split"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_Split"; - sAccel = "G, Z"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Split edge"); + sToolTipText = QT_TR_NOOP("Splits an edge into two while preserving constraints"); + sWhatsThis = "Sketcher_Split"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_Split"; + sAccel = "G, Z"; + eType = ForEdit; } void CmdSketcherSplit::activated(int iMsg) @@ -1533,17 +1622,17 @@ bool CmdSketcherSplit::isActive() DEF_STD_CMD_A(CmdSketcherExternal) CmdSketcherExternal::CmdSketcherExternal() - : Command("Sketcher_External") + : Command("Sketcher_External") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create an external geometry"); - sToolTipText = QT_TR_NOOP("Create an edge linked to an external geometry"); - sWhatsThis = "Sketcher_External"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_External"; - sAccel = "G, X"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create an external geometry"); + sToolTipText = QT_TR_NOOP("Create an edge linked to an external geometry"); + sWhatsThis = "Sketcher_External"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_External"; + sAccel = "G, X"; + eType = ForEdit; } void CmdSketcherExternal::activated(int iMsg) @@ -1562,20 +1651,20 @@ bool CmdSketcherExternal::isActive() DEF_STD_CMD_AU(CmdSketcherCarbonCopy) CmdSketcherCarbonCopy::CmdSketcherCarbonCopy() -: Command("Sketcher_CarbonCopy") + : Command("Sketcher_CarbonCopy") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create a carbon copy"); - sToolTipText = QT_TR_NOOP("Copy the geometry of another sketch"); - sWhatsThis = "Sketcher_CarbonCopy"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CarbonCopy"; - sAccel = "G, W"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create a carbon copy"); + sToolTipText = QT_TR_NOOP("Copy the geometry of another sketch"); + sWhatsThis = "Sketcher_CarbonCopy"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CarbonCopy"; + sAccel = "G, W"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCarbonCopy,"Sketcher_CarbonCopy") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCarbonCopy, "Sketcher_CarbonCopy") void CmdSketcherCarbonCopy::activated(int iMsg) { @@ -1605,11 +1694,11 @@ CmdSketcherCreateSlot::CmdSketcherCreateSlot() sWhatsThis = "Sketcher_CreateSlot"; sStatusTip = sToolTipText; sPixmap = "Sketcher_CreateSlot"; - sAccel = "G, S"; + sAccel = "G, S"; eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateSlot,"Sketcher_CreateSlot") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateSlot, "Sketcher_CreateSlot") void CmdSketcherCreateSlot::activated(int iMsg) { @@ -1627,25 +1716,25 @@ bool CmdSketcherCreateSlot::isActive() DEF_STD_CMD_AU(CmdSketcherCreateTriangle) CmdSketcherCreateTriangle::CmdSketcherCreateTriangle() - : Command("Sketcher_CreateTriangle") + : Command("Sketcher_CreateTriangle") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create equilateral triangle"); - sToolTipText = QT_TR_NOOP("Create an equilateral triangle in the sketch"); - sWhatsThis = "Sketcher_CreateTriangle"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateTriangle"; - sAccel = "G, P, 3"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create equilateral triangle"); + sToolTipText = QT_TR_NOOP("Create an equilateral triangle in the sketch"); + sWhatsThis = "Sketcher_CreateTriangle"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateTriangle"; + sAccel = "G, P, 3"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateTriangle,"Sketcher_CreateTriangle") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateTriangle, "Sketcher_CreateTriangle") void CmdSketcherCreateTriangle::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(3) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(3)); } bool CmdSketcherCreateTriangle::isActive() @@ -1656,25 +1745,25 @@ bool CmdSketcherCreateTriangle::isActive() DEF_STD_CMD_AU(CmdSketcherCreateSquare) CmdSketcherCreateSquare::CmdSketcherCreateSquare() - : Command("Sketcher_CreateSquare") + : Command("Sketcher_CreateSquare") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create square"); - sToolTipText = QT_TR_NOOP("Create a square in the sketch"); - sWhatsThis = "Sketcher_CreateSquare"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateSquare"; - sAccel = "G, P, 4"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create square"); + sToolTipText = QT_TR_NOOP("Create a square in the sketch"); + sWhatsThis = "Sketcher_CreateSquare"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateSquare"; + sAccel = "G, P, 4"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateSquare,"Sketcher_CreateSquare") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateSquare, "Sketcher_CreateSquare") void CmdSketcherCreateSquare::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(4) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(4)); } bool CmdSketcherCreateSquare::isActive() @@ -1685,25 +1774,25 @@ bool CmdSketcherCreateSquare::isActive() DEF_STD_CMD_AU(CmdSketcherCreatePentagon) CmdSketcherCreatePentagon::CmdSketcherCreatePentagon() - : Command("Sketcher_CreatePentagon") + : Command("Sketcher_CreatePentagon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create pentagon"); - sToolTipText = QT_TR_NOOP("Create a pentagon in the sketch"); - sWhatsThis = "Sketcher_CreatePentagon"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreatePentagon"; - sAccel = "G, P, 5"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create pentagon"); + sToolTipText = QT_TR_NOOP("Create a pentagon in the sketch"); + sWhatsThis = "Sketcher_CreatePentagon"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreatePentagon"; + sAccel = "G, P, 5"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePentagon,"Sketcher_CreatePentagon") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePentagon, "Sketcher_CreatePentagon") void CmdSketcherCreatePentagon::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(5) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(5)); } bool CmdSketcherCreatePentagon::isActive() @@ -1715,25 +1804,25 @@ bool CmdSketcherCreatePentagon::isActive() DEF_STD_CMD_AU(CmdSketcherCreateHexagon) CmdSketcherCreateHexagon::CmdSketcherCreateHexagon() - : Command("Sketcher_CreateHexagon") + : Command("Sketcher_CreateHexagon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create hexagon"); - sToolTipText = QT_TR_NOOP("Create a hexagon in the sketch"); - sWhatsThis = "Sketcher_CreateHexagon"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateHexagon"; - sAccel = "G, P, 6"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create hexagon"); + sToolTipText = QT_TR_NOOP("Create a hexagon in the sketch"); + sWhatsThis = "Sketcher_CreateHexagon"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateHexagon"; + sAccel = "G, P, 6"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateHexagon,"Sketcher_CreateHexagon") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateHexagon, "Sketcher_CreateHexagon") void CmdSketcherCreateHexagon::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(6) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(6)); } bool CmdSketcherCreateHexagon::isActive() @@ -1744,25 +1833,25 @@ bool CmdSketcherCreateHexagon::isActive() DEF_STD_CMD_AU(CmdSketcherCreateHeptagon) CmdSketcherCreateHeptagon::CmdSketcherCreateHeptagon() - : Command("Sketcher_CreateHeptagon") + : Command("Sketcher_CreateHeptagon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create heptagon"); - sToolTipText = QT_TR_NOOP("Create a heptagon in the sketch"); - sWhatsThis = "Sketcher_CreateHeptagon"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateHeptagon"; - sAccel = "G, P, 7"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create heptagon"); + sToolTipText = QT_TR_NOOP("Create a heptagon in the sketch"); + sWhatsThis = "Sketcher_CreateHeptagon"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateHeptagon"; + sAccel = "G, P, 7"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateHeptagon,"Sketcher_CreateHeptagon") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateHeptagon, "Sketcher_CreateHeptagon") void CmdSketcherCreateHeptagon::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(7) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(7)); } bool CmdSketcherCreateHeptagon::isActive() @@ -1773,25 +1862,25 @@ bool CmdSketcherCreateHeptagon::isActive() DEF_STD_CMD_AU(CmdSketcherCreateOctagon) CmdSketcherCreateOctagon::CmdSketcherCreateOctagon() - : Command("Sketcher_CreateOctagon") + : Command("Sketcher_CreateOctagon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create octagon"); - sToolTipText = QT_TR_NOOP("Create an octagon in the sketch"); - sWhatsThis = "Sketcher_CreateOctagon"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateOctagon"; - sAccel = "G, P, 8"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create octagon"); + sToolTipText = QT_TR_NOOP("Create an octagon in the sketch"); + sWhatsThis = "Sketcher_CreateOctagon"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateOctagon"; + sAccel = "G, P, 8"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOctagon,"Sketcher_CreateOctagon") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOctagon, "Sketcher_CreateOctagon") void CmdSketcherCreateOctagon::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(8) ); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(8)); } bool CmdSketcherCreateOctagon::isActive() @@ -1802,20 +1891,20 @@ bool CmdSketcherCreateOctagon::isActive() DEF_STD_CMD_AU(CmdSketcherCreateRegularPolygon) CmdSketcherCreateRegularPolygon::CmdSketcherCreateRegularPolygon() -: Command("Sketcher_CreateRegularPolygon") + : Command("Sketcher_CreateRegularPolygon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create regular polygon"); - sToolTipText = QT_TR_NOOP("Create a regular polygon in the sketch"); - sWhatsThis = "Sketcher_CreateRegularPolygon"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_CreateRegularPolygon"; - sAccel = "G, P, R"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create regular polygon"); + sToolTipText = QT_TR_NOOP("Create a regular polygon in the sketch"); + sWhatsThis = "Sketcher_CreateRegularPolygon"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_CreateRegularPolygon"; + sAccel = "G, P, R"; + eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRegularPolygon,"Sketcher_CreateRegularPolygon") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRegularPolygon, "Sketcher_CreateRegularPolygon") void CmdSketcherCreateRegularPolygon::activated(int iMsg) { @@ -1824,7 +1913,7 @@ void CmdSketcherCreateRegularPolygon::activated(int iMsg) // Pop-up asking for values SketcherRegularPolygonDialog srpd; if (srpd.exec() == QDialog::Accepted) - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(srpd.sides)); + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(srpd.sides)); } bool CmdSketcherCreateRegularPolygon::isActive() @@ -1835,43 +1924,48 @@ bool CmdSketcherCreateRegularPolygon::isActive() DEF_STD_CMD_ACLU(CmdSketcherCompCreateRegularPolygon) CmdSketcherCompCreateRegularPolygon::CmdSketcherCompCreateRegularPolygon() - : Command("Sketcher_CompCreateRegularPolygon") + : Command("Sketcher_CompCreateRegularPolygon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Create regular polygon"); - sToolTipText = QT_TR_NOOP("Create a regular polygon in the sketcher"); - sWhatsThis = "Sketcher_CompCreateRegularPolygon"; - sStatusTip = sToolTipText; - sAccel = "G, P, P"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Create regular polygon"); + sToolTipText = QT_TR_NOOP("Create a regular polygon in the sketcher"); + sWhatsThis = "Sketcher_CompCreateRegularPolygon"; + sStatusTip = sToolTipText; + sAccel = "G, P, P"; + eType = ForEdit; } void CmdSketcherCompCreateRegularPolygon::activated(int iMsg) { - switch( iMsg ){ - case 0: - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(3)); break; - case 1: - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(4)); break; - case 2: - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(5)); break; - case 3: - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(6)); break; - case 4: - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(7)); break; - case 5: - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(8)); break; - case 6: - { - // Pop-up asking for values - SketcherRegularPolygonDialog srpd; - if (srpd.exec() == QDialog::Accepted) - ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(srpd.sides)); - } - break; - default: - return; + switch (iMsg) { + case 0: + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(3)); + break; + case 1: + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(4)); + break; + case 2: + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(5)); + break; + case 3: + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(6)); + break; + case 4: + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(7)); + break; + case 5: + ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerRegularPolygon(8)); + break; + case 6: { + // Pop-up asking for values + SketcherRegularPolygonDialog srpd; + if (srpd.exec() == QDialog::Accepted) + ActivateHandler(getActiveGuiDocument(), + new DrawSketchHandlerRegularPolygon(srpd.sides)); + } break; + default: + return; } // Since the default icon is reset when enabling/disabling the command we have @@ -1883,7 +1977,7 @@ void CmdSketcherCompCreateRegularPolygon::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateRegularPolygon::createAction() +Gui::Action* CmdSketcherCompCreateRegularPolygon::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1923,26 +2017,27 @@ void CmdSketcherCompCreateRegularPolygon::updateAction(int mode) QList a = pcAction->actions(); int index = pcAction->property("defaultAction").toInt(); switch (mode) { - case Normal: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateTriangle")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSquare")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePentagon")); - a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHexagon")); - a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHeptagon")); - a[5]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOctagon")); - a[6]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRegularPolygon")); - getAction()->setIcon(a[index]->icon()); - break; - case Construction: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateTriangle_Constr")); - a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSquare_Constr")); - a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePentagon_Constr")); - a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHexagon_Constr")); - a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHeptagon_Constr")); - a[5]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOctagon_Constr")); - a[6]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRegularPolygon_Constr")); - getAction()->setIcon(a[index]->icon()); - break; + case Normal: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateTriangle")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSquare")); + a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePentagon")); + a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHexagon")); + a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHeptagon")); + a[5]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOctagon")); + a[6]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRegularPolygon")); + getAction()->setIcon(a[index]->icon()); + break; + case Construction: + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateTriangle_Constr")); + a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSquare_Constr")); + a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePentagon_Constr")); + a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHexagon_Constr")); + a[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHeptagon_Constr")); + a[5]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOctagon_Constr")); + a[6]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRegularPolygon_Constr")); + getAction()->setIcon(a[index]->icon()); + break; } } @@ -1956,33 +2051,50 @@ void CmdSketcherCompCreateRegularPolygon::languageChange() QList a = pcAction->actions(); QAction* triangle = a[0]; - triangle->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Triangle")); - triangle->setToolTip(QApplication::translate("Sketcher_CreateTriangle","Create an equilateral triangle by its center and by one corner")); - triangle->setStatusTip(QApplication::translate("Sketcher_CreateTriangle","Create an equilateral triangle by its center and by one corner")); + triangle->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Triangle")); + triangle->setToolTip( + QApplication::translate("Sketcher_CreateTriangle", + "Create an equilateral triangle by its center and by one corner")); + triangle->setStatusTip( + QApplication::translate("Sketcher_CreateTriangle", + "Create an equilateral triangle by its center and by one corner")); QAction* square = a[1]; - square->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Square")); - square->setToolTip(QApplication::translate("Sketcher_CreateSquare","Create a square by its center and by one corner")); - square->setStatusTip(QApplication::translate("Sketcher_CreateSquare","Create a square by its center and by one corner")); + square->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Square")); + square->setToolTip(QApplication::translate("Sketcher_CreateSquare", + "Create a square by its center and by one corner")); + square->setStatusTip(QApplication::translate( + "Sketcher_CreateSquare", "Create a square by its center and by one corner")); QAction* pentagon = a[2]; - pentagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Pentagon")); - pentagon->setToolTip(QApplication::translate("Sketcher_CreatePentagon","Create a pentagon by its center and by one corner")); - pentagon->setStatusTip(QApplication::translate("Sketcher_CreatePentagon","Create a pentagon by its center and by one corner")); + pentagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Pentagon")); + pentagon->setToolTip(QApplication::translate( + "Sketcher_CreatePentagon", "Create a pentagon by its center and by one corner")); + pentagon->setStatusTip(QApplication::translate( + "Sketcher_CreatePentagon", "Create a pentagon by its center and by one corner")); QAction* hexagon = a[3]; - hexagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Hexagon")); - hexagon->setToolTip(QApplication::translate("Sketcher_CreateHexagon","Create a hexagon by its center and by one corner")); - hexagon->setStatusTip(QApplication::translate("Sketcher_CreateHexagon","Create a hexagon by its center and by one corner")); + hexagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Hexagon")); + hexagon->setToolTip(QApplication::translate( + "Sketcher_CreateHexagon", "Create a hexagon by its center and by one corner")); + hexagon->setStatusTip(QApplication::translate( + "Sketcher_CreateHexagon", "Create a hexagon by its center and by one corner")); QAction* heptagon = a[4]; - heptagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Heptagon")); - heptagon->setToolTip(QApplication::translate("Sketcher_CreateHeptagon","Create a heptagon by its center and by one corner")); - heptagon->setStatusTip(QApplication::translate("Sketcher_CreateHeptagon","Create a heptagon by its center and by one corner")); + heptagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Heptagon")); + heptagon->setToolTip(QApplication::translate( + "Sketcher_CreateHeptagon", "Create a heptagon by its center and by one corner")); + heptagon->setStatusTip(QApplication::translate( + "Sketcher_CreateHeptagon", "Create a heptagon by its center and by one corner")); QAction* octagon = a[5]; - octagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Octagon")); - octagon->setToolTip(QApplication::translate("Sketcher_CreateOctagon","Create an octagon by its center and by one corner")); - octagon->setStatusTip(QApplication::translate("Sketcher_CreateOctagon","Create an octagon by its center and by one corner")); + octagon->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Octagon")); + octagon->setToolTip(QApplication::translate( + "Sketcher_CreateOctagon", "Create an octagon by its center and by one corner")); + octagon->setStatusTip(QApplication::translate( + "Sketcher_CreateOctagon", "Create an octagon by its center and by one corner")); QAction* regular = a[6]; - regular->setText(QApplication::translate("CmdSketcherCompCreateRegularPolygon","Regular polygon")); - regular->setToolTip(QApplication::translate("Sketcher_CreateOctagon","Create a regular polygon by its center and by one corner")); - regular->setStatusTip(QApplication::translate("Sketcher_CreateOctagon","Create a regular polygon by its center and by one corner")); + regular->setText( + QApplication::translate("CmdSketcherCompCreateRegularPolygon", "Regular polygon")); + regular->setToolTip(QApplication::translate( + "Sketcher_CreateOctagon", "Create a regular polygon by its center and by one corner")); + regular->setStatusTip(QApplication::translate( + "Sketcher_CreateOctagon", "Create a regular polygon by its center and by one corner")); } bool CmdSketcherCompCreateRegularPolygon::isActive() @@ -1992,7 +2104,7 @@ bool CmdSketcherCompCreateRegularPolygon::isActive() void CreateSketcherCommandsCreateGeo() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherCreatePoint()); rcCmdMgr.addCommand(new CmdSketcherCreateArc()); @@ -2030,8 +2142,8 @@ void CreateSketcherCommandsCreateGeo() rcCmdMgr.addCommand(new CmdSketcherCompCreateFillets()); rcCmdMgr.addCommand(new CmdSketcherCreateFillet()); rcCmdMgr.addCommand(new CmdSketcherCreatePointFillet()); - //rcCmdMgr.addCommand(new CmdSketcherCreateText()); - //rcCmdMgr.addCommand(new CmdSketcherCreateDraftLine()); + // rcCmdMgr.addCommand(new CmdSketcherCreateText()); + // rcCmdMgr.addCommand(new CmdSketcherCreateDraftLine()); rcCmdMgr.addCommand(new CmdSketcherTrimming()); rcCmdMgr.addCommand(new CmdSketcherExtend()); rcCmdMgr.addCommand(new CmdSketcherSplit()); diff --git a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp index a693606b8c..57a3a61caf 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp @@ -22,9 +22,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include @@ -49,15 +49,19 @@ using namespace std; using namespace SketcherGui; using namespace Sketcher; -bool isSketcherBSplineActive(Gui::Document *doc, bool actsOnSelection) +bool isSketcherBSplineActive(Gui::Document* doc, bool actsOnSelection) { if (doc) { // checks if a Sketch Viewprovider is in Edit and is in no special mode - if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { - if (static_cast(doc->getInEdit())->getSketchMode() == ViewProviderSketch::STATUS_NONE) { + if (doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + if (static_cast(doc->getInEdit())->getSketchMode() + == ViewProviderSketch::STATUS_NONE) { if (!actsOnSelection) return true; - else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) + else if (Gui::Selection().countObjectsOfType( + Sketcher::SketchObject::getClassTypeId()) + > 0) return true; } } @@ -65,21 +69,24 @@ bool isSketcherBSplineActive(Gui::Document *doc, bool actsOnSelection) return false; } -void ActivateBSplineHandler(Gui::Document *doc,DrawSketchHandler *handler) +void ActivateBSplineHandler(Gui::Document* doc, DrawSketchHandler* handler) { std::unique_ptr ptr(handler); if (doc) { - if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { - SketcherGui::ViewProviderSketch* vp = static_cast (doc->getInEdit()); + if (doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + SketcherGui::ViewProviderSketch* vp = + static_cast(doc->getInEdit()); vp->purgeHandler(); vp->activateHandler(ptr.release()); } } } -void ShowRestoreInformationLayer(const char * visibleelementname) +void ShowRestoreInformationLayer(const char* visibleelementname) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); bool status = hGrp->GetBool(visibleelementname, true); hGrp->SetBool(visibleelementname, !status); } @@ -88,37 +95,34 @@ void ShowRestoreInformationLayer(const char * visibleelementname) /// index within it (by OCC numbering). /// Returns true if the entities are found, false otherwise. /// If returns false, `splineGeoId` and `knotIndexOCC` have garbage values. -bool findBSplineAndKnotIndex(Sketcher::SketchObject* Obj, - int knotGeoId, Sketcher::PointPos knotPosId, - int& splineGeoId, int& knotIndexOCC) +bool findBSplineAndKnotIndex(Sketcher::SketchObject* Obj, int knotGeoId, + Sketcher::PointPos knotPosId, int& splineGeoId, int& knotIndexOCC) { for (auto const constraint : Obj->Constraints.getValues()) { - if (constraint->Type == Sketcher::InternalAlignment - && constraint->First == knotGeoId - && constraint->AlignmentType == Sketcher::BSplineKnotPoint) - { + if (constraint->Type == Sketcher::InternalAlignment && constraint->First == knotGeoId + && constraint->AlignmentType == Sketcher::BSplineKnotPoint) { splineGeoId = constraint->Second; knotIndexOCC = constraint->InternalAlignmentIndex + 1; - return true; // we have already found our knot. + return true;// we have already found our knot. } } // TODO: what to do if multiple splines have the same first/last point? - const Part::Geometry *geo = Obj->getGeometry(knotGeoId); + const Part::Geometry* geo = Obj->getGeometry(knotGeoId); if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { splineGeoId = knotGeoId; switch (knotPosId) { - case Sketcher::PointPos::start: - knotIndexOCC = 1; - return true; - case Sketcher::PointPos::end: - knotIndexOCC = static_cast(geo)->countKnots(); - return true; - default: - // If we reach here something went wrong. - // isBsplineKnotOrEndPoint (that we expect is run before) will - // only accept spline knotGeoID if knotPosId is start or end. - return false; + case Sketcher::PointPos::start: + knotIndexOCC = 1; + return true; + case Sketcher::PointPos::end: + knotIndexOCC = static_cast(geo)->countKnots(); + return true; + default: + // If we reach here something went wrong. + // isBsplineKnotOrEndPoint (that we expect is run before) will + // only accept spline knotGeoID if knotPosId is start or end. + return false; } } @@ -131,15 +135,15 @@ DEF_STD_CMD_A(CmdSketcherBSplineDegree) CmdSketcherBSplineDegree::CmdSketcherBSplineDegree() : Command("Sketcher_BSplineDegree") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Show/hide B-spline degree"); - sToolTipText = QT_TR_NOOP("Switches between showing and hiding the degree for all B-splines"); - sWhatsThis = "Sketcher_BSplineDegree"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineDegree"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Show/hide B-spline degree"); + sToolTipText = QT_TR_NOOP("Switches between showing and hiding the degree for all B-splines"); + sWhatsThis = "Sketcher_BSplineDegree"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineDegree"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherBSplineDegree::activated(int iMsg) @@ -160,15 +164,16 @@ DEF_STD_CMD_A(CmdSketcherBSplinePolygon) CmdSketcherBSplinePolygon::CmdSketcherBSplinePolygon() : Command("Sketcher_BSplinePolygon") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Show/hide B-spline control polygon"); - sToolTipText = QT_TR_NOOP("Switches between showing and hiding the control polygons for all B-splines"); - sWhatsThis = "Sketcher_BSplinePolygon"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplinePolygon"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Show/hide B-spline control polygon"); + sToolTipText = + QT_TR_NOOP("Switches between showing and hiding the control polygons for all B-splines"); + sWhatsThis = "Sketcher_BSplinePolygon"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplinePolygon"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherBSplinePolygon::activated(int iMsg) @@ -189,15 +194,16 @@ DEF_STD_CMD_A(CmdSketcherBSplineComb) CmdSketcherBSplineComb::CmdSketcherBSplineComb() : Command("Sketcher_BSplineComb") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Show/hide B-spline curvature comb"); - sToolTipText = QT_TR_NOOP("Switches between showing and hiding the curvature comb for all B-splines"); - sWhatsThis = "Sketcher_BSplineComb"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineComb"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Show/hide B-spline curvature comb"); + sToolTipText = + QT_TR_NOOP("Switches between showing and hiding the curvature comb for all B-splines"); + sWhatsThis = "Sketcher_BSplineComb"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineComb"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherBSplineComb::activated(int iMsg) @@ -218,15 +224,16 @@ DEF_STD_CMD_A(CmdSketcherBSplineKnotMultiplicity) CmdSketcherBSplineKnotMultiplicity::CmdSketcherBSplineKnotMultiplicity() : Command("Sketcher_BSplineKnotMultiplicity") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Show/hide B-spline knot multiplicity"); - sToolTipText = QT_TR_NOOP("Switches between showing and hiding the knot multiplicity for all B-splines"); - sWhatsThis = "Sketcher_BSplineKnotMultiplicity"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineKnotMultiplicity"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Show/hide B-spline knot multiplicity"); + sToolTipText = + QT_TR_NOOP("Switches between showing and hiding the knot multiplicity for all B-splines"); + sWhatsThis = "Sketcher_BSplineKnotMultiplicity"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineKnotMultiplicity"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherBSplineKnotMultiplicity::activated(int iMsg) @@ -250,7 +257,8 @@ CmdSketcherBSplinePoleWeight::CmdSketcherBSplinePoleWeight() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Show/hide B-spline control point weight"); - sToolTipText = QT_TR_NOOP("Switches between showing and hiding the control point weight for all B-splines"); + sToolTipText = QT_TR_NOOP( + "Switches between showing and hiding the control point weight for all B-splines"); sWhatsThis = "Sketcher_BSplinePoleWeight"; sStatusTip = sToolTipText; sPixmap = "Sketcher_BSplinePoleWeight"; @@ -273,22 +281,23 @@ bool CmdSketcherBSplinePoleWeight::isActive() // Composite drop down menu for show/hide geometry information layer DEF_STD_CMD_ACLU(CmdSketcherCompBSplineShowHideGeometryInformation) -CmdSketcherCompBSplineShowHideGeometryInformation::CmdSketcherCompBSplineShowHideGeometryInformation() +CmdSketcherCompBSplineShowHideGeometryInformation:: + CmdSketcherCompBSplineShowHideGeometryInformation() : Command("Sketcher_CompBSplineShowHideGeometryInformation") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Show/hide B-spline information layer"); - sToolTipText = sMenuText; - sWhatsThis = "Sketcher_CompBSplineShowHideGeometryInformation"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Show/hide B-spline information layer"); + sToolTipText = sMenuText; + sWhatsThis = "Sketcher_CompBSplineShowHideGeometryInformation"; + sStatusTip = sToolTipText; + eType = ForEdit; } void CmdSketcherCompBSplineShowHideGeometryInformation::activated(int iMsg) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); - Gui::Command * cmd; + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::Command* cmd; if (iMsg == 0) cmd = rcCmdMgr.getCommandByName("Sketcher_BSplineDegree"); @@ -316,7 +325,7 @@ void CmdSketcherCompBSplineShowHideGeometryInformation::activated(int iMsg) pcAction->setToolTip(a[iMsg]->toolTip()); } -Gui::Action * CmdSketcherCompBSplineShowHideGeometryInformation::createAction() +Gui::Action* CmdSketcherCompBSplineShowHideGeometryInformation::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -355,44 +364,53 @@ void CmdSketcherCompBSplineShowHideGeometryInformation::languageChange() QAction* c1 = a[0]; c1->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", "Show/hide B-spline degree")); - c1->setToolTip(QApplication::translate("Sketcher_BSplineDegree", - "Switches between showing and hiding the degree for all B-splines")); - c1->setStatusTip(QApplication::translate("Sketcher_BSplineDegree", - "Switches between showing and hiding the degree for all B-splines")); + c1->setToolTip(QApplication::translate( + "Sketcher_BSplineDegree", + "Switches between showing and hiding the degree for all B-splines")); + c1->setStatusTip(QApplication::translate( + "Sketcher_BSplineDegree", + "Switches between showing and hiding the degree for all B-splines")); QAction* c2 = a[1]; c2->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", "Show/hide B-spline control polygon")); - c2->setToolTip(QApplication::translate("Sketcher_BSplinePolygon", - "Switches between showing and hiding the control polygons for all B-splines")); - c2->setStatusTip(QApplication::translate("Sketcher_BSplinePolygon", - "Switches between showing and hiding the control polygons for all B-splines")); + c2->setToolTip(QApplication::translate( + "Sketcher_BSplinePolygon", + "Switches between showing and hiding the control polygons for all B-splines")); + c2->setStatusTip(QApplication::translate( + "Sketcher_BSplinePolygon", + "Switches between showing and hiding the control polygons for all B-splines")); QAction* c3 = a[2]; c3->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", "Show/hide B-spline curvature comb")); - c3->setToolTip(QApplication::translate("Sketcher_BSplineComb", - "Switches between showing and hiding the curvature comb for all B-splines")); - c3->setStatusTip(QApplication::translate("Sketcher_BSplineComb", - "Switches between showing and hiding the curvature comb for all B-splines")); + c3->setToolTip(QApplication::translate( + "Sketcher_BSplineComb", + "Switches between showing and hiding the curvature comb for all B-splines")); + c3->setStatusTip(QApplication::translate( + "Sketcher_BSplineComb", + "Switches between showing and hiding the curvature comb for all B-splines")); QAction* c4 = a[3]; c4->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", "Show/hide B-spline knot multiplicity")); - c4->setToolTip(QApplication::translate("Sketcher_BSplineKnotMultiplicity", - "Switches between showing and hiding the knot multiplicity for all B-splines")); - c4->setStatusTip(QApplication::translate("Sketcher_BSplineKnotMultiplicity", - "Switches between showing and hiding the knot multiplicity for all B-splines")); + c4->setToolTip(QApplication::translate( + "Sketcher_BSplineKnotMultiplicity", + "Switches between showing and hiding the knot multiplicity for all B-splines")); + c4->setStatusTip(QApplication::translate( + "Sketcher_BSplineKnotMultiplicity", + "Switches between showing and hiding the knot multiplicity for all B-splines")); QAction* c5 = a[4]; c5->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", - "Show/hide B-spline control point weight")); - c5->setToolTip(QApplication::translate("Sketcher_BSplinePoleWeight", + "Show/hide B-spline control point weight")); + c5->setToolTip(QApplication::translate( + "Sketcher_BSplinePoleWeight", "Switches between showing and hiding the control point weight for all B-splines")); - c5->setStatusTip(QApplication::translate("Sketcher_BSplinePoleWeight", + c5->setStatusTip(QApplication::translate( + "Sketcher_BSplinePoleWeight", "Switches between showing and hiding the control point weight for all B-splines")); } void CmdSketcherCompBSplineShowHideGeometryInformation::updateAction(int /*mode*/) -{ -} +{} bool CmdSketcherCompBSplineShowHideGeometryInformation::isActive() { @@ -405,15 +423,15 @@ DEF_STD_CMD_A(CmdSketcherConvertToNURBS) CmdSketcherConvertToNURBS::CmdSketcherConvertToNURBS() : Command("Sketcher_BSplineConvertToNURBS") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Convert geometry to B-spline"); - sToolTipText = QT_TR_NOOP("Converts the selected geometry to a B-spline"); - sWhatsThis = "Sketcher_BSplineConvertToNURBS"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineApproximate"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Convert geometry to B-spline"); + sToolTipText = QT_TR_NOOP("Converts the selected geometry to a B-spline"); + sWhatsThis = "Sketcher_BSplineConvertToNURBS"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineApproximate"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherConvertToNURBS::activated(int iMsg) @@ -430,7 +448,7 @@ void CmdSketcherConvertToNURBS::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); openCommand(QT_TRANSLATE_NOOP("Command", "Convert to NURBS")); @@ -439,12 +457,12 @@ void CmdSketcherConvertToNURBS::activated(int iMsg) for (const auto& subName : SubNames) { // only handle edges - if (subName.size() > 4 && subName.substr(0,4) == "Edge") { - int GeoId = std::atoi(subName.substr(4,4000).c_str()) - 1; + if (subName.size() > 4 && subName.substr(0, 4) == "Edge") { + int GeoId = std::atoi(subName.substr(4, 4000).c_str()) - 1; GeoIdList.push_back(GeoId); } - else if (subName.size() > 12 && subName.substr(0,12) == "ExternalEdge") { - int GeoId = - (std::atoi(subName.substr(12,4000).c_str()) + 2); + else if (subName.size() > 12 && subName.substr(0, 12) == "ExternalEdge") { + int GeoId = -(std::atoi(subName.substr(12, 4000).c_str()) + 2); GeoIdList.push_back(GeoId); } } @@ -461,8 +479,8 @@ void CmdSketcherConvertToNURBS::activated(int iMsg) abortCommand(); Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("None of the selected elements is an edge.")); + QObject::tr("Wrong selection"), + QObject::tr("None of the selected elements is an edge.")); } else { commitCommand(); @@ -481,15 +499,15 @@ DEF_STD_CMD_A(CmdSketcherIncreaseDegree) CmdSketcherIncreaseDegree::CmdSketcherIncreaseDegree() : Command("Sketcher_BSplineIncreaseDegree") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Increase B-spline degree"); - sToolTipText = QT_TR_NOOP("Increases the degree of the B-spline"); - sWhatsThis = "Sketcher_BSplineIncreaseDegree"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineIncreaseDegree"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Increase B-spline degree"); + sToolTipText = QT_TR_NOOP("Increases the degree of the B-spline"); + sWhatsThis = "Sketcher_BSplineIncreaseDegree"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineIncreaseDegree"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherIncreaseDegree::activated(int iMsg) @@ -506,23 +524,25 @@ void CmdSketcherIncreaseDegree::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); openCommand(QT_TRANSLATE_NOOP("Command", "Increase spline degree")); bool ignored = false; - for (size_t i=0; i < SubNames.size(); i++) { + for (size_t i = 0; i < SubNames.size(); i++) { // only handle edges - if (SubNames[i].size() > 4 && SubNames[i].substr(0,4) == "Edge") { - int GeoId = std::atoi(SubNames[i].substr(4,4000).c_str()) - 1; - const Part::Geometry * geo = Obj->getGeometry(GeoId); + if (SubNames[i].size() > 4 && SubNames[i].substr(0, 4) == "Edge") { + int GeoId = std::atoi(SubNames[i].substr(4, 4000).c_str()) - 1; + const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - Gui::cmdAppObjectArgs(selection[0].getObject(), "increaseBSplineDegree(%d) ", GeoId); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "increaseBSplineDegree(%d) ", GeoId); // add new control points - Gui::cmdAppObjectArgs(selection[0].getObject(), "exposeInternalGeometry(%d)", GeoId); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "exposeInternalGeometry(%d)", GeoId); } else { ignored = true; @@ -532,9 +552,9 @@ void CmdSketcherIncreaseDegree::activated(int iMsg) if (ignored) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("At least one of the selected " - "objects was not a B-Spline and was ignored.")); + QObject::tr("Wrong selection"), + QObject::tr("At least one of the selected " + "objects was not a B-Spline and was ignored.")); } commitCommand(); @@ -554,15 +574,15 @@ DEF_STD_CMD_A(CmdSketcherDecreaseDegree) CmdSketcherDecreaseDegree::CmdSketcherDecreaseDegree() : Command("Sketcher_BSplineDecreaseDegree") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Decrease B-spline degree"); - sToolTipText = QT_TR_NOOP("Decreases the degree of the B-spline"); - sWhatsThis = "Sketcher_BSplineDecreaseDegree"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineDecreaseDegree"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Decrease B-spline degree"); + sToolTipText = QT_TR_NOOP("Decreases the degree of the B-spline"); + sWhatsThis = "Sketcher_BSplineDecreaseDegree"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineDecreaseDegree"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherDecreaseDegree::activated(int iMsg) @@ -581,26 +601,30 @@ void CmdSketcherDecreaseDegree::activated(int iMsg) getSelection().clearSelection(); // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); openCommand(QT_TRANSLATE_NOOP("Command", "Decrease spline degree")); bool ignored = false; - for (size_t i=0; i < SubNames.size(); i++) { + for (size_t i = 0; i < SubNames.size(); i++) { // only handle edges - if (SubNames[i].size() > 4 && SubNames[i].substr(0,4) == "Edge") { - int GeoId = std::atoi(SubNames[i].substr(4,4000).c_str()) - 1; - const Part::Geometry * geo = Obj->getGeometry(GeoId); + if (SubNames[i].size() > 4 && SubNames[i].substr(0, 4) == "Edge") { + int GeoId = std::atoi(SubNames[i].substr(4, 4000).c_str()) - 1; + const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - Gui::cmdAppObjectArgs(selection[0].getObject(), "decreaseBSplineDegree(%d) ", GeoId); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "decreaseBSplineDegree(%d) ", GeoId); // add new control points - // Currently exposeInternalGeometry is called from within decreaseBSplineDegree because - // the old spline is deleted and a new one is added so that the GeoId is invalid afterwards - //Gui::cmdAppObjectArgs(selection[0].getObject(), "exposeInternalGeometry(%d)", GeoId); - break; // cannot handle more than spline because the GeoIds will be invalidated after the first change + // Currently exposeInternalGeometry is called from within decreaseBSplineDegree + // because the old spline is deleted and a new one is added so that the GeoId is + // invalid afterwards + // Gui::cmdAppObjectArgs(selection[0].getObject(), "exposeInternalGeometry(%d)", + // GeoId); + break;// cannot handle more than spline because the GeoIds will be invalidated after + // the first change } else { ignored = true; @@ -610,9 +634,9 @@ void CmdSketcherDecreaseDegree::activated(int iMsg) if (ignored) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("At least one of the selected " - "objects was not a B-Spline and was ignored.")); + QObject::tr("Wrong selection"), + QObject::tr("At least one of the selected " + "objects was not a B-Spline and was ignored.")); } commitCommand(); @@ -631,15 +655,15 @@ DEF_STD_CMD_A(CmdSketcherIncreaseKnotMultiplicity) CmdSketcherIncreaseKnotMultiplicity::CmdSketcherIncreaseKnotMultiplicity() : Command("Sketcher_BSplineIncreaseKnotMultiplicity") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Increase knot multiplicity"); - sToolTipText = QT_TR_NOOP("Increases the multiplicity of the selected knot of a B-spline"); - sWhatsThis = "Sketcher_BSplineIncreaseKnotMultiplicity"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineIncreaseKnotMultiplicity"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Increase knot multiplicity"); + sToolTipText = QT_TR_NOOP("Increases the multiplicity of the selected knot of a B-spline"); + sWhatsThis = "Sketcher_BSplineIncreaseKnotMultiplicity"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineIncreaseKnotMultiplicity"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) @@ -656,14 +680,16 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.size() > 1) { // Check that only one object is selected, // as we need only one object to get the new GeoId after multiplicity change - Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("The selection comprises more than one item. Please select just one knot.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument()->getDocument(), + QObject::tr("Wrong selection"), + QObject::tr( + "The selection comprises more than one item. Please select just one knot.")); return; } @@ -679,8 +705,8 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) int knotIndexOCC; bool applied = false; - bool notaknot = !(isBsplineKnotOrEndPoint(Obj, GeoId, PosId) && - findBSplineAndKnotIndex(Obj, GeoId, PosId, splineGeoId, knotIndexOCC)); + bool notaknot = !(isBsplineKnotOrEndPoint(Obj, GeoId, PosId) + && findBSplineAndKnotIndex(Obj, GeoId, PosId, splineGeoId, knotIndexOCC)); boost::uuids::uuid bsplinetag; if (!notaknot) { @@ -689,7 +715,9 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) try { Gui::cmdAppObjectArgs(selection[0].getObject(), "modifyBSplineKnotMultiplicity(%d, %d, %d) ", - splineGeoId, knotIndexOCC, 1); + splineGeoId, + knotIndexOCC, + 1); applied = true; // Warning: GeoId list might have changed @@ -699,39 +727,37 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) catch (const Base::CADKernelError& e) { e.ReportException(); if (e.getTranslatable()) { - Gui::TranslatedUserError(Obj, - QObject::tr("CAD Kernel Error"), - QObject::tr(e.getMessage().c_str())); - + Gui::TranslatedUserError( + Obj, QObject::tr("CAD Kernel Error"), QObject::tr(e.getMessage().c_str())); } getSelection().clearSelection(); } catch (const Base::Exception& e) { e.ReportException(); if (e.getTranslatable()) { - Gui::TranslatedUserError(Obj, - QObject::tr("Input Error"), - QObject::tr(e.getMessage().c_str())); + Gui::TranslatedUserError( + Obj, QObject::tr("Input Error"), QObject::tr(e.getMessage().c_str())); } getSelection().clearSelection(); } } if (notaknot) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("None of the selected elements is a knot of a B-spline")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("None of the selected elements is a knot of a B-spline")); } - if (applied) - { + if (applied) { // find new geoid for B-spline as GeoId might have changed - const std::vector< Part::Geometry * > &gvals = Obj->getInternalGeometry(); + const std::vector& gvals = Obj->getInternalGeometry(); int ngeoid = 0; bool ngfound = false; - for (std::vector::const_iterator geo = gvals.begin(); geo != gvals.end(); geo++, ngeoid++) { + for (std::vector::const_iterator geo = gvals.begin(); geo != gvals.end(); + geo++, ngeoid++) { if ((*geo) && (*geo)->getTag() == bsplinetag) { ngfound = true; break; @@ -741,12 +767,12 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) if (ngfound) { try { // add internalalignment for new pole - Gui::cmdAppObjectArgs(selection[0].getObject(), "exposeInternalGeometry(%d)", ngeoid); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "exposeInternalGeometry(%d)", ngeoid); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); getSelection().clearSelection(); } } @@ -773,15 +799,15 @@ DEF_STD_CMD_A(CmdSketcherDecreaseKnotMultiplicity) CmdSketcherDecreaseKnotMultiplicity::CmdSketcherDecreaseKnotMultiplicity() : Command("Sketcher_BSplineDecreaseKnotMultiplicity") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Decrease knot multiplicity"); - sToolTipText = QT_TR_NOOP("Decreases the multiplicity of the selected knot of a B-spline"); - sWhatsThis = "Sketcher_BSplineDecreaseKnotMultiplicity"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineDecreaseKnotMultiplicity"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Decrease knot multiplicity"); + sToolTipText = QT_TR_NOOP("Decreases the multiplicity of the selected knot of a B-spline"); + sWhatsThis = "Sketcher_BSplineDecreaseKnotMultiplicity"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineDecreaseKnotMultiplicity"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) @@ -798,14 +824,16 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.size() > 1) { // Check that only one object is selected, // as we need only one object to get the new GeoId after multiplicity change - Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("The selection comprises more than one item. Please select just one knot.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument()->getDocument(), + QObject::tr("Wrong selection"), + QObject::tr( + "The selection comprises more than one item. Please select just one knot.")); return; } @@ -821,8 +849,8 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) int knotIndexOCC; bool applied = false; - bool notaknot = !(isBsplineKnotOrEndPoint(Obj, GeoId, PosId) && - findBSplineAndKnotIndex(Obj, GeoId, PosId, splineGeoId, knotIndexOCC)); + bool notaknot = !(isBsplineKnotOrEndPoint(Obj, GeoId, PosId) + && findBSplineAndKnotIndex(Obj, GeoId, PosId, splineGeoId, knotIndexOCC)); boost::uuids::uuid bsplinetag; if (!notaknot) { @@ -831,36 +859,39 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) try { Gui::cmdAppObjectArgs(selection[0].getObject(), "modifyBSplineKnotMultiplicity(%d, %d, %d) ", - splineGeoId, knotIndexOCC, -1); + splineGeoId, + knotIndexOCC, + -1); applied = true; - // Warning: GeoId list might have changed as the consequence of deleting pole circles and - // particularly B-spline GeoID might have changed. + // Warning: GeoId list might have changed as the consequence of deleting pole circles + // and particularly B-spline GeoID might have changed. } catch (const Base::Exception& e) { Gui::TranslatedUserError(Obj, - QObject::tr("Error"), - QObject::tr(getStrippedPythonExceptionString(e).c_str())); + QObject::tr("Error"), + QObject::tr(getStrippedPythonExceptionString(e).c_str())); getSelection().clearSelection(); } } if (notaknot) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("None of the selected elements is a knot of a B-spline")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("None of the selected elements is a knot of a B-spline")); } - if (applied) - { + if (applied) { // find new geoid for B-spline as GeoId might have changed - const std::vector< Part::Geometry * > &gvals = Obj->getInternalGeometry(); + const std::vector& gvals = Obj->getInternalGeometry(); int ngeoid = 0; bool ngfound = false; - for (std::vector::const_iterator geo = gvals.begin(); geo != gvals.end(); geo++, ngeoid++) { + for (std::vector::const_iterator geo = gvals.begin(); geo != gvals.end(); + geo++, ngeoid++) { if ((*geo) && (*geo)->getTag() == bsplinetag) { ngfound = true; break; @@ -870,12 +901,12 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) if (ngfound) { try { // add internalalignment for new pole - Gui::cmdAppObjectArgs(selection[0].getObject(), "exposeInternalGeometry(%d)", ngeoid); + Gui::cmdAppObjectArgs( + selection[0].getObject(), "exposeInternalGeometry(%d)", ngeoid); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); getSelection().clearSelection(); } } @@ -904,20 +935,20 @@ DEF_STD_CMD_ACLU(CmdSketcherCompModifyKnotMultiplicity) CmdSketcherCompModifyKnotMultiplicity::CmdSketcherCompModifyKnotMultiplicity() : Command("Sketcher_CompModifyKnotMultiplicity") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Modify knot multiplicity"); - sToolTipText = QT_TR_NOOP("Modifies the multiplicity of the selected knot of a B-spline"); - sWhatsThis = "Sketcher_CompModifyKnotMultiplicity"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Modify knot multiplicity"); + sToolTipText = QT_TR_NOOP("Modifies the multiplicity of the selected knot of a B-spline"); + sWhatsThis = "Sketcher_CompModifyKnotMultiplicity"; + sStatusTip = sToolTipText; + eType = ForEdit; } void CmdSketcherCompModifyKnotMultiplicity::activated(int iMsg) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); - Gui::Command * cmd; + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::Command* cmd; if (iMsg == 0) cmd = rcCmdMgr.getCommandByName("Sketcher_BSplineIncreaseKnotMultiplicity"); @@ -937,7 +968,7 @@ void CmdSketcherCompModifyKnotMultiplicity::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompModifyKnotMultiplicity::createAction() +Gui::Action* CmdSketcherCompModifyKnotMultiplicity::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -970,22 +1001,25 @@ void CmdSketcherCompModifyKnotMultiplicity::languageChange() QAction* c1 = a[0]; c1->setText(QApplication::translate("CmdSketcherCompModifyKnotMultiplicity", "Increase knot multiplicity")); - c1->setToolTip(QApplication::translate("Sketcher_BSplineIncreaseKnotMultiplicity", - "Increases the multiplicity of the selected knot of a B-spline")); - c1->setStatusTip(QApplication::translate("Sketcher_BSplineIncreaseKnotMultiplicity", - "Increases the multiplicity of the selected knot of a B-spline")); + c1->setToolTip( + QApplication::translate("Sketcher_BSplineIncreaseKnotMultiplicity", + "Increases the multiplicity of the selected knot of a B-spline")); + c1->setStatusTip( + QApplication::translate("Sketcher_BSplineIncreaseKnotMultiplicity", + "Increases the multiplicity of the selected knot of a B-spline")); QAction* c2 = a[1]; c2->setText(QApplication::translate("CmdSketcherCompModifyKnotMultiplicity", "Decrease knot multiplicity")); - c2->setToolTip(QApplication::translate("Sketcher_BSplineDecreaseKnotMultiplicity", - "Decreases the multiplicity of the selected knot of a B-spline")); - c2->setStatusTip(QApplication::translate("Sketcher_BSplineDecreaseKnotMultiplicity", - "Decreases the multiplicity of the selected knot of a B-spline")); + c2->setToolTip( + QApplication::translate("Sketcher_BSplineDecreaseKnotMultiplicity", + "Decreases the multiplicity of the selected knot of a B-spline")); + c2->setStatusTip( + QApplication::translate("Sketcher_BSplineDecreaseKnotMultiplicity", + "Decreases the multiplicity of the selected knot of a B-spline")); } void CmdSketcherCompModifyKnotMultiplicity::updateAction(int /*mode*/) -{ -} +{} bool CmdSketcherCompModifyKnotMultiplicity::isActive() { @@ -1000,15 +1034,16 @@ public: , GeoId(_GeoId) , EditMarkers(1) { - auto bsp = static_cast(Obj->getGeometry(GeoId)); + auto bsp = static_cast(Obj->getGeometry(GeoId)); guessParam = bsp->getFirstParameter(); } - ~DrawSketchHandlerBSplineInsertKnot() override {} + ~DrawSketchHandlerBSplineInsertKnot() override + {} void mouseMove(Base::Vector2d onSketchPos) override { - auto bsp = static_cast(Obj->getGeometry(GeoId)); + auto bsp = static_cast(Obj->getGeometry(GeoId)); // get closest parameter using OCC // TODO: This is called every time we move the cursor. Can get overwhelming. @@ -1047,8 +1082,7 @@ public: boost::uuids::uuid bsplinetag = Obj->getGeometry(GeoId)->getTag(); try { - Gui::cmdAppObjectArgs(Obj, "insertBSplineKnot(%d, %lf, %d) ", - GeoId, guessParam, 1); + Gui::cmdAppObjectArgs(Obj, "insertBSplineKnot(%d, %lf, %d) ", GeoId, guessParam, 1); applied = true; // Warning: GeoId list might have changed @@ -1058,29 +1092,28 @@ public: catch (const Base::CADKernelError& e) { e.ReportException(); if (e.getTranslatable()) { - Gui::TranslatedUserError(Obj, - QObject::tr("CAD Kernel Error"), - QObject::tr(e.getMessage().c_str())); + Gui::TranslatedUserError( + Obj, QObject::tr("CAD Kernel Error"), QObject::tr(e.getMessage().c_str())); } } catch (const Base::Exception& e) { e.ReportException(); if (e.getTranslatable()) { - Gui::TranslatedUserError(Obj, - QObject::tr("Input Error"), - QObject::tr(e.getMessage().c_str())); + Gui::TranslatedUserError( + Obj, QObject::tr("Input Error"), QObject::tr(e.getMessage().c_str())); } } int newGeoId = 0; bool newGeoIdFound = false; - if (applied) - { + if (applied) { // find new geoid for B-spline as GeoId might have changed - const std::vector< Part::Geometry * > &gvals = Obj->getInternalGeometry(); + const std::vector& gvals = Obj->getInternalGeometry(); - for (std::vector::const_iterator geo = gvals.begin(); geo != gvals.end(); geo++, newGeoId++) { + for (std::vector::const_iterator geo = gvals.begin(); + geo != gvals.end(); + geo++, newGeoId++) { if ((*geo) && (*geo)->getTag() == bsplinetag) { newGeoIdFound = true; break; @@ -1093,9 +1126,8 @@ public: Gui::cmdAppObjectArgs(Obj, "exposeInternalGeometry(%d)", newGeoId); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); } } } @@ -1107,8 +1139,9 @@ public: tryAutoRecomputeIfNotSolve(Obj); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode && newGeoIdFound) { // This code enables the continuous creation mode. @@ -1122,14 +1155,16 @@ public: * right button of the mouse */ } else { - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } return true; } private: - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_InsertKnot"); } @@ -1145,15 +1180,16 @@ DEF_STD_CMD_A(CmdSketcherInsertKnot) CmdSketcherInsertKnot::CmdSketcherInsertKnot() : Command("Sketcher_BSplineInsertKnot") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Insert knot"); - sToolTipText = QT_TR_NOOP("Inserts knot at given parameter. If a knot already exists at that parameter, it's multiplicity is increased by one."); - sWhatsThis = "Sketcher_BSplineInsertKnot"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_BSplineInsertKnot"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Insert knot"); + sToolTipText = QT_TR_NOOP("Inserts knot at given parameter. If a knot already exists at that " + "parameter, it's multiplicity is increased by one."); + sWhatsThis = "Sketcher_BSplineInsertKnot"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_BSplineInsertKnot"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherInsertKnot::activated(int iMsg) @@ -1171,29 +1207,31 @@ void CmdSketcherInsertKnot::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { // Check that only one object is selected, // as we need only one object to get the new GeoId after multiplicity change Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Selection is empty"), - QObject::tr("Nothing is selected. Please select a b-spline.")); + QObject::tr("Selection is empty"), + QObject::tr("Nothing is selected. Please select a b-spline.")); return; } Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); // TODO: Ensure GeoId is for the BSpline and not for it's internal geometry - int GeoId = std::atoi(SubNames[0].substr(4,4000).c_str()) - 1; - const Part::Geometry * geo = Obj->getGeometry(GeoId); + int GeoId = std::atoi(SubNames[0].substr(4, 4000).c_str()) - 1; + const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) - ActivateBSplineHandler(getActiveGuiDocument(), new DrawSketchHandlerBSplineInsertKnot(Obj, GeoId)); + ActivateBSplineHandler(getActiveGuiDocument(), + new DrawSketchHandlerBSplineInsertKnot(Obj, GeoId)); else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Please select a b-spline curve to insert a knot (not a knot on it). " - "If the curve is not a b-spline, please convert it into one first.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Please select a b-spline curve to insert a knot (not a knot on it). " + "If the curve is not a b-spline, please convert it into one first.")); } getSelection().clearSelection(); @@ -1209,15 +1247,15 @@ DEF_STD_CMD_A(CmdSketcherJoinCurves) CmdSketcherJoinCurves::CmdSketcherJoinCurves() : Command("Sketcher_JoinCurves") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Join curves"); - sToolTipText = QT_TR_NOOP("Join two curves at selected end points"); - sWhatsThis = "Sketcher_JoinCurves"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_JoinCurves"; - sAccel = ""; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Join curves"); + sToolTipText = QT_TR_NOOP("Join two curves at selected end points"); + sWhatsThis = "Sketcher_JoinCurves"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_JoinCurves"; + sAccel = ""; + eType = ForEdit; } void CmdSketcherJoinCurves::activated(int iMsg) @@ -1234,7 +1272,7 @@ void CmdSketcherJoinCurves::activated(int iMsg) } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); int GeoIds[2]; Sketcher::PointPos PosIds[2]; @@ -1242,82 +1280,89 @@ void CmdSketcherJoinCurves::activated(int iMsg) Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); switch (SubNames.size()) { - case 0: { - // Nothing is selected - Gui::TranslatedUserWarning(Obj, - QObject::tr("Selection is empty"), - QObject::tr("Nothing is selected. Please select end points of curves.")); - return; - } - case 1: { - std::vector GeoIdList; - std::vector PosIdList; + case 0: { + // Nothing is selected + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Selection is empty"), + QObject::tr("Nothing is selected. Please select end points of curves.")); + return; + } + case 1: { + std::vector GeoIdList; + std::vector PosIdList; - int selGeoId; - Sketcher::PointPos selPosId; + int selGeoId; + Sketcher::PointPos selPosId; - getIdsFromName(SubNames[0], Obj, selGeoId, selPosId); + getIdsFromName(SubNames[0], Obj, selGeoId, selPosId); - Obj->getDirectlyCoincidentPoints(selGeoId, selPosId, GeoIdList, PosIdList); + Obj->getDirectlyCoincidentPoints(selGeoId, selPosId, GeoIdList, PosIdList); - // Find the right pair of coincident points - size_t j = 0; - for (size_t i = 0; i < GeoIdList.size(); ++i) { - if (Sketcher::PointPos::start == PosIdList[i] || - Sketcher::PointPos::end == PosIdList[i]) { - if (j < 2) { - GeoIds[j] = GeoIdList[i]; - PosIds[j] = PosIdList[i]; - ++j; - } - else { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Too many curves on point"), - QObject::tr("Exactly two curves should end at the selected point to be able to join them.")); + // Find the right pair of coincident points + size_t j = 0; + for (size_t i = 0; i < GeoIdList.size(); ++i) { + if (Sketcher::PointPos::start == PosIdList[i] + || Sketcher::PointPos::end == PosIdList[i]) { + if (j < 2) { + GeoIds[j] = GeoIdList[i]; + PosIds[j] = PosIdList[i]; + ++j; + } + else { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Too many curves on point"), + QObject::tr("Exactly two curves should end at the selected point to be " + "able to join them.")); - return; + return; + } } } + if (j < 2) { + Gui::TranslatedUserWarning(Obj, + QObject::tr("Too few curves on point"), + QObject::tr("Exactly two curves should end at the " + "selected point to be able to join them.")); + + return; + } + + break; } - if (j < 2) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Too few curves on point"), - QObject::tr("Exactly two curves should end at the selected point to be able to join them.")); + case 2: { + getIdsFromName(SubNames[0], Obj, GeoIds[0], PosIds[0]); + getIdsFromName(SubNames[1], Obj, GeoIds[1], PosIds[1]); + break; + } + default: { + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Two end points, or coincident point should be selected.")); return; } - - break; - } - case 2: { - getIdsFromName(SubNames[0], Obj, GeoIds[0], PosIds[0]); - getIdsFromName(SubNames[1], Obj, GeoIds[1], PosIds[1]); - break; - } - default: { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Two end points, or coincident point should be selected.")); - - return; - } } Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Join Curves")); bool applied = false; try { - Gui::cmdAppObjectArgs(selection[0].getObject(), "join(%d, %d, %d, %d) ", - GeoIds[0], static_cast(PosIds[0]), - GeoIds[1], static_cast(PosIds[1])); + Gui::cmdAppObjectArgs(selection[0].getObject(), + "join(%d, %d, %d, %d) ", + GeoIds[0], + static_cast(PosIds[0]), + GeoIds[1], + static_cast(PosIds[1])); applied = true; // Warning: GeoId list will have changed } catch (const Base::Exception& e) { - Gui::TranslatedUserError(Obj, - QObject::tr("Error"), - QObject::tr(getStrippedPythonExceptionString(e).c_str())); + Gui::TranslatedUserError( + Obj, QObject::tr("Error"), QObject::tr(getStrippedPythonExceptionString(e).c_str())); getSelection().clearSelection(); } @@ -1338,7 +1383,7 @@ bool CmdSketcherJoinCurves::isActive(void) void CreateSketcherCommandsBSpline() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherBSplineDegree()); rcCmdMgr.addCommand(new CmdSketcherBSplinePolygon()); diff --git a/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp b/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp index f4541c3727..92e293ce4f 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp @@ -90,8 +90,8 @@ void CmdSketcherSelectConstraints::activated(int iMsg) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(doc->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -163,8 +163,9 @@ void CmdSketcherSelectOrigin::activated(int iMsg) SketcherGui::ViewProviderSketch* vp = static_cast(doc->getInEdit()); Sketcher::SketchObject* Obj = vp->getSketchObject(); - // ViewProviderSketch * vp = static_cast(Gui::Application::Instance->getViewProvider(docobj)); - // Sketcher::SketchObject* Obj = vp->getSketchObject(); + // ViewProviderSketch * vp = static_cast(Gui::Application::Instance->getViewProvider(docobj)); Sketcher::SketchObject* Obj = + // vp->getSketchObject(); std::string doc_name = Obj->getDocument()->getName(); std::string obj_name = Obj->getNameInDocument(); @@ -626,8 +627,8 @@ void CmdSketcherSelectElementsAssociatedWithConstraints::activated(int iMsg) if (elementSubNames.empty()) { Gui::TranslatedUserWarning(Obj, - QObject::tr("No constraint selected"), - QObject::tr("At least one constraint must be selected")); + QObject::tr("No constraint selected"), + QObject::tr("At least one constraint must be selected")); } else { Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), elementSubNames); @@ -705,8 +706,8 @@ void CmdSketcherSelectElementsWithDoFs::activated(int iMsg) if (solvext->getGeometry() == Sketcher::SolverGeometryExtension::NotFullyConstraint) { - // Coded for consistency with getGeometryWithDependentParameters, read the comments - // on that function + // Coded for consistency with getGeometryWithDependentParameters, read the + // comments on that function if (solvext->getEdge() == SolverGeometryExtension::Dependent) testselectedge(geoid); if (solvext->getStart() == SolverGeometryExtension::Dependent) @@ -765,8 +766,8 @@ void CmdSketcherRestoreInternalAlignmentGeometry::activated(int iMsg) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(doc->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -828,9 +829,8 @@ void CmdSketcherRestoreInternalAlignmentGeometry::activated(int iMsg) } } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); tryAutoRecomputeIfNotSolve(static_cast(Obj)); @@ -882,8 +882,8 @@ void CmdSketcherSymmetry::activated(int iMsg) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -891,8 +891,8 @@ void CmdSketcherSymmetry::activated(int iMsg) const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -999,20 +999,20 @@ void CmdSketcherSymmetry::activated(int iMsg) if (geoids == 0 || (geoids == 1 && LastGeoId >= 0 && !lastvertexoraxis)) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("A symmetric construction requires " - "at least two geometric elements, " - "the last geometric element being the reference " - "for the symmetry construction.")); + QObject::tr("Wrong selection"), + QObject::tr("A symmetric construction requires " + "at least two geometric elements, " + "the last geometric element being the reference " + "for the symmetry construction.")); return; } if (lastgeotype == invalid) { Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("The last element must be a point " - "or a line serving as reference " - "for the symmetry construction.")); + QObject::tr("Wrong selection"), + QObject::tr("The last element must be a point " + "or a line serving as reference " + "for the symmetry construction.")); return; } @@ -1049,9 +1049,8 @@ void CmdSketcherSymmetry::activated(int iMsg) Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Invalid Constraint"), e.what()); Gui::Command::abortCommand(); } tryAutoRecomputeIfNotSolve(Obj); @@ -1121,15 +1120,15 @@ class DrawSketchHandlerCopy: public DrawSketchHandler public: DrawSketchHandlerCopy(string geoidlist, int origingeoid, Sketcher::PointPos originpos, int nelements, SketcherCopy::Op op) - : Mode(STATUS_SEEK_First), - snapMode(SnapMode::Free), - geoIdList(geoidlist), - Origin(), - OriginGeoId(origingeoid), - OriginPos(originpos), - nElements(nelements), - Op(op), - EditCurve(2) + : Mode(STATUS_SEEK_First) + , snapMode(SnapMode::Free) + , geoIdList(geoidlist) + , Origin() + , OriginGeoId(origingeoid) + , OriginPos(originpos) + , nElements(nelements) + , Op(op) + , EditCurve(2) {} ~DrawSketchHandlerCopy() override @@ -1218,9 +1217,8 @@ public: Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(sketchgui->getObject(), - QT_TRANSLATE_NOOP("Notifications", "Error"), - e.what()); + Gui::NotifyUserError( + sketchgui->getObject(), QT_TRANSLATE_NOOP("Notifications", "Error"), e.what()); Gui::Command::abortCommand(); } @@ -1270,8 +1268,8 @@ void SketcherCopy::activate(SketcherCopy::Op op) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -1280,8 +1278,8 @@ void SketcherCopy::activate(SketcherCopy::Op op) const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -1340,9 +1338,10 @@ void SketcherCopy::activate(SketcherCopy::Op op) } if (geoids < 1) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("A copy requires at least one selected non-external geometric element")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("A copy requires at least one selected non-external geometric element")); return; } @@ -1356,7 +1355,8 @@ void SketcherCopy::activate(SketcherCopy::Op op) geoIdList.append(1, ']'); // if the last element is not a point serving as a reference for the copy process - // then make the start point of the last element the copy reference (if it exists, if not the center point) + // then make the start point of the last element the copy reference (if it exists, if not the + // center point) if (LastPointPos == Sketcher::PointPos::none) { if (LastGeo->getTypeId() == Part::GeomCircle::getClassTypeId() || LastGeo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { @@ -1369,9 +1369,10 @@ void SketcherCopy::activate(SketcherCopy::Op op) // Ask the user if they want to clone or to simple copy /* - int ret = QMessageBox::question(Gui::getMainWindow(), QObject::tr("Dimensional/Geometric constraints"), - QObject::tr("Do you want to clone the object, i.e. substitute dimensional constraints by geometric constraints?"), - QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); + int ret = QMessageBox::question(Gui::getMainWindow(), QObject::tr("Dimensional/Geometric + constraints"), QObject::tr("Do you want to clone the object, i.e. substitute dimensional + constraints by geometric constraints?"), QMessageBox::Yes, QMessageBox::No, + QMessageBox::Cancel); // use an equality constraint if (ret == QMessageBox::Yes) { clone = true; @@ -1692,18 +1693,18 @@ public: Sketcher::PointPos originpos, int nelements, bool clone, int rows, int cols, bool constraintSeparation, bool equalVerticalHorizontalSpacing) - : Mode(STATUS_SEEK_First), - snapMode(SnapMode::Free), - geoIdList(geoidlist), - OriginGeoId(origingeoid), - OriginPos(originpos), - nElements(nelements), - Clone(clone), - Rows(rows), - Cols(cols), - ConstraintSeparation(constraintSeparation), - EqualVerticalHorizontalSpacing(equalVerticalHorizontalSpacing), - EditCurve(2) + : Mode(STATUS_SEEK_First) + , snapMode(SnapMode::Free) + , geoIdList(geoidlist) + , OriginGeoId(origingeoid) + , OriginPos(originpos) + , nElements(nelements) + , Clone(clone) + , Rows(rows) + , Cols(cols) + , ConstraintSeparation(constraintSeparation) + , EqualVerticalHorizontalSpacing(equalVerticalHorizontalSpacing) + , EditCurve(2) {} ~DrawSketchHandlerRectangularArray() override @@ -1793,9 +1794,8 @@ public: Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - e.what()); + Gui::NotifyUserError( + sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), e.what()); Gui::Command::abortCommand(); } @@ -1869,8 +1869,8 @@ void CmdSketcherRectangularArray::activated(int iMsg) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -1879,8 +1879,8 @@ void CmdSketcherRectangularArray::activated(int iMsg) const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -1941,9 +1941,10 @@ void CmdSketcherRectangularArray::activated(int iMsg) } if (geoids < 1) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("A copy requires at least one selected non-external geometric element")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("A copy requires at least one selected non-external geometric element")); return; } @@ -1957,7 +1958,8 @@ void CmdSketcherRectangularArray::activated(int iMsg) geoIdList.append(1, ']'); // if the last element is not a point serving as a reference for the copy process - // then make the start point of the last element the copy reference (if it exists, if not the center point) + // then make the start point of the last element the copy reference (if it exists, if not the + // center point) if (LastPointPos == Sketcher::PointPos::none) { if (LastGeo->getTypeId() == Part::GeomCircle::getClassTypeId() || LastGeo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { @@ -2034,9 +2036,8 @@ void CmdSketcherDeleteAllGeometry::activated(int iMsg) Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Failed to delete all geometry"), - e.what()); + Gui::NotifyUserError( + Obj, QT_TRANSLATE_NOOP("Notifications", "Failed to delete all geometry"), e.what()); Gui::Command::abortCommand(); } @@ -2103,9 +2104,10 @@ void CmdSketcherDeleteAllConstraints::activated(int iMsg) Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Failed to delete all constraints"), - e.what()); + Gui::NotifyUserError( + Obj, + QT_TRANSLATE_NOOP("Notifications", "Failed to delete all constraints"), + e.what()); Gui::Command::abortCommand(); } @@ -2159,8 +2161,8 @@ void CmdSketcherRemoveAxesAlignment::activated(int iMsg) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -2169,8 +2171,8 @@ void CmdSketcherRemoveAxesAlignment::activated(int iMsg) const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(getActiveGuiDocument()->getDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select elements from a single sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select elements from a single sketch.")); return; } @@ -2214,10 +2216,11 @@ void CmdSketcherRemoveAxesAlignment::activated(int iMsg) } if (geoids < 1) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Removal of axes alignment requires at least one selected " - "non-external geometric element")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Removal of axes alignment requires at least one selected " + "non-external geometric element")); return; } @@ -2237,9 +2240,7 @@ void CmdSketcherRemoveAxesAlignment::activated(int iMsg) Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(Obj, - QT_TRANSLATE_NOOP("Notifications", "Error"), - e.what()); + Gui::NotifyUserError(Obj, QT_TRANSLATE_NOOP("Notifications", "Error"), e.what()); Gui::Command::abortCommand(); } diff --git a/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp b/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp index 9a7dbf73fb..f469a70881 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp @@ -22,23 +22,23 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif -#include #include +#include +#include #include -#include -#include -#include +#include #include +#include #include #include -#include -#include +#include +#include -#include "ViewProviderSketch.h" #include "DrawSketchHandler.h" +#include "ViewProviderSketch.h" #include #include @@ -50,15 +50,19 @@ using namespace std; using namespace SketcherGui; using namespace Sketcher; -bool isSketcherVirtualSpaceActive(Gui::Document *doc, bool actsOnSelection ) +bool isSketcherVirtualSpaceActive(Gui::Document* doc, bool actsOnSelection) { if (doc) { // checks if a Sketch Viewprovider is in Edit and is in no special mode - if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { - if (static_cast(doc->getInEdit())->getSketchMode() == ViewProviderSketch::STATUS_NONE) { + if (doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + if (static_cast(doc->getInEdit())->getSketchMode() + == ViewProviderSketch::STATUS_NONE) { if (!actsOnSelection) return true; - else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) + else if (Gui::Selection().countObjectsOfType( + Sketcher::SketchObject::getClassTypeId()) + > 0) return true; } } @@ -66,11 +70,13 @@ bool isSketcherVirtualSpaceActive(Gui::Document *doc, bool actsOnSelection ) return false; } -void ActivateVirtualSpaceHandler(Gui::Document *doc, DrawSketchHandler *handler) +void ActivateVirtualSpaceHandler(Gui::Document* doc, DrawSketchHandler* handler) { if (doc) { - if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { - SketcherGui::ViewProviderSketch* vp = static_cast(doc->getInEdit()); + if (doc->getInEdit() + && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) { + SketcherGui::ViewProviderSketch* vp = + static_cast(doc->getInEdit()); vp->purgeHandler(); vp->activateHandler(handler); } @@ -83,15 +89,16 @@ DEF_STD_CMD_A(CmdSketcherSwitchVirtualSpace) CmdSketcherSwitchVirtualSpace::CmdSketcherSwitchVirtualSpace() : Command("Sketcher_SwitchVirtualSpace") { - sAppModule = "Sketcher"; - sGroup = "Sketcher"; - sMenuText = QT_TR_NOOP("Switch virtual space"); - sToolTipText = QT_TR_NOOP("Switches the selected constraints or the view to the other virtual space"); - sWhatsThis = "Sketcher_SwitchVirtualSpace"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_SwitchVirtualSpace"; - sAccel = "Z, Z"; - eType = ForEdit; + sAppModule = "Sketcher"; + sGroup = "Sketcher"; + sMenuText = QT_TR_NOOP("Switch virtual space"); + sToolTipText = + QT_TR_NOOP("Switches the selected constraints or the view to the other virtual space"); + sWhatsThis = "Sketcher_SwitchVirtualSpace"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_SwitchVirtualSpace"; + sAccel = "Z, Z"; + eType = ForEdit; } void CmdSketcherSwitchVirtualSpace::activated(int iMsg) @@ -106,23 +113,25 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) selection = getSelection().getSelectionEx(); // only one sketch with its subelements are allowed to be selected - if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { + if (selection.size() != 1 + || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraint(s) from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select constraint(s) from the sketch.")); return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraint(s) from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select constraint(s) from the sketch.")); return; } - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { // see if we have constraints, if we do it is not a mode change, but a toggle. if (it->size() > 10 && it->substr(0, 10) == "Constraint") modeChange = false; @@ -130,24 +139,26 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) } if (modeChange) { - Gui::Document * doc = getActiveGuiDocument(); + Gui::Document* doc = getActiveGuiDocument(); - SketcherGui::ViewProviderSketch* vp = static_cast(doc->getInEdit()); + SketcherGui::ViewProviderSketch* vp = + static_cast(doc->getInEdit()); vp->setIsShownVirtualSpace(!vp->getIsShownVirtualSpace()); } // toggle the selected constraint(s) else { // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraint(s) from the sketch.")); + QObject::tr("Wrong selection"), + QObject::tr("Select constraint(s) from the sketch.")); return; } - SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); + SketcherGui::ViewProviderSketch* sketchgui = + static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); // undo command open @@ -155,11 +166,13 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) int successful = SubNames.size(); // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { // only handle constraints - if (it->size() > 10 && it->substr(0,10) == "Constraint") { + if (it->size() > 10 && it->substr(0, 10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); try { Gui::cmdAppObjectArgs(Obj, "toggleVirtualSpace(%d)", ConstrId); } @@ -187,7 +200,7 @@ bool CmdSketcherSwitchVirtualSpace::isActive() void CreateSketcherCommandsVirtualSpace() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSketcherSwitchVirtualSpace()); } diff --git a/src/Mod/Sketcher/Gui/ConstraintFilters.h b/src/Mod/Sketcher/Gui/ConstraintFilters.h index a4f1dca849..d9d561b9f4 100644 --- a/src/Mod/Sketcher/Gui/ConstraintFilters.h +++ b/src/Mod/Sketcher/Gui/ConstraintFilters.h @@ -26,120 +26,138 @@ #include #include -namespace SketcherGui { +namespace SketcherGui +{ -namespace ConstraintFilter { +namespace ConstraintFilter +{ - // FilterValue and SpecialFilterValue are the filters used for Constraint Filtering in the Constraint's Widget. - // FilterValue includes the filters used for the Multi-Filter dialog (SpecialFilterValue is not part of the multi-filter). - // - // The values are hardcoded to be the same as the indices in the combobox and viewlist. Addition of an element here requires - // the addition of the corresponding entry there and vice versa. +// FilterValue and SpecialFilterValue are the filters used for Constraint Filtering in the +// Constraint's Widget. FilterValue includes the filters used for the Multi-Filter dialog +// (SpecialFilterValue is not part of the multi-filter). +// +// The values are hardcoded to be the same as the indices in the combobox and viewlist. Addition of +// an element here requires the addition of the corresponding entry there and vice versa. - enum class FilterValue { - All = 0, - Geometric = 1, - Coincident = 2, - PointOnObject = 3, - Vertical = 4, - Horizontal = 5, - Parallel = 6, - Perpendicular = 7, - Tangent = 8, - Equality = 9, - Symmetric = 10, - Block = 11, - InternalAlignment = 12, - Datums = 13, - HorizontalDistance = 14, - VerticalDistance = 15, - Distance = 16, - Radius = 17, - Weight = 18, - Diameter = 19, - Angle = 20, - SnellsLaw = 21, - Named = 22, - NonDriving = 23, - NumFilterValue // SpecialFilterValue shall start at the same index as this - }; +enum class FilterValue +{ + All = 0, + Geometric = 1, + Coincident = 2, + PointOnObject = 3, + Vertical = 4, + Horizontal = 5, + Parallel = 6, + Perpendicular = 7, + Tangent = 8, + Equality = 9, + Symmetric = 10, + Block = 11, + InternalAlignment = 12, + Datums = 13, + HorizontalDistance = 14, + VerticalDistance = 15, + Distance = 16, + Radius = 17, + Weight = 18, + Diameter = 19, + Angle = 20, + SnellsLaw = 21, + Named = 22, + NonDriving = 23, + NumFilterValue// SpecialFilterValue shall start at the same index as this +}; - constexpr auto FilterValueLength = static_cast>(FilterValue::NumFilterValue); +constexpr auto FilterValueLength = + static_cast>(FilterValue::NumFilterValue); - enum class SpecialFilterValue { - Selection = FilterValueLength, // = 24 - AssociatedConstraints, // = 25 - NumSpecialFilterValue - }; +enum class SpecialFilterValue +{ + Selection = FilterValueLength,// = 24 + AssociatedConstraints, // = 25 + NumSpecialFilterValue +}; - constexpr auto SpecialFilterValue = static_cast>(SpecialFilterValue::NumSpecialFilterValue); +constexpr auto SpecialFilterValue = + static_cast>(SpecialFilterValue::NumSpecialFilterValue); - /// A std::bitset sized to provide one bit per FilterValue value - using FilterValueBitset = std::bitset; - - /// Helper function to retrieve the underlying integral type of a filter value - template - inline auto getFilterIntegral(T filterValue) { - return static_cast>(filterValue); - } - - /// Helper function to test whether a FilterValue value is set in a FilterValueBitset - inline bool checkFilterBitset(FilterValueBitset set, FilterValue filter) - { - auto underlyingFilterValue = static_cast>(filter); - - return set[underlyingFilterValue]; - } - - /// Helper function expanding a parameter pack value of enum classes to create a integral underlying type having - /// the bits corresponding to the parameter pack set - template - constexpr decltype(auto) buildBitset(Args... args) { - return (... | (1 << static_cast>(args))); - } - - /// Array of FilterValue bit sets of size of the number of FilterValues indicating for each FilterValue, which other - /// FilterValues are comprised therein. It defines the dependencies between filters. - constexpr std::array< FilterValueBitset, FilterValueLength> filterAggregates { - buildBitset(FilterValue::All, FilterValue::Geometric, FilterValue::Horizontal, - FilterValue::Vertical, FilterValue::Coincident, FilterValue::PointOnObject, FilterValue::Parallel, FilterValue::Perpendicular, - FilterValue::Tangent, FilterValue::Equality, FilterValue::Symmetric, FilterValue::Block, FilterValue::Datums, FilterValue::Distance, - FilterValue::HorizontalDistance, FilterValue::VerticalDistance, FilterValue::Radius, FilterValue::Weight, FilterValue::Diameter, - FilterValue::Angle, FilterValue::SnellsLaw, FilterValue::Named, FilterValue::NonDriving, FilterValue::InternalAlignment), // All = All other groups are covered (0) - buildBitset(FilterValue::Geometric, FilterValue::Horizontal, FilterValue::Vertical, FilterValue::Coincident, FilterValue::PointOnObject, - FilterValue::Parallel, FilterValue::Perpendicular, FilterValue::Tangent, FilterValue::Equality, FilterValue::Symmetric, - FilterValue::Block, FilterValue::InternalAlignment), // Geometric = All others not being datums (1) - - buildBitset(FilterValue::Coincident), // Coincident = Just this (2) - buildBitset(FilterValue::PointOnObject), // PointOnObject = Just this (3) - buildBitset(FilterValue::Vertical), // Vertical = Just this (4) - buildBitset(FilterValue::Horizontal), // Horizontal = Just this (5) - buildBitset(FilterValue::Parallel), // Parallel = Just this (6) - buildBitset(FilterValue::Perpendicular), // Perpendicular = Just this (7) - buildBitset(FilterValue::Tangent), // Tangent = Just this (8) - buildBitset(FilterValue::Equality), // Equality = Just this (9) - buildBitset(FilterValue::Symmetric), // Symmetric = Just this (10) - buildBitset(FilterValue::Block), // Block = Just this (11) - buildBitset(FilterValue::InternalAlignment), // InternalAlignment = Just this (12) - - buildBitset(FilterValue::Datums, FilterValue::Distance, FilterValue::HorizontalDistance, FilterValue::VerticalDistance, FilterValue::Radius, - FilterValue::Weight, FilterValue::Diameter, FilterValue::Angle, FilterValue::SnellsLaw), // Datum = all others not being geometric (13) - - buildBitset(FilterValue::HorizontalDistance), // HorizontalDistance = Just this (14) - buildBitset(FilterValue::VerticalDistance), // VerticalDistance = Just this (15) - buildBitset(FilterValue::Distance), // Distance = Just this (16) - buildBitset(FilterValue::Radius), // Radius = Just this (17) - buildBitset(FilterValue::Weight), // Weight = Just this (18) - buildBitset(FilterValue::Diameter), // Diameter = Just this (19) - buildBitset(FilterValue::Angle), // Angle = Just this (20) - buildBitset(FilterValue::SnellsLaw), // SnellsLaw = Just this (21) - - buildBitset(FilterValue::Named), // Named = Just this (22) - buildBitset(FilterValue::NonDriving) // NonDriving = Just this (23) - }; +/// A std::bitset sized to provide one bit per FilterValue value +using FilterValueBitset = std::bitset; +/// Helper function to retrieve the underlying integral type of a filter value +template +inline auto getFilterIntegral(T filterValue) +{ + return static_cast>(filterValue); } +/// Helper function to test whether a FilterValue value is set in a FilterValueBitset +inline bool checkFilterBitset(FilterValueBitset set, FilterValue filter) +{ + auto underlyingFilterValue = static_cast>(filter); + + return set[underlyingFilterValue]; } -#endif // SKETCHERGUI_ConstraintFilters_H +/// Helper function expanding a parameter pack value of enum classes to create a integral underlying +/// type having the bits corresponding to the parameter pack set +template +constexpr decltype(auto) buildBitset(Args... args) +{ + return (... | (1 << static_cast>(args))); +} + +/// Array of FilterValue bit sets of size of the number of FilterValues indicating for each +/// FilterValue, which other FilterValues are comprised therein. It defines the dependencies between +/// filters. +constexpr std::array filterAggregates { + buildBitset(FilterValue::All, FilterValue::Geometric, FilterValue::Horizontal, + FilterValue::Vertical, FilterValue::Coincident, FilterValue::PointOnObject, + FilterValue::Parallel, FilterValue::Perpendicular, FilterValue::Tangent, + FilterValue::Equality, FilterValue::Symmetric, FilterValue::Block, + FilterValue::Datums, FilterValue::Distance, FilterValue::HorizontalDistance, + FilterValue::VerticalDistance, FilterValue::Radius, FilterValue::Weight, + FilterValue::Diameter, FilterValue::Angle, FilterValue::SnellsLaw, + FilterValue::Named, FilterValue::NonDriving, + FilterValue::InternalAlignment),// All = All other groups are covered (0) + buildBitset(FilterValue::Geometric, FilterValue::Horizontal, FilterValue::Vertical, + FilterValue::Coincident, FilterValue::PointOnObject, FilterValue::Parallel, + FilterValue::Perpendicular, FilterValue::Tangent, FilterValue::Equality, + FilterValue::Symmetric, FilterValue::Block, + FilterValue::InternalAlignment),// Geometric = All others not being datums (1) + + buildBitset(FilterValue::Coincident), // Coincident = Just this (2) + buildBitset(FilterValue::PointOnObject), // PointOnObject = Just this (3) + buildBitset(FilterValue::Vertical), // Vertical = Just this (4) + buildBitset(FilterValue::Horizontal), // Horizontal = Just this (5) + buildBitset(FilterValue::Parallel), // Parallel = Just this (6) + buildBitset(FilterValue::Perpendicular), // Perpendicular = Just this (7) + buildBitset(FilterValue::Tangent), // Tangent = Just this (8) + buildBitset(FilterValue::Equality), // Equality = Just this (9) + buildBitset(FilterValue::Symmetric), // Symmetric = Just this (10) + buildBitset(FilterValue::Block), // Block = Just this (11) + buildBitset(FilterValue::InternalAlignment),// InternalAlignment = Just this (12) + + buildBitset(FilterValue::Datums, FilterValue::Distance, FilterValue::HorizontalDistance, + FilterValue::VerticalDistance, FilterValue::Radius, FilterValue::Weight, + FilterValue::Diameter, FilterValue::Angle, + FilterValue::SnellsLaw),// Datum = all others not being geometric (13) + + buildBitset(FilterValue::HorizontalDistance),// HorizontalDistance = Just this (14) + buildBitset(FilterValue::VerticalDistance), // VerticalDistance = Just this (15) + buildBitset(FilterValue::Distance), // Distance = Just this (16) + buildBitset(FilterValue::Radius), // Radius = Just this (17) + buildBitset(FilterValue::Weight), // Weight = Just this (18) + buildBitset(FilterValue::Diameter), // Diameter = Just this (19) + buildBitset(FilterValue::Angle), // Angle = Just this (20) + buildBitset(FilterValue::SnellsLaw), // SnellsLaw = Just this (21) + + buildBitset(FilterValue::Named), // Named = Just this (22) + buildBitset(FilterValue::NonDriving)// NonDriving = Just this (23) +}; + +}// namespace ConstraintFilter + +}// namespace SketcherGui + +#endif// SKETCHERGUI_ConstraintFilters_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp index c35404e0c3..a33eaa525e 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp @@ -22,11 +22,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#endif// #ifndef _PreComp_ #include #include @@ -38,8 +38,8 @@ #include #include -#include "DrawSketchHandler.h" #include "CommandConstraints.h" +#include "DrawSketchHandler.h" #include "Utils.h" #include "ViewProviderSketch.h" @@ -49,72 +49,91 @@ using namespace Sketcher; /************************************ Attorney *******************************************/ -inline void ViewProviderSketchDrawSketchHandlerAttorney::setConstraintSelectability(ViewProviderSketch &vp, bool enabled /*= true*/) +inline void +ViewProviderSketchDrawSketchHandlerAttorney::setConstraintSelectability(ViewProviderSketch& vp, + bool enabled /*= true*/) { vp.setConstraintSelectability(enabled); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(ViewProviderSketch &vp, const Base::Vector2d &Pos, const SbString &txt) +inline void ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(ViewProviderSketch& vp, + const Base::Vector2d& Pos, + const SbString& txt) { - vp.setPositionText(Pos,txt); + vp.setPositionText(Pos, txt); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(ViewProviderSketch &vp, const Base::Vector2d &Pos) +inline void ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(ViewProviderSketch& vp, + const Base::Vector2d& Pos) { vp.setPositionText(Pos); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::resetPositionText(ViewProviderSketch &vp) +inline void ViewProviderSketchDrawSketchHandlerAttorney::resetPositionText(ViewProviderSketch& vp) { vp.resetPositionText(); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEdit(ViewProviderSketch &vp, const std::vector &EditCurve) +inline void +ViewProviderSketchDrawSketchHandlerAttorney::drawEdit(ViewProviderSketch& vp, + const std::vector& EditCurve) { vp.drawEdit(EditCurve); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEdit(ViewProviderSketch &vp, const std::list> &list) +inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEdit( + ViewProviderSketch& vp, const std::list>& list) { vp.drawEdit(list); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers(ViewProviderSketch &vp, const std::vector &EditMarkers, unsigned int augmentationlevel) +inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers( + ViewProviderSketch& vp, const std::vector& EditMarkers, + unsigned int augmentationlevel) { vp.drawEditMarkers(EditMarkers, augmentationlevel); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::setAxisPickStyle(ViewProviderSketch &vp, bool on) +inline void ViewProviderSketchDrawSketchHandlerAttorney::setAxisPickStyle(ViewProviderSketch& vp, + bool on) { vp.setAxisPickStyle(on); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::moveCursorToSketchPoint(ViewProviderSketch &vp, Base::Vector2d point) +inline void +ViewProviderSketchDrawSketchHandlerAttorney::moveCursorToSketchPoint(ViewProviderSketch& vp, + Base::Vector2d point) { vp.moveCursorToSketchPoint(point); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::preselectAtPoint(ViewProviderSketch &vp, Base::Vector2d point) +inline void ViewProviderSketchDrawSketchHandlerAttorney::preselectAtPoint(ViewProviderSketch& vp, + Base::Vector2d point) { vp.preselectAtPoint(point); } -inline int ViewProviderSketchDrawSketchHandlerAttorney::getPreselectPoint(const ViewProviderSketch &vp) +inline int +ViewProviderSketchDrawSketchHandlerAttorney::getPreselectPoint(const ViewProviderSketch& vp) { - return vp.getPreselectPoint(); + return vp.getPreselectPoint(); } -inline int ViewProviderSketchDrawSketchHandlerAttorney::getPreselectCurve(const ViewProviderSketch &vp) +inline int +ViewProviderSketchDrawSketchHandlerAttorney::getPreselectCurve(const ViewProviderSketch& vp) { return vp.getPreselectCurve(); } -inline int ViewProviderSketchDrawSketchHandlerAttorney::getPreselectCross(const ViewProviderSketch &vp) +inline int +ViewProviderSketchDrawSketchHandlerAttorney::getPreselectCross(const ViewProviderSketch& vp) { return vp.getPreselectCross(); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping(ViewProviderSketch &vp, bool enable, Base::Vector2d referencePoint) +inline void +ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping(ViewProviderSketch& vp, bool enable, + Base::Vector2d referencePoint) { vp.setAngleSnapping(enable, referencePoint); } @@ -125,11 +144,14 @@ inline void ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping(ViewPr CurveConverter::CurveConverter() { try { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); hGrp->Attach(this); } - catch(const Base::ValueError & e) { // ensure that if parameter strings are not well-formed, the exception is not propagated - Base::Console().DeveloperError("CurveConverter", "Malformed parameter string: %s\n", e.what()); + catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the + // exception is not propagated + Base::Console().DeveloperError( + "CurveConverter", "Malformed parameter string: %s\n", e.what()); } updateCurvedEdgeCountSegmentsParameter(); @@ -138,40 +160,45 @@ CurveConverter::CurveConverter() CurveConverter::~CurveConverter() { try { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); hGrp->Detach(this); } - catch(const Base::ValueError & e) {// ensure that if parameter strings are not well-formed, the program is not terminated when calling the noexcept destructor. - Base::Console().DeveloperError("CurveConverter", "Malformed parameter string: %s\n", e.what()); + catch (const Base::ValueError& + e) {// ensure that if parameter strings are not well-formed, the program is not + // terminated when calling the noexcept destructor. + Base::Console().DeveloperError( + "CurveConverter", "Malformed parameter string: %s\n", e.what()); } } -std::vector CurveConverter::toVector2D(const Part::Geometry * geometry) +std::vector CurveConverter::toVector2D(const Part::Geometry* geometry) { std::vector vector2d; const auto type = geometry->getTypeId(); - auto emplaceasvector2d = [&vector2d](const Base::Vector3d & point) { - vector2d.emplace_back(point.x,point.y); + auto emplaceasvector2d = [&vector2d](const Base::Vector3d& point) { + vector2d.emplace_back(point.x, point.y); }; auto isconic = type.isDerivedFrom(Part::GeomConic::getClassTypeId()); auto isbounded = type.isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId()); - if (type == Part::GeomLineSegment::getClassTypeId()) { // add a line - auto geo = static_cast(geometry); + if (type == Part::GeomLineSegment::getClassTypeId()) {// add a line + auto geo = static_cast(geometry); emplaceasvector2d(geo->getStartPoint()); emplaceasvector2d(geo->getEndPoint()); } - else if ( isconic || isbounded ) { + else if (isconic || isbounded) { - auto geo = static_cast(geometry); + auto geo = static_cast(geometry); - double segment = (geo->getLastParameter() - geo->getFirstParameter()) / curvedEdgeCountSegments; + double segment = + (geo->getLastParameter() - geo->getFirstParameter()) / curvedEdgeCountSegments; - for (int i=0; i < curvedEdgeCountSegments; i++) + for (int i = 0; i < curvedEdgeCountSegments; i++) emplaceasvector2d(geo->value(geo->getFirstParameter() + i * segment)); // either close the curve for untrimmed conic or set the last point for bounded curves @@ -181,11 +208,12 @@ std::vector CurveConverter::toVector2D(const Part::Geometry * ge return vector2d; } -std::list> CurveConverter::toVector2DList(const std::vector &geometries) +std::list> +CurveConverter::toVector2DList(const std::vector& geometries) { std::list> list; - for(const auto & geo : geometries) + for (const auto& geo : geometries) list.push_back(toVector2D(geo)); return list; @@ -193,7 +221,8 @@ std::list> CurveConverter::toVector2DList(const std: void CurveConverter::updateCurvedEdgeCountSegmentsParameter() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); int stdcountsegments = hGrp->GetInt("SegmentsPerGeometry", 50); // value cannot be smaller than 6 @@ -204,14 +233,13 @@ void CurveConverter::updateCurvedEdgeCountSegmentsParameter() }; /** Observer for parameter group. */ -void CurveConverter::OnChange(Base::Subject &rCaller, const char * sReason) +void CurveConverter::OnChange(Base::Subject& rCaller, const char* sReason) { - (void) rCaller; + (void)rCaller; - if(strcmp(sReason, "SegmentsPerGeometry") == 0) { + if (strcmp(sReason, "SegmentsPerGeometry") == 0) { updateCurvedEdgeCountSegmentsParameter(); } - } /**************************** DrawSketchHandler *******************************************/ @@ -220,16 +248,19 @@ void CurveConverter::OnChange(Base::Subject &rCaller, const char * //************************************************************************** // Construction/Destruction -DrawSketchHandler::DrawSketchHandler() : sketchgui(nullptr) {} +DrawSketchHandler::DrawSketchHandler() + : sketchgui(nullptr) +{} -DrawSketchHandler::~DrawSketchHandler() {} +DrawSketchHandler::~DrawSketchHandler() +{} QString DrawSketchHandler::getCrosshairCursorSVGName() const { return QString::fromLatin1("None"); } -void DrawSketchHandler::activate(ViewProviderSketch * vp) +void DrawSketchHandler::activate(ViewProviderSketch* vp) { sketchgui = vp; @@ -288,16 +319,17 @@ int DrawSketchHandler::getHighestCurveIndex(void) unsigned long DrawSketchHandler::getCrosshairColor() { - unsigned long color = 0xFFFFFFFF; // white - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); + unsigned long color = 0xFFFFFFFF;// white + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); color = hGrp->GetUnsigned("CursorCrosshairColor", color); // from rgba to rgb color = (color >> 8) & 0xFFFFFF; return color; } -void DrawSketchHandler::setCrosshairCursor(const QString & svgName) { +void DrawSketchHandler::setCrosshairCursor(const QString& svgName) +{ const unsigned long defaultCrosshairColor = 0xFFFFFF; unsigned long color = getCrosshairColor(); auto colorMapping = std::map(); @@ -308,12 +340,14 @@ void DrawSketchHandler::setCrosshairCursor(const QString & svgName) { setSvgCursor(svgName, hotX, hotY, colorMapping); } -void DrawSketchHandler::setCrosshairCursor(const char* svgName) { +void DrawSketchHandler::setCrosshairCursor(const char* svgName) +{ QString cursorName = QString::fromLatin1(svgName); setCrosshairCursor(cursorName); } -void DrawSketchHandler::setSvgCursor(const QString & cursorName, int x, int y, const std::map& colorMapping) +void DrawSketchHandler::setSvgCursor(const QString& cursorName, int x, int y, + const std::map& colorMapping) { // The Sketcher_Pointer_*.svg icons have a default size of 64x64. When directly creating // them with a size of 32x32 they look very bad. @@ -333,14 +367,15 @@ void DrawSketchHandler::setSvgCursor(const QString & cursorName, int x, int y, c #endif qreal cursorSize = defaultCursorSize * pRatio; - QPixmap pointer = Gui::BitmapFactory().pixmapFromSvg(cursorName.toStdString().c_str(), QSizeF(cursorSize, cursorSize), colorMapping); + QPixmap pointer = Gui::BitmapFactory().pixmapFromSvg( + cursorName.toStdString().c_str(), QSizeF(cursorSize, cursorSize), colorMapping); if (isRatioOne) pointer = pointer.scaled(32, 32); pointer.setDevicePixelRatio(pRatio); setCursor(pointer, hotX, hotY, false); } -void DrawSketchHandler::setCursor(const QPixmap &p,int x,int y, bool autoScale) +void DrawSketchHandler::setCursor(const QPixmap& p, int x, int y, bool autoScale) { Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { @@ -351,8 +386,8 @@ void DrawSketchHandler::setCursor(const QPixmap &p,int x,int y, bool autoScale) // TODO remove autoScale after all cursors are SVG-based if (autoScale) { qreal pRatio = viewer->devicePixelRatio(); - int newWidth = p.width()*pRatio; - int newHeight = p.height()*pRatio; + int newWidth = p.width() * pRatio; + int newHeight = p.height() * pRatio; p1 = p1.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); p1.setDevicePixelRatio(pRatio); qreal hotX = x; @@ -364,7 +399,8 @@ void DrawSketchHandler::setCursor(const QPixmap &p,int x,int y, bool autoScale) } #endif cursor = QCursor(p1, hotX, hotY); - } else { + } + else { // already scaled cursor = QCursor(p1, x, y); } @@ -376,7 +412,8 @@ void DrawSketchHandler::setCursor(const QPixmap &p,int x,int y, bool autoScale) } } -void DrawSketchHandler::addCursorTail( std::vector &pixmaps ) { +void DrawSketchHandler::addCursorTail(std::vector& pixmaps) +{ // Create a pixmap that will contain icon and each autoconstraint icon Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { @@ -388,7 +425,7 @@ void DrawSketchHandler::addCursorTail( std::vector &pixmaps ) { qreal baseCursorHeight = baseIcon.height(); int tailWidth = 0; - for (auto const& p: pixmaps) { + for (auto const& p : pixmaps) { tailWidth += p.width(); } @@ -401,15 +438,14 @@ void DrawSketchHandler::addCursorTail( std::vector &pixmaps ) { QPainter qp; qp.begin(&newIcon); - qp.drawPixmap(QPointF(0,0), baseIcon.scaled( - baseCursorWidth * pixelRatio, - baseCursorHeight * pixelRatio, - Qt::KeepAspectRatio, - Qt::SmoothTransformation - )); + qp.drawPixmap(QPointF(0, 0), + baseIcon.scaled(baseCursorWidth * pixelRatio, + baseCursorHeight * pixelRatio, + Qt::KeepAspectRatio, + Qt::SmoothTransformation)); // Iterate through pixmaps and them to the cursor pixmap - std::vector::iterator pit=pixmaps.begin(); + std::vector::iterator pit = pixmaps.begin(); int i = 0; qreal currentIconX = baseCursorWidth; qreal currentIconY; @@ -421,10 +457,10 @@ void DrawSketchHandler::addCursorTail( std::vector &pixmaps ) { currentIconX += icon.width(); } - qp.end(); // Finish painting + qp.end();// Finish painting // Create the new cursor with the icon. - QPoint p=actCursor.hotSpot(); + QPoint p = actCursor.hotSpot(); newIcon.setDevicePixelRatio(pixelRatio); QCursor newCursor(newIcon, p.x(), p.y()); applyCursor(newCursor); @@ -435,7 +471,7 @@ void DrawSketchHandler::updateCursor() { auto cursorstring = getCrosshairCursorSVGName(); - if(cursorstring != QString::fromLatin1("None")) + if (cursorstring != QString::fromLatin1("None")) setCrosshairCursor(cursorstring); } @@ -444,7 +480,7 @@ void DrawSketchHandler::applyCursor(void) applyCursor(actCursor); } -void DrawSketchHandler::applyCursor(QCursor &newCursor) +void DrawSketchHandler::applyCursor(QCursor& newCursor) { Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { @@ -462,7 +498,8 @@ void DrawSketchHandler::unsetCursor(void) } } -qreal DrawSketchHandler::devicePixelRatio() { +qreal DrawSketchHandler::devicePixelRatio() +{ qreal pixelRatio = 1; Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { @@ -472,60 +509,62 @@ qreal DrawSketchHandler::devicePixelRatio() { return pixelRatio; } -std::vector DrawSketchHandler::suggestedConstraintsPixmaps( - std::vector &suggestedConstraints) { +std::vector +DrawSketchHandler::suggestedConstraintsPixmaps(std::vector& suggestedConstraints) +{ std::vector pixmaps; // Iterate through AutoConstraints types and get their pixmaps - std::vector::iterator it=suggestedConstraints.begin(); + std::vector::iterator it = suggestedConstraints.begin(); int i = 0; for (; it != suggestedConstraints.end(); ++it, i++) { QString iconType; - switch (it->Type) - { - case Horizontal: - iconType = QString::fromLatin1("Constraint_Horizontal"); - break; - case Vertical: - iconType = QString::fromLatin1("Constraint_Vertical"); - break; - case Coincident: - iconType = QString::fromLatin1("Constraint_PointOnPoint"); - break; - case PointOnObject: - iconType = QString::fromLatin1("Constraint_PointOnObject"); - break; - case Tangent: - iconType = QString::fromLatin1("Constraint_Tangent"); - break; - default: - break; + switch (it->Type) { + case Horizontal: + iconType = QString::fromLatin1("Constraint_Horizontal"); + break; + case Vertical: + iconType = QString::fromLatin1("Constraint_Vertical"); + break; + case Coincident: + iconType = QString::fromLatin1("Constraint_PointOnPoint"); + break; + case PointOnObject: + iconType = QString::fromLatin1("Constraint_PointOnObject"); + break; + case Tangent: + iconType = QString::fromLatin1("Constraint_Tangent"); + break; + default: + break; } if (!iconType.isEmpty()) { qreal pixelRatio = 1; Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { - Gui::View3DInventorViewer* viewer = static_cast(view)->getViewer(); + Gui::View3DInventorViewer* viewer = + static_cast(view)->getViewer(); pixelRatio = viewer->devicePixelRatio(); } int iconWidth = 16 * pixelRatio; - QPixmap icon = Gui::BitmapFactory() - .pixmapFromSvg(iconType.toStdString().c_str(), QSize(iconWidth, iconWidth)); + QPixmap icon = Gui::BitmapFactory().pixmapFromSvg(iconType.toStdString().c_str(), + QSize(iconWidth, iconWidth)); pixmaps.push_back(icon); } } return pixmaps; } -int DrawSketchHandler::seekAutoConstraint(std::vector &suggestedConstraints, +int DrawSketchHandler::seekAutoConstraint(std::vector& suggestedConstraints, const Base::Vector2d& Pos, const Base::Vector2d& Dir, AutoConstraint::TargetType type) { suggestedConstraints.clear(); if (!sketchgui->Autoconstraints.getValue()) - return 0; // If Autoconstraints property is not set quit + return 0;// If Autoconstraints property is not set quit - Base::Vector3d hitShapeDir = Base::Vector3d(0,0,0); // direction of hit shape (if it is a line, the direction of the line) + Base::Vector3d hitShapeDir = Base::Vector3d( + 0, 0, 0);// direction of hit shape (if it is a line, the direction of the line) // Get Preselection int preSelPnt = getPreselectPoint(); @@ -537,31 +576,29 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested if (preSelPnt != -1) sketchgui->getSketchObject()->getGeoVertexIndex(preSelPnt, GeoId, PosId); - else if (preSelCrv != -1){ - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(preSelCrv); + else if (preSelCrv != -1) { + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(preSelCrv); // ensure geom exists in case object was called before preselection is updated if (geom) { GeoId = preSelCrv; if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *line = static_cast(geom); - hitShapeDir= line->getEndPoint()-line->getStartPoint(); + const Part::GeomLineSegment* line = static_cast(geom); + hitShapeDir = line->getEndPoint() - line->getStartPoint(); } } - } - else if (preSelCrs == 0) { // root point + else if (preSelCrs == 0) {// root point GeoId = Sketcher::GeoEnum::RtPnt; PosId = Sketcher::PointPos::start; } - else if (preSelCrs == 1){ // x axis + else if (preSelCrs == 1) {// x axis GeoId = Sketcher::GeoEnum::HAxis; - hitShapeDir = Base::Vector3d(1,0,0); - + hitShapeDir = Base::Vector3d(1, 0, 0); } - else if (preSelCrs == 2){ // y axis + else if (preSelCrs == 2) {// y axis GeoId = Sketcher::GeoEnum::VAxis; - hitShapeDir = Base::Vector3d(0,1,0); + hitShapeDir = Base::Vector3d(0, 1, 0); } if (GeoId != GeoEnum::GeoUndef) { @@ -570,22 +607,30 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested constr.Type = Sketcher::None; constr.GeoId = GeoId; constr.PosId = PosId; - if ((type == AutoConstraint::VERTEX || type == AutoConstraint::VERTEX_NO_TANGENCY) && PosId != Sketcher::PointPos::none) + if ((type == AutoConstraint::VERTEX || type == AutoConstraint::VERTEX_NO_TANGENCY) + && PosId != Sketcher::PointPos::none) constr.Type = Sketcher::Coincident; else if (type == AutoConstraint::CURVE && PosId != Sketcher::PointPos::none) constr.Type = Sketcher::PointOnObject; - else if ((type == AutoConstraint::VERTEX || type == AutoConstraint::VERTEX_NO_TANGENCY) && PosId == Sketcher::PointPos::none) + else if ((type == AutoConstraint::VERTEX || type == AutoConstraint::VERTEX_NO_TANGENCY) + && PosId == Sketcher::PointPos::none) constr.Type = Sketcher::PointOnObject; else if (type == AutoConstraint::CURVE && PosId == Sketcher::PointPos::none) constr.Type = Sketcher::Tangent; - if(constr.Type == Sketcher::Tangent && Dir.Length() > 1e-8 && hitShapeDir.Length() > 1e-8) { // We are hitting a line and have hitting vector information - Base::Vector3d dir3d = Base::Vector3d(Dir.x,Dir.y,0); - double cosangle=dir3d.Normalize()*hitShapeDir.Normalize(); + if (constr.Type == Sketcher::Tangent && Dir.Length() > 1e-8 + && hitShapeDir.Length() + > 1e-8) {// We are hitting a line and have hitting vector information + Base::Vector3d dir3d = Base::Vector3d(Dir.x, Dir.y, 0); + double cosangle = dir3d.Normalize() * hitShapeDir.Normalize(); - // the angle between the line and the hitting direction are over around 6 degrees (it is substantially parallel) - // or if it is an sketch axis (that can not move to accommodate to the shape), then only if it is around 6 degrees with the normal (around 84 degrees) - if (fabs(cosangle) < 0.995f || ((GeoId==Sketcher::GeoEnum::HAxis || GeoId==Sketcher::GeoEnum::VAxis) && fabs(cosangle) < 0.1)) + // the angle between the line and the hitting direction are over around 6 degrees (it is + // substantially parallel) or if it is an sketch axis (that can not move to accommodate + // to the shape), then only if it is around 6 degrees with the normal (around 84 + // degrees) + if (fabs(cosangle) < 0.995f + || ((GeoId == Sketcher::GeoEnum::HAxis || GeoId == Sketcher::GeoEnum::VAxis) + && fabs(cosangle) < 0.1)) suggestedConstraints.push_back(constr); @@ -604,14 +649,14 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested // Number of Degree of deviation from horizontal or vertical lines const double angleDev = 2; - const double angleDevRad = angleDev * M_PI / 180.; + const double angleDevRad = angleDev * M_PI / 180.; AutoConstraint constr; constr.Type = Sketcher::None; constr.GeoId = GeoEnum::GeoUndef; constr.PosId = Sketcher::PointPos::none; double angle = std::abs(atan2(Dir.y, Dir.x)); - if (angle < angleDevRad || (M_PI - angle) < angleDevRad ) + if (angle < angleDevRad || (M_PI - angle) < angleDevRad) // Suggest horizontal constraint constr.Type = Sketcher::Horizontal; else if (std::abs(angle - M_PI_2) < angleDevRad) @@ -634,25 +679,27 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested double tangDeviation = 0.1 * sketchgui->getScaleFactor(); // Get geometry list - const std::vector geomlist = sketchgui->getSketchObject()->getCompleteGeometry(); + const std::vector geomlist = + sketchgui->getSketchObject()->getCompleteGeometry(); - Base::Vector3d tmpPos(Pos.x, Pos.y, 0.f); // Current cursor point - Base::Vector3d tmpDir(Dir.x, Dir.y, 0.f); // Direction of line - Base::Vector3d tmpStart(Pos.x-Dir.x, Pos.y-Dir.y, 0.f); // Start point + Base::Vector3d tmpPos(Pos.x, Pos.y, 0.f); // Current cursor point + Base::Vector3d tmpDir(Dir.x, Dir.y, 0.f); // Direction of line + Base::Vector3d tmpStart(Pos.x - Dir.x, Pos.y - Dir.y, 0.f);// Start point // Iterate through geometry int i = 0; - for (std::vector::const_iterator it=geomlist.begin(); it != geomlist.end(); ++it, i++) { + for (std::vector::const_iterator it = geomlist.begin(); it != geomlist.end(); + ++it, i++) { if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast((*it)); + const Part::GeomCircle* circle = static_cast((*it)); Base::Vector3d center = circle->getCenter(); double radius = circle->getRadius(); // ignore if no touch (use dot product) - if(tmpDir * (center-tmpPos) > 0 || tmpDir * (center-tmpStart) < 0) + if (tmpDir * (center - tmpPos) > 0 || tmpDir * (center - tmpStart) < 0) continue; Base::Vector3d projPnt(0.f, 0.f, 0.f); @@ -664,10 +711,10 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested tangId = i; tangDeviation = projDist; } + } + else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - - const Part::GeomEllipse *ellipse = static_cast((*it)); + const Part::GeomEllipse* ellipse = static_cast((*it)); Base::Vector3d center = ellipse->getCenter(); @@ -675,32 +722,33 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested double b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); - double cf = sqrt(a*a - b*b); + double cf = sqrt(a * a - b * b); Base::Vector3d focus1P = center + cf * majdir; Base::Vector3d focus2P = center - cf * majdir; - Base::Vector3d norm = Base::Vector3d(Dir.y,-Dir.x).Normalize(); + Base::Vector3d norm = Base::Vector3d(Dir.y, -Dir.x).Normalize(); - double distancetoline = norm*(tmpPos - focus1P); // distance focus1 to line + double distancetoline = norm * (tmpPos - focus1P);// distance focus1 to line - Base::Vector3d focus1PMirrored = focus1P + 2*distancetoline*norm; // mirror of focus1 with respect to the line + Base::Vector3d focus1PMirrored = + focus1P + 2 * distancetoline * norm;// mirror of focus1 with respect to the line - double error = fabs((focus1PMirrored-focus2P).Length() - 2*a); + double error = fabs((focus1PMirrored - focus2P).Length() - 2 * a); - if ( error< tangDeviation) { - tangId = i; - tangDeviation = error; + if (error < tangDeviation) { + tangId = i; + tangDeviation = error; } - - } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast((*it)); + } + else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = static_cast((*it)); Base::Vector3d center = arc->getCenter(); double radius = arc->getRadius(); // ignore if no touch (use dot product) - if(tmpDir * (center-tmpPos) > 0 || tmpDir * (center-tmpStart) < 0) + if (tmpDir * (center - tmpPos) > 0 || tmpDir * (center - tmpStart) < 0) continue; Base::Vector3d projPnt(0.f, 0.f, 0.f); @@ -712,17 +760,18 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested arc->getRange(startAngle, endAngle, /*emulateCCW=*/true); double angle = atan2(projPnt.y, projPnt.x); - while(angle < startAngle) - angle += 2*D_PI; // Bring it to range of arc + while (angle < startAngle) + angle += 2 * D_PI;// Bring it to range of arc // if the point is on correct side of arc - if (angle <= endAngle) { // Now need to check only one side + if (angle <= endAngle) {// Now need to check only one side tangId = i; tangDeviation = projDist; } } - } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *aoe = static_cast((*it)); + } + else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoe = static_cast((*it)); Base::Vector3d center = aoe->getCenter(); @@ -730,22 +779,23 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested double b = aoe->getMinorRadius(); Base::Vector3d majdir = aoe->getMajorAxisDir(); - double cf = sqrt(a*a - b*b); + double cf = sqrt(a * a - b * b); Base::Vector3d focus1P = center + cf * majdir; Base::Vector3d focus2P = center - cf * majdir; - Base::Vector3d norm = Base::Vector3d(Dir.y,-Dir.x).Normalize(); + Base::Vector3d norm = Base::Vector3d(Dir.y, -Dir.x).Normalize(); - double distancetoline = norm*(tmpPos - focus1P); // distance focus1 to line + double distancetoline = norm * (tmpPos - focus1P);// distance focus1 to line - Base::Vector3d focus1PMirrored = focus1P + 2*distancetoline*norm; // mirror of focus1 with respect to the line + Base::Vector3d focus1PMirrored = + focus1P + 2 * distancetoline * norm;// mirror of focus1 with respect to the line - double error = fabs((focus1PMirrored-focus2P).Length() - 2*a); + double error = fabs((focus1PMirrored - focus2P).Length() - 2 * a); - if ( error< tangDeviation ) { - tangId = i; - tangDeviation = error; + if (error < tangDeviation) { + tangId = i; + tangDeviation = error; } if (error < tangDeviation) { @@ -753,15 +803,19 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested aoe->getRange(startAngle, endAngle, /*emulateCCW=*/true); double angle = Base::fmod( - atan2(-aoe->getMajorRadius()*((tmpPos.x-center.x)*majdir.y-(tmpPos.y-center.y)*majdir.x), - aoe->getMinorRadius()*((tmpPos.x-center.x)*majdir.x+(tmpPos.y-center.y)*majdir.y) - )- startAngle, 2.f*M_PI); + atan2( + -aoe->getMajorRadius() + * ((tmpPos.x - center.x) * majdir.y - (tmpPos.y - center.y) * majdir.x), + aoe->getMinorRadius() + * ((tmpPos.x - center.x) * majdir.x + (tmpPos.y - center.y) * majdir.y)) + - startAngle, + 2.f * M_PI); - while(angle < startAngle) - angle += 2*D_PI; // Bring it to range of arc + while (angle < startAngle) + angle += 2 * D_PI;// Bring it to range of arc // if the point is on correct side of arc - if (angle <= endAngle) { // Now need to check only one side + if (angle <= endAngle) {// Now need to check only one side tangId = i; tangDeviation = error; } @@ -770,7 +824,7 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested } if (tangId != GeoEnum::GeoUndef) { - if (tangId > getHighestCurveIndex()) // external Geometry + if (tangId > getHighestCurveIndex())// external Geometry tangId = getHighestCurveIndex() - tangId; // Suggest vertical constraint constr.Type = Tangent; @@ -782,15 +836,16 @@ int DrawSketchHandler::seekAutoConstraint(std::vector &suggested return suggestedConstraints.size(); } -void DrawSketchHandler::createAutoConstraints(const std::vector &autoConstrs, - int geoId1, Sketcher::PointPos posId1, bool createowncommand /*= true*/) +void DrawSketchHandler::createAutoConstraints(const std::vector& autoConstrs, + int geoId1, Sketcher::PointPos posId1, + bool createowncommand /*= true*/) { if (!sketchgui->Autoconstraints.getValue()) - return; // If Autoconstraints property is not set quit + return;// If Autoconstraints property is not set quit if (!autoConstrs.empty()) { - if(createowncommand) { + if (createowncommand) { // Open the Command Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add auto constraints")); } @@ -800,119 +855,144 @@ void DrawSketchHandler::createAutoConstraints(const std::vector for (; it != autoConstrs.end(); ++it) { int geoId2 = it->GeoId; - switch (it->Type) - { - case Sketcher::Coincident: { - if (posId1 == Sketcher::PointPos::none) - continue; - // If the auto constraint has a point create a coincident otherwise it is an edge on a point - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d)) " - , geoId1, static_cast(posId1), it->GeoId, static_cast(it->PosId)); + switch (it->Type) { + case Sketcher::Coincident: { + if (posId1 == Sketcher::PointPos::none) + continue; + // If the auto constraint has a point create a coincident otherwise it is an + // edge on a point + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d)) ", + geoId1, + static_cast(posId1), + it->GeoId, + static_cast(it->PosId)); } break; - case Sketcher::PointOnObject: { - Sketcher::PointPos posId2 = it->PosId; - if (posId1 == Sketcher::PointPos::none) { - // Auto constraining an edge so swap parameters - std::swap(geoId1,geoId2); - std::swap(posId1,posId2); - } - - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d)) " - , geoId1, static_cast(posId1), geoId2); - } break; - // In special case of Horizontal/Vertical constraint, geoId2 is normally unused and should be 'Constraint::GeoUndef' - // However it can be used as a way to require the function to apply these constraints on another geometry - // In this case the caller as to set geoId2, then it will be used as target instead of geoId2 - case Sketcher::Horizontal: { - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Horizontal',%d)) ", - geoId2 != GeoEnum::GeoUndef ? geoId2 : geoId1); - } break; - case Sketcher::Vertical: { - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Vertical',%d)) ", - geoId2 != GeoEnum::GeoUndef ? geoId2 : geoId1); - } break; - case Sketcher::Tangent: { - Sketcher::SketchObject* Obj = static_cast(sketchgui->getObject()); - - const Part::Geometry *geom1 = Obj->getGeometry(geoId1); - const Part::Geometry *geom2 = Obj->getGeometry(it->GeoId); - - // ellipse tangency support using construction elements (lines) - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() )){ - - if(geom1->getTypeId() != Part::GeomEllipse::getClassTypeId()) - std::swap(geoId1,geoId2); - - // geoId1 is the ellipse - geom1 = Obj->getGeometry(geoId1); - geom2 = Obj->getGeometry(geoId2); - - if( geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() ) { - // in all these cases an intermediate element is needed - makeTangentToEllipseviaNewPoint(Obj, - static_cast(geom1), - geom2, geoId1, geoId2); - return; + case Sketcher::PointOnObject: { + Sketcher::PointPos posId2 = it->PosId; + if (posId1 == Sketcher::PointPos::none) { + // Auto constraining an edge so swap parameters + std::swap(geoId1, geoId2); + std::swap(posId1, posId2); } - } - // arc of ellipse tangency support using external elements - if( geom1 && geom2 && - ( geom1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() )){ - - if(geom1->getTypeId() != Part::GeomArcOfEllipse::getClassTypeId()) - std::swap(geoId1,geoId2); - - // geoId1 is the arc of ellipse - geom1 = Obj->getGeometry(geoId1); - geom2 = Obj->getGeometry(geoId2); - - if( geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geom2->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() ) { - // in all these cases an intermediate element is needed - makeTangentToArcOfEllipseviaNewPoint(Obj, - static_cast(geom1), geom2, geoId1, geoId2); - return; - } - } - - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Tangent',%d, %d)) " - , geoId1, it->GeoId); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d)) ", + geoId1, + static_cast(posId1), + geoId2); } break; - default: - break; + // In special case of Horizontal/Vertical constraint, geoId2 is normally unused + // and should be 'Constraint::GeoUndef' However it can be used as a way to + // require the function to apply these constraints on another geometry In this + // case the caller as to set geoId2, then it will be used as target instead of + // geoId2 + case Sketcher::Horizontal: { + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Horizontal',%d)) ", + geoId2 != GeoEnum::GeoUndef ? geoId2 : geoId1); + } break; + case Sketcher::Vertical: { + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Vertical',%d)) ", + geoId2 != GeoEnum::GeoUndef ? geoId2 : geoId1); + } break; + case Sketcher::Tangent: { + Sketcher::SketchObject* Obj = + static_cast(sketchgui->getObject()); + + const Part::Geometry* geom1 = Obj->getGeometry(geoId1); + const Part::Geometry* geom2 = Obj->getGeometry(it->GeoId); + + // ellipse tangency support using construction elements (lines) + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomEllipse::getClassTypeId())) { + + if (geom1->getTypeId() != Part::GeomEllipse::getClassTypeId()) + std::swap(geoId1, geoId2); + + // geoId1 is the ellipse + geom1 = Obj->getGeometry(geoId1); + geom2 = Obj->getGeometry(geoId2); + + if (geom2->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + // in all these cases an intermediate element is needed + makeTangentToEllipseviaNewPoint( + Obj, + static_cast(geom1), + geom2, + geoId1, + geoId2); + return; + } + } + + // arc of ellipse tangency support using external elements + if (geom1 && geom2 + && (geom1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId())) { + + if (geom1->getTypeId() != Part::GeomArcOfEllipse::getClassTypeId()) + std::swap(geoId1, geoId2); + + // geoId1 is the arc of ellipse + geom1 = Obj->getGeometry(geoId1); + geom2 = Obj->getGeometry(geoId2); + + if (geom2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geom2->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + // in all these cases an intermediate element is needed + makeTangentToArcOfEllipseviaNewPoint( + Obj, + static_cast(geom1), + geom2, + geoId1, + geoId2); + return; + } + } + + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Tangent',%d, %d)) ", + geoId1, + it->GeoId); + } break; + default: + break; } - if(createowncommand) { + if (createowncommand) { Gui::Command::commitCommand(); } - //Gui::Command::updateActive(); // There is already an recompute in each command creation, this is redundant. + // Gui::Command::updateActive(); // There is already an recompute in each command + // creation, this is redundant. } } } -void DrawSketchHandler::renderSuggestConstraintsCursor(std::vector &suggestedConstraints) +void DrawSketchHandler::renderSuggestConstraintsCursor( + std::vector& suggestedConstraints) { std::vector pixmaps = suggestedConstraintsPixmaps(suggestedConstraints); addCursorTail(pixmaps); } -void DrawSketchHandler::setPositionText(const Base::Vector2d &Pos, const SbString &text) +void DrawSketchHandler::setPositionText(const Base::Vector2d& Pos, const SbString& text) { ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(*sketchgui, Pos, text); } -void DrawSketchHandler::setPositionText(const Base::Vector2d &Pos) +void DrawSketchHandler::setPositionText(const Base::Vector2d& Pos) { - ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(*sketchgui,Pos); + ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(*sketchgui, Pos); } void DrawSketchHandler::resetPositionText(void) @@ -920,17 +1000,17 @@ void DrawSketchHandler::resetPositionText(void) ViewProviderSketchDrawSketchHandlerAttorney::resetPositionText(*sketchgui); } -void DrawSketchHandler::drawEdit(const std::vector &EditCurve) +void DrawSketchHandler::drawEdit(const std::vector& EditCurve) { ViewProviderSketchDrawSketchHandlerAttorney::drawEdit(*sketchgui, EditCurve); } -void DrawSketchHandler::drawEdit(const std::list> &list) +void DrawSketchHandler::drawEdit(const std::list>& list) { ViewProviderSketchDrawSketchHandlerAttorney::drawEdit(*sketchgui, list); } -void DrawSketchHandler::drawEdit(const std::vector &geometries) +void DrawSketchHandler::drawEdit(const std::vector& geometries) { static CurveConverter c; @@ -939,15 +1019,16 @@ void DrawSketchHandler::drawEdit(const std::vector &geometries drawEdit(list); } -void DrawSketchHandler::drawPositionAtCursor(const Base::Vector2d & position) +void DrawSketchHandler::drawPositionAtCursor(const Base::Vector2d& position) { setPositionText(position); } -void DrawSketchHandler::drawDirectionAtCursor(const Base::Vector2d & position, const Base::Vector2d & origin) +void DrawSketchHandler::drawDirectionAtCursor(const Base::Vector2d& position, + const Base::Vector2d& origin) { float length = (position - origin).Length(); - float angle = (position - origin).GetAngle(Base::Vector2d(1.f,0.f)); + float angle = (position - origin).GetAngle(Base::Vector2d(1.f, 0.f)); if (showCursorCoords()) { SbString text; @@ -958,9 +1039,11 @@ void DrawSketchHandler::drawDirectionAtCursor(const Base::Vector2d & position, c } } -void DrawSketchHandler::drawEditMarkers(const std::vector &EditMarkers, unsigned int augmentationlevel) +void DrawSketchHandler::drawEditMarkers(const std::vector& EditMarkers, + unsigned int augmentationlevel) { - ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers(*sketchgui, EditMarkers, augmentationlevel); + ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers( + *sketchgui, EditMarkers, augmentationlevel); } void DrawSketchHandler::setAxisPickStyle(bool on) @@ -993,12 +1076,13 @@ int DrawSketchHandler::getPreselectCross(void) const return ViewProviderSketchDrawSketchHandlerAttorney::getPreselectCross(*sketchgui); } -Sketcher::SketchObject * DrawSketchHandler::getSketchObject() +Sketcher::SketchObject* DrawSketchHandler::getSketchObject() { return sketchgui->getSketchObject(); } void DrawSketchHandler::setAngleSnapping(bool enable, Base::Vector2d referencePoint) { - ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping(*sketchgui, enable, referencePoint); + ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping( + *sketchgui, enable, referencePoint); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.h b/src/Mod/Sketcher/Gui/DrawSketchHandler.h index 750db4e87e..11269f6540 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.h @@ -25,7 +25,9 @@ #include +#include #include +#include #include #include "AutoConstraint.h" @@ -33,36 +35,39 @@ class QPixmap; -namespace Sketcher { - class Sketch; - class SketchObject; -} +namespace Sketcher +{ +class Sketch; +class SketchObject; +}// namespace Sketcher -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; - /** * Class to convert Part::Geometry to Vector2d based collections */ -class CurveConverter final : public ParameterGrp::ObserverType { +class CurveConverter final: public ParameterGrp::ObserverType +{ public: CurveConverter(); ~CurveConverter(); - std::vector toVector2D(const Part::Geometry * geometry); + std::vector toVector2D(const Part::Geometry* geometry); - std::list> toVector2DList(const std::vector &geometries); + std::list> + toVector2DList(const std::vector& geometries); private: void updateCurvedEdgeCountSegmentsParameter(); /** Observer for parameter group. */ - void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject& rCaller, const char* sReason) override; private: int curvedEdgeCountSegments; @@ -74,57 +79,68 @@ private: * too tight coupling, while still allowing well defined collaboration, * DrawSketchHandler accesses ViewProviderSketch via this Attorney class */ -class ViewProviderSketchDrawSketchHandlerAttorney { +class ViewProviderSketchDrawSketchHandlerAttorney +{ private: - static inline void setConstraintSelectability(ViewProviderSketch &vp, bool enabled = true); - static inline void setPositionText(ViewProviderSketch &vp, const Base::Vector2d &Pos, const SbString &txt); - static inline void setPositionText(ViewProviderSketch &vp, const Base::Vector2d &Pos); - static inline void resetPositionText(ViewProviderSketch &vp); - static inline void drawEdit(ViewProviderSketch &vp, const std::vector &EditCurve); - static inline void drawEdit(ViewProviderSketch &vp, const std::list> &list); - static inline void drawEditMarkers(ViewProviderSketch &vp, const std::vector &EditMarkers, unsigned int augmentationlevel = 0); - static inline void setAxisPickStyle(ViewProviderSketch &vp, bool on); - static inline void moveCursorToSketchPoint(ViewProviderSketch &vp, Base::Vector2d point); - static inline void preselectAtPoint(ViewProviderSketch &vp, Base::Vector2d point); - static inline void setAngleSnapping(ViewProviderSketch &vp, bool enable, Base::Vector2d referencePoint = Base::Vector2d(0., 0.)); + static inline void setConstraintSelectability(ViewProviderSketch& vp, bool enabled = true); + static inline void setPositionText(ViewProviderSketch& vp, const Base::Vector2d& Pos, + const SbString& txt); + static inline void setPositionText(ViewProviderSketch& vp, const Base::Vector2d& Pos); + static inline void resetPositionText(ViewProviderSketch& vp); + static inline void drawEdit(ViewProviderSketch& vp, + const std::vector& EditCurve); + static inline void drawEdit(ViewProviderSketch& vp, + const std::list>& list); + static inline void drawEditMarkers(ViewProviderSketch& vp, + const std::vector& EditMarkers, + unsigned int augmentationlevel = 0); + static inline void setAxisPickStyle(ViewProviderSketch& vp, bool on); + static inline void moveCursorToSketchPoint(ViewProviderSketch& vp, Base::Vector2d point); + static inline void preselectAtPoint(ViewProviderSketch& vp, Base::Vector2d point); + static inline void setAngleSnapping(ViewProviderSketch& vp, bool enable, + Base::Vector2d referencePoint = Base::Vector2d(0., 0.)); - static inline int getPreselectPoint(const ViewProviderSketch &vp); - static inline int getPreselectCurve(const ViewProviderSketch &vp); - static inline int getPreselectCross(const ViewProviderSketch &vp); + static inline int getPreselectPoint(const ViewProviderSketch& vp); + static inline int getPreselectCurve(const ViewProviderSketch& vp); + static inline int getPreselectCross(const ViewProviderSketch& vp); friend class DrawSketchHandler; }; /** Handler to create new sketch geometry - * This class has to be reimplemented to create geometry in the - * sketcher while its in editing. - * - * DrawSketchHandler takes over the responsibility of drawing edit temporal curves and - * markers necessary to enable visual feedback to the user, as well as the UI interaction during - * such edits. This is its exclusive responsibility under the Single Responsibility Principle. - * - * A plethora of speciliased handlers derive from DrawSketchHandler for each specialised editing (see - * for example all the handlers for creation of new geometry). These derived classes do * not * have - * direct access to the ViewProviderSketchDrawSketchHandlerAttorney. This is intended to keep coupling - * under control. However, generic functionality requiring access to the Attorney can be implemented - * in DrawSketchHandler and used from its derived classes by virtue of the inheritance. This promotes a - * concentrating the coupling in a single point (and code reuse). - */ + * This class has to be reimplemented to create geometry in the + * sketcher while its in editing. + * + * DrawSketchHandler takes over the responsibility of drawing edit temporal curves and + * markers necessary to enable visual feedback to the user, as well as the UI interaction during + * such edits. This is its exclusive responsibility under the Single Responsibility Principle. + * + * A plethora of speciliased handlers derive from DrawSketchHandler for each specialised editing + * (see for example all the handlers for creation of new geometry). These derived classes do * not * + * have direct access to the ViewProviderSketchDrawSketchHandlerAttorney. This is intended to keep + * coupling under control. However, generic functionality requiring access to the Attorney can be + * implemented in DrawSketchHandler and used from its derived classes by virtue of the inheritance. + * This promotes a concentrating the coupling in a single point (and code reuse). + */ class SketcherGuiExport DrawSketchHandler { public: DrawSketchHandler(); virtual ~DrawSketchHandler(); - void activate(ViewProviderSketch *); + void activate(ViewProviderSketch*); void deactivate(); - virtual void mouseMove(Base::Vector2d onSketchPos)=0; - virtual bool pressButton(Base::Vector2d onSketchPos)=0; - virtual bool releaseButton(Base::Vector2d onSketchPos)=0; - virtual bool onSelectionChanged(const Gui::SelectionChanges&) { return false; } - virtual void registerPressedKey(bool /*pressed*/, int /*key*/){} + virtual void mouseMove(Base::Vector2d onSketchPos) = 0; + virtual bool pressButton(Base::Vector2d onSketchPos) = 0; + virtual bool releaseButton(Base::Vector2d onSketchPos) = 0; + virtual bool onSelectionChanged(const Gui::SelectionChanges&) + { + return false; + } + virtual void registerPressedKey(bool /*pressed*/, int /*key*/) + {} virtual void quit(); @@ -135,26 +151,31 @@ public: // get the actual highest edge index, the next use will be +1 int getHighestCurveIndex(); - int seekAutoConstraint(std::vector &suggestedConstraints, - const Base::Vector2d &Pos, const Base::Vector2d &Dir, + int seekAutoConstraint(std::vector& suggestedConstraints, + const Base::Vector2d& Pos, const Base::Vector2d& Dir, AutoConstraint::TargetType type = AutoConstraint::VERTEX); - // createowncommand indicates whether a separate command shall be create and committed (for example for undo purposes) or not - // is not it is the responsibility of the developer to create and commit the command appropriately. - void createAutoConstraints(const std::vector &autoConstrs, - int geoId, Sketcher::PointPos pointPos=Sketcher::PointPos::none, bool createowncommand = true); + // createowncommand indicates whether a separate command shall be create and committed (for + // example for undo purposes) or not is not it is the responsibility of the developer to create + // and commit the command appropriately. + void createAutoConstraints(const std::vector& autoConstrs, int geoId, + Sketcher::PointPos pointPos = Sketcher::PointPos::none, + bool createowncommand = true); - void setPositionText(const Base::Vector2d &Pos, const SbString &text); - void setPositionText(const Base::Vector2d &Pos); + void setPositionText(const Base::Vector2d& Pos, const SbString& text); + void setPositionText(const Base::Vector2d& Pos); void resetPositionText(); - void renderSuggestConstraintsCursor(std::vector &suggestedConstraints); + void renderSuggestConstraintsCursor(std::vector& suggestedConstraints); -private: // NVI +private:// NVI virtual void preActivated(); - virtual void activated(){} - virtual void deactivated(){} - virtual void postDeactivated(){} + virtual void activated() + {} + virtual void deactivated() + {} + virtual void postDeactivated() + {} -protected: // NVI requiring base implementation +protected:// NVI requiring base implementation virtual QString getCrosshairCursorSVGName() const; protected: @@ -168,13 +189,14 @@ protected: /** @name Icon helpers */ //@{ - void setCursor(const QPixmap &pixmap, int x,int y, bool autoScale=true); + void setCursor(const QPixmap& pixmap, int x, int y, bool autoScale = true); /// updates the actCursor with the icon by calling getCrosshairCursorSVGName(), /// enabling to set data member dependent icons (i.e. for different construction methods) void updateCursor(); - /// restitutes the cursor that was in use at the moment of starting the DrawSketchHandler (i.e. oldCursor) + /// restitutes the cursor that was in use at the moment of starting the DrawSketchHandler (i.e. + /// oldCursor) void unsetCursor(); /// restitutes the DSH cached cursor (e.g. without any tail due to autoconstraints, ...) @@ -188,52 +210,53 @@ protected: qreal devicePixelRatio(); //@} - void drawEdit(const std::vector &EditCurve); - void drawEdit(const std::list> &list); - void drawEdit(const std::vector &geometries); - void drawEditMarkers(const std::vector &EditMarkers, unsigned int augmentationlevel = 0); + void drawEdit(const std::vector& EditCurve); + void drawEdit(const std::list>& list); + void drawEdit(const std::vector& geometries); + void drawEditMarkers(const std::vector& EditMarkers, + unsigned int augmentationlevel = 0); void setAxisPickStyle(bool on); void moveCursorToSketchPoint(Base::Vector2d point); void preselectAtPoint(Base::Vector2d point); - void drawPositionAtCursor(const Base::Vector2d & position); - void drawDirectionAtCursor(const Base::Vector2d & position, const Base::Vector2d & origin); + void drawPositionAtCursor(const Base::Vector2d& position); + void drawDirectionAtCursor(const Base::Vector2d& position, const Base::Vector2d& origin); int getPreselectPoint() const; int getPreselectCurve() const; int getPreselectCross() const; - Sketcher::SketchObject * getSketchObject(); + Sketcher::SketchObject* getSketchObject(); void setAngleSnapping(bool enable, Base::Vector2d referencePoint = Base::Vector2d(0., 0.)); private: - void setSvgCursor(const QString &svgName, int x, int y, - const std::map& colorMapping = std::map()); + void setSvgCursor(const QString& svgName, int x, int y, + const std::map& colorMapping = + std::map()); - void addCursorTail(std::vector &pixmaps); + void addCursorTail(std::vector& pixmaps); - void applyCursor(QCursor &newCursor); + void applyCursor(QCursor& newCursor); - void setCrosshairCursor(const QString & svgName); + void setCrosshairCursor(const QString& svgName); void setCrosshairCursor(const char* svgName); protected: /** * Returns constraints icons scaled to width. **/ - std::vector suggestedConstraintsPixmaps( - std::vector &suggestedConstraints); + std::vector + suggestedConstraintsPixmaps(std::vector& suggestedConstraints); - ViewProviderSketch *sketchgui; + ViewProviderSketch* sketchgui; QCursor oldCursor; QCursor actCursor; QPixmap actCursorPixmap; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandler_H - +#endif// SKETCHERGUI_DrawSketchHandler_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h index 2259cb0b88..292be97f42 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h @@ -30,55 +30,58 @@ using namespace std; -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class DrawSketchHandlerArc : public DrawSketchHandler +class DrawSketchHandlerArc: public DrawSketchHandler { public: DrawSketchHandlerArc() - : Mode(STATUS_SEEK_First) - , EditCurve(2) - , rx(0), ry(0) - , startAngle(0) - , endAngle(0) - , arcAngle(0) - { - } - virtual ~DrawSketchHandlerArc(){} + : Mode(STATUS_SEEK_First) + , EditCurve(2) + , rx(0) + , ry(0) + , startAngle(0) + , endAngle(0) + , arcAngle(0) + {} + virtual ~DrawSketchHandlerArc() + {} /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ - STATUS_SEEK_Third, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ + STATUS_SEEK_Third, /**< enum value ----. */ STATUS_End }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { double dx_ = onSketchPos.x - EditCurve[0].x; double dy_ = onSketchPos.y - EditCurve[0].y; - for (int i=0; i < 16; i++) { - double angle = i*M_PI/16.0; + for (int i = 0; i < 16; i++) { + double angle = i * M_PI / 16.0; double dx = dx_ * cos(angle) + dy_ * sin(angle); double dy = -dx_ * sin(angle) + dy_ * cos(angle); - EditCurve[1+i] = Base::Vector2d(EditCurve[0].x + dx, EditCurve[0].y + dy); - EditCurve[17+i] = Base::Vector2d(EditCurve[0].x - dx, EditCurve[0].y - dy); + EditCurve[1 + i] = Base::Vector2d(EditCurve[0].x + dx, EditCurve[0].y + dy); + EditCurve[17 + i] = Base::Vector2d(EditCurve[0].x - dx, EditCurve[0].y - dy); } EditCurve[33] = EditCurve[1]; // Display radius and start angle float radius = (onSketchPos - EditCurve[0]).Length(); - float angle = atan2f(dy_ , dx_); + float angle = atan2f(dy_, dx_); if (showCursorCoords()) { SbString text; @@ -89,18 +92,18 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr2); return; } } - else if (Mode==STATUS_SEEK_Third) { - double angle1 = atan2(onSketchPos.y - CenterPoint.y, - onSketchPos.x - CenterPoint.x) - startAngle; - double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI ; - arcAngle = abs(angle1-arcAngle) < abs(angle2-arcAngle) ? angle1 : angle2; - for (int i=1; i <= 29; i++) { - double angle = i*arcAngle/29.0; + else if (Mode == STATUS_SEEK_Third) { + double angle1 = + atan2(onSketchPos.y - CenterPoint.y, onSketchPos.x - CenterPoint.x) - startAngle; + double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI; + arcAngle = abs(angle1 - arcAngle) < abs(angle2 - arcAngle) ? angle1 : angle2; + for (int i = 1; i <= 29; i++) { + double angle = i * arcAngle / 29.0; double dx = rx * cos(angle) - ry * sin(angle); double dy = rx * sin(angle) + ry * cos(angle); EditCurve[i] = Base::Vector2d(CenterPoint.x + dx, CenterPoint.y + dy); @@ -118,25 +121,24 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.0,0.0))) { + if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.0, 0.0))) { renderSuggestConstraintsCursor(sugConstr3); return; } } applyCursor(); - } bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { CenterPoint = onSketchPos; EditCurve.resize(34); EditCurve[0] = onSketchPos; setAngleSnapping(true, EditCurve[0]); Mode = STATUS_SEEK_Second; } - else if (Mode==STATUS_SEEK_Second){ + else if (Mode == STATUS_SEEK_Second) { EditCurve.resize(31); EditCurve[0] = onSketchPos; EditCurve[30] = CenterPoint; @@ -148,10 +150,10 @@ public: } else { EditCurve.resize(30); - double angle1 = atan2(onSketchPos.y - CenterPoint.y, - onSketchPos.x - CenterPoint.x) - startAngle; - double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI ; - arcAngle = abs(angle1-arcAngle) < abs(angle2-arcAngle) ? angle1 : angle2; + double angle1 = + atan2(onSketchPos.y - CenterPoint.y, onSketchPos.x - CenterPoint.x) - startAngle; + double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI; + arcAngle = abs(angle1 - arcAngle) < abs(angle2 - arcAngle) ? angle1 : angle2; if (arcAngle > 0) endAngle = startAngle + arcAngle; else { @@ -171,24 +173,30 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (Mode==STATUS_End) { + if (Mode == STATUS_End) { unsetCursor(); resetPositionText(); try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch arc")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.ArcOfCircle" + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.ArcOfCircle" "(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%f,%f),%s)", - CenterPoint.x, CenterPoint.y, sqrt(rx*rx + ry*ry), - startAngle, endAngle, - geometryCreationMode==Construction?"True":"False"); //arcAngle > 0 ? 0 : 1); + CenterPoint.x, + CenterPoint.y, + sqrt(rx * rx + ry * ry), + startAngle, + endAngle, + geometryCreationMode == Construction ? "True" + : "False");// arcAngle > 0 ? 0 : 1); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); Gui::Command::abortCommand(); } @@ -200,35 +208,44 @@ public: // Auto Constraint first picked point if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex(), (arcAngle > 0) ? Sketcher::PointPos::start : Sketcher::PointPos::end ); + createAutoConstraints(sugConstr2, + getHighestCurveIndex(), + (arcAngle > 0) ? Sketcher::PointPos::start + : Sketcher::PointPos::end); sugConstr2.clear(); } // Auto Constraint second picked point if (!sugConstr3.empty()) { - createAutoConstraints(sugConstr3, getHighestCurveIndex(), (arcAngle > 0) ? Sketcher::PointPos::end : Sketcher::PointPos::start); + createAutoConstraints(sugConstr3, + getHighestCurveIndex(), + (arcAngle > 0) ? Sketcher::PointPos::end + : Sketcher::PointPos::start); sugConstr3.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -239,6 +256,7 @@ private: { return QString::fromLatin1("Sketcher_Pointer_Create_Arc"); } + protected: SelectMode Mode; std::vector EditCurve; @@ -247,48 +265,53 @@ protected: std::vector sugConstr1, sugConstr2, sugConstr3; }; -class DrawSketchHandler3PointArc : public DrawSketchHandler +class DrawSketchHandler3PointArc: public DrawSketchHandler { public: DrawSketchHandler3PointArc() - : Mode(STATUS_SEEK_First), EditCurve(2) - , radius(0), startAngle(0) - , endAngle(0), arcAngle(0) - , arcPos1(Sketcher::PointPos::none) - , arcPos2(Sketcher::PointPos::none) - { - } - virtual ~DrawSketchHandler3PointArc(){} + : Mode(STATUS_SEEK_First) + , EditCurve(2) + , radius(0) + , startAngle(0) + , endAngle(0) + , arcAngle(0) + , arcPos1(Sketcher::PointPos::none) + , arcPos2(Sketcher::PointPos::none) + {} + virtual ~DrawSketchHandler3PointArc() + {} /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ - STATUS_SEEK_Third, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ + STATUS_SEEK_Third, /**< enum value ----. */ STATUS_End }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { - CenterPoint = EditCurve[0] = (onSketchPos - FirstPoint)/2 + FirstPoint; + else if (Mode == STATUS_SEEK_Second) { + CenterPoint = EditCurve[0] = (onSketchPos - FirstPoint) / 2 + FirstPoint; EditCurve[1] = EditCurve[33] = onSketchPos; radius = (onSketchPos - CenterPoint).Length(); double lineAngle = GetPointAngle(CenterPoint, onSketchPos); // Build a 32 point circle ignoring already constructed points - for (int i=1; i <= 32; i++) { + for (int i = 1; i <= 32; i++) { // Start at current angle - double angle = (i-1)*2*M_PI/32.0 + lineAngle; // N point closed circle has N segments - if (i != 1 && i != 17 ) { - EditCurve[i] = Base::Vector2d(CenterPoint.x + radius*cos(angle), - CenterPoint.y + radius*sin(angle)); + double angle = + (i - 1) * 2 * M_PI / 32.0 + lineAngle;// N point closed circle has N segments + if (i != 1 && i != 17) { + EditCurve[i] = Base::Vector2d(CenterPoint.x + radius * cos(angle), + CenterPoint.y + radius * sin(angle)); } } @@ -303,19 +326,20 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr2); return; } } - else if (Mode==STATUS_SEEK_Third) { + else if (Mode == STATUS_SEEK_Third) { /* Centerline inverts when the arc flips sides. Easily taken care of by replacing centerline with a point. It happens because the direction the curve is being drawn reverses. */ try { - CenterPoint = EditCurve[30] = Part::Geom2dCircle::getCircleCenter(FirstPoint, SecondPoint, onSketchPos); + CenterPoint = EditCurve[30] = + Part::Geom2dCircle::getCircleCenter(FirstPoint, SecondPoint, onSketchPos); radius = (SecondPoint - CenterPoint).Length(); @@ -325,47 +349,47 @@ public: // Always build arc counter-clockwise // Point 3 is between Point 1 and 2 - if ( angle3 > min(angle1, angle2) && angle3 < max(angle1, angle2) ) { + if (angle3 > min(angle1, angle2) && angle3 < max(angle1, angle2)) { if (angle2 > angle1) { - EditCurve[0] = FirstPoint; + EditCurve[0] = FirstPoint; EditCurve[29] = SecondPoint; arcPos1 = Sketcher::PointPos::start; arcPos2 = Sketcher::PointPos::end; } else { - EditCurve[0] = SecondPoint; + EditCurve[0] = SecondPoint; EditCurve[29] = FirstPoint; arcPos1 = Sketcher::PointPos::end; arcPos2 = Sketcher::PointPos::start; } startAngle = min(angle1, angle2); - endAngle = max(angle1, angle2); + endAngle = max(angle1, angle2); arcAngle = endAngle - startAngle; } // Point 3 is not between Point 1 and 2 else { if (angle2 > angle1) { - EditCurve[0] = SecondPoint; + EditCurve[0] = SecondPoint; EditCurve[29] = FirstPoint; arcPos1 = Sketcher::PointPos::end; arcPos2 = Sketcher::PointPos::start; } else { - EditCurve[0] = FirstPoint; + EditCurve[0] = FirstPoint; EditCurve[29] = SecondPoint; arcPos1 = Sketcher::PointPos::start; arcPos2 = Sketcher::PointPos::end; } startAngle = max(angle1, angle2); - endAngle = min(angle1, angle2); - arcAngle = 2*M_PI - (startAngle - endAngle); + endAngle = min(angle1, angle2); + arcAngle = 2 * M_PI - (startAngle - endAngle); } // Build a 30 point circle ignoring already constructed points - for (int i=1; i <= 28; i++) { - double angle = startAngle + i*arcAngle/29.0; // N point arc has N-1 segments - EditCurve[i] = Base::Vector2d(CenterPoint.x + radius*cos(angle), - CenterPoint.y + radius*sin(angle)); + for (int i = 1; i <= 28; i++) { + double angle = startAngle + i * arcAngle / 29.0;// N point arc has N-1 segments + EditCurve[i] = Base::Vector2d(CenterPoint.x + radius * cos(angle), + CenterPoint.y + radius * sin(angle)); } if (showCursorCoords()) { @@ -377,13 +401,13 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.0,0.0), - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr3, onSketchPos, Base::Vector2d(0.0, 0.0), AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr3); return; } } - catch(Base::ValueError &e) { + catch (Base::ValueError& e) { e.ReportException(); } } @@ -392,7 +416,7 @@ public: bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { // 32 point curve + center + endpoint EditCurve.resize(34); // 17 is circle halfway point (1+32/2) @@ -400,7 +424,7 @@ public: Mode = STATUS_SEEK_Second; } - else if (Mode==STATUS_SEEK_Second){ + else if (Mode == STATUS_SEEK_Second) { // 30 point arc and center point EditCurve.resize(31); SecondPoint = onSketchPos; @@ -422,24 +446,29 @@ public: { Q_UNUSED(onSketchPos); // Need to look at. rx might need fixing. - if (Mode==STATUS_End) { + if (Mode == STATUS_End) { unsetCursor(); resetPositionText(); try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch arc")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.ArcOfCircle" + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.ArcOfCircle" "(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%f,%f),%s)", - CenterPoint.x, CenterPoint.y, radius, - startAngle, endAngle, - geometryCreationMode==Construction?"True":"False"); + CenterPoint.x, + CenterPoint.y, + radius, + startAngle, + endAngle, + geometryCreationMode == Construction ? "True" : "False"); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); Gui::Command::abortCommand(); } @@ -461,24 +490,27 @@ public: sugConstr3.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -499,8 +531,7 @@ protected: Sketcher::PointPos arcPos1, arcPos2; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerArc_H - +#endif// SKETCHERGUI_DrawSketchHandlerArc_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h index bdbfb9a7fa..21bd951be6 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h @@ -27,47 +27,56 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class DrawSketchHandlerArcOfEllipse : public DrawSketchHandler +class DrawSketchHandlerArcOfEllipse: public DrawSketchHandler { public: DrawSketchHandlerArcOfEllipse() - : Mode(STATUS_SEEK_First), EditCurve(34) - , rx(0), ry(0), startAngle(0), endAngle(0) - , arcAngle(0), arcAngle_t(0) {} + : Mode(STATUS_SEEK_First) + , EditCurve(34) + , rx(0) + , ry(0) + , startAngle(0) + , endAngle(0) + , arcAngle(0) + , arcAngle_t(0) + {} virtual ~DrawSketchHandlerArcOfEllipse() = default; /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ - STATUS_SEEK_Third, /**< enum value ----. */ - STATUS_SEEK_Fourth, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ + STATUS_SEEK_Third, /**< enum value ----. */ + STATUS_SEEK_Fourth, /**< enum value ----. */ STATUS_Close }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { // TODO: ellipse prio 1 + if (seekAutoConstraint( + sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) {// TODO: ellipse prio 1 renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { double rx0 = onSketchPos.x - EditCurve[0].x; double ry0 = onSketchPos.y - EditCurve[0].y; - for (int i=0; i < 16; i++) { - double angle = i*M_PI/16.0; + for (int i = 0; i < 16; i++) { + double angle = i * M_PI / 16.0; double rx1 = rx0 * cos(angle) + ry0 * sin(angle); double ry1 = -rx0 * sin(angle) + ry0 * cos(angle); - EditCurve[1+i] = Base::Vector2d(EditCurve[0].x + rx1, EditCurve[0].y + ry1); - EditCurve[17+i] = Base::Vector2d(EditCurve[0].x - rx1, EditCurve[0].y - ry1); + EditCurve[1 + i] = Base::Vector2d(EditCurve[0].x + rx1, EditCurve[0].y + ry1); + EditCurve[17 + i] = Base::Vector2d(EditCurve[0].x - rx1, EditCurve[0].y - ry1); } EditCurve[33] = EditCurve[1]; @@ -82,27 +91,30 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, onSketchPos - centerPoint, - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr2, onSketchPos, onSketchPos - centerPoint, AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr2); return; } } - else if (Mode==STATUS_SEEK_Third) { + else if (Mode == STATUS_SEEK_Third) { // angle between the major axis of the ellipse and the X axis - double a = (EditCurve[1]-EditCurve[0]).Length(); - double phi = atan2(EditCurve[1].y-EditCurve[0].y,EditCurve[1].x-EditCurve[0].x); + double a = (EditCurve[1] - EditCurve[0]).Length(); + double phi = atan2(EditCurve[1].y - EditCurve[0].y, EditCurve[1].x - EditCurve[0].x); // This is the angle at cursor point - double angleatpoint = acos((onSketchPos.x-EditCurve[0].x+(onSketchPos.y-EditCurve[0].y)*tan(phi))/(a*(cos(phi)+tan(phi)*sin(phi)))); - double b=(onSketchPos.y-EditCurve[0].y-a*cos(angleatpoint)*sin(phi))/(sin(angleatpoint)*cos(phi)); + double angleatpoint = + acos((onSketchPos.x - EditCurve[0].x + (onSketchPos.y - EditCurve[0].y) * tan(phi)) + / (a * (cos(phi) + tan(phi) * sin(phi)))); + double b = (onSketchPos.y - EditCurve[0].y - a * cos(angleatpoint) * sin(phi)) + / (sin(angleatpoint) * cos(phi)); - for (int i=1; i < 16; i++) { - double angle = i*M_PI/16.0; + for (int i = 1; i < 16; i++) { + double angle = i * M_PI / 16.0; double rx1 = a * cos(angle) * cos(phi) - b * sin(angle) * sin(phi); double ry1 = a * cos(angle) * sin(phi) + b * sin(angle) * cos(phi); - EditCurve[1+i] = Base::Vector2d(EditCurve[0].x + rx1, EditCurve[0].y + ry1); - EditCurve[17+i] = Base::Vector2d(EditCurve[0].x - rx1, EditCurve[0].y - ry1); + EditCurve[1 + i] = Base::Vector2d(EditCurve[0].x + rx1, EditCurve[0].y + ry1); + EditCurve[17 + i] = Base::Vector2d(EditCurve[0].x - rx1, EditCurve[0].y - ry1); } EditCurve[33] = EditCurve[1]; EditCurve[17] = EditCurve[16]; @@ -117,38 +129,47 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr3); return; } } - else if (Mode==STATUS_SEEK_Fourth) { // here we differ from ellipse creation + else if (Mode == STATUS_SEEK_Fourth) {// here we differ from ellipse creation // angle between the major axis of the ellipse and the X axis - double a = (axisPoint-centerPoint).Length(); - double phi = atan2(axisPoint.y-centerPoint.y,axisPoint.x-centerPoint.x); + double a = (axisPoint - centerPoint).Length(); + double phi = atan2(axisPoint.y - centerPoint.y, axisPoint.x - centerPoint.x); // This is the angle at cursor point - double angleatpoint = acos((startingPoint.x-centerPoint.x+(startingPoint.y-centerPoint.y)*tan(phi))/(a*(cos(phi)+tan(phi)*sin(phi)))); - double b=abs((startingPoint.y-centerPoint.y-a*cos(angleatpoint)*sin(phi))/(sin(angleatpoint)*cos(phi))); + double angleatpoint = acos( + (startingPoint.x - centerPoint.x + (startingPoint.y - centerPoint.y) * tan(phi)) + / (a * (cos(phi) + tan(phi) * sin(phi)))); + double b = abs((startingPoint.y - centerPoint.y - a * cos(angleatpoint) * sin(phi)) + / (sin(angleatpoint) * cos(phi))); double rxs = startingPoint.x - centerPoint.x; double rys = startingPoint.y - centerPoint.y; - startAngle = atan2(a*(rys*cos(phi)-rxs*sin(phi)), b*(rxs*cos(phi)+rys*sin(phi))); // eccentric anomaly angle + startAngle = atan2(a * (rys * cos(phi) - rxs * sin(phi)), + b * (rxs * cos(phi) + rys * sin(phi)));// eccentric anomaly angle - double angle1 = atan2(a*((onSketchPos.y - centerPoint.y)*cos(phi)-(onSketchPos.x - centerPoint.x)*sin(phi)), - b*((onSketchPos.x - centerPoint.x)*cos(phi)+(onSketchPos.y - centerPoint.y)*sin(phi)))- startAngle; + double angle1 = atan2(a + * ((onSketchPos.y - centerPoint.y) * cos(phi) + - (onSketchPos.x - centerPoint.x) * sin(phi)), + b + * ((onSketchPos.x - centerPoint.x) * cos(phi) + + (onSketchPos.y - centerPoint.y) * sin(phi))) + - startAngle; - double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI ; - arcAngle = abs(angle1-arcAngle) < abs(angle2-arcAngle) ? angle1 : angle2; + double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI; + arcAngle = abs(angle1 - arcAngle) < abs(angle2 - arcAngle) ? angle1 : angle2; - for (int i=0; i < 34; i++) { - double angle = startAngle+i*arcAngle/34.0; + for (int i = 0; i < 34; i++) { + double angle = startAngle + i * arcAngle / 34.0; double rx1 = a * cos(angle) * cos(phi) - b * sin(angle) * sin(phi); double ry1 = a * cos(angle) * sin(phi) + b * sin(angle) * cos(phi); EditCurve[i] = Base::Vector2d(centerPoint.x + rx1, centerPoint.y + ry1); } -// EditCurve[33] = EditCurve[1]; -// EditCurve[17] = EditCurve[16]; + // EditCurve[33] = EditCurve[1]; + // EditCurve[17] = EditCurve[16]; // Display radii and angle for user if (showCursorCoords()) { @@ -156,42 +177,42 @@ public: std::string aString = lengthToDisplayFormat(a, 1); std::string bString = lengthToDisplayFormat(b, 1); std::string angleString = angleToDisplayFormat(arcAngle * 180.0 / M_PI, 1); - text.sprintf(" (R%s, R%s, %s)", aString.c_str(), bString.c_str(), angleString.c_str()); + text.sprintf( + " (R%s, R%s, %s)", aString.c_str(), bString.c_str(), angleString.c_str()); setPositionText(onSketchPos, text); } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr4, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr4, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr4); return; } } - applyCursor(); } bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { EditCurve[0] = onSketchPos; centerPoint = onSketchPos; setAngleSnapping(true, centerPoint); Mode = STATUS_SEEK_Second; } - else if(Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { EditCurve[1] = onSketchPos; axisPoint = onSketchPos; Mode = STATUS_SEEK_Third; } - else if(Mode==STATUS_SEEK_Third) { + else if (Mode == STATUS_SEEK_Third) { startingPoint = onSketchPos; arcAngle = 0.; - arcAngle_t= 0.; + arcAngle_t = 0.; Mode = STATUS_SEEK_Fourth; } - else { // Fourth + else {// Fourth endPoint = onSketchPos; setAngleSnapping(false); @@ -203,86 +224,106 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (Mode==STATUS_Close) { + if (Mode == STATUS_Close) { unsetCursor(); resetPositionText(); // angle between the major axis of the ellipse and the X axisEllipse - double a = (axisPoint-centerPoint).Length(); - double phi = atan2(axisPoint.y-centerPoint.y,axisPoint.x-centerPoint.x); + double a = (axisPoint - centerPoint).Length(); + double phi = atan2(axisPoint.y - centerPoint.y, axisPoint.x - centerPoint.x); // This is the angle at cursor point - double angleatpoint = acos((startingPoint.x-centerPoint.x+(startingPoint.y-centerPoint.y)*tan(phi))/(a*(cos(phi)+tan(phi)*sin(phi)))); - double b=abs((startingPoint.y-centerPoint.y-a*cos(angleatpoint)*sin(phi))/(sin(angleatpoint)*cos(phi))); + double angleatpoint = acos( + (startingPoint.x - centerPoint.x + (startingPoint.y - centerPoint.y) * tan(phi)) + / (a * (cos(phi) + tan(phi) * sin(phi)))); + double b = abs((startingPoint.y - centerPoint.y - a * cos(angleatpoint) * sin(phi)) + / (sin(angleatpoint) * cos(phi))); - double angle1 = atan2(a*((endPoint.y - centerPoint.y)*cos(phi)-(endPoint.x - centerPoint.x)*sin(phi)), - b*((endPoint.x - centerPoint.x)*cos(phi)+(endPoint.y - centerPoint.y)*sin(phi)))- startAngle; + double angle1 = atan2(a + * ((endPoint.y - centerPoint.y) * cos(phi) + - (endPoint.x - centerPoint.x) * sin(phi)), + b + * ((endPoint.x - centerPoint.x) * cos(phi) + + (endPoint.y - centerPoint.y) * sin(phi))) + - startAngle; - double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI ; - arcAngle = abs(angle1-arcAngle) < abs(angle2-arcAngle) ? angle1 : angle2; + double angle2 = angle1 + (angle1 < 0. ? 2 : -2) * M_PI; + arcAngle = abs(angle1 - arcAngle) < abs(angle2 - arcAngle) ? angle1 : angle2; - bool isOriginalArcCCW=true; + bool isOriginalArcCCW = true; if (arcAngle > 0) endAngle = startAngle + arcAngle; else { endAngle = startAngle; startAngle += arcAngle; - isOriginalArcCCW=false; + isOriginalArcCCW = false; } - Base::Vector2d majAxisDir,minAxisDir,minAxisPoint,majAxisPoint; - // We always create a CCW ellipse, because we want our XY reference system to be in the +X +Y direction - // Our normal will then always be in the +Z axis (local +Z axis of the sketcher) + Base::Vector2d majAxisDir, minAxisDir, minAxisPoint, majAxisPoint; + // We always create a CCW ellipse, because we want our XY reference system to be in the + // +X +Y direction Our normal will then always be in the +Z axis (local +Z axis of the + // sketcher) - if(a>b) - { + if (a > b) { // force second semidiameter to be perpendicular to first semidiamater majAxisDir = axisPoint - centerPoint; - Base::Vector2d perp(-majAxisDir.y,majAxisDir.x); + Base::Vector2d perp(-majAxisDir.y, majAxisDir.x); perp.Normalize(); perp.Scale(abs(b)); - minAxisPoint = centerPoint+perp; - majAxisPoint = centerPoint+majAxisDir; + minAxisPoint = centerPoint + perp; + majAxisPoint = centerPoint + majAxisDir; } else { // force second semidiameter to be perpendicular to first semidiamater minAxisDir = axisPoint - centerPoint; - Base::Vector2d perp(minAxisDir.y,-minAxisDir.x); + Base::Vector2d perp(minAxisDir.y, -minAxisDir.x); perp.Normalize(); perp.Scale(abs(b)); - majAxisPoint = centerPoint+perp; - minAxisPoint = centerPoint+minAxisDir; - endAngle += M_PI/2; - startAngle += M_PI/2; - phi-=M_PI/2; - double t=a; a=b; b=t;//swap a,b + majAxisPoint = centerPoint + perp; + minAxisPoint = centerPoint + minAxisDir; + endAngle += M_PI / 2; + startAngle += M_PI / 2; + phi -= M_PI / 2; + double t = a; + a = b; + b = t;// swap a,b } int currentgeoid = getHighestCurveIndex(); try { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch arc of ellipse")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add sketch arc of ellipse")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.ArcOfEllipse" - "(Part.Ellipse(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%f,%f),%s)", - majAxisPoint.x, majAxisPoint.y, - minAxisPoint.x, minAxisPoint.y, - centerPoint.x, centerPoint.y, - startAngle, endAngle, - geometryCreationMode==Construction?"True":"False"); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.ArcOfEllipse" + "(Part.Ellipse(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App." + "Vector(%f,%f,0)),%f,%f),%s)", + majAxisPoint.x, + majAxisPoint.y, + minAxisPoint.x, + minAxisPoint.y, + centerPoint.x, + centerPoint.y, + startAngle, + endAngle, + geometryCreationMode == Construction ? "True" : "False"); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc of ellipse")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc of ellipse")); Gui::Command::abortCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); return false; } @@ -303,41 +344,51 @@ public: // add suggested constraints for start of arc if (!sugConstr3.empty()) { - createAutoConstraints(sugConstr3, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::start:Sketcher::PointPos::end); + createAutoConstraints(sugConstr3, + currentgeoid, + isOriginalArcCCW ? Sketcher::PointPos::start + : Sketcher::PointPos::end); sugConstr3.clear(); } // add suggested constraints for start of arc if (!sugConstr4.empty()) { - createAutoConstraints(sugConstr4, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::end:Sketcher::PointPos::start); + createAutoConstraints(sugConstr4, + currentgeoid, + isOriginalArcCCW ? Sketcher::PointPos::end + : Sketcher::PointPos::start); sugConstr4.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(34); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; } private: - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Create_ArcOfEllipse"); } @@ -349,8 +400,7 @@ protected: std::vector sugConstr1, sugConstr2, sugConstr3, sugConstr4; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerArcOfEllipse_H - +#endif// SKETCHERGUI_DrawSketchHandlerArcOfEllipse_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h index 92c6656b74..8ce665f50b 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h @@ -30,26 +30,29 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class DrawSketchHandlerArcOfHyperbola : public DrawSketchHandler +class DrawSketchHandlerArcOfHyperbola: public DrawSketchHandler { public: DrawSketchHandlerArcOfHyperbola() - : Mode(STATUS_SEEK_First) - , EditCurve(34) - , arcAngle(0) - , arcAngle_t(0) {} + : Mode(STATUS_SEEK_First) + , EditCurve(34) + , arcAngle(0) + , arcAngle_t(0) + {} virtual ~DrawSketchHandlerArcOfHyperbola() = default; /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ - STATUS_SEEK_Third, /**< enum value ----. */ - STATUS_SEEK_Fourth, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ + STATUS_SEEK_Third, /**< enum value ----. */ + STATUS_SEEK_Fourth, /**< enum value ----. */ STATUS_Close }; @@ -62,8 +65,8 @@ public: return; } } - else if (Mode==STATUS_SEEK_Second) { - EditCurve[1]= onSketchPos; + else if (Mode == STATUS_SEEK_Second) { + EditCurve[1] = onSketchPos; // Display radius for user float radius = (onSketchPos - centerPoint).Length(); @@ -75,29 +78,32 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f), AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr2); return; } } - else if (Mode==STATUS_SEEK_Third) { + else if (Mode == STATUS_SEEK_Third) { // angle between the major axis of the hyperbola and the X axis - double a = (axisPoint-centerPoint).Length(); - double phi = atan2(axisPoint.y-centerPoint.y,axisPoint.x-centerPoint.x); + double a = (axisPoint - centerPoint).Length(); + double phi = atan2(axisPoint.y - centerPoint.y, axisPoint.x - centerPoint.x); // This is the angle at cursor point - double angleatpoint = acosh(((onSketchPos.x-centerPoint.x)*cos(phi)+(onSketchPos.y-centerPoint.y)*sin(phi))/a); - double b=(onSketchPos.y-centerPoint.y-a*cosh(angleatpoint)*sin(phi))/(sinh(angleatpoint)*cos(phi)); + double angleatpoint = acosh(((onSketchPos.x - centerPoint.x) * cos(phi) + + (onSketchPos.y - centerPoint.y) * sin(phi)) + / a); + double b = (onSketchPos.y - centerPoint.y - a * cosh(angleatpoint) * sin(phi)) + / (sinh(angleatpoint) * cos(phi)); if (!boost::math::isnan(b)) { - for (int i=15; i >= -15; i--) { + for (int i = 15; i >= -15; i--) { // P(U) = O + MajRad*Cosh(U)*XDir + MinRad*Sinh(U)*YDir - //double angle = i*M_PI/16.0; - double angle=i*angleatpoint/15; + // double angle = i*M_PI/16.0; + double angle = i * angleatpoint / 15; double rx = a * cosh(angle) * cos(phi) - b * sinh(angle) * sin(phi); double ry = a * cosh(angle) * sin(phi) + b * sinh(angle) * cos(phi); - EditCurve[15+i] = Base::Vector2d(centerPoint.x + rx, centerPoint.y + ry); + EditCurve[15 + i] = Base::Vector2d(centerPoint.x + rx, centerPoint.y + ry); } // Display radius for user @@ -116,21 +122,29 @@ public: } } } - else if (Mode==STATUS_SEEK_Fourth) { + else if (Mode == STATUS_SEEK_Fourth) { // angle between the major axis of the hyperbola and the X axis - double a = (axisPoint-centerPoint).Length(); - double phi = atan2(axisPoint.y-centerPoint.y,axisPoint.x-centerPoint.x); + double a = (axisPoint - centerPoint).Length(); + double phi = atan2(axisPoint.y - centerPoint.y, axisPoint.x - centerPoint.x); // This is the angle at cursor point - double angleatstartingpoint = acosh(((startingPoint.x-centerPoint.x)*cos(phi)+(startingPoint.y-centerPoint.y)*sin(phi))/a); - double b=(startingPoint.y-centerPoint.y-a*cosh(angleatstartingpoint)*sin(phi))/(sinh(angleatstartingpoint)*cos(phi)); + double angleatstartingpoint = acosh(((startingPoint.x - centerPoint.x) * cos(phi) + + (startingPoint.y - centerPoint.y) * sin(phi)) + / a); + double b = (startingPoint.y - centerPoint.y - a * cosh(angleatstartingpoint) * sin(phi)) + / (sinh(angleatstartingpoint) * cos(phi)); double startAngle = angleatstartingpoint; - //double angleatpoint = acosh(((onSketchPos.x-centerPoint.x)*cos(phi)+(onSketchPos.y-centerPoint.y)*sin(phi))/a); + // double angleatpoint = + // acosh(((onSketchPos.x-centerPoint.x)*cos(phi)+(onSketchPos.y-centerPoint.y)*sin(phi))/a); - double angleatpoint = atanh( (((onSketchPos.y-centerPoint.y)*cos(phi)-(onSketchPos.x-centerPoint.x)*sin(phi))*a) / - (((onSketchPos.x-centerPoint.x)*cos(phi)+(onSketchPos.y-centerPoint.y)*sin(phi))*b) ); + double angleatpoint = atanh((((onSketchPos.y - centerPoint.y) * cos(phi) + - (onSketchPos.x - centerPoint.x) * sin(phi)) + * a) + / (((onSketchPos.x - centerPoint.x) * cos(phi) + + (onSketchPos.y - centerPoint.y) * sin(phi)) + * b)); /*double angle1 = angleatpoint - startAngle; @@ -139,13 +153,13 @@ public: arcAngle = angleatpoint - startAngle; - //if(!boost::math::isnan(angle1) && !boost::math::isnan(angle2)){ + // if(!boost::math::isnan(angle1) && !boost::math::isnan(angle2)){ if (!boost::math::isnan(arcAngle)) { EditCurve.resize(33); - for (int i=0; i < 33; i++) { + for (int i = 0; i < 33; i++) { // P(U) = O + MajRad*Cosh(U)*XDir + MinRad*Sinh(U)*YDir - //double angle=i*angleatpoint/16; - double angle = startAngle+i*arcAngle/32.0; + // double angle=i*angleatpoint/16; + double angle = startAngle + i * arcAngle / 32.0; double rx = a * cosh(angle) * cos(phi) - b * sinh(angle) * sin(phi); double ry = a * cosh(angle) * sin(phi) + b * sinh(angle) * cos(phi); EditCurve[i] = Base::Vector2d(centerPoint.x + rx, centerPoint.y + ry); @@ -161,11 +175,11 @@ public: } } else { - arcAngle=0.; + arcAngle = 0.; } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr4, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr4, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr4); return; } @@ -176,25 +190,25 @@ public: bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { EditCurve[0] = onSketchPos; centerPoint = onSketchPos; EditCurve.resize(2); Mode = STATUS_SEEK_Second; } - else if(Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { EditCurve[1] = onSketchPos; axisPoint = onSketchPos; EditCurve.resize(31); Mode = STATUS_SEEK_Third; } - else if(Mode==STATUS_SEEK_Third) { + else if (Mode == STATUS_SEEK_Third) { startingPoint = onSketchPos; arcAngle = 0.; - arcAngle_t= 0.; + arcAngle_t = 0.; Mode = STATUS_SEEK_Fourth; } - else { // Fourth + else {// Fourth endPoint = onSketchPos; Mode = STATUS_Close; @@ -204,99 +218,120 @@ public: bool releaseButton(Base::Vector2d /*onSketchPos*/) override { - if (Mode==STATUS_Close) { + if (Mode == STATUS_Close) { unsetCursor(); resetPositionText(); // angle between the major axis of the hyperbola and the X axis - double a = (axisPoint-centerPoint).Length(); - double phi = atan2(axisPoint.y-centerPoint.y,axisPoint.x-centerPoint.x); + double a = (axisPoint - centerPoint).Length(); + double phi = atan2(axisPoint.y - centerPoint.y, axisPoint.x - centerPoint.x); // This is the angle at cursor point - double angleatstartingpoint = acosh(((startingPoint.x-centerPoint.x)*cos(phi)+(startingPoint.y-centerPoint.y)*sin(phi))/a); - double b=(startingPoint.y-centerPoint.y-a*cosh(angleatstartingpoint)*sin(phi))/(sinh(angleatstartingpoint)*cos(phi)); + double angleatstartingpoint = acosh(((startingPoint.x - centerPoint.x) * cos(phi) + + (startingPoint.y - centerPoint.y) * sin(phi)) + / a); + double b = (startingPoint.y - centerPoint.y - a * cosh(angleatstartingpoint) * sin(phi)) + / (sinh(angleatstartingpoint) * cos(phi)); double startAngle = angleatstartingpoint; - //double angleatpoint = acosh(((onSketchPos.x-centerPoint.x)*cos(phi)+(onSketchPos.y-centerPoint.y)*sin(phi))/a); + // double angleatpoint = + // acosh(((onSketchPos.x-centerPoint.x)*cos(phi)+(onSketchPos.y-centerPoint.y)*sin(phi))/a); - double endAngle = atanh( (((endPoint.y-centerPoint.y)*cos(phi)-(endPoint.x-centerPoint.x)*sin(phi))*a) / - (((endPoint.x-centerPoint.x)*cos(phi)+(endPoint.y-centerPoint.y)*sin(phi))*b) ); + double endAngle = atanh( + (((endPoint.y - centerPoint.y) * cos(phi) - (endPoint.x - centerPoint.x) * sin(phi)) + * a) + / (((endPoint.x - centerPoint.x) * cos(phi) + + (endPoint.y - centerPoint.y) * sin(phi)) + * b)); if (boost::math::isnan(startAngle) || boost::math::isnan(endAngle)) { sketchgui->purgeHandler(); - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of hyperbola from invalid angles, try again!")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP( + "Notifications", + "Cannot create arc of hyperbola from invalid angles, try again!")); return false; } - bool isOriginalArcCCW=true; + bool isOriginalArcCCW = true; if (arcAngle > 0) endAngle = startAngle + arcAngle; else { endAngle = startAngle; startAngle += arcAngle; - isOriginalArcCCW=false; + isOriginalArcCCW = false; } - Base::Vector2d majAxisDir,minAxisDir,minAxisPoint,majAxisPoint; - // We always create a CCW hyperbola, because we want our XY reference system to be in the +X +Y direction - // Our normal will then always be in the +Z axis (local +Z axis of the sketcher) + Base::Vector2d majAxisDir, minAxisDir, minAxisPoint, majAxisPoint; + // We always create a CCW hyperbola, because we want our XY reference system to be in + // the +X +Y direction Our normal will then always be in the +Z axis (local +Z axis of + // the sketcher) - if(a>b) - { + if (a > b) { // force second semidiameter to be perpendicular to first semidiamater majAxisDir = axisPoint - centerPoint; - Base::Vector2d perp(-majAxisDir.y,majAxisDir.x); + Base::Vector2d perp(-majAxisDir.y, majAxisDir.x); perp.Normalize(); perp.Scale(abs(b)); - minAxisPoint = centerPoint+perp; - majAxisPoint = centerPoint+majAxisDir; + minAxisPoint = centerPoint + perp; + majAxisPoint = centerPoint + majAxisDir; } else { // force second semidiameter to be perpendicular to first semidiamater minAxisDir = axisPoint - centerPoint; - Base::Vector2d perp(minAxisDir.y,-minAxisDir.x); + Base::Vector2d perp(minAxisDir.y, -minAxisDir.x); perp.Normalize(); perp.Scale(abs(b)); - majAxisPoint = centerPoint+perp; - minAxisPoint = centerPoint+minAxisDir; - endAngle += M_PI/2; - startAngle += M_PI/2; + majAxisPoint = centerPoint + perp; + minAxisPoint = centerPoint + minAxisDir; + endAngle += M_PI / 2; + startAngle += M_PI / 2; } int currentgeoid = getHighestCurveIndex(); try { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch arc of hyperbola")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add sketch arc of hyperbola")); - //Add arc of hyperbola, point and constrain point as focus2. We add focus2 for it to balance - //the intrinsic focus1, in order to balance out the intrinsic invisible focus1 when AOE is - //dragged by its center - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.ArcOfHyperbola" - "(Part.Hyperbola(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%f,%f),%s)", - majAxisPoint.x, majAxisPoint.y, - minAxisPoint.x, minAxisPoint.y, - centerPoint.x, centerPoint.y, - startAngle, endAngle, - geometryCreationMode==Construction?"True":"False"); + // Add arc of hyperbola, point and constrain point as focus2. We add focus2 for it + // to balance the intrinsic focus1, in order to balance out the intrinsic invisible + // focus1 when AOE is dragged by its center + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.ArcOfHyperbola" + "(Part.Hyperbola(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App." + "Vector(%f,%f,0)),%f,%f),%s)", + majAxisPoint.x, + majAxisPoint.y, + minAxisPoint.x, + minAxisPoint.y, + centerPoint.x, + centerPoint.y, + startAngle, + endAngle, + geometryCreationMode == Construction ? "True" : "False"); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of hyperbola")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of hyperbola")); Gui::Command::abortCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); return false; } @@ -317,22 +352,30 @@ public: // add suggested constraints for start of arc if (!sugConstr3.empty()) { - createAutoConstraints(sugConstr3, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::start:Sketcher::PointPos::end); + createAutoConstraints(sugConstr3, + currentgeoid, + isOriginalArcCCW ? Sketcher::PointPos::start + : Sketcher::PointPos::end); sugConstr3.clear(); } // add suggested constraints for start of arc if (!sugConstr4.empty()) { - createAutoConstraints(sugConstr4, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::end:Sketcher::PointPos::start); + createAutoConstraints(sugConstr4, + currentgeoid, + isOriginalArcCCW ? Sketcher::PointPos::end + : Sketcher::PointPos::start); sugConstr4.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. Mode = STATUS_SEEK_First; EditCurve.clear(); @@ -344,15 +387,17 @@ public: * handler is destroyed by the quit() method on pressing the * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; } private: - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Create_ArcOfHyperbola"); } @@ -363,12 +408,10 @@ protected: Base::Vector2d centerPoint, axisPoint, startingPoint, endPoint; double arcAngle, arcAngle_t; std::vector sugConstr1, sugConstr2, sugConstr3, sugConstr4; - }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerArcOfHyperbola_H - +#endif// SKETCHERGUI_DrawSketchHandlerArcOfHyperbola_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h index 8da1c78551..fb65154f8a 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h @@ -27,11 +27,12 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class DrawSketchHandlerArcOfParabola : public DrawSketchHandler +class DrawSketchHandlerArcOfParabola: public DrawSketchHandler { public: DrawSketchHandlerArcOfParabola() @@ -40,30 +41,32 @@ public: , startAngle(0) , endAngle(0) , arcAngle(0) - , arcAngle_t(0) {} + , arcAngle_t(0) + {} virtual ~DrawSketchHandlerArcOfParabola() = default; /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ - STATUS_SEEK_Third, /**< enum value ----. */ - STATUS_SEEK_Fourth, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ + STATUS_SEEK_Third, /**< enum value ----. */ + STATUS_SEEK_Fourth, /**< enum value ----. */ STATUS_Close }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { - EditCurve[1]= onSketchPos; + else if (Mode == STATUS_SEEK_Second) { + EditCurve[1] = onSketchPos; // Display radius for user float radius = (onSketchPos - focusPoint).Length(); @@ -75,30 +78,31 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr2); return; } } - else if (Mode==STATUS_SEEK_Third) { - double focal = (axisPoint-focusPoint).Length(); - double phi = atan2(focusPoint.y-axisPoint.y,focusPoint.x-axisPoint.x); + else if (Mode == STATUS_SEEK_Third) { + double focal = (axisPoint - focusPoint).Length(); + double phi = atan2(focusPoint.y - axisPoint.y, focusPoint.x - axisPoint.x); // P(U) = O + U*U/(4.*F)*XDir + U*YDir // - // pnt = Base::Vector3d(pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * sin(phi), - // pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * cos(phi), - // 0.f); + // pnt = Base::Vector3d(pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * + // sin(phi), + // pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * + // cos(phi), 0.f); // This is the angle at cursor point - double u = - ( cos(phi) * (onSketchPos.y - axisPoint.y) - (onSketchPos.x - axisPoint.x) * sin(phi)); + double u = (cos(phi) * (onSketchPos.y - axisPoint.y) + - (onSketchPos.x - axisPoint.x) * sin(phi)); - for (int i=15; i >= -15; i--) { - double angle=i*u/15; + for (int i = 15; i >= -15; i--) { + double angle = i * u / 15; double rx = angle * angle / 4 / focal * cos(phi) - angle * sin(phi); double ry = angle * angle / 4 / focal * sin(phi) + angle * cos(phi); - EditCurve[15+i] = Base::Vector2d(axisPoint.x + rx, axisPoint.y + ry); + EditCurve[15 + i] = Base::Vector2d(axisPoint.x + rx, axisPoint.y + ry); } // Display radius for user @@ -111,37 +115,38 @@ public: drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr3); return; } } - else if (Mode==STATUS_SEEK_Fourth) { - double focal = (axisPoint-focusPoint).Length(); - double phi = atan2(focusPoint.y-axisPoint.y,focusPoint.x-axisPoint.x); + else if (Mode == STATUS_SEEK_Fourth) { + double focal = (axisPoint - focusPoint).Length(); + double phi = atan2(focusPoint.y - axisPoint.y, focusPoint.x - axisPoint.x); // P(U) = O + U*U/(4.*F)*XDir + U*YDir // - // pnt = Base::Vector3d(pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * sin(phi), - // pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * cos(phi), - // 0.f); + // pnt = Base::Vector3d(pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * + // sin(phi), + // pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * + // cos(phi), 0.f); // This is the angle at starting point - double ustartpoint = - ( cos(phi) * (startingPoint.y - axisPoint.y) - (startingPoint.x - axisPoint.x) * sin(phi)); + double ustartpoint = (cos(phi) * (startingPoint.y - axisPoint.y) + - (startingPoint.x - axisPoint.x) * sin(phi)); double startValue = ustartpoint; - double u = - ( cos(phi) * (onSketchPos.y - axisPoint.y) - (onSketchPos.x - axisPoint.x) * sin(phi)); + double u = (cos(phi) * (onSketchPos.y - axisPoint.y) + - (onSketchPos.x - axisPoint.x) * sin(phi)); arcAngle = u - startValue; if (!boost::math::isnan(arcAngle)) { EditCurve.resize(33); - for (std::size_t i=0; i < 33; i++) { - double angle = startValue+i*arcAngle/32.0; + for (std::size_t i = 0; i < 33; i++) { + double angle = startValue + i * arcAngle / 32.0; double rx = angle * angle / 4 / focal * cos(phi) - angle * sin(phi); double ry = angle * angle / 4 / focal * sin(phi) + angle * cos(phi); EditCurve[i] = Base::Vector2d(axisPoint.x + rx, axisPoint.y + ry); @@ -155,11 +160,11 @@ public: } } else { - arcAngle=0.; + arcAngle = 0.; } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr4, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr4, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr4); return; } @@ -170,25 +175,25 @@ public: bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { EditCurve[0] = onSketchPos; focusPoint = onSketchPos; EditCurve.resize(2); Mode = STATUS_SEEK_Second; } - else if(Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { EditCurve[1] = onSketchPos; axisPoint = onSketchPos; EditCurve.resize(31); Mode = STATUS_SEEK_Third; } - else if(Mode==STATUS_SEEK_Third) { + else if (Mode == STATUS_SEEK_Third) { startingPoint = onSketchPos; arcAngle = 0.; - arcAngle_t= 0.; + arcAngle_t = 0.; Mode = STATUS_SEEK_Fourth; } - else { // Fourth + else {// Fourth endPoint = onSketchPos; Mode = STATUS_Close; } @@ -197,23 +202,23 @@ public: bool releaseButton(Base::Vector2d /*onSketchPos*/) override { - if (Mode==STATUS_Close) { + if (Mode == STATUS_Close) { unsetCursor(); resetPositionText(); - double phi = atan2(focusPoint.y-axisPoint.y,focusPoint.x-axisPoint.x); + double phi = atan2(focusPoint.y - axisPoint.y, focusPoint.x - axisPoint.x); - double ustartpoint = - ( cos(phi) * (startingPoint.y - axisPoint.y) - (startingPoint.x - axisPoint.x) * sin(phi)); + double ustartpoint = (cos(phi) * (startingPoint.y - axisPoint.y) + - (startingPoint.x - axisPoint.x) * sin(phi)); double uendpoint = - ( cos(phi) * (endPoint.y - axisPoint.y) - (endPoint.x - axisPoint.x) * sin(phi)); + (cos(phi) * (endPoint.y - axisPoint.y) - (endPoint.x - axisPoint.x) * sin(phi)); double startAngle = ustartpoint; double endAngle = uendpoint; - bool isOriginalArcCCW=true; + bool isOriginalArcCCW = true; if (arcAngle > 0) { endAngle = startAngle + arcAngle; @@ -221,33 +226,42 @@ public: else { endAngle = startAngle; startAngle += arcAngle; - isOriginalArcCCW=false; + isOriginalArcCCW = false; } int currentgeoid = getHighestCurveIndex(); try { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch arc of Parabola")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add sketch arc of Parabola")); - //Add arc of parabola - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.ArcOfParabola" - "(Part.Parabola(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App.Vector(0,0,1)),%f,%f),%s)", - focusPoint.x, focusPoint.y, - axisPoint.x, axisPoint.y, - startAngle, endAngle, - geometryCreationMode==Construction?"True":"False"); + // Add arc of parabola + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.ArcOfParabola" + "(Part.Parabola(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App." + "Vector(0,0,1)),%f,%f),%s)", + focusPoint.x, + focusPoint.y, + axisPoint.x, + axisPoint.y, + startAngle, + endAngle, + geometryCreationMode == Construction ? "True" : "False"); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of parabola")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of parabola")); Gui::Command::abortCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); return false; } @@ -256,7 +270,7 @@ public: // add auto constraints for the focus point if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, currentgeoid+1, Sketcher::PointPos::start); + createAutoConstraints(sugConstr1, currentgeoid + 1, Sketcher::PointPos::start); sugConstr1.clear(); } @@ -268,20 +282,28 @@ public: // add suggested constraints for start of arc if (!sugConstr3.empty()) { - createAutoConstraints(sugConstr3, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::start:Sketcher::PointPos::end); + createAutoConstraints(sugConstr3, + currentgeoid, + isOriginalArcCCW ? Sketcher::PointPos::start + : Sketcher::PointPos::end); sugConstr3.clear(); } // add suggested constraints for start of arc if (!sugConstr4.empty()) { - createAutoConstraints(sugConstr4, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::end:Sketcher::PointPos::start); + createAutoConstraints(sugConstr4, + currentgeoid, + isOriginalArcCCW ? Sketcher::PointPos::end + : Sketcher::PointPos::start); sugConstr4.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { // This code enables the continuous creation mode. Mode = STATUS_SEEK_First; @@ -295,14 +317,16 @@ public: * right button of the mouse */ } else { - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; } private: - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Create_ArcOfParabola"); } @@ -314,8 +338,7 @@ protected: std::vector sugConstr1, sugConstr2, sugConstr3, sugConstr4; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerArcOfParabola_H - +#endif// SKETCHERGUI_DrawSketchHandlerArcOfParabola_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h index ab047e18cb..6415578854 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h @@ -23,27 +23,28 @@ #ifndef SKETCHERGUI_DrawSketchHandlerBSpline_H #define SKETCHERGUI_DrawSketchHandlerBSpline_H -#include #include +#include #include #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp class DrawSketchHandlerBSpline: public DrawSketchHandler { public: explicit DrawSketchHandlerBSpline(int constructionMethod) - : Mode(STATUS_SEEK_FIRST_CONTROLPOINT) - , MousePressMode(MOUSE_NOT_PRESSED) - , ConstrMethod(constructionMethod) - , SplineDegree(3) - , IsClosed(false) + : Mode(STATUS_SEEK_FIRST_CONTROLPOINT) + , MousePressMode(MOUSE_NOT_PRESSED) + , ConstrMethod(constructionMethod) + , SplineDegree(3) + , IsClosed(false) { addSugConstraint(); applyCursor(); @@ -52,7 +53,8 @@ public: virtual ~DrawSketchHandlerBSpline() = default; /// modes - enum SELECT_MODE { + enum SELECT_MODE + { STATUS_SEEK_FIRST_CONTROLPOINT, STATUS_SEEK_ADDITIONAL_CONTROLPOINTS, STATUS_CLOSE @@ -61,7 +63,8 @@ public: // TODO: this kind of behavior will be useful in a superclass // when LMB is pressed it's a transitional state so some undos can't be done // (like delete last pole) - enum MOUSE_PRESS_MODE { + enum MOUSE_PRESS_MODE + { MOUSE_PRESSED, MOUSE_NOT_PRESSED }; @@ -70,21 +73,21 @@ public: { prevCursorPosition = onSketchPos; - if (Mode==STATUS_SEEK_FIRST_CONTROLPOINT) { + if (Mode == STATUS_SEEK_FIRST_CONTROLPOINT) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr.back(), onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr.back(), onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr.back()); return; } } - else if (Mode==STATUS_SEEK_ADDITIONAL_CONTROLPOINTS) { + else if (Mode == STATUS_SEEK_ADDITIONAL_CONTROLPOINTS) { drawControlPolygonToPosition(onSketchPos); drawCursorToPosition(onSketchPos); - if (seekAutoConstraint(sugConstr.back(), onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr.back(), onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr.back()); return; } @@ -106,46 +109,51 @@ public: try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add Pole circle")); - //Add pole - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),10),True)", - BSplinePoles.back().x, BSplinePoles.back().y); + // Add pole + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),10),True)", + BSplinePoles.back().x, + BSplinePoles.back().y); poleGeoIds.push_back(getHighestCurveIndex()); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Weight',%d,%f)) ", - poleGeoIds.back(), 1.0 ); // First pole defaults to 1.0 weight + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Weight',%d,%f)) ", + poleGeoIds.back(), + 1.0);// First pole defaults to 1.0 weight } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error adding B-Spline pole")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error adding B-Spline pole")); Gui::Command::abortCommand(); - static_cast(sketchgui->getObject())->solve(); + static_cast(sketchgui->getObject())->solve(); return false; } - //Gui::Command::commitCommand(); + // Gui::Command::commitCommand(); - //static_cast(sketchgui->getObject())->solve(); + // static_cast(sketchgui->getObject())->solve(); // add auto constraints on pole if (!sugConstr.back().empty()) { - createAutoConstraints(sugConstr.back(), poleGeoIds.back(), Sketcher::PointPos::mid, false); + createAutoConstraints( + sugConstr.back(), poleGeoIds.back(), Sketcher::PointPos::mid, false); } - static_cast(sketchgui->getObject())->solve(); + static_cast(sketchgui->getObject())->solve(); addSugConstraint(); - } else if (Mode == STATUS_SEEK_ADDITIONAL_CONTROLPOINTS) { BSplinePoles.push_back(onSketchPos); // check if coincident with first pole - for(auto & ac : sugConstr.back()) { + for (auto& ac : sugConstr.back()) { if (ac.Type == Sketcher::Coincident) { if (ac.GeoId == poleGeoIds[0] && ac.PosId == Sketcher::PointPos::mid) IsClosed = true; @@ -153,9 +161,9 @@ public: // The coincidence with first point may be indirect const auto coincidents = static_cast(sketchgui->getObject()) - ->getAllCoincidentPoints(ac.GeoId, ac.PosId); - if (coincidents.find(poleGeoIds[0]) != coincidents.end() && - coincidents.at(poleGeoIds[0]) == Sketcher::PointPos::mid) + ->getAllCoincidentPoints(ac.GeoId, ac.PosId); + if (coincidents.find(poleGeoIds[0]) != coincidents.end() + && coincidents.at(poleGeoIds[0]) == Sketcher::PointPos::mid) IsClosed = true; } } @@ -164,7 +172,7 @@ public: if (IsClosed) { Mode = STATUS_CLOSE; - if (ConstrMethod == 1) { // if periodic we do not need the last pole + if (ConstrMethod == 1) {// if periodic we do not need the last pole BSplinePoles.pop_back(); sugConstr.pop_back(); @@ -175,44 +183,48 @@ public: // insert circle point for pole, defer internal alignment constraining. try { - //Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add Pole circle")); + // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add Pole circle")); - //Add pole - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),10),True)", - BSplinePoles.back().x,BSplinePoles.back().y); + // Add pole + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),10),True)", + BSplinePoles.back().x, + BSplinePoles.back().y); poleGeoIds.push_back(getHighestCurveIndex()); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Equal',%d,%d)) ", - poleGeoIds[0], poleGeoIds.back()); - + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Equal',%d,%d)) ", + poleGeoIds[0], + poleGeoIds.back()); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error creating BSpline pole")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error creating BSpline pole")); Gui::Command::abortCommand(); - static_cast(sketchgui->getObject())->solve(); + static_cast(sketchgui->getObject())->solve(); return false; } - //Gui::Command::commitCommand(); + // Gui::Command::commitCommand(); - //static_cast(sketchgui->getObject())->solve(); + // static_cast(sketchgui->getObject())->solve(); // add auto constraints on pole if (!sugConstr.back().empty()) { - createAutoConstraints(sugConstr.back(), poleGeoIds.back(), Sketcher::PointPos::mid, false); + createAutoConstraints( + sugConstr.back(), poleGeoIds.back(), Sketcher::PointPos::mid, false); } - //static_cast(sketchgui->getObject())->solve(); + // static_cast(sketchgui->getObject())->solve(); if (!IsClosed) { addSugConstraint(); } - } return true; } @@ -228,12 +240,15 @@ public: void registerPressedKey(bool pressed, int key) override { if (SoKeyboardEvent::D == key && pressed) { - SplineDegree = QInputDialog::getInt( - Gui::getMainWindow(), - QObject::tr("B-Spline Degree"), - QObject::tr("Define B-Spline Degree, between 1 and %1:") - .arg(QString::number(Geom_BSplineCurve::MaxDegree())), - SplineDegree, 1, Geom_BSplineCurve::MaxDegree(), 1); + SplineDegree = + QInputDialog::getInt(Gui::getMainWindow(), + QObject::tr("B-Spline Degree"), + QObject::tr("Define B-Spline Degree, between 1 and %1:") + .arg(QString::number(Geom_BSplineCurve::MaxDegree())), + SplineDegree, + 1, + Geom_BSplineCurve::MaxDegree(), + 1); // FIXME: Pressing Esc here also finishes the B-Spline creation. // The user may only want to exit the dialog. } @@ -244,8 +259,7 @@ public: return; // can only delete last pole if it exists - if (STATUS_SEEK_FIRST_CONTROLPOINT == Mode || - STATUS_CLOSE == Mode) + if (STATUS_SEEK_FIRST_CONTROLPOINT == Mode || STATUS_CLOSE == Mode) return; // if only first pole exists it's equivalent to canceling current spline @@ -259,23 +273,25 @@ public: try { // already ensured that CurrentConstraint == EditCurve.size() > 1 const int delGeoId = poleGeoIds.back(); - const auto& constraints = static_cast(sketchgui->getObject())->Constraints.getValues(); + const auto& constraints = + static_cast(sketchgui->getObject()) + ->Constraints.getValues(); for (int i = constraints.size() - 1; i >= 0; --i) { - if (delGeoId == constraints[i]->First || - delGeoId == constraints[i]->Second || - delGeoId == constraints[i]->Third) + if (delGeoId == constraints[i]->First || delGeoId == constraints[i]->Second + || delGeoId == constraints[i]->Third) Gui::cmdAppObjectArgs(sketchgui->getObject(), "delConstraint(%d)", i); } // Remove pole Gui::cmdAppObjectArgs(sketchgui->getObject(), "delGeometry(%d)", delGeoId); - static_cast(sketchgui->getObject())->solve(); + static_cast(sketchgui->getObject())->solve(); poleGeoIds.pop_back(); BSplinePoles.pop_back(); - // last entry is kept, as it corresponds to the current pole, but the one corresponding to the erased pole is removed + // last entry is kept, as it corresponds to the current pole, but the one + // corresponding to the erased pole is removed sugConstr.erase(std::prev(std::prev(sugConstr.end()))); @@ -285,12 +301,13 @@ public: } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error deleting last pole")); - // some commands might have already deleted some constraints/geometries but not others + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error deleting last pole")); + // some commands might have already deleted some constraints/geometries but not + // others Gui::Command::abortCommand(); - static_cast(sketchgui->getObject())->solve(); + static_cast(sketchgui->getObject())->solve(); return; } @@ -306,24 +323,27 @@ public: // We must see if we need to create a B-spline before cancelling everything // and now just like any other Handler, - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (poleGeoIds.size() > 1) { // create B-spline from existing poles - Mode=STATUS_CLOSE; - finishCommand(Base::Vector2d(0.f,0.f)); + Mode = STATUS_CLOSE; + finishCommand(Base::Vector2d(0.f, 0.f)); } - else if(poleGeoIds.size() == 1) { - // if we just have one point and we can not close anything, then cancel this creation but continue according to continuous mode - //sketchgui->getDocument()->undo(1); + else if (poleGeoIds.size() == 1) { + // if we just have one point and we can not close anything, then cancel this creation + // but continue according to continuous mode + // sketchgui->getDocument()->undo(1); Gui::Command::abortCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - if(!continuousMode){ + if (!continuousMode) { DrawSketchHandler::quit(); } else { @@ -331,7 +351,8 @@ public: resetHandlerState(); } } - else { // we have no data (CurrentConstraint == 0) so user when right-clicking really wants to exit + else {// we have no data (CurrentConstraint == 0) so user when right-clicking really wants + // to exit DrawSketchHandler::quit(); } } @@ -355,16 +376,19 @@ private: IsClosed = false; } - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Create_BSpline"); } - void addSugConstraint() { + void addSugConstraint() + { std::vector sugConstr1; sugConstr.push_back(std::move(sugConstr1)); } - void drawControlPolygonToPosition(Base::Vector2d position) { + void drawControlPolygonToPosition(Base::Vector2d position) + { std::vector editcurve(BSplinePoles); editcurve.push_back(position); @@ -372,33 +396,37 @@ private: drawEdit(editcurve); } - void drawCursorToPosition(Base::Vector2d position) { + void drawCursorToPosition(Base::Vector2d position) + { if (!BSplinePoles.empty()) { float length = (position - BSplinePoles.back()).Length(); - float angle = (position - BSplinePoles.back()).GetAngle(Base::Vector2d(1.f,0.f)); + float angle = (position - BSplinePoles.back()).GetAngle(Base::Vector2d(1.f, 0.f)); if (showCursorCoords()) { SbString text; std::string lengthString = lengthToDisplayFormat(length, 1); - std::string angleString = angleToDisplayFormat((angle != -FLOAT_MAX) ? angle * 180 / M_PI : 0, 1); + std::string angleString = + angleToDisplayFormat((angle != -FLOAT_MAX) ? angle * 180 / M_PI : 0, 1); text.sprintf(" (%s, %s)", lengthString.c_str(), angleString.c_str()); setPositionText(position, text); } } } - void eraseEditCurve() { + void eraseEditCurve() + { drawEdit(std::vector()); } - bool finishCommand(Base::Vector2d position) { - if (Mode==STATUS_CLOSE) { + bool finishCommand(Base::Vector2d position) + { + if (Mode == STATUS_CLOSE) { unsetCursor(); resetPositionText(); std::stringstream stream; - for (auto & pole : BSplinePoles) { + for (auto& pole : BSplinePoles) { stream << "App.Vector(" << pole.x << "," << pole.y << "),"; } @@ -408,15 +436,16 @@ private: int index = controlpoints.rfind(','); controlpoints.resize(index); - controlpoints.insert(0,1,'['); - controlpoints.append(1,']'); + controlpoints.insert(0, 1, '['); + controlpoints.append(1, ']'); int currentgeoid = getHighestCurveIndex(); - unsigned int maxDegree = ConstrMethod == 0 ? (BSplinePoles.size()-1) : (BSplinePoles.size()); + unsigned int maxDegree = + ConstrMethod == 0 ? (BSplinePoles.size() - 1) : (BSplinePoles.size()); try { - //Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add B-spline curve")); + // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add B-spline curve")); /*Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.BSplineCurve" "(%s,%s)," @@ -425,28 +454,35 @@ private: ConstrMethod == 0 ?"False":"True", geometryCreationMode==Construction?"True":"False"); */ - // {"poles", "mults", "knots", "periodic", "degree", "weights", "CheckRational", NULL}; - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.BSplineCurve" + // {"poles", "mults", "knots", "periodic", "degree", "weights", "CheckRational", + // NULL}; + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.BSplineCurve" "(%s,None,None,%s,%d,None,False),%s)", controlpoints.c_str(), - ConstrMethod == 0 ?"False":"True", + ConstrMethod == 0 ? "False" : "True", std::min(maxDegree, SplineDegree), - geometryCreationMode==Construction?"True":"False"); + geometryCreationMode == Construction ? "True" : "False"); currentgeoid++; - // autoconstraints were added to the circles of the poles, which is ok because they must go to the - // right position, or the user will freak-out if they appear out of the autoconstrained position. - // However, autoconstraints on the first and last pole, in normal non-periodic b-splines (with appropriate endpoint knot multiplicity) - // as the ones created by this tool are intended for the b-spline endpoints, and not for the poles, - // so here we retrieve any autoconstraint on those poles' center and mangle it to the endpoint. + // autoconstraints were added to the circles of the poles, which is ok because they + // must go to the right position, or the user will freak-out if they appear out of + // the autoconstrained position. However, autoconstraints on the first and last + // pole, in normal non-periodic b-splines (with appropriate endpoint knot + // multiplicity) as the ones created by this tool are intended for the b-spline + // endpoints, and not for the poles, so here we retrieve any autoconstraint on those + // poles' center and mangle it to the endpoint. if (ConstrMethod == 0) { - for(auto & constr : static_cast(sketchgui->getObject())->Constraints.getValues()) { - if(constr->First == poleGeoIds[0] && constr->FirstPos == Sketcher::PointPos::mid) { + for (auto& constr : static_cast(sketchgui->getObject()) + ->Constraints.getValues()) { + if (constr->First == poleGeoIds[0] + && constr->FirstPos == Sketcher::PointPos::mid) { constr->First = currentgeoid; constr->FirstPos = Sketcher::PointPos::start; } - else if(constr->First == poleGeoIds.back() && constr->FirstPos == Sketcher::PointPos::mid) { + else if (constr->First == poleGeoIds.back() + && constr->FirstPos == Sketcher::PointPos::mid) { constr->First = currentgeoid; constr->FirstPos = Sketcher::PointPos::end; } @@ -459,37 +495,44 @@ private: cstream << "conList = []\n"; for (size_t i = 0; i < poleGeoIds.size(); i++) { - cstream << "conList.append(Sketcher.Constraint('InternalAlignment:Sketcher::BSplineControlPoint'," << poleGeoIds[0] + i - << "," << static_cast(Sketcher::PointPos::mid) << "," << currentgeoid << "," << i << "))\n"; + cstream << "conList.append(Sketcher.Constraint('InternalAlignment:Sketcher::" + "BSplineControlPoint'," + << poleGeoIds[0] + i << "," << static_cast(Sketcher::PointPos::mid) + << "," << currentgeoid << "," << i << "))\n"; } - cstream << Gui::Command::getObjectCmd(sketchgui->getObject()) << ".addConstraint(conList)\n"; + cstream << Gui::Command::getObjectCmd(sketchgui->getObject()) + << ".addConstraint(conList)\n"; cstream << "del conList\n"; Gui::Command::doCommand(Gui::Command::Doc, cstream.str().c_str()); // for showing the knots on creation - Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error creating B-Spline")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error creating B-Spline")); Gui::Command::abortCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); return false; } Gui::Command::commitCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. resetHandlerState(); @@ -500,8 +543,9 @@ private: * handler is destroyed by the quit() method on pressing the * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } else { @@ -530,8 +574,7 @@ protected: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerBSpline_H - +#endif// SKETCHERGUI_DrawSketchHandlerBSpline_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h index dd9d19b7b5..4a0972cd2d 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSplineByInterpolation.h @@ -40,11 +40,11 @@ class DrawSketchHandlerBSplineByInterpolation: public DrawSketchHandler { public: explicit DrawSketchHandlerBSplineByInterpolation(int constructionMethod) - : Mode(STATUS_SEEK_FIRST_POINT), - MousePressMode(MOUSE_NOT_PRESSED), - ConstrMethod(constructionMethod), - SplineDegree(3), - IsClosed(false) + : Mode(STATUS_SEEK_FIRST_POINT) + , MousePressMode(MOUSE_NOT_PRESSED) + , ConstrMethod(constructionMethod) + , SplineDegree(3) + , IsClosed(false) { addSugConstraint(); applyCursor(); @@ -120,8 +120,8 @@ public: } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot add knot point")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Cannot add knot point")); Gui::Command::abortCommand(); static_cast(sketchgui->getObject())->solve(); @@ -149,15 +149,15 @@ public: // The coincidence with first point may be indirect const auto coincidents = static_cast(sketchgui->getObject()) - ->getAllCoincidentPoints(ac.GeoId, ac.PosId); - if (coincidents.find(knotGeoIds[0]) != coincidents.end() && - coincidents.at(knotGeoIds[0]) == Sketcher::PointPos::start) + ->getAllCoincidentPoints(ac.GeoId, ac.PosId); + if (coincidents.find(knotGeoIds[0]) != coincidents.end() + && coincidents.at(knotGeoIds[0]) == Sketcher::PointPos::start) IsClosed = true; - else if (coincidents.find(knotGeoIds.back()) != coincidents.end() && - coincidents.at(knotGeoIds.back()) == Sketcher::PointPos::start) { + else if (coincidents.find(knotGeoIds.back()) != coincidents.end() + && coincidents.at(knotGeoIds.back()) + == Sketcher::PointPos::start) { return true;// OCCT doesn't allow consecutive points being coincident } - } } } @@ -189,9 +189,10 @@ public: knotGeoIds.push_back(getHighestCurveIndex()); } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot add internal alignment points")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Cannot add internal alignment points")); Gui::Command::abortCommand(); static_cast(sketchgui->getObject())->solve(); @@ -299,8 +300,8 @@ public: } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error removing knot")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error removing knot")); // some commands might have already deleted some constraints/geometries but not // others Gui::Command::abortCommand(); @@ -609,8 +610,8 @@ private: } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error creating B-Spline")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error creating B-Spline")); Gui::Command::abortCommand(); tryAutoRecomputeIfNotSolve( @@ -632,8 +633,8 @@ private: * right button of the mouse */ } else { - sketchgui - ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider + sketchgui->purgeHandler();// no code after this line, Handler get deleted in + // ViewProvider } return false; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h index 8e3810898f..b96032a136 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h @@ -28,63 +28,80 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class CarbonCopySelection : public Gui::SelectionFilterGate +class CarbonCopySelection: public Gui::SelectionFilterGate { App::DocumentObject* object; + public: explicit CarbonCopySelection(App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()), object(obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) {} - bool allow(App::Document *pDoc, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) { Q_UNUSED(sSubName); - Sketcher::SketchObject *sketch = static_cast(object); - sketch->setAllowOtherBody(QApplication::keyboardModifiers() == Qt::ControlModifier || QApplication::keyboardModifiers() == (Qt::ControlModifier | Qt::AltModifier)); - sketch->setAllowUnaligned(QApplication::keyboardModifiers() == (Qt::ControlModifier | Qt::AltModifier)); + Sketcher::SketchObject* sketch = static_cast(object); + sketch->setAllowOtherBody(QApplication::keyboardModifiers() == Qt::ControlModifier + || QApplication::keyboardModifiers() + == (Qt::ControlModifier | Qt::AltModifier)); + sketch->setAllowUnaligned(QApplication::keyboardModifiers() + == (Qt::ControlModifier | Qt::AltModifier)); this->notAllowedReason = ""; Sketcher::SketchObject::eReasonList msg; // Reusing code: All good reasons not to allow a carbon copy bool xinv = false, yinv = false; - if (!sketch->isCarbonCopyAllowed(pDoc, pObj, xinv, yinv, &msg)){ - switch(msg){ + if (!sketch->isCarbonCopyAllowed(pDoc, pObj, xinv, yinv, &msg)) { + switch (msg) { case Sketcher::SketchObject::rlCircularReference: - this->notAllowedReason = QT_TR_NOOP("Carbon copy would cause a circular dependency."); + this->notAllowedReason = + QT_TR_NOOP("Carbon copy would cause a circular dependency."); break; case Sketcher::SketchObject::rlOtherDoc: this->notAllowedReason = QT_TR_NOOP("This object is in another document."); break; case Sketcher::SketchObject::rlOtherBody: - this->notAllowedReason = QT_TR_NOOP("This object belongs to another body. Hold Ctrl to allow cross-references."); + this->notAllowedReason = QT_TR_NOOP("This object belongs to another body. Hold " + "Ctrl to allow cross-references."); break; case Sketcher::SketchObject::rlOtherBodyWithLinks: - this->notAllowedReason = QT_TR_NOOP("This object belongs to another body and it contains external geometry. Cross-reference not allowed."); + this->notAllowedReason = + QT_TR_NOOP("This object belongs to another body and it contains external " + "geometry. Cross-reference not allowed."); break; case Sketcher::SketchObject::rlOtherPart: this->notAllowedReason = QT_TR_NOOP("This object belongs to another part."); break; case Sketcher::SketchObject::rlNonParallel: - this->notAllowedReason = QT_TR_NOOP("The selected sketch is not parallel to this sketch. Hold Ctrl+Alt to allow non-parallel sketches."); + this->notAllowedReason = + QT_TR_NOOP("The selected sketch is not parallel to this sketch. Hold " + "Ctrl+Alt to allow non-parallel sketches."); break; case Sketcher::SketchObject::rlAxesMisaligned: - this->notAllowedReason = QT_TR_NOOP("The XY axes of the selected sketch do not have the same direction as this sketch. Hold Ctrl+Alt to disregard it."); + this->notAllowedReason = + QT_TR_NOOP("The XY axes of the selected sketch do not have the same " + "direction as this sketch. Hold Ctrl+Alt to disregard it."); break; case Sketcher::SketchObject::rlOriginsMisaligned: - this->notAllowedReason = QT_TR_NOOP("The origin of the selected sketch is not aligned with the origin of this sketch. Hold Ctrl+Alt to disregard it."); + this->notAllowedReason = + QT_TR_NOOP("The origin of the selected sketch is not aligned with the " + "origin of this sketch. Hold Ctrl+Alt to disregard it."); break; default: break; } return false; } - // Carbon copy only works on sketches that are not disallowed (e.g. would produce a circular reference) - return true; + // Carbon copy only works on sketches that are not disallowed (e.g. would produce a circular + // reference) + return true; } }; @@ -114,16 +131,17 @@ public: { Q_UNUSED(onSketchPos); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ return true; } bool onSelectionChanged(const Gui::SelectionChanges& msg) override { if (msg.Type == Gui::SelectionChanges::AddSelection) { - App::DocumentObject* obj = sketchgui->getObject()->getDocument()->getObject(msg.pObjectName); + App::DocumentObject* obj = + sketchgui->getObject()->getDocument()->getObject(msg.pObjectName); if (!obj) throw Base::ValueError("Sketcher: Carbon Copy: Invalid object in selection"); @@ -131,27 +149,31 @@ public: try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create a carbon copy")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "carbonCopy(\"%s\",%s)", - msg.pObjectName, geometryCreationMode==Construction?"True":"False"); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "carbonCopy(\"%s\",%s)", + msg.pObjectName, + geometryCreationMode == Construction ? "True" : "False"); Gui::Command::commitCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); Gui::Selection().clearSelection(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add carbon copy")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add carbon copy")); Gui::Command::abortCommand(); } return true; - } + } } return false; } @@ -160,9 +182,9 @@ private: void activated() override { setAxisPickStyle(false); - Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); - Gui::View3DInventorViewer *viewer; - viewer = static_cast(mdi)->getViewer(); + Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView(); + Gui::View3DInventorViewer* viewer; + viewer = static_cast(mdi)->getViewer(); viewer->setSelectionEnabled(true); Gui::Selection().clearSelection(); @@ -170,7 +192,8 @@ private: Gui::Selection().addSelectionGate(new CarbonCopySelection(sketchgui->getObject())); } - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_CarbonCopy"); } @@ -181,8 +204,7 @@ private: } }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerCarbonCopy_H - +#endif// SKETCHERGUI_DrawSketchHandlerCarbonCopy_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h index 060b6c586b..09532dae27 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h @@ -26,40 +26,46 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class DrawSketchHandlerCircle : public DrawSketchHandler +class DrawSketchHandlerCircle: public DrawSketchHandler { public: - DrawSketchHandlerCircle() : Mode(STATUS_SEEK_First),EditCurve(34){} - virtual ~DrawSketchHandlerCircle(){} + DrawSketchHandlerCircle() + : Mode(STATUS_SEEK_First) + , EditCurve(34) + {} + virtual ~DrawSketchHandlerCircle() + {} /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_Close }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { double rx0 = onSketchPos.x - EditCurve[0].x; double ry0 = onSketchPos.y - EditCurve[0].y; - for (int i=0; i < 16; i++) { - double angle = i*M_PI/16.0; + for (int i = 0; i < 16; i++) { + double angle = i * M_PI / 16.0; double rx = rx0 * cos(angle) + ry0 * sin(angle); double ry = -rx0 * sin(angle) + ry0 * cos(angle); - EditCurve[1+i] = Base::Vector2d(EditCurve[0].x + rx, EditCurve[0].y + ry); - EditCurve[17+i] = Base::Vector2d(EditCurve[0].x - rx, EditCurve[0].y - ry); + EditCurve[1 + i] = Base::Vector2d(EditCurve[0].x + rx, EditCurve[0].y + ry); + EditCurve[17 + i] = Base::Vector2d(EditCurve[0].x - rx, EditCurve[0].y - ry); } EditCurve[33] = EditCurve[1]; @@ -73,8 +79,8 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, onSketchPos - EditCurve[0], - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr2, onSketchPos, onSketchPos - EditCurve[0], AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr2); return; } @@ -84,10 +90,11 @@ public: bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { EditCurve[0] = onSketchPos; Mode = STATUS_SEEK_Second; - } else { + } + else { EditCurve[1] = onSketchPos; Mode = STATUS_Close; } @@ -97,7 +104,7 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (Mode==STATUS_Close) { + if (Mode == STATUS_Close) { double rx = EditCurve[1].x - EditCurve[0].x; double ry = EditCurve[1].y - EditCurve[0].y; unsetCursor(); @@ -105,11 +112,13 @@ public: try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch circle")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.Circle" - "(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%s)", - EditCurve[0].x, EditCurve[0].y, - sqrt(rx*rx + ry*ry), - geometryCreationMode==Construction?"True":"False"); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.Circle" + "(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%s)", + EditCurve[0].x, + EditCurve[0].y, + sqrt(rx * rx + ry * ry), + geometryCreationMode == Construction ? "True" : "False"); Gui::Command::commitCommand(); } @@ -132,24 +141,27 @@ public: sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(34); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -165,20 +177,25 @@ protected: SelectMode Mode; std::vector EditCurve; std::vector sugConstr1, sugConstr2; - }; -class DrawSketchHandler3PointCircle : public DrawSketchHandler +class DrawSketchHandler3PointCircle: public DrawSketchHandler { public: DrawSketchHandler3PointCircle() - : Mode(STATUS_SEEK_First),EditCurve(2),radius(1),N(32.0){} - virtual ~DrawSketchHandler3PointCircle(){} + : Mode(STATUS_SEEK_First) + , EditCurve(2) + , radius(1) + , N(32.0) + {} + virtual ~DrawSketchHandler3PointCircle() + {} /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ - STATUS_SEEK_Third, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ + STATUS_SEEK_Third, /**< enum value ----. */ STATUS_End }; @@ -186,28 +203,29 @@ public: { if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f), AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr1); return; } } else if (Mode == STATUS_SEEK_Second || Mode == STATUS_SEEK_Third) { - try - { + try { if (Mode == STATUS_SEEK_Second) - CenterPoint = EditCurve[N+1] = (onSketchPos - FirstPoint)/2 + FirstPoint; + CenterPoint = EditCurve[N + 1] = (onSketchPos - FirstPoint) / 2 + FirstPoint; else - CenterPoint = EditCurve[N+1] = Part::Geom2dCircle::getCircleCenter(FirstPoint, SecondPoint, onSketchPos); + CenterPoint = EditCurve[N + 1] = + Part::Geom2dCircle::getCircleCenter(FirstPoint, SecondPoint, onSketchPos); radius = (onSketchPos - CenterPoint).Length(); double lineAngle = GetPointAngle(CenterPoint, onSketchPos); // Build a N point circle - for (int i=1; i < N; i++) { + for (int i = 1; i < N; i++) { // Start at current angle - double angle = i*2*M_PI/N + lineAngle; // N point closed circle has N segments - EditCurve[i] = Base::Vector2d(CenterPoint.x + radius*cos(angle), - CenterPoint.y + radius*sin(angle)); + double angle = + i * 2 * M_PI / N + lineAngle;// N point closed circle has N segments + EditCurve[i] = Base::Vector2d(CenterPoint.x + radius * cos(angle), + CenterPoint.y + radius * sin(angle)); } // Beginning and end of curve should be exact EditCurve[0] = EditCurve[N] = onSketchPos; @@ -217,28 +235,32 @@ public: if (showCursorCoords()) { SbString text; std::string radiusString = lengthToDisplayFormat(radius, 1); - std::string angleString = angleToDisplayFormat( lineAngle * 180.0 / M_PI, 1); + std::string angleString = angleToDisplayFormat(lineAngle * 180.0 / M_PI, 1); text.sprintf(" (R%s, %s)", radiusString.c_str(), angleString.c_str()); setPositionText(onSketchPos, text); } drawEdit(EditCurve); if (Mode == STATUS_SEEK_Second) { - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint(sugConstr2, + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr2); return; } } else { - if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.f,0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint(sugConstr3, + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr3); return; } } } - catch(Base::ValueError &e) { + catch (Base::ValueError& e) { e.ReportException(); } } @@ -249,7 +271,7 @@ public: { if (Mode == STATUS_SEEK_First) { // N point curve + center + endpoint - EditCurve.resize(N+2); + EditCurve.resize(N + 2); FirstPoint = onSketchPos; Mode = STATUS_SEEK_Second; @@ -274,24 +296,26 @@ public: { Q_UNUSED(onSketchPos); // Need to look at. rx might need fixing. - if (Mode==STATUS_End) { + if (Mode == STATUS_End) { unsetCursor(); resetPositionText(); try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch circle")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.Circle" - "(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%s)", - CenterPoint.x, CenterPoint.y, - radius, - geometryCreationMode==Construction?"True":"False"); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.Circle" + "(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%s)", + CenterPoint.x, + CenterPoint.y, + radius, + geometryCreationMode == Construction ? "True" : "False"); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add circle")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add circle")); Gui::Command::abortCommand(); } @@ -313,24 +337,27 @@ public: sugConstr3.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -346,13 +373,12 @@ protected: SelectMode Mode; std::vector EditCurve; Base::Vector2d CenterPoint, FirstPoint, SecondPoint; - double radius, N; // N should be even + double radius, N;// N should be even std::vector sugConstr1, sugConstr2, sugConstr3; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerCircle_H - +#endif// SKETCHERGUI_DrawSketchHandlerCircle_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h index 43e57268e6..5c129fbea0 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h @@ -23,18 +23,19 @@ #ifndef SKETCHERGUI_DrawSketchHandlerEllipse_H #define SKETCHERGUI_DrawSketchHandlerEllipse_H -#include -#include #include +#include +#include #include #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp /* Ellipse ==============================================================================*/ /** @@ -63,9 +64,11 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo * a &\equiv& \textrm{ length of the semi-major axis, colloquially 'radius'}\\ * b &\equiv& \textrm{ length of the semi-minor axis, colloquially 'radius'}\\ * e &\equiv& \textrm{ eccentricity of the ellipse}\\ - * \theta_b &\equiv& \textrm{ angle to the intersection of the semi-minor axis and the ellipse, relative to the focus}\\ + * \theta_b &\equiv& \textrm{ angle to the intersection of the semi-minor axis and the + * ellipse, relative to the focus}\\ * ae &\equiv& \textrm{ distance from the focus to the centroid}\\ - * r &=& \frac{a(1-e^2)}{1+e\cos(\theta)} = \frac{r_a(1-e)}{1+e\cos(\theta)} = \frac{r_p(1+e)}{1+e\cos(\theta)}\\ + * r &=& \frac{a(1-e^2)}{1+e\cos(\theta)} = \frac{r_a(1-e)}{1+e\cos(\theta)} = + * \frac{r_p(1+e)}{1+e\cos(\theta)}\\ * r_a &=& a(1-e)\\ * r_p &=& a(1+e)\\ * a &=& \frac{r_p+r_a}{2}\\ @@ -75,32 +78,42 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo * \f} * */ -class DrawSketchHandlerEllipse : public DrawSketchHandler +class DrawSketchHandlerEllipse: public DrawSketchHandler { public: explicit DrawSketchHandlerEllipse(int constructionMethod) - : mode(STATUS_Close) - , method(CENTER_PERIAPSIS_B) - , constrMethod(constructionMethod) - , a(0), b(0), e(0), ratio(0), ae(0) - , num(0), r(0), theta(0), phi(0) - , editCurve(33), fixedAxisLength(0) - { - } - virtual ~DrawSketchHandlerEllipse(){} + : mode(STATUS_Close) + , method(CENTER_PERIAPSIS_B) + , constrMethod(constructionMethod) + , a(0) + , b(0) + , e(0) + , ratio(0) + , ae(0) + , num(0) + , r(0) + , theta(0) + , phi(0) + , editCurve(33) + , fixedAxisLength(0) + {} + virtual ~DrawSketchHandlerEllipse() + {} /// Mode table, describes what step of the process we are in - enum SelectMode { - STATUS_SEEK_PERIAPSIS, /**< enum value, looking for click to set periapsis. */ - STATUS_SEEK_APOAPSIS, /**< enum value, looking for click to set apoapsis. */ - STATUS_SEEK_CENTROID, /**< enum value, looking for click to set centroid. */ - STATUS_SEEK_A, /**< enum value, looking for click to set a. */ - STATUS_SEEK_B, /**< enum value, looking for click to set b. */ - STATUS_Close /**< enum value, finalizing and saving ellipse. */ + enum SelectMode + { + STATUS_SEEK_PERIAPSIS, /**< enum value, looking for click to set periapsis. */ + STATUS_SEEK_APOAPSIS, /**< enum value, looking for click to set apoapsis. */ + STATUS_SEEK_CENTROID, /**< enum value, looking for click to set centroid. */ + STATUS_SEEK_A, /**< enum value, looking for click to set a. */ + STATUS_SEEK_B, /**< enum value, looking for click to set b. */ + STATUS_Close /**< enum value, finalizing and saving ellipse. */ }; /// Construction methods, describes the method used to construct the ellipse - enum ConstructionMethod { - CENTER_PERIAPSIS_B, /**< enum value, click on center, then periapsis, then b point. */ - PERIAPSIS_APOAPSIS_B /**< enum value, click on periapsis, then apoapsis, then b point. */ + enum ConstructionMethod + { + CENTER_PERIAPSIS_B, /**< enum value, click on center, then periapsis, then b point. */ + PERIAPSIS_APOAPSIS_B /**< enum value, click on periapsis, then apoapsis, then b point. */ }; /** @@ -112,12 +125,13 @@ public: if (method == PERIAPSIS_APOAPSIS_B) { if (mode == STATUS_SEEK_PERIAPSIS) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f), AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr1); return; } - } else if (mode == STATUS_SEEK_APOAPSIS) { + } + else if (mode == STATUS_SEEK_APOAPSIS) { solveEllipse(onSketchPos); approximateEllipse(); @@ -133,12 +147,13 @@ public: drawEdit(editCurve); // Suggestions for ellipse and curves are disabled because many tangent constraints // need an intermediate point or line. - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f), AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr2); return; } - } else if (mode == STATUS_SEEK_B) { + } + else if (mode == STATUS_SEEK_B) { solveEllipse(onSketchPos); approximateEllipse(); @@ -152,20 +167,23 @@ public: } drawEdit(editCurve); - if (seekAutoConstraint(sugConstr3, onSketchPos, Base::Vector2d(0.f,0.f), - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr3, onSketchPos, Base::Vector2d(0.f, 0.f), AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr3); return; } } - } else { // method is CENTER_PERIAPSIS_B + } + else {// method is CENTER_PERIAPSIS_B if (mode == STATUS_SEEK_CENTROID) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { // TODO: ellipse prio 1 + if (seekAutoConstraint( + sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) {// TODO: ellipse prio 1 renderSuggestConstraintsCursor(sugConstr1); return; } - } else if (mode == STATUS_SEEK_PERIAPSIS) { + } + else if (mode == STATUS_SEEK_PERIAPSIS) { solveEllipse(onSketchPos); approximateEllipse(); @@ -179,12 +197,13 @@ public: } drawEdit(editCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, onSketchPos - centroid, - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr2, onSketchPos, onSketchPos - centroid, AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr2); return; } - } else if ((mode == STATUS_SEEK_A) || (mode == STATUS_SEEK_B)) { + } + else if ((mode == STATUS_SEEK_A) || (mode == STATUS_SEEK_B)) { solveEllipse(onSketchPos); approximateEllipse(); @@ -198,8 +217,8 @@ public: } drawEdit(editCurve); - if (seekAutoConstraint(sugConstr3, onSketchPos, onSketchPos - centroid, - AutoConstraint::CURVE)) { + if (seekAutoConstraint( + sugConstr3, onSketchPos, onSketchPos - centroid, AutoConstraint::CURVE)) { renderSuggestConstraintsCursor(sugConstr3); return; } @@ -229,7 +248,8 @@ public: else { mode = STATUS_Close; } - } else { // method is CENTER_PERIAPSIS_B + } + else {// method is CENTER_PERIAPSIS_B if (mode == STATUS_SEEK_CENTROID) { centroid = onSketchPos; setAngleSnapping(true, centroid); @@ -257,14 +277,16 @@ public: Q_UNUSED(onSketchPos); if (mode == STATUS_Close) { saveEllipse(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { if (constrMethod == 0) { method = CENTER_PERIAPSIS_B; mode = STATUS_SEEK_CENTROID; - } else { + } + else { method = PERIAPSIS_APOAPSIS_B; mode = STATUS_SEEK_PERIAPSIS; } @@ -283,7 +305,8 @@ private: if (constrMethod == 0) { method = CENTER_PERIAPSIS_B; mode = STATUS_SEEK_CENTROID; - } else { + } + else { method = PERIAPSIS_APOAPSIS_B; mode = STATUS_SEEK_PERIAPSIS; } @@ -295,6 +318,7 @@ private: protected: std::vector sugConstr1, sugConstr2, sugConstr3; + private: SelectMode mode; /// the method of constructing the ellipse @@ -366,7 +390,7 @@ private: void solveEllipse(Base::Vector2d onSketchPos) { const double GOLDEN_RATIO = 1.6180339887; - Base::Vector3d k(0,0,1); + Base::Vector3d k(0, 0, 1); if (method == PERIAPSIS_APOAPSIS_B) { if (mode == STATUS_SEEK_APOAPSIS) { @@ -380,16 +404,19 @@ private: centroid = periapsis + centroid; if (mode == STATUS_SEEK_APOAPSIS) { // for first step, we draw an ellipse inscribed in a golden rectangle - ratio = 1 / GOLDEN_RATIO; // ~= 0.6180339887 - e = sqrt(ratio); // ~= 0.7861513777 + ratio = 1 / GOLDEN_RATIO;// ~= 0.6180339887 + e = sqrt(ratio); // ~= 0.7861513777 b = a * ratio; } else if (mode == STATUS_SEEK_B) { - // Get the closest distance from onSketchPos to apse line, as a 'requested' value for b - Base::Vector2d cursor = Base::Vector2d(onSketchPos - f); // vector from f to cursor pos + // Get the closest distance from onSketchPos to apse line, as a 'requested' value + // for b + Base::Vector2d cursor = + Base::Vector2d(onSketchPos - f);// vector from f to cursor pos // decompose cursor with a projection, then length of w_2 will give us b Base::Vector2d w_1 = cursor; - w_1.ProjectToLine(cursor, (periapsis - apoapsis)); // projection of cursor line onto apse line + w_1.ProjectToLine( + cursor, (periapsis - apoapsis));// projection of cursor line onto apse line Base::Vector2d w_2 = (cursor - w_1); b = w_2.Length(); @@ -399,7 +426,7 @@ private: } e = sqrt(1 - ((b * b) / (a * a))); - ratio = sqrt(1 - (e*e)); + ratio = sqrt(1 - (e * e)); } ae = a * e; f = apseHat; @@ -411,7 +438,8 @@ private: phi = atan2(apseHat.y, apseHat.x); num = a * (1 - (e * e)); // The ellipse is now solved - } else { // method == CENTER_PERIAPSIS_B + } + else {// method == CENTER_PERIAPSIS_B if (mode == STATUS_SEEK_PERIAPSIS) { // solve the ellipse inscribed in a golden rectangle periapsis = onSketchPos; @@ -419,11 +447,11 @@ private: iPrime.x = periapsis.x - centroid.x; iPrime.y = periapsis.y - centroid.y; iPrime.z = 0; - jPrime = k % iPrime; // j = k cross i + jPrime = k % iPrime;// j = k cross i // these are constant for any ellipse inscribed in a golden rectangle - ratio = 1 / GOLDEN_RATIO; // ~= 0.6180339887 - e = sqrt(ratio); // ~= 0.7861513777 + ratio = 1 / GOLDEN_RATIO;// ~= 0.6180339887 + e = sqrt(ratio); // ~= 0.7861513777 b = a * ratio; ae = a * e; @@ -442,14 +470,18 @@ private: num = a * (1 - (e * e)); fixedAxisLength = a; fixedAxis = periapsis; - } else if ((mode == STATUS_SEEK_B) || (mode == STATUS_SEEK_A)) { + } + else if ((mode == STATUS_SEEK_B) || (mode == STATUS_SEEK_A)) { // while looking for the last click, we may switch back and forth // between looking for a b point and looking for periapsis, so ensure // we are in the right mode - Base::Vector2d cursor = Base::Vector2d(onSketchPos - centroid); // vector from centroid to cursor pos + Base::Vector2d cursor = + Base::Vector2d(onSketchPos - centroid);// vector from centroid to cursor pos // decompose cursor with a projection, then length of w_2 will give us b Base::Vector2d w_1 = cursor; - w_1.ProjectToLine(cursor, (fixedAxis - centroid)); // projection of cursor line onto fixed axis line + w_1.ProjectToLine( + cursor, + (fixedAxis - centroid));// projection of cursor line onto fixed axis line Base::Vector2d w_2 = (cursor - w_1); if (w_2.Length() > fixedAxisLength) { // b is fixed, we are seeking a @@ -457,16 +489,17 @@ private: jPrime.x = (fixedAxis - centroid).x; jPrime.y = (fixedAxis - centroid).y; jPrime.Normalize(); - iPrime = jPrime % k; // cross + iPrime = jPrime % k;// cross b = fixedAxisLength; a = w_2.Length(); - } else { + } + else { // a is fixed, we are seeking b mode = STATUS_SEEK_B; iPrime.x = (fixedAxis - centroid).x; iPrime.y = (fixedAxis - centroid).y; iPrime.Normalize(); - jPrime = k % iPrime; // cross + jPrime = k % iPrime;// cross a = fixedAxisLength; b = w_2.Length(); } @@ -474,7 +507,7 @@ private: periapsis.x = centroid.x + (iPrime * a).x; periapsis.y = centroid.y + (iPrime * a).y; e = sqrt(1 - ((b * b) / (a * a))); - ratio = sqrt(1 - (e*e)); + ratio = sqrt(1 - (e * e)); ae = a * e; apseHat = (periapsis - centroid); apseHat.Normalize(); @@ -509,49 +542,53 @@ private: // the semi-minor axis. double partitionAngle = (M_PI - atan2(b, ae)) / n; double radianShift = 0; - if (e > 0.8) {radianShift = (partitionAngle / 5) * 4;} - for (int i=0; i < n; i++) { + if (e > 0.8) { + radianShift = (partitionAngle / 5) * 4; + } + for (int i = 0; i < n; i++) { theta = i * partitionAngle; - if (i > 0) {theta = theta + radianShift;} + if (i > 0) { + theta = theta + radianShift; + } r = num / (1 + (e * cos(theta))); // r(pi/2) is semi-latus rectum, if we need it - pos.x = r*cos(theta+phi); // phi rotates, sin/cos translate - pos.y = r*sin(theta+phi); + pos.x = r * cos(theta + phi);// phi rotates, sin/cos translate + pos.y = r * sin(theta + phi); pos = pos + f; - posPrime.x = r*cos(theta+phi+M_PI); - posPrime.y = r*sin(theta+phi+M_PI); + posPrime.x = r * cos(theta + phi + M_PI); + posPrime.y = r * sin(theta + phi + M_PI); posPrime = posPrime + fPrime; // over the loop, loads Quadrant I points, by using f as origin editCurve[i] = pos; // over the loop, loads Quadrant III points, by using fPrime as origin - editCurve[(2*n) + i] = posPrime; + editCurve[(2 * n) + i] = posPrime; // load points with negative theta angles (i.e. cw) - if (i>0) { - pos.x = r*cos(-1*theta+phi); - pos.y = r*sin(-1*theta+phi); + if (i > 0) { + pos.x = r * cos(-1 * theta + phi); + pos.y = r * sin(-1 * theta + phi); pos = pos + f; // loads Quadrant IV points - editCurve[(4*n) - i] = pos; - posPrime.x = r*cos(-1*theta+phi+M_PI); - posPrime.y = r*sin(-1*theta+phi+M_PI); + editCurve[(4 * n) - i] = pos; + posPrime.x = r * cos(-1 * theta + phi + M_PI); + posPrime.y = r * sin(-1 * theta + phi + M_PI); posPrime = posPrime + fPrime; // loads Quadrant II points - editCurve[(2*n) - i] = posPrime; + editCurve[(2 * n) - i] = posPrime; } } // load pos & neg b points - theta = M_PI - atan2(b, ae); // the angle from f to the positive b point + theta = M_PI - atan2(b, ae);// the angle from f to the positive b point r = num / (1 + (e * cos(theta))); - pos.x = r*cos(theta+phi); - pos.y = r*sin(theta+phi); + pos.x = r * cos(theta + phi); + pos.y = r * sin(theta + phi); pos = pos + f; - editCurve[n] = pos; // positive - pos.x = r*cos(-1*theta+phi); - pos.y = r*sin(-1*theta+phi); + editCurve[n] = pos;// positive + pos.x = r * cos(-1 * theta + phi); + pos.y = r * sin(-1 * theta + phi); pos = pos + f; - editCurve[(3*n)] = pos; // negative + editCurve[(3 * n)] = pos;// negative // force the curve to be a closed shape - editCurve[(4*n)] = editCurve[0]; + editCurve[(4 * n)] = editCurve[0]; } /** @@ -578,17 +615,17 @@ private: octave << "fPrime = [" << fPrime.x << ", " << fPrime.y << "];\n"; octave << "phi = " << phi << ";\n\n"; octave << "x = ["; - for (int i=0; i < 4*n + 1; i++) { + for (int i = 0; i < 4 * n + 1; i++) { octave << editCurve[i].x; - if (i < 4*n) { + if (i < 4 * n) { octave << ", "; } } octave << "];\n"; octave << "y = ["; - for (int i=0; i < 4*n + 1; i++) { + for (int i = 0; i < 4 * n + 1; i++) { octave << editCurve[i].y; - if (i < 4*n) { + if (i < 4 * n) { octave << ", "; } } @@ -611,10 +648,14 @@ private: octave << "set (centroidVec, \"maxheadsize\", 0.01, \"color\", \"black\");\n"; octave << "bVec = quiver(0,0,positiveB(1),positiveB(2), 0);\n"; octave << "set (bVec, \"maxheadsize\", 0.01, \"color\", \"black\");\n\n"; - octave << "% Draw the local x & y basis vectors, scaled to a and b, in red and blue, respectively\n"; - octave << "xLocalVec = quiver(centroid(1),centroid(2),periapsis(1)-centroid(1),periapsis(2)-centroid(2), 0);\n"; + octave << "% Draw the local x & y basis vectors, scaled to a and b, in red and blue, " + "respectively\n"; + octave << "xLocalVec = " + "quiver(centroid(1),centroid(2),periapsis(1)-centroid(1),periapsis(2)-centroid(2)" + ", 0);\n"; octave << "set (xLocalVec, \"maxheadsize\", 0.01, \"color\", \"red\");\n"; - octave << "yLocalVec = quiver(centroid(1),centroid(2), positiveB(1)-centroid(1), positiveB(2)-centroid(2), 0);\n"; + octave << "yLocalVec = quiver(centroid(1),centroid(2), positiveB(1)-centroid(1), " + "positiveB(2)-centroid(2), 0);\n"; octave << "set (yLocalVec, \"maxheadsize\", 0.01, \"color\", \"blue\");\nhold off;\n"; qDebug() << QString::fromStdString(octave.str()); } @@ -679,12 +720,12 @@ private: /* GC_MakeEllipse requires a right-handed coordinate system, with +X * from centroid to periapsis, +Z out of the page. */ - Base::Vector3d k(0,0,1); + Base::Vector3d k(0, 0, 1); Base::Vector3d i(periapsis.x - centroid.x, periapsis.y - centroid.y, 0); - Base::Vector3d j = k % i; // j = k cross i + Base::Vector3d j = k % i;// j = k cross i double beta = 1e-7; int count = 0; - int limit = 25; // no infinite loops! + int limit = 25;// no infinite loops! bool success = false; double tempB = b; @@ -710,9 +751,9 @@ private: positiveB.y = atof(bpy); negativeB.x = atof(bnx); negativeB.y = atof(bny); - GC_MakeEllipse me(gp_Pnt(periapsis.x,periapsis.y,0), - gp_Pnt(positiveB.x,positiveB.y,0), - gp_Pnt(centroid.x,centroid.y,0)); + GC_MakeEllipse me(gp_Pnt(periapsis.x, periapsis.y, 0), + gp_Pnt(positiveB.x, positiveB.y, 0), + gp_Pnt(centroid.x, centroid.y, 0)); minorLength = (negativeB - positiveB).Length(); count++; success = me.IsDone() && (minorLength + beta < majorLength); @@ -732,28 +773,35 @@ private: fPrime.Scale(-1 * ae); fPrime = centroid + fPrime; - int currentgeoid = getHighestCurveIndex(); // index of the ellipse we just created + int currentgeoid = getHighestCurveIndex();// index of the ellipse we just created try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch ellipse")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.Ellipse" - "(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", - periapsis.x, periapsis.y, - positiveB.x, positiveB.y, - centroid.x, centroid.y, - geometryCreationMode==Construction?"True":"False"); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.Ellipse" + "(App.Vector(%f,%f,0),App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", + periapsis.x, + periapsis.y, + positiveB.x, + positiveB.y, + centroid.x, + centroid.y, + geometryCreationMode == Construction ? "True" : "False"); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add an ellipse")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add an ellipse")); Gui::Command::abortCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); return; } @@ -791,41 +839,42 @@ private: } } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); // This code enables the continuous creation mode. if (constrMethod == 0) { method = CENTER_PERIAPSIS_B; mode = STATUS_SEEK_CENTROID; - } else { + } + else { method = PERIAPSIS_APOAPSIS_B; mode = STATUS_SEEK_PERIAPSIS; } editCurve.clear(); drawEdit(editCurve); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. editCurve.resize(33); applyCursor(); /* It is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } - } }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerEllipse_H - +#endif// SKETCHERGUI_DrawSketchHandlerEllipse_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h index ff968064c9..f0ec6cd42d 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h @@ -28,13 +28,15 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class ExtendSelection : public Gui::SelectionFilterGate +class ExtendSelection: public Gui::SelectionFilterGate { App::DocumentObject* object; + public: explicit ExtendSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()) @@ -42,7 +44,7 @@ public: , disabled(false) {} - bool allow(App::Document * /*pDoc*/, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) { if (pObj != this->object) return false; @@ -53,18 +55,20 @@ public: std::string element(sSubName); if (element.substr(0, 4) == "Edge") { int GeoId = std::atoi(element.substr(4, 4000).c_str()) - 1; - Sketcher::SketchObject *Sketch = static_cast(object); - const Part::Geometry *geom = Sketch->getGeometry(GeoId); - if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() || - geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + Sketcher::SketchObject* Sketch = static_cast(object); + const Part::Geometry* geom = Sketch->getGeometry(GeoId); + if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() + || geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) return true; } return false; } - void setDisabled(bool isDisabled) { + void setDisabled(bool isDisabled) + { disabled = isDisabled; } + protected: bool disabled; }; @@ -79,13 +83,15 @@ public: , BaseGeoId(-1) , ExtendFromStart(false) , SavedExtendFromStart(false) - , Increment(0) {} + , Increment(0) + {} virtual ~DrawSketchHandlerExtend() { Gui::Selection().rmvSelectionGate(); } - enum SelectMode { + enum SelectMode + { STATUS_SEEK_First, STATUS_SEEK_Second, }; @@ -94,9 +100,10 @@ public: { Q_UNUSED(onSketchPos); if (Mode == STATUS_SEEK_Second) { - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(BaseGeoId); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(BaseGeoId); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geom); + const Part::GeomLineSegment* lineSeg = + static_cast(geom); // project point to the existing curve Base::Vector3d start3d = lineSeg->getStartPoint(); Base::Vector3d end3d = lineSeg->getEndPoint(); @@ -110,7 +117,8 @@ public: if (recenteredPoint.Length() < recenteredPoint.Distance(recenteredLine)) { EditCurve[0] = startPoint + projection; EditCurve[1] = endPoint; - } else { + } + else { EditCurve[0] = startPoint; EditCurve[1] = startPoint + projection; } @@ -122,18 +130,25 @@ public: * expand. */ bool inCurve = (projection.Length() < recenteredLine.Length() - && projection.GetAngle(recenteredLine) < 0.1); // Two possible values here, M_PI and 0, but 0.1 is to avoid floating point problems. + && projection.GetAngle(recenteredLine) + < 0.1);// Two possible values here, M_PI and 0, but 0.1 is to + // avoid floating point problems. if (inCurve) { - Increment = SavedExtendFromStart ? -1 * projection.Length() : projection.Length() - recenteredLine.Length(); + Increment = SavedExtendFromStart + ? -1 * projection.Length() + : projection.Length() - recenteredLine.Length(); ExtendFromStart = SavedExtendFromStart; - } else { - ExtendFromStart = onSketchPos.Distance(startPoint) < onSketchPos.Distance(endPoint); - Increment = ExtendFromStart ? projection.Length() : projection.Length() - recenteredLine.Length(); + } + else { + ExtendFromStart = + onSketchPos.Distance(startPoint) < onSketchPos.Distance(endPoint); + Increment = ExtendFromStart ? projection.Length() + : projection.Length() - recenteredLine.Length(); } drawEdit(EditCurve); - - } else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); + } + else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = static_cast(geom); Base::Vector3d center = arc->getCenter(); double radius = arc->getRadius(); @@ -141,11 +156,13 @@ public: arc->getRange(start, end, true); double arcAngle = end - start; - Base::Vector2d angle = Base::Vector2d(onSketchPos.x - center.x, onSketchPos.y - center.y); + Base::Vector2d angle = + Base::Vector2d(onSketchPos.x - center.x, onSketchPos.y - center.y); Base::Vector2d startAngle = Base::Vector2d(cos(start), sin(start)); Base::Vector2d endAngle = Base::Vector2d(cos(end), sin(end)); - Base::Vector2d arcHalf = Base::Vector2d(cos(start + arcAngle/ 2.0), sin(start+ arcAngle / 2.0)); + Base::Vector2d arcHalf = + Base::Vector2d(cos(start + arcAngle / 2.0), sin(start + arcAngle / 2.0)); double angleToEndAngle = angle.GetAngle(endAngle); double angleToStartAngle = angle.GetAngle(startAngle); @@ -157,46 +174,55 @@ public: bool isCCWFromStart = crossProduct(angle, startAngle) < 0; if (outOfArc) { if (isCCWFromStart) { - modStartAngle -= 2*M_PI - angleToStartAngle; - modArcAngle += 2*M_PI - angleToStartAngle; - } else { + modStartAngle -= 2 * M_PI - angleToStartAngle; + modArcAngle += 2 * M_PI - angleToStartAngle; + } + else { modStartAngle -= angleToStartAngle; modArcAngle += angleToStartAngle; } - } else { + } + else { if (isCCWFromStart) { modStartAngle += angleToStartAngle; modArcAngle -= angleToStartAngle; - } else { - modStartAngle += 2*M_PI - angleToStartAngle; - modArcAngle -= 2*M_PI - angleToStartAngle; + } + else { + modStartAngle += 2 * M_PI - angleToStartAngle; + modArcAngle -= 2 * M_PI - angleToStartAngle; } } - } else { + } + else { bool isCWFromEnd = crossProduct(angle, endAngle) >= 0; if (outOfArc) { if (isCWFromEnd) { - modArcAngle += 2*M_PI - angleToEndAngle; - } else { + modArcAngle += 2 * M_PI - angleToEndAngle; + } + else { modArcAngle += angleToEndAngle; } - } else { + } + else { if (isCWFromEnd) { modArcAngle -= angleToEndAngle; - } else { - modArcAngle -= 2*M_PI - angleToEndAngle; + } + else { + modArcAngle -= 2 * M_PI - angleToEndAngle; } } } Increment = modArcAngle - (end - start); for (int i = 0; i < 31; i++) { - double angle = modStartAngle + i * modArcAngle/30.0; - EditCurve[i] = Base::Vector2d(center.x + radius * cos(angle), center.y + radius * sin(angle)); + double angle = modStartAngle + i * modArcAngle / 30.0; + EditCurve[i] = Base::Vector2d(center.x + radius * cos(angle), + center.y + radius * sin(angle)); } drawEdit(EditCurve); } int curveId = getPreselectCurve(); - if (BaseGeoId != curveId && seekAutoConstraint(SugConstr, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (BaseGeoId != curveId + && seekAutoConstraint(SugConstr, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(SugConstr); return; } @@ -215,76 +241,95 @@ public: if (Mode == STATUS_SEEK_First) { BaseGeoId = getPreselectCurve(); if (BaseGeoId > -1) { - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(BaseGeoId); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(BaseGeoId); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *seg = static_cast(geom); + const Part::GeomLineSegment* seg = + static_cast(geom); Base::Vector3d start3d = seg->getStartPoint(); Base::Vector3d end3d = seg->getEndPoint(); Base::Vector2d start = Base::Vector2d(start3d.x, start3d.y); Base::Vector2d end = Base::Vector2d(end3d.x, end3d.y); - SavedExtendFromStart = (onSketchPos.Distance(start) < onSketchPos.Distance(end)); + SavedExtendFromStart = + (onSketchPos.Distance(start) < onSketchPos.Distance(end)); ExtendFromStart = SavedExtendFromStart; Mode = STATUS_SEEK_Second; - } else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geom); + } + else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geom); double start, end; arc->getRange(start, end, true); Base::Vector3d center = arc->getCenter(); - Base::Vector2d angle = Base::Vector2d(onSketchPos.x - center.x, onSketchPos.y - center.y); + Base::Vector2d angle = + Base::Vector2d(onSketchPos.x - center.x, onSketchPos.y - center.y); double angleToStart = angle.GetAngle(Base::Vector2d(cos(start), sin(start))); double angleToEnd = angle.GetAngle(Base::Vector2d(cos(end), sin(end))); - ExtendFromStart = (angleToStart < angleToEnd); // move start point if closer to angle than end point + ExtendFromStart = + (angleToStart + < angleToEnd);// move start point if closer to angle than end point EditCurve.resize(31); Mode = STATUS_SEEK_Second; } filterGate->setDisabled(true); } - } else if (Mode == STATUS_SEEK_Second) { + } + else if (Mode == STATUS_SEEK_Second) { try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Extend edge")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "extend(%d, %f, %d)\n", // GeoId, increment, PointPos - BaseGeoId, Increment, ExtendFromStart ? static_cast(Sketcher::PointPos::start) : static_cast(Sketcher::PointPos::end)); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "extend(%d, %f, %d)\n",// GeoId, increment, PointPos + BaseGeoId, + Increment, + ExtendFromStart ? static_cast(Sketcher::PointPos::start) + : static_cast(Sketcher::PointPos::end)); Gui::Command::commitCommand(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool autoRecompute = hGrp->GetBool("AutoRecompute",false); - if(autoRecompute) + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool autoRecompute = hGrp->GetBool("AutoRecompute", false); + if (autoRecompute) Gui::Command::updateActive(); // constrain chosen point if (!SugConstr.empty()) { - createAutoConstraints(SugConstr, BaseGeoId, (ExtendFromStart) ? Sketcher::PointPos::start : Sketcher::PointPos::end); + createAutoConstraints(SugConstr, + BaseGeoId, + (ExtendFromStart) ? Sketcher::PointPos::start + : Sketcher::PointPos::end); SugConstr.clear(); } - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; filterGate->setDisabled(false); EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ - } else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ + } + else { + sketchgui->purgeHandler();// no code after this line, Handler get deleted in + // ViewProvider } } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to extend edge")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to extend edge")); Gui::Command::abortCommand(); } - - } else { // exit extension tool if user clicked on empty space + } + else {// exit extension tool if user clicked on empty space BaseGeoId = -1; - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } return true; } @@ -298,7 +343,8 @@ private: Gui::Selection().addSelectionGate(filterGate); } - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Extension"); } @@ -307,20 +353,20 @@ protected: std::vector EditCurve; int BaseGeoId; ExtendSelection* filterGate = nullptr; - bool ExtendFromStart; // if true, extend from start, else extend from end (circle only) + bool ExtendFromStart;// if true, extend from start, else extend from end (circle only) bool SavedExtendFromStart; double Increment; std::vector SugConstr; private: - int crossProduct(Base::Vector2d &vec1, Base::Vector2d &vec2) { + int crossProduct(Base::Vector2d& vec1, Base::Vector2d& vec2) + { return vec1.x * vec2.y - vec1.y * vec2.x; } }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerExtend_H - +#endif// SKETCHERGUI_DrawSketchHandlerExtend_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h index 4fe78ba92a..bddfc8dd4f 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h @@ -28,65 +28,73 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class ExternalSelection : public Gui::SelectionFilterGate +class ExternalSelection: public Gui::SelectionFilterGate { App::DocumentObject* object; + public: explicit ExternalSelection(App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()), object(obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) {} - bool allow(App::Document *pDoc, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) { - Sketcher::SketchObject *sketch = static_cast(object); + Sketcher::SketchObject* sketch = static_cast(object); this->notAllowedReason = ""; Sketcher::SketchObject::eReasonList msg; - if (!sketch->isExternalAllowed(pDoc, pObj, &msg)){ - switch(msg){ - case Sketcher::SketchObject::rlCircularReference: - this->notAllowedReason = QT_TR_NOOP("Linking this will cause circular dependency."); - break; - case Sketcher::SketchObject::rlOtherDoc: - this->notAllowedReason = QT_TR_NOOP("This object is in another document."); - break; - case Sketcher::SketchObject::rlOtherBody: - this->notAllowedReason = QT_TR_NOOP("This object belongs to another body, can't link."); - break; - case Sketcher::SketchObject::rlOtherPart: - this->notAllowedReason = QT_TR_NOOP("This object belongs to another part, can't link."); - break; - default: - break; + if (!sketch->isExternalAllowed(pDoc, pObj, &msg)) { + switch (msg) { + case Sketcher::SketchObject::rlCircularReference: + this->notAllowedReason = + QT_TR_NOOP("Linking this will cause circular dependency."); + break; + case Sketcher::SketchObject::rlOtherDoc: + this->notAllowedReason = QT_TR_NOOP("This object is in another document."); + break; + case Sketcher::SketchObject::rlOtherBody: + this->notAllowedReason = + QT_TR_NOOP("This object belongs to another body, can't link."); + break; + case Sketcher::SketchObject::rlOtherPart: + this->notAllowedReason = + QT_TR_NOOP("This object belongs to another part, can't link."); + break; + default: + break; } return false; } - // Note: its better to search the support of the sketch in case the sketch support is a base plane - //Part::BodyBase* body = Part::BodyBase::findBodyOf(sketch); - //if ( body && body->hasFeature ( pObj ) && body->isAfter ( pObj, sketch ) ) { - // Don't allow selection after the sketch in the same body - // NOTE: allowness of features in other bodies is handled by SketchObject::isExternalAllowed() - // TODO may be this should be in SketchObject::isExternalAllowed() (2015-08-07, Fat-Zer) - //return false; + // Note: its better to search the support of the sketch in case the sketch support is a base + // plane + // Part::BodyBase* body = Part::BodyBase::findBodyOf(sketch); + // if ( body && body->hasFeature ( pObj ) && body->isAfter ( pObj, sketch ) ) { + // Don't allow selection after the sketch in the same body + // NOTE: allowness of features in other bodies is handled by + // SketchObject::isExternalAllowed() + // TODO may be this should be in SketchObject::isExternalAllowed() (2015-08-07, Fat-Zer) + // return false; //} if (!sSubName || sSubName[0] == '\0') return false; std::string element(sSubName); - if ((element.size() > 4 && element.substr(0,4) == "Edge") || - (element.size() > 6 && element.substr(0,6) == "Vertex") || - (element.size() > 4 && element.substr(0,4) == "Face")) { + if ((element.size() > 4 && element.substr(0, 4) == "Edge") + || (element.size() > 6 && element.substr(0, 6) == "Vertex") + || (element.size() > 4 && element.substr(0, 4) == "Face")) { return true; } - if (pObj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) || - pObj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) + if (pObj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) + || pObj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) return true; - return false; + return false; } }; @@ -116,47 +124,53 @@ public: { Q_UNUSED(onSketchPos); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ return true; } bool onSelectionChanged(const Gui::SelectionChanges& msg) override { if (msg.Type == Gui::SelectionChanges::AddSelection) { - App::DocumentObject* obj = sketchgui->getObject()->getDocument()->getObject(msg.pObjectName); + App::DocumentObject* obj = + sketchgui->getObject()->getDocument()->getObject(msg.pObjectName); if (!obj) throw Base::ValueError("Sketcher: External geometry: Invalid object in selection"); std::string subName(msg.pSubName); - if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) || - obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId()) || - (subName.size() > 4 && subName.substr(0,4) == "Edge") || - (subName.size() > 6 && subName.substr(0,6) == "Vertex") || - (subName.size() > 4 && subName.substr(0,4) == "Face")) { + if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) + || obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId()) + || (subName.size() > 4 && subName.substr(0, 4) == "Edge") + || (subName.size() > 6 && subName.substr(0, 6) == "Vertex") + || (subName.size() > 4 && subName.substr(0, 4) == "Face")) { try { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add external geometry")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addExternal(\"%s\",\"%s\")", - msg.pObjectName, msg.pSubName); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add external geometry")); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addExternal(\"%s\",\"%s\")", + msg.pObjectName, + msg.pSubName); Gui::Command::commitCommand(); - // adding external geometry does not require a solve() per se (the DoF is the same), - // however a solve is required to update the amount of solver geometry, because we only - // redraw a changed Sketch if the solver geometry amount is the same as the SkethObject - // geometry amount (as this avoids other issues). - // This solver is a very low cost one anyway (there is actually nothing to solve). - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + // adding external geometry does not require a solve() per se (the DoF is the + // same), however a solve is required to update the amount of solver geometry, + // because we only redraw a changed Sketch if the solver geometry amount is the + // same as the SkethObject geometry amount (as this avoids other issues). This + // solver is a very low cost one anyway (there is actually nothing to solve). + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); Gui::Selection().clearSelection(); - /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + /* this is ok not to call to purgeHandler + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add external geometry")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add external geometry")); Gui::Selection().clearSelection(); Gui::Command::abortCommand(); } @@ -170,9 +184,9 @@ private: void activated() override { setAxisPickStyle(false); - Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); - Gui::View3DInventorViewer *viewer; - viewer = static_cast(mdi)->getViewer(); + Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView(); + Gui::View3DInventorViewer* viewer; + viewer = static_cast(mdi)->getViewer(); viewer->setSelectionEnabled(true); Gui::Selection().clearSelection(); @@ -180,7 +194,8 @@ private: Gui::Selection().addSelectionGate(new ExternalSelection(sketchgui->getObject())); } - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_External"); } @@ -192,8 +207,7 @@ private: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerExternal_H - +#endif// SKETCHERGUI_DrawSketchHandlerExternal_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h index ef00f9921a..ad0ebfeb2a 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h @@ -28,47 +28,50 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class FilletSelection : public Gui::SelectionFilterGate +class FilletSelection: public Gui::SelectionFilterGate { App::DocumentObject* object; + public: explicit FilletSelection(App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()), object(obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) {} - bool allow(App::Document * /*pDoc*/, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) { if (pObj != this->object) return false; if (!sSubName || sSubName[0] == '\0') return false; std::string element(sSubName); - if (element.substr(0,4) == "Edge") { - int GeoId = std::atoi(element.substr(4,4000).c_str()) - 1; - Sketcher::SketchObject *Sketch = static_cast(object); - const Part::Geometry *geom = Sketch->getGeometry(GeoId); + if (element.substr(0, 4) == "Edge") { + int GeoId = std::atoi(element.substr(4, 4000).c_str()) - 1; + Sketcher::SketchObject* Sketch = static_cast(object); + const Part::Geometry* geom = Sketch->getGeometry(GeoId); if (geom->getTypeId().isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId())) return true; } - if (element.substr(0,6) == "Vertex") { - int VtId = std::atoi(element.substr(6,4000).c_str()) - 1; - Sketcher::SketchObject *Sketch = static_cast(object); + if (element.substr(0, 6) == "Vertex") { + int VtId = std::atoi(element.substr(6, 4000).c_str()) - 1; + Sketcher::SketchObject* Sketch = static_cast(object); std::vector GeoIdList; std::vector PosIdList; Sketch->getDirectlyCoincidentPoints(VtId, GeoIdList, PosIdList); - if (GeoIdList.size() == 2 && GeoIdList[0] >= 0 && GeoIdList[1] >= 0) { - const Part::Geometry *geom1 = Sketch->getGeometry(GeoIdList[0]); - const Part::Geometry *geom2 = Sketch->getGeometry(GeoIdList[1]); - if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) + if (GeoIdList.size() == 2 && GeoIdList[0] >= 0 && GeoIdList[1] >= 0) { + const Part::Geometry* geom1 = Sketch->getGeometry(GeoIdList[0]); + const Part::Geometry* geom2 = Sketch->getGeometry(GeoIdList[1]); + if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) return true; } } - return false; + return false; } }; @@ -76,18 +79,24 @@ public: class DrawSketchHandlerFillet: public DrawSketchHandler { public: - enum FilletType { + enum FilletType + { SimpleFillet, ConstraintPreservingFillet }; - explicit DrawSketchHandlerFillet(FilletType filletType) : filletType(filletType), Mode(STATUS_SEEK_First), firstCurve(0) {} + explicit DrawSketchHandlerFillet(FilletType filletType) + : filletType(filletType) + , Mode(STATUS_SEEK_First) + , firstCurve(0) + {} virtual ~DrawSketchHandlerFillet() { Gui::Selection().rmvSelectionGate(); } - enum SelectMode{ + enum SelectMode + { STATUS_SEEK_First, STATUS_SEEK_Second }; @@ -105,29 +114,35 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { - bool construction=false; + bool construction = false; int VtId = getPreselectPoint(); if (Mode == STATUS_SEEK_First && VtId != -1) { int GeoId; - Sketcher::PointPos PosId=Sketcher::PointPos::none; - sketchgui->getSketchObject()->getGeoVertexIndex(VtId,GeoId,PosId); - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(GeoId); - if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - (PosId == Sketcher::PointPos::start || PosId == Sketcher::PointPos::end)) { + Sketcher::PointPos PosId = Sketcher::PointPos::none; + sketchgui->getSketchObject()->getGeoVertexIndex(VtId, GeoId, PosId); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(GeoId); + if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && (PosId == Sketcher::PointPos::start || PosId == Sketcher::PointPos::end)) { // guess fillet radius - double radius=-1; + double radius = -1; std::vector GeoIdList; std::vector PosIdList; - sketchgui->getSketchObject()->getDirectlyCoincidentPoints(GeoId, PosId, GeoIdList, PosIdList); - if (GeoIdList.size() == 2 && GeoIdList[0] >= 0 && GeoIdList[1] >= 0) { - const Part::Geometry *geom1 = sketchgui->getSketchObject()->getGeometry(GeoIdList[0]); - const Part::Geometry *geom2 = sketchgui->getSketchObject()->getGeometry(GeoIdList[1]); - construction=Sketcher::GeometryFacade::getConstruction(geom1) && Sketcher::GeometryFacade::getConstruction(geom2); - if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geom1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geom2); + sketchgui->getSketchObject()->getDirectlyCoincidentPoints( + GeoId, PosId, GeoIdList, PosIdList); + if (GeoIdList.size() == 2 && GeoIdList[0] >= 0 && GeoIdList[1] >= 0) { + const Part::Geometry* geom1 = + sketchgui->getSketchObject()->getGeometry(GeoIdList[0]); + const Part::Geometry* geom2 = + sketchgui->getSketchObject()->getGeometry(GeoIdList[1]); + construction = Sketcher::GeometryFacade::getConstruction(geom1) + && Sketcher::GeometryFacade::getConstruction(geom2); + if (geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geom2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = + static_cast(geom1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geom2); Base::Vector3d dir1 = lineSeg1->getEndPoint() - lineSeg1->getStartPoint(); Base::Vector3d dir2 = lineSeg2->getEndPoint() - lineSeg2->getStartPoint(); if (PosIdList[0] == Sketcher::PointPos::end) @@ -137,109 +152,130 @@ public: double l1 = dir1.Length(); double l2 = dir2.Length(); double angle = dir1.GetAngle(dir2); - radius = (l1 < l2 ? l1 : l2) * 0.2 * sin(angle/2); + radius = (l1 < l2 ? l1 : l2) * 0.2 * sin(angle / 2); } } if (radius < 0) return false; - int currentgeoid= getHighestCurveIndex(); + int currentgeoid = getHighestCurveIndex(); // create fillet at point try { bool pointFillet = (filletType == 1); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create fillet")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "fillet(%d,%d,%f,%s,%s)", GeoId, static_cast(PosId), radius, "True", - pointFillet ? "True":"False"); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "fillet(%d,%d,%f,%s,%s)", + GeoId, + static_cast(PosId), + radius, + "True", + pointFillet ? "True" : "False"); if (construction) { - Gui::cmdAppObjectArgs(sketchgui->getObject(), "toggleConstruction(%d) ", currentgeoid+1); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "toggleConstruction(%d) ", currentgeoid + 1); } Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - Gui::NotifyUserError(sketchgui->getObject(), - QT_TRANSLATE_NOOP("Notifications", "Failed to create fillet"), - e.what()); + Gui::NotifyUserError( + sketchgui->getObject(), + QT_TRANSLATE_NOOP("Notifications", "Failed to create fillet"), + e.what()); Gui::Command::abortCommand(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); } return true; } int GeoId = getPreselectCurve(); if (GeoId > -1) { - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(GeoId); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(GeoId); if (geom->getTypeId().isDerivedFrom(Part::GeomBoundedCurve::getClassTypeId())) { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { firstCurve = GeoId; firstPos = onSketchPos; Mode = STATUS_SEEK_Second; // add the line to the selection std::stringstream ss; ss << "Edge" << firstCurve + 1; - Gui::Selection().addSelection(sketchgui->getSketchObject()->getDocument()->getName() - ,sketchgui->getSketchObject()->getNameInDocument() - ,ss.str().c_str() - ,onSketchPos.x - ,onSketchPos.y - ,0.f); + Gui::Selection().addSelection( + sketchgui->getSketchObject()->getDocument()->getName(), + sketchgui->getSketchObject()->getNameInDocument(), + ss.str().c_str(), + onSketchPos.x, + onSketchPos.y, + 0.f); } - else if (Mode==STATUS_SEEK_Second) { + else if (Mode == STATUS_SEEK_Second) { int secondCurve = GeoId; Base::Vector2d secondPos = onSketchPos; Base::Vector3d refPnt1(firstPos.x, firstPos.y, 0.f); Base::Vector3d refPnt2(secondPos.x, secondPos.y, 0.f); - const Part::Geometry *geom1 = sketchgui->getSketchObject()->getGeometry(firstCurve); + const Part::Geometry* geom1 = + sketchgui->getSketchObject()->getGeometry(firstCurve); double radius = 0; - if( geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geom1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // guess fillet radius - const Part::GeomLineSegment *lineSeg1 = static_cast - (sketchgui->getSketchObject()->getGeometry(firstCurve)); - const Part::GeomLineSegment *lineSeg2 = static_cast - (sketchgui->getSketchObject()->getGeometry(secondCurve)); + const Part::GeomLineSegment* lineSeg1 = + static_cast( + sketchgui->getSketchObject()->getGeometry(firstCurve)); + const Part::GeomLineSegment* lineSeg2 = + static_cast( + sketchgui->getSketchObject()->getGeometry(secondCurve)); radius = Part::suggestFilletRadius(lineSeg1, lineSeg2, refPnt1, refPnt2); if (radius < 0) return false; - construction=Sketcher::GeometryFacade::getConstruction(lineSeg1) && Sketcher::GeometryFacade::getConstruction(lineSeg2); + construction = Sketcher::GeometryFacade::getConstruction(lineSeg1) + && Sketcher::GeometryFacade::getConstruction(lineSeg2); } - else { // other supported curves - const Part::Geometry *geo1 = static_cast - (sketchgui->getSketchObject()->getGeometry(firstCurve)); - const Part::Geometry *geo2 = static_cast - (sketchgui->getSketchObject()->getGeometry(secondCurve)); + else {// other supported curves + const Part::Geometry* geo1 = static_cast( + sketchgui->getSketchObject()->getGeometry(firstCurve)); + const Part::Geometry* geo2 = static_cast( + sketchgui->getSketchObject()->getGeometry(secondCurve)); - construction=Sketcher::GeometryFacade::getConstruction(geo1) && Sketcher::GeometryFacade::getConstruction(geo2); + construction = Sketcher::GeometryFacade::getConstruction(geo1) + && Sketcher::GeometryFacade::getConstruction(geo2); } - int currentgeoid= getHighestCurveIndex(); + int currentgeoid = getHighestCurveIndex(); // create fillet between lines try { bool pointFillet = (filletType == 1); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create fillet")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "fillet(%d,%d,App.Vector(%f,%f,0),App.Vector(%f,%f,0),%f,%s,%s)", - firstCurve, secondCurve, - firstPos.x, firstPos.y, - secondPos.x, secondPos.y, radius, - "True", pointFillet ? "True":"False"); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "fillet(%d,%d,App.Vector(%f,%f,0),App.Vector(%f,%f,0),%f,%s,%s)", + firstCurve, + secondCurve, + firstPos.x, + firstPos.y, + secondPos.x, + secondPos.y, + radius, + "True", + pointFillet ? "True" : "False"); Gui::Command::commitCommand(); } catch (const Base::CADKernelError& e) { - if(e.getTranslatable()) { + if (e.getTranslatable()) { Gui::TranslatedUserError(sketchgui, - QObject::tr("CAD Kernel Error"), - QObject::tr(e.getMessage().c_str())); + QObject::tr("CAD Kernel Error"), + QObject::tr(e.getMessage().c_str())); } Gui::Selection().clearSelection(); Gui::Command::abortCommand(); @@ -247,18 +283,18 @@ public: } catch (const Base::ValueError& e) { Gui::TranslatedUserError(sketchgui, - QObject::tr("Value Error"), - QObject::tr(e.getMessage().c_str())); + QObject::tr("Value Error"), + QObject::tr(e.getMessage().c_str())); Gui::Selection().clearSelection(); Gui::Command::abortCommand(); Mode = STATUS_SEEK_First; } - tryAutoRecompute(static_cast(sketchgui->getObject())); + tryAutoRecompute(static_cast(sketchgui->getObject())); - if(construction) { - Gui::cmdAppObjectArgs(sketchgui->getObject(), "toggleConstruction(%d) ", - currentgeoid+1); + if (construction) { + Gui::cmdAppObjectArgs( + sketchgui->getObject(), "toggleConstruction(%d) ", currentgeoid + 1); } @@ -268,8 +304,9 @@ public: } } - if (VtId < 0 && GeoId < 0) // exit the fillet tool if the user clicked on empty space - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + if (VtId < 0 && GeoId < 0)// exit the fillet tool if the user clicked on empty space + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider return true; } @@ -289,8 +326,7 @@ protected: Base::Vector2d firstPos; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerFillet_H - +#endif// SKETCHERGUI_DrawSketchHandlerFillet_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h index 060a46f365..b805cee998 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h @@ -27,34 +27,40 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp class DrawSketchHandlerLine: public DrawSketchHandler { public: - DrawSketchHandlerLine():Mode(STATUS_SEEK_First),EditCurve(2){} - virtual ~DrawSketchHandlerLine(){} + DrawSketchHandlerLine() + : Mode(STATUS_SEEK_First) + , EditCurve(2) + {} + virtual ~DrawSketchHandlerLine() + {} /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_End }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second){ + else if (Mode == STATUS_SEEK_Second) { float length = (onSketchPos - EditCurve[0]).Length(); - float angle = (onSketchPos - EditCurve[0]).GetAngle(Base::Vector2d(1.f,0.f)); + float angle = (onSketchPos - EditCurve[0]).GetAngle(Base::Vector2d(1.f, 0.f)); if (showCursorCoords()) { SbString text; std::string lengthString = lengthToDisplayFormat(length, 1); @@ -75,7 +81,7 @@ public: bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { EditCurve[0] = onSketchPos; setAngleSnapping(true, EditCurve[0]); @@ -93,35 +99,46 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (Mode==STATUS_End){ + if (Mode == STATUS_End) { unsetCursor(); resetPositionText(); try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch line")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", - EditCurve[0].x,EditCurve[0].y,EditCurve[1].x,EditCurve[1].y, - geometryCreationMode==Construction?"True":"False"); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", + EditCurve[0].x, + EditCurve[0].y, + EditCurve[1].x, + EditCurve[1].y, + geometryCreationMode == Construction ? "True" : "False"); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add line")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add line")); Gui::Command::abortCommand(); } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool avoidredundant = sketchgui->AvoidRedundant.getValue() && sketchgui->Autoconstraints.getValue(); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool avoidredundant = + sketchgui->AvoidRedundant.getValue() && sketchgui->Autoconstraints.getValue(); - if(avoidredundant) - removeRedundantHorizontalVertical(static_cast(sketchgui->getObject()),sugConstr1,sugConstr2); + if (avoidredundant) + removeRedundantHorizontalVertical( + static_cast(sketchgui->getObject()), + sugConstr1, + sugConstr2); // add auto constraints for the line segment start if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); + createAutoConstraints( + sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr1.clear(); } @@ -131,31 +148,32 @@ public: sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); EditCurve.clear(); drawEdit(EditCurve); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.resize(2); applyCursor(); /* It is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; } private: - QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Line"); @@ -167,8 +185,7 @@ protected: std::vector sugConstr1, sugConstr2; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerLine_H - +#endif// SKETCHERGUI_DrawSketchHandlerLine_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h index b2b673daa5..c801e652ac 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h @@ -23,42 +23,46 @@ #ifndef SKETCHERGUI_DrawSketchHandlerLineSet_H #define SKETCHERGUI_DrawSketchHandlerLineSet_H -#include #include +#include #include #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp class DrawSketchHandlerLineSet: public DrawSketchHandler { public: DrawSketchHandlerLineSet() - : Mode(STATUS_SEEK_First), SegmentMode(SEGMENT_MODE_Line) - , TransitionMode(TRANSITION_MODE_Free) - , SnapMode(SNAP_MODE_Free) - , suppressTransition(false) - , EditCurve(2) - , firstCurve(-1) - , previousCurve(-1) - , firstPosId(Sketcher::PointPos::none) - , previousPosId(Sketcher::PointPos::none) - , startAngle(0) - , endAngle(0) - , arcRadius(0) - , firstsegment(true) {} + : Mode(STATUS_SEEK_First) + , SegmentMode(SEGMENT_MODE_Line) + , TransitionMode(TRANSITION_MODE_Free) + , SnapMode(SNAP_MODE_Free) + , suppressTransition(false) + , EditCurve(2) + , firstCurve(-1) + , previousCurve(-1) + , firstPosId(Sketcher::PointPos::none) + , previousPosId(Sketcher::PointPos::none) + , startAngle(0) + , endAngle(0) + , arcRadius(0) + , firstsegment(true) + {} virtual ~DrawSketchHandlerLineSet() = default; /// mode table - enum SELECT_MODE { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum SELECT_MODE + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_Do, STATUS_Close }; @@ -86,7 +90,7 @@ public: void registerPressedKey(bool pressed, int key) override { if (Mode != STATUS_SEEK_Second) - return; // SegmentMode can be changed only in STATUS_SEEK_Second mode + return;// SegmentMode can be changed only in STATUS_SEEK_Second mode if (key == SoKeyboardEvent::M && pressed && previousCurve != -1) { // loop through the following modes: @@ -101,50 +105,51 @@ public: Base::Vector2d onSketchPos; if (SegmentMode == SEGMENT_MODE_Line) - onSketchPos = EditCurve[EditCurve.size()-1]; + onSketchPos = EditCurve[EditCurve.size() - 1]; else onSketchPos = EditCurve[29]; - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(previousCurve); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(previousCurve); if (SegmentMode == SEGMENT_MODE_Line) { switch (TransitionMode) { case TRANSITION_MODE_Free: - if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // 3rd mode + if (geom->getTypeId() + == Part::GeomArcOfCircle::getClassTypeId()) {// 3rd mode SegmentMode = SEGMENT_MODE_Arc; TransitionMode = TRANSITION_MODE_Tangent; } - else // 1st mode + else// 1st mode TransitionMode = TRANSITION_MODE_Perpendicular_L; break; - case TRANSITION_MODE_Perpendicular_L: // 2nd mode + case TRANSITION_MODE_Perpendicular_L:// 2nd mode if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) TransitionMode = TRANSITION_MODE_Free; else TransitionMode = TRANSITION_MODE_Tangent; break; case TRANSITION_MODE_Tangent: - if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) // 1st mode + if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId())// 1st mode TransitionMode = TRANSITION_MODE_Perpendicular_L; - else { // 3rd mode + else {// 3rd mode SegmentMode = SEGMENT_MODE_Arc; TransitionMode = TRANSITION_MODE_Tangent; } break; - default: // unexpected mode + default:// unexpected mode TransitionMode = TRANSITION_MODE_Free; break; } } else { switch (TransitionMode) { - case TRANSITION_MODE_Tangent: // 4th mode + case TRANSITION_MODE_Tangent:// 4th mode TransitionMode = TRANSITION_MODE_Perpendicular_L; break; - case TRANSITION_MODE_Perpendicular_L: // 5th mode + case TRANSITION_MODE_Perpendicular_L:// 5th mode TransitionMode = TRANSITION_MODE_Perpendicular_R; break; - default: // 6th mode (Perpendicular_R) + unexpected mode + default:// 6th mode (Perpendicular_R) + unexpected mode SegmentMode = SEGMENT_MODE_Line; if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) TransitionMode = TRANSITION_MODE_Tangent; @@ -158,25 +163,25 @@ public: EditCurve.resize(TransitionMode == TRANSITION_MODE_Free ? 2 : 3); else EditCurve.resize(32); - mouseMove(onSketchPos); // trigger an update of EditCurve + mouseMove(onSketchPos);// trigger an update of EditCurve } } void mouseMove(Base::Vector2d onSketchPos) override { suppressTransition = false; - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second){ + else if (Mode == STATUS_SEEK_Second) { if (SegmentMode == SEGMENT_MODE_Line) { - EditCurve[EditCurve.size()-1] = onSketchPos; + EditCurve[EditCurve.size() - 1] = onSketchPos; if (TransitionMode == TRANSITION_MODE_Tangent) { - Base::Vector2d Tangent(dirVec.x,dirVec.y); + Base::Vector2d Tangent(dirVec.x, dirVec.y); EditCurve[1].ProjectToLine(EditCurve[2] - EditCurve[0], Tangent); if (EditCurve[1] * Tangent < 0) { EditCurve[1] = EditCurve[2]; @@ -185,9 +190,9 @@ public: else EditCurve[1] = EditCurve[0] + EditCurve[1]; } - else if (TransitionMode == TRANSITION_MODE_Perpendicular_L || - TransitionMode == TRANSITION_MODE_Perpendicular_R) { - Base::Vector2d Perpendicular(-dirVec.y,dirVec.x); + else if (TransitionMode == TRANSITION_MODE_Perpendicular_L + || TransitionMode == TRANSITION_MODE_Perpendicular_R) { + Base::Vector2d Perpendicular(-dirVec.y, dirVec.x); EditCurve[1].ProjectToLine(EditCurve[2] - EditCurve[0], Perpendicular); EditCurve[1] = EditCurve[0] + EditCurve[1]; } @@ -195,7 +200,7 @@ public: drawEdit(EditCurve); float length = (EditCurve[1] - EditCurve[0]).Length(); - float angle = (EditCurve[1] - EditCurve[0]).GetAngle(Base::Vector2d(1.f,0.f)); + float angle = (EditCurve[1] - EditCurve[0]).GetAngle(Base::Vector2d(1.f, 0.f)); if (showCursorCoords()) { SbString text; @@ -214,61 +219,63 @@ public: } else if (SegmentMode == SEGMENT_MODE_Arc) { - if(QApplication::keyboardModifiers() == Qt::ControlModifier) + if (QApplication::keyboardModifiers() == Qt::ControlModifier) SnapMode = SNAP_MODE_45Degree; else SnapMode = SNAP_MODE_Free; Base::Vector2d Tangent; - if (TransitionMode == TRANSITION_MODE_Tangent) - Tangent = Base::Vector2d(dirVec.x,dirVec.y); - else if (TransitionMode == TRANSITION_MODE_Perpendicular_L) - Tangent = Base::Vector2d(-dirVec.y,dirVec.x); - else if (TransitionMode == TRANSITION_MODE_Perpendicular_R) - Tangent = Base::Vector2d(dirVec.y,-dirVec.x); + if (TransitionMode == TRANSITION_MODE_Tangent) + Tangent = Base::Vector2d(dirVec.x, dirVec.y); + else if (TransitionMode == TRANSITION_MODE_Perpendicular_L) + Tangent = Base::Vector2d(-dirVec.y, dirVec.x); + else if (TransitionMode == TRANSITION_MODE_Perpendicular_R) + Tangent = Base::Vector2d(dirVec.y, -dirVec.x); double theta = Tangent.GetAngle(onSketchPos - EditCurve[0]); - arcRadius = (onSketchPos - EditCurve[0]).Length()/(2.0*sin(theta)); + arcRadius = (onSketchPos - EditCurve[0]).Length() / (2.0 * sin(theta)); // At this point we need a unit normal vector pointing towards // the center of the arc we are drawing. Derivation of the formula - // used here can be found at http://people.richland.edu/james/lecture/m116/matrices/area.html + // used here can be found at + // http://people.richland.edu/james/lecture/m116/matrices/area.html double x1 = EditCurve[0].x; double y1 = EditCurve[0].y; double x2 = x1 + Tangent.x; double y2 = y1 + Tangent.y; double x3 = onSketchPos.x; double y3 = onSketchPos.y; - if ((x2*y3-x3*y2)-(x1*y3-x3*y1)+(x1*y2-x2*y1) > 0) + if ((x2 * y3 - x3 * y2) - (x1 * y3 - x3 * y1) + (x1 * y2 - x2 * y1) > 0) arcRadius *= -1; if (boost::math::isnan(arcRadius) || boost::math::isinf(arcRadius)) arcRadius = 0.f; - CenterPoint = EditCurve[0] + Base::Vector2d(arcRadius * Tangent.y, -arcRadius * Tangent.x); + CenterPoint = + EditCurve[0] + Base::Vector2d(arcRadius * Tangent.y, -arcRadius * Tangent.x); double rx = EditCurve[0].x - CenterPoint.x; double ry = EditCurve[0].y - CenterPoint.y; - startAngle = atan2(ry,rx); + startAngle = atan2(ry, rx); double rxe = onSketchPos.x - CenterPoint.x; double rye = onSketchPos.y - CenterPoint.y; - double arcAngle = atan2(-rxe*ry + rye*rx, rxe*rx + rye*ry); + double arcAngle = atan2(-rxe * ry + rye * rx, rxe * rx + rye * ry); if (boost::math::isnan(arcAngle) || boost::math::isinf(arcAngle)) arcAngle = 0.f; if (arcRadius >= 0 && arcAngle > 0) - arcAngle -= 2*M_PI; + arcAngle -= 2 * M_PI; if (arcRadius < 0 && arcAngle < 0) - arcAngle += 2*M_PI; + arcAngle += 2 * M_PI; if (SnapMode == SNAP_MODE_45Degree) - arcAngle = round(arcAngle / (M_PI/4)) * M_PI/4; + arcAngle = round(arcAngle / (M_PI / 4)) * M_PI / 4; endAngle = startAngle + arcAngle; - for (int i=1; i <= 29; i++) { - double angle = i*arcAngle/29.0; + for (int i = 1; i <= 29; i++) { + double angle = i * arcAngle / 29.0; double dx = rx * cos(angle) - ry * sin(angle); double dy = rx * sin(angle) + ry * cos(angle); EditCurve[i] = Base::Vector2d(CenterPoint.x + dx, CenterPoint.y + dy); @@ -287,7 +294,7 @@ public: setPositionText(onSketchPos, text); } - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr2); return; } @@ -300,28 +307,31 @@ public: { if (Mode == STATUS_SEEK_First) { - EditCurve[0] = onSketchPos; // this may be overwritten if previousCurve is found + EditCurve[0] = onSketchPos;// this may be overwritten if previousCurve is found - virtualsugConstr1 = sugConstr1; // store original autoconstraints. + virtualsugConstr1 = sugConstr1;// store original autoconstraints. // here we check if there is a preselected point and // we set up a transition from the neighbouring segment. // (peviousCurve, previousPosId, dirVec, TransitionMode) - for (unsigned int i=0; i < sugConstr1.size(); i++) + for (unsigned int i = 0; i < sugConstr1.size(); i++) if (sugConstr1[i].Type == Sketcher::Coincident) { - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(sugConstr1[i].GeoId); - if ((geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() || - geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) && - (sugConstr1[i].PosId == Sketcher::PointPos::start || - sugConstr1[i].PosId == Sketcher::PointPos::end)) { + const Part::Geometry* geom = + sketchgui->getSketchObject()->getGeometry(sugConstr1[i].GeoId); + if ((geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() + || geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) + && (sugConstr1[i].PosId == Sketcher::PointPos::start + || sugConstr1[i].PosId == Sketcher::PointPos::end)) { previousCurve = sugConstr1[i].GeoId; previousPosId = sugConstr1[i].PosId; - updateTransitionData(previousCurve,previousPosId); // -> dirVec, EditCurve[0] + updateTransitionData(previousCurve, + previousPosId);// -> dirVec, EditCurve[0] if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { TransitionMode = TRANSITION_MODE_Tangent; SnapMode = SNAP_MODE_Free; } - sugConstr1.erase(sugConstr1.begin()+i); // actually we should clear the vector completely + sugConstr1.erase(sugConstr1.begin() + + i);// actually we should clear the vector completely break; } } @@ -344,32 +354,34 @@ public: EditCurve.clear(); drawEdit(EditCurve); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; - SegmentMode=SEGMENT_MODE_Line; - TransitionMode=TRANSITION_MODE_Free; + Mode = STATUS_SEEK_First; + SegmentMode = SEGMENT_MODE_Line; + TransitionMode = TRANSITION_MODE_Free; SnapMode = SNAP_MODE_Free; - suppressTransition=false; - firstCurve=-1; - previousCurve=-1; - firstPosId=Sketcher::PointPos::none; - previousPosId=Sketcher::PointPos::none; + suppressTransition = false; + firstCurve = -1; + previousCurve = -1; + firstPosId = Sketcher::PointPos::none; + previousPosId = Sketcher::PointPos::none; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ return true; } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui->purgeHandler();// no code after this line, Handler get deleted in + // ViewProvider return true; } } @@ -379,13 +391,15 @@ public: if (getPreselectPoint() != -1 && firstPosId != Sketcher::PointPos::none) { int GeoId; Sketcher::PointPos PosId; - sketchgui->getSketchObject()->getGeoVertexIndex(getPreselectPoint(),GeoId,PosId); - if (sketchgui->getSketchObject()->arePointsCoincident(GeoId,PosId,firstCurve,firstPosId)) + sketchgui->getSketchObject()->getGeoVertexIndex(getPreselectPoint(), GeoId, PosId); + if (sketchgui->getSketchObject()->arePointsCoincident( + GeoId, PosId, firstCurve, firstPosId)) Mode = STATUS_Close; } else if (getPreselectCross() == 0 && firstPosId != Sketcher::PointPos::none) { // close line started at root point - if (sketchgui->getSketchObject()->arePointsCoincident(-1,Sketcher::PointPos::start,firstCurve,firstPosId)) + if (sketchgui->getSketchObject()->arePointsCoincident( + -1, Sketcher::PointPos::start, firstCurve, firstPosId)) Mode = STATUS_Close; } } @@ -400,112 +414,156 @@ public: // issue the geometry try { // open the transaction - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add line to sketch wire")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", - EditCurve[0].x,EditCurve[0].y,EditCurve[1].x,EditCurve[1].y, - geometryCreationMode==Construction?"True":"False"); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add line to sketch wire")); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", + EditCurve[0].x, + EditCurve[0].y, + EditCurve[1].x, + EditCurve[1].y, + geometryCreationMode == Construction ? "True" : "False"); } catch (const Base::Exception& e) { addedGeometry = false; Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add line")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add line")); Gui::Command::abortCommand(); } - firstsegment=false; + firstsegment = false; } - else if (SegmentMode == SEGMENT_MODE_Arc) { // We're dealing with an Arc + else if (SegmentMode == SEGMENT_MODE_Arc) {// We're dealing with an Arc if (!boost::math::isnormal(arcRadius)) { Mode = STATUS_SEEK_Second; return true; } try { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add arc to sketch wire")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.ArcOfCircle" + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add arc to sketch wire")); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.ArcOfCircle" "(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),%f),%f,%f),%s)", - CenterPoint.x, CenterPoint.y, std::abs(arcRadius), - std::min(startAngle,endAngle), std::max(startAngle,endAngle), - geometryCreationMode==Construction?"True":"False"); + CenterPoint.x, + CenterPoint.y, + std::abs(arcRadius), + std::min(startAngle, endAngle), + std::max(startAngle, endAngle), + geometryCreationMode == Construction ? "True" : "False"); } catch (const Base::Exception& e) { addedGeometry = false; Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); Gui::Command::abortCommand(); } - firstsegment=false; + firstsegment = false; } int lastCurve = getHighestCurveIndex(); // issue the constraint if (addedGeometry && (previousPosId != Sketcher::PointPos::none)) { - Sketcher::PointPos lastStartPosId = (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) ? - Sketcher::PointPos::end : Sketcher::PointPos::start; - Sketcher::PointPos lastEndPosId = (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) ? - Sketcher::PointPos::start : Sketcher::PointPos::end; + Sketcher::PointPos lastStartPosId = + (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) + ? Sketcher::PointPos::end + : Sketcher::PointPos::start; + Sketcher::PointPos lastEndPosId = + (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) + ? Sketcher::PointPos::start + : Sketcher::PointPos::end; // in case of a tangency constraint, the coincident constraint is redundant std::string constrType = "Coincident"; if (!suppressTransition && previousCurve != -1) { if (TransitionMode == TRANSITION_MODE_Tangent) constrType = "Tangent"; - else if (TransitionMode == TRANSITION_MODE_Perpendicular_L || - TransitionMode == TRANSITION_MODE_Perpendicular_R) + else if (TransitionMode == TRANSITION_MODE_Perpendicular_L + || TransitionMode == TRANSITION_MODE_Perpendicular_R) constrType = "Perpendicular"; } - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('%s',%i,%i,%i,%i)) ", - constrType.c_str(), previousCurve, static_cast(previousPosId), lastCurve, static_cast(lastStartPosId)); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('%s',%i,%i,%i,%i)) ", + constrType.c_str(), + previousCurve, + static_cast(previousPosId), + lastCurve, + static_cast(lastStartPosId)); - if(SnapMode == SNAP_MODE_45Degree && Mode != STATUS_Close) { - // -360, -315, -270, -225, -180, -135, -90, -45, 0, 45, 90, 135, 180, 225, 270, 315, 360 - // N/A, a, perp, a, par, a,perp, a,N/A, a,perp, a, par, a,perp, a, N/A + if (SnapMode == SNAP_MODE_45Degree && Mode != STATUS_Close) { + // -360, -315, -270, -225, -180, -135, -90, -45, 0, 45, 90, 135, 180, 225, + // 270, 315, 360 + // N/A, a, perp, a, par, a,perp, a,N/A, a,perp, a, par, a,perp, + // a, N/A - // #3974: if in radians, the printf %f defaults to six decimals, which leads to loss of precision - double arcAngle = abs(round( (endAngle - startAngle) / (M_PI/4)) * 45); // in degrees + // #3974: if in radians, the printf %f defaults to six decimals, which leads to + // loss of precision + double arcAngle = + abs(round((endAngle - startAngle) / (M_PI / 4)) * 45);// in degrees - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Angle',%i,App.Units.Quantity('%f deg'))) ", - lastCurve, arcAngle); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Angle',%i,App.Units." + "Quantity('%f deg'))) ", + lastCurve, + arcAngle); } if (Mode == STATUS_Close) { // close the loop by constrain to the first curve point - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addConstraint(Sketcher.Constraint('Coincident',%i,%i,%i,%i)) ", - lastCurve,static_cast(lastEndPosId),firstCurve,static_cast(firstPosId)); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Coincident',%i,%i,%i,%i)) ", + lastCurve, + static_cast(lastEndPosId), + firstCurve, + static_cast(firstPosId)); } Gui::Command::commitCommand(); - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool avoidredundant = sketchgui->AvoidRedundant.getValue() && sketchgui->Autoconstraints.getValue(); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool avoidredundant = + sketchgui->AvoidRedundant.getValue() && sketchgui->Autoconstraints.getValue(); if (Mode == STATUS_Close) { - if(avoidredundant) { - if (SegmentMode == SEGMENT_MODE_Line) { // avoid redundant constraints. + if (avoidredundant) { + if (SegmentMode == SEGMENT_MODE_Line) {// avoid redundant constraints. if (sugConstr1.size() > 0) - removeRedundantHorizontalVertical(static_cast(sketchgui->getObject()),sugConstr1,sugConstr2); + removeRedundantHorizontalVertical( + static_cast(sketchgui->getObject()), + sugConstr1, + sugConstr2); else - removeRedundantHorizontalVertical(static_cast(sketchgui->getObject()),virtualsugConstr1,sugConstr2); + removeRedundantHorizontalVertical( + static_cast(sketchgui->getObject()), + virtualsugConstr1, + sugConstr2); } } if (!sugConstr2.empty()) { // exclude any coincidence constraints std::vector sugConstr; - for (unsigned int i=0; i < sugConstr2.size(); i++) { + for (unsigned int i = 0; i < sugConstr2.size(); i++) { if (sugConstr2[i].Type != Sketcher::Coincident) sugConstr.push_back(sugConstr2[i]); } - createAutoConstraints(sugConstr, getHighestCurveIndex(), Sketcher::PointPos::end); + createAutoConstraints( + sugConstr, getHighestCurveIndex(), Sketcher::PointPos::end); sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); unsetCursor(); @@ -513,71 +571,85 @@ public: EditCurve.clear(); drawEdit(EditCurve); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; - SegmentMode=SEGMENT_MODE_Line; - TransitionMode=TRANSITION_MODE_Free; + Mode = STATUS_SEEK_First; + SegmentMode = SEGMENT_MODE_Line; + TransitionMode = TRANSITION_MODE_Free; SnapMode = SNAP_MODE_Free; - suppressTransition=false; - firstCurve=-1; - previousCurve=-1; - firstPosId=Sketcher::PointPos::none; - previousPosId=Sketcher::PointPos::none; + suppressTransition = false; + firstCurve = -1; + previousCurve = -1; + firstPosId = Sketcher::PointPos::none; + previousPosId = Sketcher::PointPos::none; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui->purgeHandler();// no code after this line, Handler get deleted in + // ViewProvider } } else { Gui::Command::commitCommand(); // Add auto constraints - if (!sugConstr1.empty()) { // this is relevant only to the very first point - createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); + if (!sugConstr1.empty()) {// this is relevant only to the very first point + createAutoConstraints( + sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr1.clear(); } - if(avoidredundant) { - if (SegmentMode == SEGMENT_MODE_Line) { // avoid redundant constraints. + if (avoidredundant) { + if (SegmentMode == SEGMENT_MODE_Line) {// avoid redundant constraints. if (sugConstr1.size() > 0) - removeRedundantHorizontalVertical(static_cast(sketchgui->getObject()),sugConstr1,sugConstr2); + removeRedundantHorizontalVertical( + static_cast(sketchgui->getObject()), + sugConstr1, + sugConstr2); else - removeRedundantHorizontalVertical(static_cast(sketchgui->getObject()),virtualsugConstr1,sugConstr2); + removeRedundantHorizontalVertical( + static_cast(sketchgui->getObject()), + virtualsugConstr1, + sugConstr2); } } - virtualsugConstr1 = sugConstr2; // these are the initial constraints for the next iteration. + virtualsugConstr1 = + sugConstr2;// these are the initial constraints for the next iteration. if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex(), - (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) ? - Sketcher::PointPos::start : Sketcher::PointPos::end); + createAutoConstraints(sugConstr2, + getHighestCurveIndex(), + (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) + ? Sketcher::PointPos::start + : Sketcher::PointPos::end); sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); // remember the vertex for the next rounds constraint.. previousCurve = getHighestCurveIndex(); - previousPosId = (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) ? - Sketcher::PointPos::start : Sketcher::PointPos::end; // cw arcs are rendered in reverse + previousPosId = (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) + ? Sketcher::PointPos::start + : Sketcher::PointPos::end;// cw arcs are rendered in reverse // setup for the next line segment // calculate dirVec and EditCurve[0] - updateTransitionData(previousCurve,previousPosId); + updateTransitionData(previousCurve, previousPosId); applyCursor(); Mode = STATUS_SEEK_Second; @@ -593,19 +665,21 @@ public: SegmentMode = SEGMENT_MODE_Line; SnapMode = SNAP_MODE_Free; EditCurve[1] = EditCurve[0]; - mouseMove(onSketchPos); // trigger an update of EditCurve + mouseMove(onSketchPos);// trigger an update of EditCurve } } return true; } - void quit() override { + void quit() override + { // We must see if we need to create a B-spline before cancelling everything // and now just like any other Handler, - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (firstsegment) { // user when right-clicking with no segment in really wants to exit @@ -613,21 +687,21 @@ public: } else { - if(!continuousMode){ + if (!continuousMode) { DrawSketchHandler::quit(); } else { // This code disregards existing data and enables the continuous creation mode. - Mode=STATUS_SEEK_First; - SegmentMode=SEGMENT_MODE_Line; - TransitionMode=TRANSITION_MODE_Free; + Mode = STATUS_SEEK_First; + SegmentMode = SEGMENT_MODE_Line; + TransitionMode = TRANSITION_MODE_Free; SnapMode = SNAP_MODE_Free; - suppressTransition=false; - firstCurve=-1; - previousCurve=-1; - firstPosId=Sketcher::PointPos::none; - previousPosId=Sketcher::PointPos::none; - firstsegment=true; + suppressTransition = false; + firstCurve = -1; + previousCurve = -1; + firstPosId = Sketcher::PointPos::none; + previousPosId = Sketcher::PointPos::none; + firstsegment = true; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(2); @@ -637,7 +711,8 @@ public: } private: - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Create_Lineset"); } @@ -653,7 +728,8 @@ protected: int previousCurve; Sketcher::PointPos firstPosId; Sketcher::PointPos previousPosId; - // the latter stores those constraints that a first point would have been given in absence of the transition mechanism + // the latter stores those constraints that a first point would have been given in absence of + // the transition mechanism std::vector sugConstr1, sugConstr2, virtualsugConstr1; Base::Vector2d CenterPoint; @@ -662,31 +738,37 @@ protected: bool firstsegment; - void updateTransitionData(int GeoId, Sketcher::PointPos PosId) { + void updateTransitionData(int GeoId, Sketcher::PointPos PosId) + { // Use updated startPoint/endPoint as autoconstraints can modify the position - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(GeoId); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(GeoId); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geom); + const Part::GeomLineSegment* lineSeg = static_cast(geom); dirVec.Set(lineSeg->getEndPoint().x - lineSeg->getStartPoint().x, lineSeg->getEndPoint().y - lineSeg->getStartPoint().y, 0.f); if (PosId == Sketcher::PointPos::start) { dirVec *= -1; - EditCurve[0] = Base::Vector2d(lineSeg->getStartPoint().x, lineSeg->getStartPoint().y); + EditCurve[0] = + Base::Vector2d(lineSeg->getStartPoint().x, lineSeg->getStartPoint().y); } else EditCurve[0] = Base::Vector2d(lineSeg->getEndPoint().x, lineSeg->getEndPoint().y); } else if (geom->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arcSeg = static_cast(geom); + const Part::GeomArcOfCircle* arcSeg = static_cast(geom); if (PosId == Sketcher::PointPos::start) { - EditCurve[0] = Base::Vector2d(arcSeg->getStartPoint(/*emulateCCW=*/true).x,arcSeg->getStartPoint(/*emulateCCW=*/true).y); - dirVec = Base::Vector3d(0.f,0.f,-1.0) % (arcSeg->getStartPoint(/*emulateCCW=*/true)-arcSeg->getCenter()); + EditCurve[0] = Base::Vector2d(arcSeg->getStartPoint(/*emulateCCW=*/true).x, + arcSeg->getStartPoint(/*emulateCCW=*/true).y); + dirVec = Base::Vector3d(0.f, 0.f, -1.0) + % (arcSeg->getStartPoint(/*emulateCCW=*/true) - arcSeg->getCenter()); } else { - EditCurve[0] = Base::Vector2d(arcSeg->getEndPoint(/*emulateCCW=*/true).x,arcSeg->getEndPoint(/*emulateCCW=*/true).y); - dirVec = Base::Vector3d(0.f,0.f,1.0) % (arcSeg->getEndPoint(/*emulateCCW=*/true)-arcSeg->getCenter()); + EditCurve[0] = Base::Vector2d(arcSeg->getEndPoint(/*emulateCCW=*/true).x, + arcSeg->getEndPoint(/*emulateCCW=*/true).y); + dirVec = Base::Vector3d(0.f, 0.f, 1.0) + % (arcSeg->getEndPoint(/*emulateCCW=*/true) - arcSeg->getCenter()); } } dirVec.Normalize(); @@ -694,8 +776,7 @@ protected: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerLineSet_H - +#endif// SKETCHERGUI_DrawSketchHandlerLineSet_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h index 0d2bb42a38..cb2231d53e 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h @@ -28,20 +28,24 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp class DrawSketchHandlerPoint: public DrawSketchHandler { public: - DrawSketchHandlerPoint() : selectionDone(false) {} - virtual ~DrawSketchHandlerPoint() {} + DrawSketchHandlerPoint() + : selectionDone(false) + {} + virtual ~DrawSketchHandlerPoint() + {} void mouseMove(Base::Vector2d onSketchPos) override { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr); return; } @@ -58,21 +62,23 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (selectionDone){ + if (selectionDone) { unsetCursor(); resetPositionText(); try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch point")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "addGeometry(Part.Point(App.Vector(%f,%f,0)))", - EditPoint.x,EditPoint.y); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "addGeometry(Part.Point(App.Vector(%f,%f,0)))", + EditPoint.x, + EditPoint.y); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add point")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add point")); Gui::Command::abortCommand(); } @@ -83,20 +89,23 @@ public: sugConstr.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { // This code enables the continuous creation mode. applyCursor(); /* It is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -115,8 +124,7 @@ protected: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerPoint_H - +#endif// SKETCHERGUI_DrawSketchHandlerPoint_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h index 0edd33d9fb..72bed77b96 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h @@ -29,48 +29,50 @@ #include "SketcherRegularPolygonDialog.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp class DrawSketchHandlerRegularPolygon: public DrawSketchHandler { public: - explicit DrawSketchHandlerRegularPolygon( size_t nof_corners ): - Corners( nof_corners ), - AngleOfSeparation( 2.0*M_PI/static_cast(Corners) ), - cos_v( cos( AngleOfSeparation ) ), - sin_v( sin( AngleOfSeparation ) ), - Mode(STATUS_SEEK_First), - EditCurve(Corners+1) - { - } - virtual ~DrawSketchHandlerRegularPolygon(){} + explicit DrawSketchHandlerRegularPolygon(size_t nof_corners) + : Corners(nof_corners) + , AngleOfSeparation(2.0 * M_PI / static_cast(Corners)) + , cos_v(cos(AngleOfSeparation)) + , sin_v(sin(AngleOfSeparation)) + , Mode(STATUS_SEEK_First) + , EditCurve(Corners + 1) + {} + virtual ~DrawSketchHandlerRegularPolygon() + {} /// mode table - enum SelectMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum SelectMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_End }; void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { - EditCurve[0]= Base::Vector2d(onSketchPos.x, onSketchPos.y); - EditCurve[Corners]= Base::Vector2d(onSketchPos.x, onSketchPos.y); + else if (Mode == STATUS_SEEK_Second) { + EditCurve[0] = Base::Vector2d(onSketchPos.x, onSketchPos.y); + EditCurve[Corners] = Base::Vector2d(onSketchPos.x, onSketchPos.y); Base::Vector2d dV = onSketchPos - StartPos; double rx = dV.x; double ry = dV.y; - for (int i=1; i < static_cast(Corners); i++) { + for (int i = 1; i < static_cast(Corners); i++) { const double old_rx = rx; rx = cos_v * rx - sin_v * ry; ry = cos_v * ry + sin_v * old_rx; @@ -79,18 +81,18 @@ public: // Display radius for user const float radius = dV.Length(); - const float angle = ( 180.0 / M_PI ) * atan2( dV.y, dV.x ); + const float angle = (180.0 / M_PI) * atan2(dV.y, dV.x); if (showCursorCoords()) { SbString text; std::string radiusString = lengthToDisplayFormat(radius, 1); std::string angleString = angleToDisplayFormat(angle, 1); - text.sprintf(" (R%s, %s)", radiusString.c_str(), angleString.c_str()); - setPositionText(onSketchPos, text); + text.sprintf(" (R%s, %s)", radiusString.c_str(), angleString.c_str()); + setPositionText(onSketchPos, text); } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr2); return; } @@ -100,7 +102,7 @@ public: bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ + if (Mode == STATUS_SEEK_First) { StartPos = onSketchPos; Mode = STATUS_SEEK_Second; } @@ -113,63 +115,72 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (Mode==STATUS_End){ + if (Mode == STATUS_End) { unsetCursor(); resetPositionText(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add hexagon")); try { Gui::Command::doCommand(Gui::Command::Doc, - "import ProfileLib.RegularPolygon\n" - "ProfileLib.RegularPolygon.makeRegularPolygon(%s,%i,App.Vector(%f,%f,0),App.Vector(%f,%f,0),%s)", - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(), - Corners, - StartPos.x,StartPos.y,EditCurve[0].x,EditCurve[0].y, - geometryCreationMode==Construction?"True":"False"); + "import ProfileLib.RegularPolygon\n" + "ProfileLib.RegularPolygon.makeRegularPolygon(%s,%i,App." + "Vector(%f,%f,0),App.Vector(%f,%f,0),%s)", + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(), + Corners, + StartPos.x, + StartPos.y, + EditCurve[0].x, + EditCurve[0].y, + geometryCreationMode == Construction ? "True" : "False"); Gui::Command::commitCommand(); // add auto constraints at the center of the polygon if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::mid); + createAutoConstraints( + sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::mid); sugConstr1.clear(); } // add auto constraints to the last side of the polygon if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex() - 1, Sketcher::PointPos::end); + createAutoConstraints( + sugConstr2, getHighestCurveIndex() - 1, Sketcher::PointPos::end); sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add polygon")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add polygon")); Gui::Command::abortCommand(); - tryAutoRecompute(static_cast(sketchgui->getObject())); + tryAutoRecompute(static_cast(sketchgui->getObject())); } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); - if(continuousMode){ + if (continuousMode) { // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); - EditCurve.resize(Corners+1); + EditCurve.resize(Corners + 1); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -180,6 +191,7 @@ private: { return QString::fromLatin1("Sketcher_Pointer_Regular_Polygon"); } + protected: const size_t Corners; const double AngleOfSeparation; @@ -191,8 +203,7 @@ protected: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerPolygon_H - +#endif// SKETCHERGUI_DrawSketchHandlerPolygon_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h index 08f9e8e15a..fdadc2d2af 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h @@ -28,44 +28,49 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp class DrawSketchHandlerBox: public DrawSketchHandler { public: - enum ConstructionMethod { + enum ConstructionMethod + { Diagonal, CenterAndCorner }; - explicit DrawSketchHandlerBox(ConstructionMethod constrMethod = Diagonal): Mode(STATUS_SEEK_First), - EditCurve(5), - constructionMethod(constrMethod){} - virtual ~DrawSketchHandlerBox(){} + explicit DrawSketchHandlerBox(ConstructionMethod constrMethod = Diagonal) + : Mode(STATUS_SEEK_First) + , EditCurve(5) + , constructionMethod(constrMethod) + {} + virtual ~DrawSketchHandlerBox() + {} /// mode table - enum BoxMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum BoxMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_End }; public: - void mouseMove(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First) { + if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f,0.f))) { + if (seekAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f))) { renderSuggestConstraintsCursor(sugConstr1); return; } } - else if (Mode==STATUS_SEEK_Second) { - if(constructionMethod == Diagonal) { + else if (Mode == STATUS_SEEK_Second) { + if (constructionMethod == Diagonal) { float dx = onSketchPos.x - EditCurve[0].x; float dy = onSketchPos.y - EditCurve[0].y; if (showCursorCoords()) { @@ -77,14 +82,13 @@ public: } EditCurve[2] = onSketchPos; - EditCurve[1] = Base::Vector2d(onSketchPos.x ,EditCurve[0].y); - EditCurve[3] = Base::Vector2d(EditCurve[0].x,onSketchPos.y); - + EditCurve[1] = Base::Vector2d(onSketchPos.x, EditCurve[0].y); + EditCurve[3] = Base::Vector2d(EditCurve[0].x, onSketchPos.y); } else if (constructionMethod == CenterAndCorner) { float dx = onSketchPos.x - center.x; float dy = onSketchPos.y - center.y; - if (showCursorCoords()) { + if (showCursorCoords()) { SbString text; std::string dxString = lengthToDisplayFormat(dx, 1); std::string dyString = lengthToDisplayFormat(dy, 1); @@ -93,26 +97,25 @@ public: } EditCurve[0] = center - (onSketchPos - center); - EditCurve[1] = Base::Vector2d(EditCurve[0].x,onSketchPos.y); + EditCurve[1] = Base::Vector2d(EditCurve[0].x, onSketchPos.y); EditCurve[2] = onSketchPos; - EditCurve[3] = Base::Vector2d(onSketchPos.x,EditCurve[0].y); + EditCurve[3] = Base::Vector2d(onSketchPos.x, EditCurve[0].y); EditCurve[4] = EditCurve[0]; } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.0,0.0))) { + if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(0.0, 0.0))) { renderSuggestConstraintsCursor(sugConstr2); return; } - } applyCursor(); } bool pressButton(Base::Vector2d onSketchPos) override { - if (Mode==STATUS_SEEK_First){ - if(constructionMethod == Diagonal) { + if (Mode == STATUS_SEEK_First) { + if (constructionMethod == Diagonal) { EditCurve[0] = onSketchPos; EditCurve[4] = onSketchPos; } @@ -123,18 +126,18 @@ public: Mode = STATUS_SEEK_Second; } else { - if(constructionMethod == Diagonal) { + if (constructionMethod == Diagonal) { EditCurve[2] = onSketchPos; - EditCurve[1] = Base::Vector2d(onSketchPos.x ,EditCurve[0].y); - EditCurve[3] = Base::Vector2d(EditCurve[0].x,onSketchPos.y); + EditCurve[1] = Base::Vector2d(onSketchPos.x, EditCurve[0].y); + EditCurve[3] = Base::Vector2d(EditCurve[0].x, onSketchPos.y); drawEdit(EditCurve); Mode = STATUS_End; } else if (constructionMethod == CenterAndCorner) { EditCurve[0] = center - (onSketchPos - center); - EditCurve[1] = Base::Vector2d(EditCurve[0].x,onSketchPos.y); + EditCurve[1] = Base::Vector2d(EditCurve[0].x, onSketchPos.y); EditCurve[2] = onSketchPos; - EditCurve[3] = Base::Vector2d(onSketchPos.x,EditCurve[0].y); + EditCurve[3] = Base::Vector2d(onSketchPos.x, EditCurve[0].y); EditCurve[4] = EditCurve[0]; drawEdit(EditCurve); Mode = STATUS_End; @@ -146,20 +149,25 @@ public: bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); - if (Mode==STATUS_End){ + if (Mode == STATUS_End) { unsetCursor(); resetPositionText(); int firstCurve = getHighestCurveIndex() + 1; try { - if(constructionMethod == Diagonal) { + if (constructionMethod == Diagonal) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch box")); - Gui::Command::doCommand(Gui::Command::Doc, + Gui::Command::doCommand( + Gui::Command::Doc, "geoList = []\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" "%s.addGeometry(geoList,%s)\n" "conList = []\n" "conList.append(Sketcher.Constraint('Coincident',%i,2,%i,1))\n" @@ -172,32 +180,56 @@ public: "conList.append(Sketcher.Constraint('Vertical',%i))\n" "%s.addConstraint(conList)\n" "del geoList, conList\n", - EditCurve[0].x,EditCurve[0].y,EditCurve[1].x,EditCurve[1].y, // line 1 - EditCurve[1].x,EditCurve[1].y,EditCurve[2].x,EditCurve[2].y, // line 2 - EditCurve[2].x,EditCurve[2].y,EditCurve[3].x,EditCurve[3].y, // line 3 - EditCurve[3].x,EditCurve[3].y,EditCurve[0].x,EditCurve[0].y, // line 4 - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(), // the sketch - geometryCreationMode==Construction?"True":"False", // geometry as construction or not - firstCurve,firstCurve+1, // coincident1 - firstCurve+1,firstCurve+2, // coincident2 - firstCurve+2,firstCurve+3, // coincident3 - firstCurve+3,firstCurve, // coincident4 - firstCurve, // horizontal1 - firstCurve+2, // horizontal2 - firstCurve+1, // vertical1 - firstCurve+3, // vertical2 - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str()); // the sketch + EditCurve[0].x, + EditCurve[0].y, + EditCurve[1].x, + EditCurve[1].y,// line 1 + EditCurve[1].x, + EditCurve[1].y, + EditCurve[2].x, + EditCurve[2].y,// line 2 + EditCurve[2].x, + EditCurve[2].y, + EditCurve[3].x, + EditCurve[3].y,// line 3 + EditCurve[3].x, + EditCurve[3].y, + EditCurve[0].x, + EditCurve[0].y, // line 4 + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(),// the sketch + geometryCreationMode == Construction + ? "True" + : "False",// geometry as construction or not + firstCurve, + firstCurve + 1,// coincident1 + firstCurve + 1, + firstCurve + 2,// coincident2 + firstCurve + 2, + firstCurve + 3,// coincident3 + firstCurve + 3, + firstCurve, // coincident4 + firstCurve, // horizontal1 + firstCurve + 2, // horizontal2 + firstCurve + 1, // vertical1 + firstCurve + 3, // vertical2 + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str());// the sketch - Gui::Command::commitCommand(); + Gui::Command::commitCommand(); } else if (constructionMethod == CenterAndCorner) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add centered sketch box")); - Gui::Command::doCommand(Gui::Command::Doc, + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Add centered sketch box")); + Gui::Command::doCommand( + Gui::Command::Doc, "geoList = []\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" + "geoList.append(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)))" + "\n" "geoList.append(Part.Point(App.Vector(%f,%f,0)))\n" "%s.addGeometry(geoList,%s)\n" "conList = []\n" @@ -212,94 +244,119 @@ public: "conList.append(Sketcher.Constraint('Symmetric',%i,2,%i,1,%i,1))\n" "%s.addConstraint(conList)\n" "del geoList, conList\n", - EditCurve[0].x,EditCurve[0].y,EditCurve[1].x,EditCurve[1].y, // line 1 - EditCurve[1].x,EditCurve[1].y,EditCurve[2].x,EditCurve[2].y, // line 2 - EditCurve[2].x,EditCurve[2].y,EditCurve[3].x,EditCurve[3].y, // line 3 - EditCurve[3].x,EditCurve[3].y,EditCurve[0].x,EditCurve[0].y, // line 4 - center.x,center.y, // center point - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(), // the sketch - geometryCreationMode==Construction?"True":"False", // geometry as construction or not - firstCurve,firstCurve+1, // coincident1 - firstCurve+1,firstCurve+2, // coincident2 - firstCurve+2,firstCurve+3, // coincident3 - firstCurve+3,firstCurve, // coincident4 - firstCurve+1, // horizontal1 - firstCurve+3, // horizontal2 - firstCurve, // vertical1 - firstCurve+2, // vertical2 - firstCurve+1, firstCurve, firstCurve + 4, // Symmetric - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str()); // the sketch + EditCurve[0].x, + EditCurve[0].y, + EditCurve[1].x, + EditCurve[1].y,// line 1 + EditCurve[1].x, + EditCurve[1].y, + EditCurve[2].x, + EditCurve[2].y,// line 2 + EditCurve[2].x, + EditCurve[2].y, + EditCurve[3].x, + EditCurve[3].y,// line 3 + EditCurve[3].x, + EditCurve[3].y, + EditCurve[0].x, + EditCurve[0].y,// line 4 + center.x, + center.y, // center point + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(),// the sketch + geometryCreationMode == Construction + ? "True" + : "False",// geometry as construction or not + firstCurve, + firstCurve + 1,// coincident1 + firstCurve + 1, + firstCurve + 2,// coincident2 + firstCurve + 2, + firstCurve + 3,// coincident3 + firstCurve + 3, + firstCurve, // coincident4 + firstCurve + 1,// horizontal1 + firstCurve + 3,// horizontal2 + firstCurve, // vertical1 + firstCurve + 2,// vertical2 + firstCurve + 1, + firstCurve, + firstCurve + 4, // Symmetric + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str());// the sketch - Gui::Command::commitCommand(); + Gui::Command::commitCommand(); } } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add box")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add box")); Gui::Command::abortCommand(); } - if(constructionMethod == Diagonal) { + if (constructionMethod == Diagonal) { // add auto constraints at the start of the first side if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, getHighestCurveIndex() - 3 , Sketcher::PointPos::start); + createAutoConstraints( + sugConstr1, getHighestCurveIndex() - 3, Sketcher::PointPos::start); sugConstr1.clear(); } // add auto constraints at the end of the second side if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex() - 2, Sketcher::PointPos::end); + createAutoConstraints( + sugConstr2, getHighestCurveIndex() - 2, Sketcher::PointPos::end); sugConstr2.clear(); } - } else if (constructionMethod == CenterAndCorner) { // add auto constraints at the start of the first side if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); + createAutoConstraints( + sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr1.clear(); } // add auto constraints at the end of the second side if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex() - 3, Sketcher::PointPos::end); + createAutoConstraints( + sugConstr2, getHighestCurveIndex() - 3, Sketcher::PointPos::end); sugConstr2.clear(); } } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool continuousMode = hGrp->GetBool("ContinuousCreationMode",true); - if(continuousMode){ - // This code enables the continuous creation mode. - Mode=STATUS_SEEK_First; + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); + if (continuousMode) { + // This code enables the continuous creation mode. + Mode = STATUS_SEEK_First; EditCurve.clear(); drawEdit(EditCurve); EditCurve.resize(5); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } - else{ - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else { + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } - - } return true; } private: - QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Box"); } + protected: BoxMode Mode; std::vector EditCurve; @@ -308,20 +365,25 @@ protected: Base::Vector2d center; }; -class DrawSketchHandlerOblong : public DrawSketchHandler +class DrawSketchHandlerOblong: public DrawSketchHandler { public: DrawSketchHandlerOblong() : Mode(STATUS_SEEK_First) - , lengthX(0), lengthY(0), radius(0), signX(1), signY(1) + , lengthX(0) + , lengthY(0) + , radius(0) + , signX(1) + , signY(1) , EditCurve(37) - { - } - virtual ~DrawSketchHandlerOblong() {} + {} + virtual ~DrawSketchHandlerOblong() + {} /// mode table - enum BoxMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum BoxMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_End }; @@ -339,11 +401,13 @@ public: float distanceX = onSketchPos.x - StartPos.x; float distanceY = onSketchPos.y - StartPos.y; - lengthX = distanceX; lengthY = distanceY; + lengthX = distanceX; + lengthY = distanceY; signX = Base::sgn(distanceX); signY = Base::sgn(distanceY); if (fabs(distanceX) > fabs(distanceY)) { - radius = fabs(distanceY) / 4; // we use a fourth of the smaller distance as default radius + radius = + fabs(distanceY) / 4;// we use a fourth of the smaller distance as default radius } else { radius = fabs(distanceX) / 4; @@ -358,40 +422,56 @@ public: double y_i = -radius * cos(angle); // we are drawing clockwise starting with the arc that is besides StartPos if (signX == signY) { - EditCurve[i] = Base::Vector2d(StartPos.x + signX * (radius + x_i), StartPos.y + signY * (radius + y_i)); - EditCurve[9 + i] = Base::Vector2d(StartPos.x + signY * (radius + y_i), StartPos.y + lengthY - signX * (radius + x_i)); - EditCurve[18 + i] = Base::Vector2d(StartPos.x + lengthX - signX * (radius + x_i), StartPos.y + lengthY - signY * (radius + y_i)); - EditCurve[27 + i] = Base::Vector2d(StartPos.x + lengthX - signY * (radius + y_i), StartPos.y + signX * (radius + x_i)); + EditCurve[i] = Base::Vector2d(StartPos.x + signX * (radius + x_i), + StartPos.y + signY * (radius + y_i)); + EditCurve[9 + i] = + Base::Vector2d(StartPos.x + signY * (radius + y_i), + StartPos.y + lengthY - signX * (radius + x_i)); + EditCurve[18 + i] = + Base::Vector2d(StartPos.x + lengthX - signX * (radius + x_i), + StartPos.y + lengthY - signY * (radius + y_i)); + EditCurve[27 + i] = + Base::Vector2d(StartPos.x + lengthX - signY * (radius + y_i), + StartPos.y + signX * (radius + x_i)); } else { - EditCurve[i] = Base::Vector2d(StartPos.x - signY * (radius + y_i), StartPos.y - signX * (radius + x_i)); - EditCurve[9 + i] = Base::Vector2d(StartPos.x + lengthX - signX * (radius + x_i), StartPos.y + signY * (radius + y_i)); - EditCurve[18 + i] = Base::Vector2d(StartPos.x + lengthX + signY * (radius + y_i), StartPos.y + lengthY + signX * (radius + x_i)); - EditCurve[27 + i] = Base::Vector2d(StartPos.x + signX * (radius + x_i), StartPos.y + lengthY - signY * (radius + y_i)); + EditCurve[i] = Base::Vector2d(StartPos.x - signY * (radius + y_i), + StartPos.y - signX * (radius + x_i)); + EditCurve[9 + i] = Base::Vector2d(StartPos.x + lengthX - signX * (radius + x_i), + StartPos.y + signY * (radius + y_i)); + EditCurve[18 + i] = + Base::Vector2d(StartPos.x + lengthX + signY * (radius + y_i), + StartPos.y + lengthY + signX * (radius + x_i)); + EditCurve[27 + i] = + Base::Vector2d(StartPos.x + signX * (radius + x_i), + StartPos.y + lengthY - signY * (radius + y_i)); } } // draw the lines if (signX == signY) { EditCurve[8] = Base::Vector2d(StartPos.x, StartPos.y + (signY * radius)); EditCurve[17] = Base::Vector2d(StartPos.x + (signX * radius), StartPos.y + lengthY); - EditCurve[26] = Base::Vector2d(StartPos.x + lengthX, StartPos.y + lengthY - (signY * radius)); + EditCurve[26] = + Base::Vector2d(StartPos.x + lengthX, StartPos.y + lengthY - (signY * radius)); EditCurve[35] = Base::Vector2d(StartPos.x + lengthX - (signX * radius), StartPos.y); } else { EditCurve[8] = Base::Vector2d(StartPos.x + (signX * radius), StartPos.y); EditCurve[17] = Base::Vector2d(StartPos.x + lengthX, StartPos.y + (signY * radius)); - EditCurve[26] = Base::Vector2d(StartPos.x + lengthX - (signX * radius), StartPos.y + lengthY); + EditCurve[26] = + Base::Vector2d(StartPos.x + lengthX - (signX * radius), StartPos.y + lengthY); EditCurve[35] = Base::Vector2d(StartPos.x, StartPos.y + lengthY - (signY * radius)); } // close the curve EditCurve[36] = EditCurve[0]; - if (showCursorCoords()) { + if (showCursorCoords()) { SbString text; std::string radiusString = lengthToDisplayFormat(radius, 1); std::string xString = lengthToDisplayFormat(lengthX, 1); std::string yString = lengthToDisplayFormat(lengthY, 1); - text.sprintf(" (R%s X%s Y%s)", radiusString.c_str(), xString.c_str(), yString.c_str()); + text.sprintf( + " (R%s X%s Y%s)", radiusString.c_str(), xString.c_str(), yString.c_str()); setPositionText(onSketchPos, text); } @@ -444,17 +524,27 @@ public: try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add rounded rectangle")); - Gui::Command::doCommand(Gui::Command::Doc, - // syntax for arcs: Part.ArcOfCircle(Part.Circle(center, axis, radius), startangle, endangle) + Gui::Command::doCommand( + Gui::Command::Doc, + // syntax for arcs: Part.ArcOfCircle(Part.Circle(center, axis, radius), + // startangle, endangle) "geoList = []\n" - "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), App.Vector(0, 0, 1), %f), %f, %f))\n" - "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, 0)))\n" - "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), App.Vector(0, 0, 1), %f), %f, %f))\n" - "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, 0)))\n" - "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), App.Vector(0, 0, 1), %f), %f, %f))\n" - "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, 0)))\n" - "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), App.Vector(0, 0, 1), %f), %f, %f))\n" - "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, 0)))\n" + "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), " + "App.Vector(0, 0, 1), %f), %f, %f))\n" + "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, " + "0)))\n" + "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), " + "App.Vector(0, 0, 1), %f), %f, %f))\n" + "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, " + "0)))\n" + "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), " + "App.Vector(0, 0, 1), %f), %f, %f))\n" + "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, " + "0)))\n" + "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), " + "App.Vector(0, 0, 1), %f), %f, %f))\n" + "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, " + "0)))\n" "%s.addGeometry(geoList, %s)\n" "conList = []\n" "conList.append(Sketcher.Constraint('Tangent', %i, 1, %i, 1))\n" @@ -474,47 +564,80 @@ public: "conList.append(Sketcher.Constraint('Equal', %i, %i))\n" "%s.addConstraint(conList)\n" "del geoList, conList\n", - StartPos.x + (signX * radius), StartPos.y + (signY * radius), // center of the arc 1 + StartPos.x + (signX * radius), + StartPos.y + (signY * radius),// center of the arc 1 radius, - start, end, // start and end angle of arc1 - EditCurve[8].x, EditCurve[8].y, EditCurve[9].x, EditCurve[9].y, // line 1 - signX == signY ? StartPos.x + (signX * radius) : StartPos.x + lengthX - (signX * radius), // center of the arc 2 - signX == signY ? StartPos.y + lengthY - (signY * radius) : StartPos.y + (signY * radius), + start, + end,// start and end angle of arc1 + EditCurve[8].x, + EditCurve[8].y, + EditCurve[9].x, + EditCurve[9].y,// line 1 + signX == signY ? StartPos.x + (signX * radius) + : StartPos.x + lengthX - (signX * radius),// center of the arc 2 + signX == signY ? StartPos.y + lengthY - (signY * radius) + : StartPos.y + (signY * radius), radius, // start and end angle of arc 2 - // the logic is that end is start + M_PI / 2 and start is the previous end - M_PI + // the logic is that end is start + M_PI / 2 and start is the previous end - + // M_PI end - M_PI, end - 0.5 * M_PI, - EditCurve[17].x, EditCurve[17].y, EditCurve[18].x, EditCurve[18].y, // line 2 - StartPos.x + lengthX - (signX * radius), StartPos.y + lengthY - (signY * radius), // center of the arc 3 + EditCurve[17].x, + EditCurve[17].y, + EditCurve[18].x, + EditCurve[18].y,// line 2 + StartPos.x + lengthX - (signX * radius), + StartPos.y + lengthY - (signY * radius),// center of the arc 3 radius, end - 1.5 * M_PI, end - M_PI, - EditCurve[26].x, EditCurve[26].y, EditCurve[27].x, EditCurve[27].y, // line 3 - signX == signY ? StartPos.x + lengthX - (signX * radius) : StartPos.x + (signX * radius), // center of the arc 4 - signX == signY ? StartPos.y + (signY * radius) : StartPos.y + lengthY - (signY * radius), + EditCurve[26].x, + EditCurve[26].y, + EditCurve[27].x, + EditCurve[27].y,// line 3 + signX == signY ? StartPos.x + lengthX - (signX * radius) + : StartPos.x + (signX * radius),// center of the arc 4 + signX == signY ? StartPos.y + (signY * radius) + : StartPos.y + lengthY - (signY * radius), radius, end - 2 * M_PI, end - 1.5 * M_PI, - EditCurve[35].x, EditCurve[35].y, EditCurve[36].x, EditCurve[36].y, // line 4 - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(), // the sketch - geometryCreationMode == Construction ? "True" : "False", // geometry as construction or not - firstCurve, firstCurve + 1, // tangent 1 - firstCurve + 1, firstCurve + 2, // tangent 2 - firstCurve + 2, firstCurve + 3, // tangent 3 - firstCurve + 3, firstCurve + 4, // tangent 4 - firstCurve + 4, firstCurve + 5, // tangent 5 - firstCurve + 5, firstCurve + 6, // tangent 6 - firstCurve + 6, firstCurve + 7, // tangent 7 - firstCurve + 7, firstCurve, // tangent 8 - signX == signY ? firstCurve + 3 : firstCurve + 1, // horizontal constraint - signX == signY ? firstCurve + 7 : firstCurve + 5, // horizontal constraint - signX == signY ? firstCurve + 1 : firstCurve + 3, // vertical constraint - signX == signY ? firstCurve + 5 : firstCurve + 7, // vertical constraint - firstCurve, firstCurve + 2, // equal 1 - firstCurve + 2, firstCurve + 4, // equal 2 - firstCurve + 4, firstCurve + 6, // equal 3 - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str()); // the sketch + EditCurve[35].x, + EditCurve[35].y, + EditCurve[36].x, + EditCurve[36].y, // line 4 + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(),// the sketch + geometryCreationMode == Construction + ? "True" + : "False",// geometry as construction or not + firstCurve, + firstCurve + 1,// tangent 1 + firstCurve + 1, + firstCurve + 2,// tangent 2 + firstCurve + 2, + firstCurve + 3,// tangent 3 + firstCurve + 3, + firstCurve + 4,// tangent 4 + firstCurve + 4, + firstCurve + 5,// tangent 5 + firstCurve + 5, + firstCurve + 6,// tangent 6 + firstCurve + 6, + firstCurve + 7,// tangent 7 + firstCurve + 7, + firstCurve, // tangent 8 + signX == signY ? firstCurve + 3 : firstCurve + 1,// horizontal constraint + signX == signY ? firstCurve + 7 : firstCurve + 5,// horizontal constraint + signX == signY ? firstCurve + 1 : firstCurve + 3,// vertical constraint + signX == signY ? firstCurve + 5 : firstCurve + 7,// vertical constraint + firstCurve, + firstCurve + 2,// equal 1 + firstCurve + 2, + firstCurve + 4,// equal 2 + firstCurve + 4, + firstCurve + 6, // equal 3 + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str());// the sketch // not all users want these extra points, some power users find them unnecessary ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( @@ -555,28 +678,33 @@ public: // add auto constraints at the StartPos auxiliary point if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, getHighestCurveIndex() - 1, Sketcher::PointPos::start); + createAutoConstraints( + sugConstr1, getHighestCurveIndex() - 1, Sketcher::PointPos::start); sugConstr1.clear(); } // add auto constraints at the EndPos auxiliary point if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex(), Sketcher::PointPos::start); + createAutoConstraints( + sugConstr2, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); } catch (const Base::Exception& e) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add rounded rectangle")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add rounded rectangle")); Gui::Command::abortCommand(); tryAutoRecompute(static_cast(sketchgui->getObject())); } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { @@ -587,12 +715,13 @@ public: EditCurve.resize(37); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } else { - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } } return true; @@ -614,8 +743,7 @@ protected: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerRectangle_H - +#endif// SKETCHERGUI_DrawSketchHandlerRectangle_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h index 05daefd394..5ac15db770 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h @@ -28,26 +28,30 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class DrawSketchHandlerSlot : public DrawSketchHandler +class DrawSketchHandlerSlot: public DrawSketchHandler { public: DrawSketchHandlerSlot() : Mode(STATUS_SEEK_First) , SnapMode(SNAP_MODE_Free) , SnapDir(SNAP_DIR_Horz) - , dx(0), dy(0), r(0) + , dx(0) + , dy(0) + , r(0) , EditCurve(35) - { - } - virtual ~DrawSketchHandlerSlot() {} + {} + virtual ~DrawSketchHandlerSlot() + {} /// mode table - enum BoxMode { - STATUS_SEEK_First, /**< enum value ----. */ - STATUS_SEEK_Second, /**< enum value ----. */ + enum BoxMode + { + STATUS_SEEK_First, /**< enum value ----. */ + STATUS_SEEK_Second, /**< enum value ----. */ STATUS_End }; @@ -77,7 +81,7 @@ public: dx = onSketchPos.x - StartPos.x; dy = onSketchPos.y - StartPos.y; - if(QApplication::keyboardModifiers() == Qt::ControlModifier) + if (QApplication::keyboardModifiers() == Qt::ControlModifier) SnapMode = SNAP_MODE_Straight; else SnapMode = SNAP_MODE_Free; @@ -88,24 +92,28 @@ public: r = fabs(dx) / 4; rev = Base::sgn(dx); SnapDir = SNAP_DIR_Horz; - if (SnapMode == SNAP_MODE_Straight) dy = 0; + if (SnapMode == SNAP_MODE_Straight) + dy = 0; } else { r = fabs(dy) / 4; a = 8; rev = Base::sgn(dy); SnapDir = SNAP_DIR_Vert; - if (SnapMode == SNAP_MODE_Straight) dx = 0; + if (SnapMode == SNAP_MODE_Straight) + dx = 0; } // draw the arcs with each 16 segments for (int i = 0; i < 17; i++) { // first get the position at the arc - // if a is 0, the end points of the arc are at the y-axis, if it is 8, they are on the x-axis + // if a is 0, the end points of the arc are at the y-axis, if it is 8, they are on + // the x-axis double angle = (i + a) * M_PI / 16.0; double rx = -r * rev * sin(angle); double ry = r * rev * cos(angle); - // now apply the rotation matrix according to the angle between StartPos and onSketchPos + // now apply the rotation matrix according to the angle between StartPos and + // onSketchPos if (!(dx == 0 || dy == 0)) { double rotAngle = atan(dy / dx); if (a > 0) @@ -120,7 +128,7 @@ public: } EditCurve[34] = EditCurve[0]; - if (showCursorCoords()) { + if (showCursorCoords()) { SbString text; std::string rString = lengthToDisplayFormat(r, 1); std::string sqrtString = lengthToDisplayFormat(sqrt(dx * dx + dy * dy), 1); @@ -129,7 +137,10 @@ public: } drawEdit(EditCurve); - if (seekAutoConstraint(sugConstr2, onSketchPos, Base::Vector2d(dx, dy), AutoConstraint::VERTEX_NO_TANGENCY)) { + if (seekAutoConstraint(sugConstr2, + onSketchPos, + Base::Vector2d(dx, dy), + AutoConstraint::VERTEX_NO_TANGENCY)) { renderSuggestConstraintsCursor(sugConstr2); return; } @@ -184,9 +195,11 @@ public: try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add slot")); - AutoConstraint lastCons = {Sketcher::None, Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none}; + AutoConstraint lastCons = { + Sketcher::None, Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none}; - if (!sugConstr2.empty()) lastCons = sugConstr2.back(); + if (!sugConstr2.empty()) + lastCons = sugConstr2.back(); ostringstream snapCon = ostringstream(""); if (SnapMode == SNAP_MODE_Straight) { @@ -199,22 +212,31 @@ public: } snapCon << "'," << firstCurve + 2 << "))\n"; - // If horizontal/vertical already applied because of snap, do not duplicate with Autocontraint - if (lastCons.Type == Sketcher::Horizontal || lastCons.Type == Sketcher::Vertical) + // If horizontal/vertical already applied because of snap, do not duplicate with + // Autocontraint + if (lastCons.Type == Sketcher::Horizontal + || lastCons.Type == Sketcher::Vertical) sugConstr2.pop_back(); } else { - // If horizontal/vertical Autoconstraint suggested, applied it on first line (rather than last arc) - if (lastCons.Type == Sketcher::Horizontal || lastCons.Type == Sketcher::Vertical) + // If horizontal/vertical Autoconstraint suggested, applied it on first line + // (rather than last arc) + if (lastCons.Type == Sketcher::Horizontal + || lastCons.Type == Sketcher::Vertical) sugConstr2.back().GeoId = firstCurve + 2; } - Gui::Command::doCommand(Gui::Command::Doc, + Gui::Command::doCommand( + Gui::Command::Doc, "geoList = []\n" - "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), App.Vector(0, 0, 1), %f), %f, %f))\n" - "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f ,0), App.Vector(0, 0, 1), %f), %f, %f))\n" - "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, 0)))\n" - "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, 0)))\n" + "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, 0), " + "App.Vector(0, 0, 1), %f), %f, %f))\n" + "geoList.append(Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f ,0), " + "App.Vector(0, 0, 1), %f), %f, %f))\n" + "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, " + "0)))\n" + "geoList.append(Part.LineSegment(App.Vector(%f, %f, 0), App.Vector(%f, %f, " + "0)))\n" "%s.addGeometry(geoList, %s)\n" "conList = []\n" "conList.append(Sketcher.Constraint('Tangent', %i, 2, %i, 1))\n" @@ -225,50 +247,71 @@ public: "%s" "%s.addConstraint(conList)\n" "del geoList, conList\n", - StartPos.x, StartPos.y, // center of the arc1 - r, // radius arc1 - start, end, // start and end angle of arc1 - StartPos.x + dx, StartPos.y + dy, // center of the arc2 - r, // radius arc2 - end, end + M_PI, // start and end angle of arc2 - EditCurve[16].x, EditCurve[16].y, EditCurve[17].x, EditCurve[17].y, // line1 - EditCurve[33].x, EditCurve[33].y, EditCurve[34].x, EditCurve[34].y, // line2 - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(), // the sketch - geometryCreationMode == Construction ? "True" : "False", // geometry as construction or not - firstCurve, firstCurve + 2, // tangent1 - firstCurve + 2, firstCurve + 1, // tangent2 - firstCurve + 1, firstCurve + 3, // tangent3 - firstCurve + 3, firstCurve, // tangent4 - firstCurve, firstCurve + 1, // equal constraint - snapCon.str().c_str(), // horizontal/vertical constraint if snapping - Gui::Command::getObjectCmd(sketchgui->getObject()).c_str()); // the sketch + StartPos.x, + StartPos.y,// center of the arc1 + r, // radius arc1 + start, + end,// start and end angle of arc1 + StartPos.x + dx, + StartPos.y + dy,// center of the arc2 + r, // radius arc2 + end, + end + M_PI,// start and end angle of arc2 + EditCurve[16].x, + EditCurve[16].y, + EditCurve[17].x, + EditCurve[17].y,// line1 + EditCurve[33].x, + EditCurve[33].y, + EditCurve[34].x, + EditCurve[34].y, // line2 + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str(),// the sketch + geometryCreationMode == Construction + ? "True" + : "False",// geometry as construction or not + firstCurve, + firstCurve + 2,// tangent1 + firstCurve + 2, + firstCurve + 1,// tangent2 + firstCurve + 1, + firstCurve + 3,// tangent3 + firstCurve + 3, + firstCurve,// tangent4 + firstCurve, + firstCurve + 1, // equal constraint + snapCon.str().c_str(),// horizontal/vertical constraint if snapping + Gui::Command::getObjectCmd(sketchgui->getObject()).c_str());// the sketch Gui::Command::commitCommand(); // add auto constraints at the center of the first arc if (!sugConstr1.empty()) { - createAutoConstraints(sugConstr1, getHighestCurveIndex() - 3, Sketcher::PointPos::mid); + createAutoConstraints( + sugConstr1, getHighestCurveIndex() - 3, Sketcher::PointPos::mid); sugConstr1.clear(); } // add auto constraints at the center of the second arc if (!sugConstr2.empty()) { - createAutoConstraints(sugConstr2, getHighestCurveIndex() - 2, Sketcher::PointPos::mid); + createAutoConstraints( + sugConstr2, getHighestCurveIndex() - 2, Sketcher::PointPos::mid); sugConstr2.clear(); } - tryAutoRecomputeIfNotSolve(static_cast(sketchgui->getObject())); + tryAutoRecomputeIfNotSolve( + static_cast(sketchgui->getObject())); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add slot")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add slot")); Gui::Command::abortCommand(); tryAutoRecompute(static_cast(sketchgui->getObject())); } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { @@ -279,17 +322,19 @@ public: EditCurve.resize(35); applyCursor(); /* this is ok not to call to purgeHandler - * in continuous creation mode because the - * handler is destroyed by the quit() method on pressing the - * right button of the mouse */ + * in continuous creation mode because the + * handler is destroyed by the quit() method on pressing the + * right button of the mouse */ } else { - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider } SnapMode = SNAP_MODE_Straight; } return true; } + private: QString getCrosshairCursorSVGName() const override { @@ -307,8 +352,7 @@ protected: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerSlot_H - +#endif// SKETCHERGUI_DrawSketchHandlerSlot_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h index cf17ac1ed3..e4fe6015b0 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h @@ -28,30 +28,33 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class SplittingSelection : public Gui::SelectionFilterGate +class SplittingSelection: public Gui::SelectionFilterGate { App::DocumentObject* object; + public: explicit SplittingSelection(App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()), object(obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) {} - bool allow(App::Document * /*pDoc*/, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) { if (pObj != this->object) return false; if (!sSubName || sSubName[0] == '\0') return false; std::string element(sSubName); - if (element.substr(0,4) == "Edge") { - int GeoId = std::atoi(element.substr(4,4000).c_str()) - 1; - Sketcher::SketchObject *Sketch = static_cast(object); - const Part::Geometry *geom = Sketch->getGeometry(GeoId); + if (element.substr(0, 4) == "Edge") { + int GeoId = std::atoi(element.substr(4, 4000).c_str()) - 1; + Sketcher::SketchObject* Sketch = static_cast(object); + const Part::Geometry* geom = Sketch->getGeometry(GeoId); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() || geom->getTypeId() == Part::GeomCircle::getClassTypeId() || geom->getTypeId() == Part::GeomEllipse::getClassTypeId() @@ -60,16 +63,16 @@ public: return true; } } - else if (element.substr(0,6) == "Vertex") { - int VertId = std::atoi(element.substr(6,4000).c_str()) - 1; + else if (element.substr(0, 6) == "Vertex") { + int VertId = std::atoi(element.substr(6, 4000).c_str()) - 1; int GeoId = Sketcher::GeoEnum::GeoUndef; Sketcher::PointPos PosId = Sketcher::PointPos::none; - Sketcher::SketchObject *Sketch = static_cast(object); + Sketcher::SketchObject* Sketch = static_cast(object); Sketch->getGeoVertexIndex(VertId, GeoId, PosId); if (isBsplineKnot(Sketch, GeoId)) return true; } - return false; + return false; } }; @@ -100,7 +103,7 @@ public: int curveGeoId = getPreselectCurve(); if (curveGeoId >= 0) { - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(curveGeoId); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(curveGeoId); if (geom->getTypeId() == Part::GeomLineSegment::getClassTypeId() || geom->getTypeId() == Part::GeomCircle::getClassTypeId() || geom->getTypeId() == Part::GeomEllipse::getClassTypeId() @@ -113,16 +116,15 @@ public: // No curve of interest is pre-selected. Try pre-selected point. int pointGeoId = getPreselectPoint(); - if (pointGeoId >=0) { + if (pointGeoId >= 0) { // TODO: This has to be a knot. Find the spline. const auto& constraints = getSketchObject()->Constraints.getValues(); - const auto& conIt = std::find_if( - constraints.begin(), constraints.end(), - [pointGeoId](auto constr) { - return (constr->Type == Sketcher::InternalAlignment && - constr->AlignmentType == Sketcher::BSplineKnotPoint && - constr->First == pointGeoId); + const auto& conIt = + std::find_if(constraints.begin(), constraints.end(), [pointGeoId](auto constr) { + return (constr->Type == Sketcher::InternalAlignment + && constr->AlignmentType == Sketcher::BSplineKnotPoint + && constr->First == pointGeoId); }); if (conIt != constraints.end()) @@ -133,15 +135,18 @@ public: if (GeoId >= 0) { try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Split edge")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "split(%d,App.Vector(%f,%f,0))", - GeoId, onSketchPos.x, onSketchPos.y); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "split(%d,App.Vector(%f,%f,0))", + GeoId, + onSketchPos.x, + onSketchPos.y); Gui::Command::commitCommand(); - tryAutoRecompute(static_cast(sketchgui->getObject())); + tryAutoRecompute(static_cast(sketchgui->getObject())); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add edge")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add edge")); Gui::Command::abortCommand(); } @@ -161,13 +166,13 @@ private: Gui::Selection().addSelectionGate(new SplittingSelection(sketchgui->getObject())); } - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Splitting"); } }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerSplitting_H - +#endif// SKETCHERGUI_DrawSketchHandlerSplitting_H diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h index 0cb0e1a45a..5064c6bdb8 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h @@ -28,40 +28,42 @@ #include "GeometryCreationMode.h" -namespace SketcherGui { +namespace SketcherGui +{ -extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo.cpp +extern GeometryCreationMode geometryCreationMode;// defined in CommandCreateGeo.cpp -class TrimmingSelection : public Gui::SelectionFilterGate +class TrimmingSelection: public Gui::SelectionFilterGate { App::DocumentObject* object; + public: explicit TrimmingSelection(App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()), object(obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) {} - bool allow(App::Document * /*pDoc*/, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) { if (pObj != this->object) return false; if (!sSubName || sSubName[0] == '\0') return false; std::string element(sSubName); - if (element.substr(0,4) == "Edge") { - int GeoId = std::atoi(element.substr(4,4000).c_str()) - 1; - Sketcher::SketchObject *Sketch = static_cast(object); - const Part::Geometry *geom = Sketch->getGeometry(GeoId); - if (geom->getTypeId().isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()) || - geom->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() - ) { + if (element.substr(0, 4) == "Edge") { + int GeoId = std::atoi(element.substr(4, 4000).c_str()) - 1; + Sketcher::SketchObject* Sketch = static_cast(object); + const Part::Geometry* geom = Sketch->getGeometry(GeoId); + if (geom->getTypeId().isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()) + || geom->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // We do not trim internal geometry of complex geometries - if( Sketcher::GeometryFacade::isInternalType(geom, Sketcher::InternalType::None)) + if (Sketcher::GeometryFacade::isInternalType(geom, Sketcher::InternalType::None)) return true; } } - return false; + return false; } }; @@ -81,30 +83,34 @@ public: int GeoId = getPreselectCurve(); if (GeoId > -1) { - auto sk = static_cast(sketchgui->getObject()); + auto sk = static_cast(sketchgui->getObject()); int GeoId1, GeoId2; Base::Vector3d intersect1, intersect2; - if(sk->seekTrimPoints(GeoId, Base::Vector3d(onSketchPos.x,onSketchPos.y,0), - GeoId1, intersect1, - GeoId2, intersect2)) { + if (sk->seekTrimPoints(GeoId, + Base::Vector3d(onSketchPos.x, onSketchPos.y, 0), + GeoId1, + intersect1, + GeoId2, + intersect2)) { EditMarkers.resize(0); - if(GeoId1 != Sketcher::GeoEnum::GeoUndef) + if (GeoId1 != Sketcher::GeoEnum::GeoUndef) EditMarkers.emplace_back(intersect1.x, intersect1.y); else { auto start = sk->getPoint(GeoId, Sketcher::PointPos::start); EditMarkers.emplace_back(start.x, start.y); } - if(GeoId2 != Sketcher::GeoEnum::GeoUndef) + if (GeoId2 != Sketcher::GeoEnum::GeoUndef) EditMarkers.emplace_back(intersect2.x, intersect2.y); else { auto end = sk->getPoint(GeoId, Sketcher::PointPos::end); - EditMarkers.emplace_back( end.x, end.y); + EditMarkers.emplace_back(end.x, end.y); } - drawEditMarkers(EditMarkers, 2); // maker augmented by two sizes (see supported marker sizes) + drawEditMarkers(EditMarkers, + 2);// maker augmented by two sizes (see supported marker sizes) } } else { @@ -123,22 +129,25 @@ public: { int GeoId = getPreselectCurve(); if (GeoId > -1) { - const Part::Geometry *geom = sketchgui->getSketchObject()->getGeometry(GeoId); - if (geom->getTypeId().isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()) || - geom->getTypeId() == Part::GeomCircle::getClassTypeId() || - geom->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geom->getTypeId() == Part::GeomBSplineCurve::getClassTypeId() ) { + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(GeoId); + if (geom->getTypeId().isDerivedFrom(Part::GeomTrimmedCurve::getClassTypeId()) + || geom->getTypeId() == Part::GeomCircle::getClassTypeId() + || geom->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geom->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Trim edge")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), "trim(%d,App.Vector(%f,%f,0))", - GeoId, onSketchPos.x, onSketchPos.y); + Gui::cmdAppObjectArgs(sketchgui->getObject(), + "trim(%d,App.Vector(%f,%f,0))", + GeoId, + onSketchPos.x, + onSketchPos.y); Gui::Command::commitCommand(); - tryAutoRecompute(static_cast(sketchgui->getObject())); + tryAutoRecompute(static_cast(sketchgui->getObject())); } catch (const Base::Exception& e) { Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to trim edge")); + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to trim edge")); Gui::Command::abortCommand(); } @@ -147,8 +156,9 @@ public: EditMarkers.resize(0); drawEditMarkers(EditMarkers); } - else // exit the trimming tool if the user clicked on empty space - sketchgui->purgeHandler(); // no code after this line, Handler get deleted in ViewProvider + else// exit the trimming tool if the user clicked on empty space + sketchgui + ->purgeHandler();// no code after this line, Handler get deleted in ViewProvider return true; } @@ -161,7 +171,8 @@ private: Gui::Selection().addSelectionGate(new TrimmingSelection(sketchgui->getObject())); } - QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override + { return QString::fromLatin1("Sketcher_Pointer_Trimming"); } @@ -170,9 +181,7 @@ private: }; - -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_DrawSketchHandlerTrimming_H - +#endif// SKETCHERGUI_DrawSketchHandlerTrimming_H diff --git a/src/Mod/Sketcher/Gui/EditDatumDialog.cpp b/src/Mod/Sketcher/Gui/EditDatumDialog.cpp index 90161f0c78..dbfd423b99 100644 --- a/src/Mod/Sketcher/Gui/EditDatumDialog.cpp +++ b/src/Mod/Sketcher/Gui/EditDatumDialog.cpp @@ -23,11 +23,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include /// Qt Include Files -# include -# include -# include +#include +#include +#include #endif #include @@ -38,13 +38,13 @@ #include #include #include -#include #include +#include -#include "ViewProviderSketch.h" -#include "ui_InsertDatum.h" #include "EditDatumDialog.h" #include "Utils.h" +#include "ViewProviderSketch.h" +#include "ui_InsertDatum.h" using namespace SketcherGui; @@ -55,7 +55,7 @@ EditDatumDialog::EditDatumDialog(ViewProviderSketch* vp, int ConstrNbr) : ConstrNbr(ConstrNbr) { sketch = vp->getSketchObject(); - const std::vector &Constraints = sketch->Constraints.getValues(); + const std::vector& Constraints = sketch->Constraints.getValues(); Constr = Constraints[ConstrNbr]; } @@ -63,14 +63,12 @@ EditDatumDialog::EditDatumDialog(Sketcher::SketchObject* pcSketch, int ConstrNbr : sketch(pcSketch) , ConstrNbr(ConstrNbr) { - const std::vector &Constraints = sketch->Constraints.getValues(); + const std::vector& Constraints = sketch->Constraints.getValues(); Constr = Constraints[ConstrNbr]; } EditDatumDialog::~EditDatumDialog() -{ - -} +{} void EditDatumDialog::exec(bool atCursor) { @@ -79,8 +77,9 @@ void EditDatumDialog::exec(bool atCursor) if (sketch->hasConflicts()) { Gui::TranslatedUserWarning(sketch, - QObject::tr("Dimensional constraint"), - QObject::tr("Not allowed to edit the datum because the sketch contains conflicting constraints")); + QObject::tr("Dimensional constraint"), + QObject::tr("Not allowed to edit the datum because the " + "sketch contains conflicting constraints")); return; } @@ -99,36 +98,42 @@ void EditDatumDialog::exec(bool atCursor) dlg.setWindowTitle(tr("Insert angle")); init_val.setUnit(Base::Unit::Angle); ui_ins_datum->label->setText(tr("Angle:")); - ui_ins_datum->labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherAngle")); + ui_ins_datum->labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherAngle")); } else if (Constr->Type == Sketcher::Radius) { dlg.setWindowTitle(tr("Insert radius")); init_val.setUnit(Base::Unit::Length); ui_ins_datum->label->setText(tr("Radius:")); - ui_ins_datum->labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherLength")); + ui_ins_datum->labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherLength")); } else if (Constr->Type == Sketcher::Diameter) { dlg.setWindowTitle(tr("Insert diameter")); init_val.setUnit(Base::Unit::Length); ui_ins_datum->label->setText(tr("Diameter:")); - ui_ins_datum->labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherLength")); + ui_ins_datum->labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherLength")); } else if (Constr->Type == Sketcher::Weight) { dlg.setWindowTitle(tr("Insert weight")); ui_ins_datum->label->setText(tr("Weight:")); - ui_ins_datum->labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherWeight")); + ui_ins_datum->labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherWeight")); } else if (Constr->Type == Sketcher::SnellsLaw) { dlg.setWindowTitle(tr("Refractive index ratio", "Constraint_SnellsLaw")); ui_ins_datum->label->setText(tr("Ratio n2/n1:", "Constraint_SnellsLaw")); - ui_ins_datum->labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherRefrIndexRatio")); + ui_ins_datum->labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherRefrIndexRatio")); ui_ins_datum->labelEdit->setSingleStep(0.05); } else { dlg.setWindowTitle(tr("Insert length")); init_val.setUnit(Base::Unit::Length); ui_ins_datum->label->setText(tr("Length:")); - ui_ins_datum->labelEdit->setParamGrpPath(QByteArray("User parameter:BaseApp/History/SketcherLength")); + ui_ins_datum->labelEdit->setParamGrpPath( + QByteArray("User parameter:BaseApp/History/SketcherLength")); } init_val.setValue(datum); @@ -139,25 +144,32 @@ void EditDatumDialog::exec(bool atCursor) ui_ins_datum->labelEdit->bind(sketch->Constraints.createPath(ConstrNbr)); ui_ins_datum->name->setText(Base::Tools::fromStdString(Constr->Name)); - ui_ins_datum->cbDriving->setChecked(! Constr->isDriving); + ui_ins_datum->cbDriving->setChecked(!Constr->isDriving); - connect(ui_ins_datum->cbDriving, &QCheckBox::toggled, this, &EditDatumDialog::drivingToggled); - connect(ui_ins_datum->labelEdit, qOverload(&Gui::QuantitySpinBox::valueChanged), - this, &EditDatumDialog::datumChanged); - connect(ui_ins_datum->labelEdit, &Gui::QuantitySpinBox::showFormulaDialog, - this, &EditDatumDialog::formEditorOpened); + connect( + ui_ins_datum->cbDriving, &QCheckBox::toggled, this, &EditDatumDialog::drivingToggled); + connect(ui_ins_datum->labelEdit, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &EditDatumDialog::datumChanged); + connect(ui_ins_datum->labelEdit, + &Gui::QuantitySpinBox::showFormulaDialog, + this, + &EditDatumDialog::formEditorOpened); connect(&dlg, &QDialog::accepted, this, &EditDatumDialog::accepted); connect(&dlg, &QDialog::rejected, this, &EditDatumDialog::rejected); if (atCursor) { - dlg.show(); // Need to show the dialog so geometry is computed + dlg.show();// Need to show the dialog so geometry is computed QRect pg = dlg.parentWidget()->geometry(); int Xmin = pg.x() + 10; int Ymin = pg.y() + 10; int Xmax = pg.x() + pg.width() - dlg.geometry().width() - 10; int Ymax = pg.y() + pg.height() - dlg.geometry().height() - 10; - int x = Xmax < Xmin ? (Xmin + Xmax)/2 : std::min(std::max(QCursor::pos().x(), Xmin), Xmax); - int y = Ymax < Ymin ? (Ymin + Ymax)/2 : std::min(std::max(QCursor::pos().y(), Ymin), Ymax); + int x = Xmax < Xmin ? (Xmin + Xmax) / 2 + : std::min(std::max(QCursor::pos().x(), Xmin), Xmax); + int y = Ymax < Ymin ? (Ymin + Ymax) / 2 + : std::min(std::max(QCursor::pos().y(), Ymin), Ymax); dlg.setGeometry(x, y, dlg.geometry().width(), dlg.geometry().height()); } @@ -168,9 +180,8 @@ void EditDatumDialog::exec(bool atCursor) void EditDatumDialog::accepted() { Base::Quantity newQuant = ui_ins_datum->labelEdit->value(); - if( newQuant.isQuantity() || - (Constr->Type == Sketcher::SnellsLaw && newQuant.isDimensionless()) || - (Constr->Type == Sketcher::Weight && newQuant.isDimensionless())) { + if (newQuant.isQuantity() || (Constr->Type == Sketcher::SnellsLaw && newQuant.isDimensionless()) + || (Constr->Type == Sketcher::Weight && newQuant.isDimensionless())) { // save the value for the history ui_ins_datum->labelEdit->pushToHistory(); @@ -183,19 +194,23 @@ void EditDatumDialog::accepted() Gui::cmdAppObjectArgs(sketch, "toggleDriving(%i)", ConstrNbr); }*/ - if (! ui_ins_datum->cbDriving->isChecked()) { + if (!ui_ins_datum->cbDriving->isChecked()) { if (ui_ins_datum->labelEdit->hasExpression()) ui_ins_datum->labelEdit->apply(); else - Gui::cmdAppObjectArgs(sketch, "setDatum(%i,App.Units.Quantity('%f %s'))", - ConstrNbr, newDatum, (const char*)newQuant.getUnit().getString().toUtf8()); + Gui::cmdAppObjectArgs(sketch, + "setDatum(%i,App.Units.Quantity('%f %s'))", + ConstrNbr, + newDatum, + (const char*)newQuant.getUnit().getString().toUtf8()); } QString constraintName = ui_ins_datum->name->text().trimmed(); if (Base::Tools::toStdString(constraintName) != sketch->Constraints[ConstrNbr]->Name) { - std::string escapedstr = Base::Tools::escapedUnicodeFromUtf8(constraintName.toUtf8().constData()); - Gui::cmdAppObjectArgs(sketch, "renameConstraint(%d, u'%s')", - ConstrNbr, escapedstr.c_str()); + std::string escapedstr = + Base::Tools::escapedUnicodeFromUtf8(constraintName.toUtf8().constData()); + Gui::cmdAppObjectArgs( + sketch, "renameConstraint(%d, u'%s')", ConstrNbr, escapedstr.c_str()); } Gui::Command::commitCommand(); @@ -208,27 +223,26 @@ void EditDatumDialog::accepted() // It appears related to a drastic change in how dependencies are calculated, see: // https://forum.freecad.org/viewtopic.php?f=3&t=55633&p=481061#p481061 // - // This is NOT the solution, as there is no point in systematically executing the ExpressionEngine - // on every dimensional constraint change. Just a quick fix to avoid clearly unwanted behaviour in - // absence of time to actually fix the root cause. + // This is NOT the solution, as there is no point in systematically executing the + // ExpressionEngine on every dimensional constraint change. Just a quick fix to avoid + // clearly unwanted behaviour in absence of time to actually fix the root cause. - //if (sketch->noRecomputes && sketch->ExpressionEngine.depsAreTouched()) { - sketch->ExpressionEngine.execute(); - sketch->solve(); + // if (sketch->noRecomputes && sketch->ExpressionEngine.depsAreTouched()) { + sketch->ExpressionEngine.execute(); + sketch->solve(); //} tryAutoRecompute(sketch); } catch (const Base::Exception& e) { - Gui::NotifyUserError(sketch, - QT_TRANSLATE_NOOP("Notifications", "Value Error"), - e.what()); + Gui::NotifyUserError( + sketch, QT_TRANSLATE_NOOP("Notifications", "Value Error"), e.what()); Gui::Command::abortCommand(); - if(sketch->noRecomputes) // if setdatum failed, it is highly likely that solver information is invalid. + if (sketch->noRecomputes)// if setdatum failed, it is highly likely that solver + // information is invalid. sketch->solve(); - } } } @@ -245,7 +259,7 @@ void EditDatumDialog::drivingToggled(bool state) ui_ins_datum->labelEdit->setToLastUsedValue(); } sketch->setDriving(ConstrNbr, !state); - if(!sketch->noRecomputes) // if noRecomputes, solve() is already done by setDriving() + if (!sketch->noRecomputes)// if noRecomputes, solve() is already done by setDriving() sketch->solve(); } diff --git a/src/Mod/Sketcher/Gui/EditDatumDialog.h b/src/Mod/Sketcher/Gui/EditDatumDialog.h index 0682e81ca9..85d4695f60 100644 --- a/src/Mod/Sketcher/Gui/EditDatumDialog.h +++ b/src/Mod/Sketcher/Gui/EditDatumDialog.h @@ -23,20 +23,23 @@ #ifndef SKETCHERGUI_EditDatumDialog_H #define SKETCHERGUI_EditDatumDialog_H -#include #include +#include -namespace Sketcher { +namespace Sketcher +{ class Constraint; class SketchObject; -} +}// namespace Sketcher -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; class Ui_InsertDatum; -class EditDatumDialog : public QObject { +class EditDatumDialog: public QObject +{ Q_OBJECT public: @@ -44,7 +47,7 @@ public: EditDatumDialog(Sketcher::SketchObject* pcSketch, int ConstrNbr); ~EditDatumDialog() override; - void exec(bool atCursor=true); + void exec(bool atCursor = true); private: Sketcher::SketchObject* sketch; @@ -60,5 +63,5 @@ private Q_SLOTS: void formEditorOpened(bool); }; -} -#endif // SKETCHERGUI_DrawSketchHandler_H +}// namespace SketcherGui +#endif// SKETCHERGUI_DrawSketchHandler_H diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp index 51ebf16652..6fb6aba3a1 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp @@ -22,29 +22,29 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif// #ifndef _PreComp_ #include -#include #include +#include #include #include @@ -61,7 +61,8 @@ using namespace SketcherGui; using namespace Sketcher; //**************************** ParameterObserver nested class ****************************** -EditModeCoinManager::ParameterObserver::ParameterObserver(EditModeCoinManager &client): Client(client) +EditModeCoinManager::ParameterObserver::ParameterObserver(EditModeCoinManager& client) + : Client(client) { initParameters(); subscribeToParameters(); @@ -74,98 +75,179 @@ EditModeCoinManager::ParameterObserver::~ParameterObserver() void EditModeCoinManager::ParameterObserver::initParameters() { - // static map to avoid substantial if/else branching + // static map to avoid substantial if/else branching // // key->first => String of parameter, // key->second => Update function to be called for the parameter, str2updatefunction = { {"SegmentsPerGeometry", - [this](const std::string & param){updateCurvedEdgeCountSegmentsParameter(param);}}, + [this](const std::string& param) { + updateCurvedEdgeCountSegmentsParameter(param); + }}, {"BSplineDegreeVisible", - [this](const std::string & param){updateOverlayVisibilityParameter(param);}}, + [this](const std::string& param) { + updateOverlayVisibilityParameter(param); + }}, {"BSplineControlPolygonVisible", - [this](const std::string & param){updateOverlayVisibilityParameter(param);}}, + [this](const std::string& param) { + updateOverlayVisibilityParameter< + OverlayVisibilityParameter::BSplineControlPolygonVisible>(param); + }}, {"BSplineCombVisible", - [this](const std::string & param){updateOverlayVisibilityParameter(param);}}, + [this](const std::string& param) { + updateOverlayVisibilityParameter( + param); + }}, {"BSplineKnotMultiplicityVisible", - [this](const std::string & param){updateOverlayVisibilityParameter(param);}}, + [this](const std::string& param) { + updateOverlayVisibilityParameter< + OverlayVisibilityParameter::BSplineKnotMultiplicityVisible>(param); + }}, {"BSplinePoleWeightVisible", - [this](const std::string & param){updateOverlayVisibilityParameter(param);}}, + [this](const std::string& param) { + updateOverlayVisibilityParameter( + param); + }}, {"ArcCircleHelperVisible", - [this](const std::string & param){updateOverlayVisibilityParameter(param);}}, + [this](const std::string& param) { + updateOverlayVisibilityParameter( + param); + }}, {"TopRenderGeometryId", - [this](const std::string & param){updateLineRenderingOrderParameters(param);}}, + [this](const std::string& param) { + updateLineRenderingOrderParameters(param); + }}, {"MidRenderGeometryId", - [this](const std::string & param){updateLineRenderingOrderParameters(param);}}, + [this](const std::string& param) { + updateLineRenderingOrderParameters(param); + }}, {"HideUnits", - [this](const std::string & param){updateConstraintPresentationParameters(param);}}, + [this](const std::string& param) { + updateConstraintPresentationParameters(param); + }}, {"ShowDimensionalName", - [this](const std::string & param){updateConstraintPresentationParameters(param);}}, + [this](const std::string& param) { + updateConstraintPresentationParameters(param); + }}, {"DimensionalStringFormat", - [this](const std::string & param){updateConstraintPresentationParameters(param);}}, + [this](const std::string& param) { + updateConstraintPresentationParameters(param); + }}, {"ViewScalingFactor", - [this](const std::string & param){updateElementSizeParameters(param);}}, + [this](const std::string& param) { + updateElementSizeParameters(param); + }}, {"MarkerSize", - [this](const std::string & param){updateElementSizeParameters(param);}}, + [this](const std::string& param) { + updateElementSizeParameters(param); + }}, {"EditSketcherFontSize", - [this](const std::string & param){updateElementSizeParameters(param);}}, + [this](const std::string& param) { + updateElementSizeParameters(param); + }}, {"CreateLineColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.CreateCurveColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.CreateCurveColor, param); + }}, {"EditedVertexColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.VertexColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.VertexColor, param); + }}, {"EditedEdgeColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.CurveColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.CurveColor, param); + }}, {"ConstructionColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.CurveDraftColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.CurveDraftColor, param); + }}, {"InternalAlignedGeoColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.InternalAlignedGeoColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.InternalAlignedGeoColor, param); + }}, {"FullyConstraintElementColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.FullyConstraintElementColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.FullyConstraintElementColor, param); + }}, {"FullyConstraintConstructionElementColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.FullyConstraintConstructionElementColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.FullyConstraintConstructionElementColor, param); + }}, {"FullyConstraintInternalAlignmentColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.FullyConstraintInternalAlignmentColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.FullyConstraintInternalAlignmentColor, param); + }}, {"FullyConstraintConstructionPointColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.FullyConstraintConstructionPointColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.FullyConstraintConstructionPointColor, param); + }}, {"FullyConstraintElementColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.FullyConstraintElementColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.FullyConstraintElementColor, param); + }}, {"InvalidSketchColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.InvalidSketchColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.InvalidSketchColor, param); + }}, {"FullyConstrainedColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.FullyConstrainedColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.FullyConstrainedColor, param); + }}, {"ConstrainedDimColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.ConstrDimColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.ConstrDimColor, param); + }}, {"ConstrainedIcoColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.ConstrIcoColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.ConstrIcoColor, param); + }}, {"NonDrivingConstrDimColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.NonDrivingConstrDimColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.NonDrivingConstrDimColor, param); + }}, {"ExprBasedConstrDimColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.ExprBasedConstrDimColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.ExprBasedConstrDimColor, param); + }}, {"DeactivatedConstrDimColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.DeactivatedConstrDimColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.DeactivatedConstrDimColor, param); + }}, {"ExternalColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.CurveExternalColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.CurveExternalColor, param); + }}, {"HighlightColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.PreselectColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.PreselectColor, param); + }}, {"SelectionColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.SelectColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.SelectColor, param); + }}, {"CursorTextColor", - [this, drawingParameters = Client.drawingParameters](const std::string & param){updateColor(drawingParameters.CursorTextColor, param);}}, + [this, drawingParameters = Client.drawingParameters](const std::string& param) { + updateColor(drawingParameters.CursorTextColor, param); + }}, {"UserSchema", - [this](const std::string& param) {updateUnit(param); }}, + [this](const std::string& param) { + updateUnit(param); + }}, }; - for( auto & val : str2updatefunction){ - auto string = val.first; - auto function = val.second; + for (auto& val : str2updatefunction) { + auto string = val.first; + auto function = val.second; function(string); } } -void EditModeCoinManager::ParameterObserver::updateCurvedEdgeCountSegmentsParameter(const std::string & parametername) +void EditModeCoinManager::ParameterObserver::updateCurvedEdgeCountSegmentsParameter( + const std::string& parametername) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); int stdcountsegments = hGrp->GetInt(parametername.c_str(), 50); // value cannot be smaller than 6 if (stdcountsegments < 6) @@ -174,88 +256,113 @@ void EditModeCoinManager::ParameterObserver::updateCurvedEdgeCountSegmentsParame Client.drawingParameters.curvedEdgeCountSegments = stdcountsegments; } -void EditModeCoinManager::ParameterObserver::updateLineRenderingOrderParameters(const std::string & parametername) +void EditModeCoinManager::ParameterObserver::updateLineRenderingOrderParameters( + const std::string& parametername) { - (void) parametername; + (void)parametername; - ParameterGrp::handle hGrpp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrpp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - Client.drawingParameters.topRenderingGeometry = DrawingParameters::GeometryRendering (hGrpp->GetInt("TopRenderGeometryId",1)); - Client.drawingParameters.midRenderingGeometry = DrawingParameters::GeometryRendering (hGrpp->GetInt("MidRenderGeometryId",2)); + Client.drawingParameters.topRenderingGeometry = + DrawingParameters::GeometryRendering(hGrpp->GetInt("TopRenderGeometryId", 1)); + Client.drawingParameters.midRenderingGeometry = + DrawingParameters::GeometryRendering(hGrpp->GetInt("MidRenderGeometryId", 2)); } -void EditModeCoinManager::ParameterObserver::updateConstraintPresentationParameters(const std::string & parametername) +void EditModeCoinManager::ParameterObserver::updateConstraintPresentationParameters( + const std::string& parametername) { - (void) parametername; + (void)parametername; - ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); Client.constraintParameters.bHideUnits = hGrpskg->GetBool("HideUnits", false); - Client.constraintParameters.bShowDimensionalName = hGrpskg->GetBool("ShowDimensionalName", false); - Client.constraintParameters.sDimensionalStringFormat = QString::fromStdString(hGrpskg->GetASCII("DimensionalStringFormat", "%N = %V")); + Client.constraintParameters.bShowDimensionalName = + hGrpskg->GetBool("ShowDimensionalName", false); + Client.constraintParameters.sDimensionalStringFormat = + QString::fromStdString(hGrpskg->GetASCII("DimensionalStringFormat", "%N = %V")); } template -void EditModeCoinManager::ParameterObserver::updateOverlayVisibilityParameter(const std::string & parametername) +void EditModeCoinManager::ParameterObserver::updateOverlayVisibilityParameter( + const std::string& parametername) { - ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplineDegree) - Client.overlayParameters.bSplineDegreeVisible = hGrpsk->GetBool(parametername.c_str(), true); - else if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplineControlPolygonVisible) - Client.overlayParameters.bSplineControlPolygonVisible = hGrpsk->GetBool(parametername.c_str(), true); + Client.overlayParameters.bSplineDegreeVisible = + hGrpsk->GetBool(parametername.c_str(), true); + else if constexpr (visibilityparameter + == OverlayVisibilityParameter::BSplineControlPolygonVisible) + Client.overlayParameters.bSplineControlPolygonVisible = + hGrpsk->GetBool(parametername.c_str(), true); else if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplineCombVisible) Client.overlayParameters.bSplineCombVisible = hGrpsk->GetBool(parametername.c_str(), true); - else if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplineKnotMultiplicityVisible) - Client.overlayParameters.bSplineKnotMultiplicityVisible = hGrpsk->GetBool(parametername.c_str(), true); + else if constexpr (visibilityparameter + == OverlayVisibilityParameter::BSplineKnotMultiplicityVisible) + Client.overlayParameters.bSplineKnotMultiplicityVisible = + hGrpsk->GetBool(parametername.c_str(), true); else if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplinePoleWeightVisible) - Client.overlayParameters.bSplinePoleWeightVisible = hGrpsk->GetBool(parametername.c_str(), true); + Client.overlayParameters.bSplinePoleWeightVisible = + hGrpsk->GetBool(parametername.c_str(), true); else if constexpr (visibilityparameter == OverlayVisibilityParameter::ArcCircleHelperVisible) - Client.overlayParameters.arcCircleHelperVisible = hGrpsk->GetBool(parametername.c_str(), false); + Client.overlayParameters.arcCircleHelperVisible = + hGrpsk->GetBool(parametername.c_str(), false); Client.overlayParameters.visibleInformationChanged = true; } -void EditModeCoinManager::ParameterObserver::updateElementSizeParameters(const std::string & parametername) +void EditModeCoinManager::ParameterObserver::updateElementSizeParameters( + const std::string& parametername) { - (void) parametername; + (void)parametername; - //Add scaling to Constraint icons - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + // Add scaling to Constraint icons + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); double viewScalingFactor = hGrp->GetFloat("ViewScalingFactor", 1.0); viewScalingFactor = Base::clamp(viewScalingFactor, 0.5, 5.0); int markersize = hGrp->GetInt("MarkerSize", 7); - int defaultFontSizePixels = Client.defaultApplicationFontSizePixels(); // returns height in pixels, not points + int defaultFontSizePixels = + Client.defaultApplicationFontSizePixels();// returns height in pixels, not points int sketcherfontSize = hGrp->GetInt("EditSketcherFontSize", defaultFontSizePixels); int dpi = Client.getApplicationLogicalDPIX(); // simple scaling factor for hardcoded pixel values in the Sketcher - Client.drawingParameters.pixelScalingFactor = viewScalingFactor * dpi / 96; // 96 ppi is the standard pixel density for which pixel quantities were calculated + Client.drawingParameters.pixelScalingFactor = viewScalingFactor * dpi + / 96;// 96 ppi is the standard pixel density for which pixel quantities were calculated // About sizes: - // SoDatumLabel takes the size in points, not in pixels. This is because it uses QFont internally. - // Coin, at least our coin at this time, takes pixels, not points. + // SoDatumLabel takes the size in points, not in pixels. This is because it uses QFont + // internally. Coin, at least our coin at this time, takes pixels, not points. // // DPI considerations: // With hdpi monitors, the coin font labels do not respect the size passed in pixels: // https://forum.freecad.org/viewtopic.php?f=3&t=54347&p=467610#p467610 // https://forum.freecad.org/viewtopic.php?f=10&t=49972&start=40#p467471 // - // Because I (abdullah) have 96 dpi logical, 82 dpi physical, and I see a 35px font setting for a "1" in a datum label as 34px, - // and I see kilsore and Elyas screenshots showing 41px and 61px in higher resolution monitors for the same configuration, I think - // that coin pixel size has to be corrected by the logical dpi of the monitor. The rationale is that: a) it obviously needs dpi - // correction, b) with physical dpi, the ratio of representation between kilsore and me is too far away. + // Because I (abdullah) have 96 dpi logical, 82 dpi physical, and I see a 35px font setting for + // a "1" in a datum label as 34px, and I see kilsore and Elyas screenshots showing 41px and 61px + // in higher resolution monitors for the same configuration, I think that coin pixel size has to + // be corrected by the logical dpi of the monitor. The rationale is that: a) it obviously needs + // dpi correction, b) with physical dpi, the ratio of representation between kilsore and me is + // too far away. // - // This means that the following correction does not have a documented basis, but appears necessary so that the Sketcher is usable in - // HDPI monitors. + // This means that the following correction does not have a documented basis, but appears + // necessary so that the Sketcher is usable in HDPI monitors. - Client.drawingParameters.coinFontSize = std::lround(sketcherfontSize * 96.0f / dpi); // this is in pixels - Client.drawingParameters.labelFontSize = std::lround(sketcherfontSize * 72.0f / dpi); // this is in points, as SoDatumLabel uses points + Client.drawingParameters.coinFontSize = + std::lround(sketcherfontSize * 96.0f / dpi);// this is in pixels + Client.drawingParameters.labelFontSize = std::lround( + sketcherfontSize * 72.0f / dpi);// this is in points, as SoDatumLabel uses points Client.drawingParameters.constraintIconSize = std::lround(0.8 * sketcherfontSize); // For marker size the global default is used. @@ -269,9 +376,11 @@ void EditModeCoinManager::ParameterObserver::updateElementSizeParameters(const s Client.updateInventorNodeSizes(); } -void EditModeCoinManager::ParameterObserver::updateColor(SbColor &sbcolor, const std::string ¶metername) +void EditModeCoinManager::ParameterObserver::updateColor(SbColor& sbcolor, + const std::string& parametername) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); float transparency = 0.f; unsigned long color = (unsigned long)(sbcolor.getPackedValue()); @@ -281,84 +390,103 @@ void EditModeCoinManager::ParameterObserver::updateColor(SbColor &sbcolor, const Client.updateInventorColors(); } -void EditModeCoinManager::ParameterObserver::updateUnit(const std::string ¶metername) +void EditModeCoinManager::ParameterObserver::updateUnit(const std::string& parametername) { Q_UNUSED(parametername); - //Nothing to do because we only need Client.redrawViewProvider(); that is already called in OnChange. + // Nothing to do because we only need Client.redrawViewProvider(); that is already called in + // OnChange. } void EditModeCoinManager::ParameterObserver::subscribeToParameters() { try { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); hGrp->Attach(this); - ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrpsk->Attach(this); - ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); hGrpskg->Attach(this); - ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); + ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Units"); hGrpu->Attach(this); } - catch(const Base::ValueError & e) { // ensure that if parameter strings are not well-formed, the exception is not propagated - Base::Console().DeveloperError("EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); + catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the + // exception is not propagated + Base::Console().DeveloperError( + "EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); } } void EditModeCoinManager::ParameterObserver::unsubscribeToParameters() { try { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); hGrp->Detach(this); - ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrpsk->Detach(this); - ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); hGrpskg->Detach(this); - ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); + ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Units"); hGrpu->Detach(this); } - catch(const Base::ValueError & e) {// ensure that if parameter strings are not well-formed, the program is not terminated when calling the noexcept destructor. - Base::Console().DeveloperError("EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); + catch (const Base::ValueError& + e) {// ensure that if parameter strings are not well-formed, the program is not + // terminated when calling the noexcept destructor. + Base::Console().DeveloperError( + "EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); } } -void EditModeCoinManager::ParameterObserver::OnChange(Base::Subject &rCaller, const char * sReason) +void EditModeCoinManager::ParameterObserver::OnChange(Base::Subject& rCaller, + const char* sReason) { - (void) rCaller; + (void)rCaller; auto key = str2updatefunction.find(sReason); - if( key != str2updatefunction.end() ) { - auto string = key->first; - auto function = key->second; + if (key != str2updatefunction.end()) { + auto string = key->first; + auto function = key->second; function(string); - Client.redrawViewProvider(); // redraw with non-temporal geometry + Client.redrawViewProvider();// redraw with non-temporal geometry } } //**************************** EditModeCoinManager class ****************************** -EditModeCoinManager::EditModeCoinManager(ViewProviderSketch &vp):viewProvider(vp) { +EditModeCoinManager::EditModeCoinManager(ViewProviderSketch& vp) + : viewProvider(vp) +{ - pEditModeConstraintCoinManager = std::make_unique(viewProvider, - drawingParameters, - geometryLayerParameters, - constraintParameters, - editModeScenegraphNodes, - coinMapping); + pEditModeConstraintCoinManager = + std::make_unique(viewProvider, + drawingParameters, + geometryLayerParameters, + constraintParameters, + editModeScenegraphNodes, + coinMapping); - pEditModeGeometryCoinManager = std::make_unique( viewProvider, - drawingParameters, - geometryLayerParameters, - analysisResults, - editModeScenegraphNodes, - coinMapping); + pEditModeGeometryCoinManager = + std::make_unique(viewProvider, + drawingParameters, + geometryLayerParameters, + analysisResults, + editModeScenegraphNodes, + coinMapping); // Create Edit Mode Scenograph createEditModeInventorNodes(); @@ -369,43 +497,51 @@ EditModeCoinManager::EditModeCoinManager(ViewProviderSketch &vp):viewProvider(vp EditModeCoinManager::~EditModeCoinManager() { Gui::coinRemoveAllChildren(editModeScenegraphNodes.EditRoot); - ViewProviderSketchCoinAttorney::removeNodeFromRoot(viewProvider, editModeScenegraphNodes.EditRoot); + ViewProviderSketchCoinAttorney::removeNodeFromRoot(viewProvider, + editModeScenegraphNodes.EditRoot); editModeScenegraphNodes.EditRoot->unref(); } /***** Temporary edit curves and markers *****/ -void EditModeCoinManager::drawEditMarkers(const std::vector &EditMarkers, unsigned int augmentationlevel) +void EditModeCoinManager::drawEditMarkers(const std::vector& EditMarkers, + unsigned int augmentationlevel) { // determine marker size int augmentedmarkersize = drawingParameters.markerSize; auto supportedsizes = Gui::Inventor::MarkerBitmaps::getSupportedSizes("CIRCLE_LINE"); - auto defaultmarker = std::find(supportedsizes.begin(), supportedsizes.end(), drawingParameters.markerSize); + auto defaultmarker = + std::find(supportedsizes.begin(), supportedsizes.end(), drawingParameters.markerSize); - if(defaultmarker != supportedsizes.end()) { - auto validAugmentationLevels = std::distance(defaultmarker,supportedsizes.end()); + if (defaultmarker != supportedsizes.end()) { + auto validAugmentationLevels = std::distance(defaultmarker, supportedsizes.end()); - if(augmentationlevel >= validAugmentationLevels) + if (augmentationlevel >= validAugmentationLevels) augmentationlevel = validAugmentationLevels - 1; augmentedmarkersize = *std::next(defaultmarker, augmentationlevel); } editModeScenegraphNodes.EditMarkerSet->markerIndex.startEditing(); - editModeScenegraphNodes.EditMarkerSet->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_LINE", augmentedmarkersize); + editModeScenegraphNodes.EditMarkerSet->markerIndex = + Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_LINE", augmentedmarkersize); // add the points to set editModeScenegraphNodes.EditMarkersCoordinate->point.setNum(EditMarkers.size()); editModeScenegraphNodes.EditMarkersMaterials->diffuseColor.setNum(EditMarkers.size()); - SbVec3f *verts = editModeScenegraphNodes.EditMarkersCoordinate->point.startEditing(); - SbColor *color = editModeScenegraphNodes.EditMarkersMaterials->diffuseColor.startEditing(); + SbVec3f* verts = editModeScenegraphNodes.EditMarkersCoordinate->point.startEditing(); + SbColor* color = editModeScenegraphNodes.EditMarkersMaterials->diffuseColor.startEditing(); - int i=0; // setting up the line set - for (std::vector::const_iterator it = EditMarkers.begin(); it != EditMarkers.end(); ++it,i++) { - verts[i].setValue(it->x, it->y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zEdit); + int i = 0;// setting up the line set + for (std::vector::const_iterator it = EditMarkers.begin(); + it != EditMarkers.end(); + ++it, i++) { + verts[i].setValue(it->x, + it->y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zEdit); color[i] = drawingParameters.InformationColor; } @@ -414,19 +550,22 @@ void EditModeCoinManager::drawEditMarkers(const std::vector &Edi editModeScenegraphNodes.EditMarkerSet->markerIndex.finishEditing(); } -void EditModeCoinManager::drawEdit(const std::vector &EditCurve) +void EditModeCoinManager::drawEdit(const std::vector& EditCurve) { editModeScenegraphNodes.EditCurveSet->numVertices.setNum(1); editModeScenegraphNodes.EditCurvesCoordinate->point.setNum(EditCurve.size()); editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.setNum(EditCurve.size()); - SbVec3f *verts = editModeScenegraphNodes.EditCurvesCoordinate->point.startEditing(); - int32_t *index = editModeScenegraphNodes.EditCurveSet->numVertices.startEditing(); - SbColor *color = editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.startEditing(); + SbVec3f* verts = editModeScenegraphNodes.EditCurvesCoordinate->point.startEditing(); + int32_t* index = editModeScenegraphNodes.EditCurveSet->numVertices.startEditing(); + SbColor* color = editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.startEditing(); - int i=0; // setting up the line set - for (std::vector::const_iterator it = EditCurve.begin(); it != EditCurve.end(); ++it,i++) { - verts[i].setValue(it->x,it->y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zEdit); + int i = 0;// setting up the line set + for (std::vector::const_iterator it = EditCurve.begin(); it != EditCurve.end(); + ++it, i++) { + verts[i].setValue(it->x, + it->y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zEdit); color[i] = drawingParameters.CreateCurveColor; } @@ -436,26 +575,29 @@ void EditModeCoinManager::drawEdit(const std::vector &EditCurve) editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.finishEditing(); } -void EditModeCoinManager::drawEdit(const std::list> &list) +void EditModeCoinManager::drawEdit(const std::list>& list) { int ncoords = 0; - for(const auto & v : list) + for (const auto& v : list) ncoords += v.size(); editModeScenegraphNodes.EditCurveSet->numVertices.setNum(list.size()); editModeScenegraphNodes.EditCurvesCoordinate->point.setNum(ncoords); editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.setNum(ncoords); - SbVec3f *verts = editModeScenegraphNodes.EditCurvesCoordinate->point.startEditing(); - int32_t *index = editModeScenegraphNodes.EditCurveSet->numVertices.startEditing(); - SbColor *color = editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.startEditing(); + SbVec3f* verts = editModeScenegraphNodes.EditCurvesCoordinate->point.startEditing(); + int32_t* index = editModeScenegraphNodes.EditCurveSet->numVertices.startEditing(); + SbColor* color = editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.startEditing(); - int coordindex=0; - int indexindex=0; - for(const auto & v : list) { - for (const auto & p : v) { - verts[coordindex].setValue(p.x, p.y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zEdit); + int coordindex = 0; + int indexindex = 0; + for (const auto& v : list) { + for (const auto& p : v) { + verts[coordindex].setValue( + p.x, + p.y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zEdit); color[coordindex] = drawingParameters.CreateCurveColor; coordindex++; } @@ -466,24 +608,26 @@ void EditModeCoinManager::drawEdit(const std::list> editModeScenegraphNodes.EditCurvesCoordinate->point.finishEditing(); editModeScenegraphNodes.EditCurveSet->numVertices.finishEditing(); editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.finishEditing(); - } -void EditModeCoinManager::setPositionText(const Base::Vector2d &Pos, const SbString &text) +void EditModeCoinManager::setPositionText(const Base::Vector2d& Pos, const SbString& text) { editModeScenegraphNodes.textX->string = text; - editModeScenegraphNodes.textPos->translation = SbVec3f(Pos.x, Pos.y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zText); + editModeScenegraphNodes.textPos->translation = + SbVec3f(Pos.x, + Pos.y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zText); } -void EditModeCoinManager::setPositionText(const Base::Vector2d &Pos) +void EditModeCoinManager::setPositionText(const Base::Vector2d& Pos) { if (showCursorCoords()) { SbString text; std::string xString = lengthToDisplayFormat(Pos.x, 1); std::string yString = lengthToDisplayFormat(Pos.y, 1); text.sprintf(" (%s, %s)", xString.c_str(), yString.c_str()); - setPositionText(Pos,text); + setPositionText(Pos, text); } } @@ -500,25 +644,27 @@ void EditModeCoinManager::setAxisPickStyle(bool on) editModeScenegraphNodes.pickStyleAxes->style = SoPickStyle::UNPICKABLE; } -EditModeCoinManager::PreselectionResult EditModeCoinManager::detectPreselection(SoPickedPoint * Point, const SbVec2s &cursorPos) +EditModeCoinManager::PreselectionResult +EditModeCoinManager::detectPreselection(SoPickedPoint* Point, const SbVec2s& cursorPos) { EditModeCoinManager::PreselectionResult result; - if(!Point) + if (!Point) return result; - //Base::Console().Log("Point pick\n"); - SoPath *path = Point->getPath(); - SoNode *tail = path->getTail(); // Tail is directly the node containing points and curves + // Base::Console().Log("Point pick\n"); + SoPath* path = Point->getPath(); + SoNode* tail = path->getTail();// Tail is directly the node containing points and curves - for(int l = 0; l < geometryLayerParameters.getCoinLayerCount(); l++) { + for (int l = 0; l < geometryLayerParameters.getCoinLayerCount(); l++) { // checking for a hit in the points if (tail == editModeScenegraphNodes.PointSet[l]) { - const SoDetail *point_detail = Point->getDetail(editModeScenegraphNodes.PointSet[l]); + const SoDetail* point_detail = Point->getDetail(editModeScenegraphNodes.PointSet[l]); if (point_detail && point_detail->getTypeId() == SoPointDetail::getClassTypeId()) { // get the index - int pindex = static_cast(point_detail)->getCoordinateIndex(); - result.PointIndex = coinMapping.getPointVertexId(pindex, l); // returns -1 for root, global VertexId for the rest of vertices. + int pindex = static_cast(point_detail)->getCoordinateIndex(); + result.PointIndex = coinMapping.getPointVertexId( + pindex, l);// returns -1 for root, global VertexId for the rest of vertices. if (result.PointIndex == -1) result.Cross = PreselectionResult::Axes::RootPoint; @@ -529,10 +675,10 @@ EditModeCoinManager::PreselectionResult EditModeCoinManager::detectPreselection( // checking for a hit in the curves if (tail == editModeScenegraphNodes.CurveSet[l]) { - const SoDetail *curve_detail = Point->getDetail(editModeScenegraphNodes.CurveSet[l]); + const SoDetail* curve_detail = Point->getDetail(editModeScenegraphNodes.CurveSet[l]); if (curve_detail && curve_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index - int curveIndex = static_cast(curve_detail)->getLineIndex(); + int curveIndex = static_cast(curve_detail)->getLineIndex(); result.GeoIndex = coinMapping.getCurveGeoId(curveIndex, l); return result; @@ -541,21 +687,22 @@ EditModeCoinManager::PreselectionResult EditModeCoinManager::detectPreselection( } // checking for a hit in the axes if (tail == editModeScenegraphNodes.RootCrossSet) { - const SoDetail *cross_detail = Point->getDetail(editModeScenegraphNodes.RootCrossSet); + const SoDetail* cross_detail = Point->getDetail(editModeScenegraphNodes.RootCrossSet); if (cross_detail && cross_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index (reserve index 0 for root point) - int CrossIndex = static_cast(cross_detail)->getLineIndex(); + int CrossIndex = static_cast(cross_detail)->getLineIndex(); - if(CrossIndex == 0) + if (CrossIndex == 0) result.Cross = PreselectionResult::Axes::HorizontalAxis; - else if(CrossIndex == 1) + else if (CrossIndex == 1) result.Cross = PreselectionResult::Axes::VerticalAxis; return result; } } // checking if a constraint is hit - result.ConstrIndices = pEditModeConstraintCoinManager->detectPreselectionConstr(Point, cursorPos); + result.ConstrIndices = + pEditModeConstraintCoinManager->detectPreselectionConstr(Point, cursorPos); return result; } @@ -565,9 +712,9 @@ SoGroup* EditModeCoinManager::getSelectedConstraints() SoGroup* group = new SoGroup(); group->ref(); - for (int i=0; i < editModeScenegraphNodes.constrGroup->getNumChildren(); i++) { + for (int i = 0; i < editModeScenegraphNodes.constrGroup->getNumChildren(); i++) { if (ViewProviderSketchCoinAttorney::isConstraintSelected(viewProvider, i)) { - SoSeparator *sep = pEditModeConstraintCoinManager->getConstraintIdSeparator(i); + SoSeparator* sep = pEditModeConstraintCoinManager->getConstraintIdSeparator(i); if (sep) group->addChild(sep); } @@ -578,7 +725,8 @@ SoGroup* EditModeCoinManager::getSelectedConstraints() /***** update coin nodes *****/ -void EditModeCoinManager::processGeometryConstraintsInformationOverlay(const GeoListFacade & geolistfacade, bool rebuildinformationlayer) +void EditModeCoinManager::processGeometryConstraintsInformationOverlay( + const GeoListFacade& geolistfacade, bool rebuildinformationlayer) { overlayParameters.rebuildInformationLayer = rebuildinformationlayer; @@ -595,42 +743,52 @@ void EditModeCoinManager::processGeometryConstraintsInformationOverlay(const Geo void EditModeCoinManager::updateOverlayParameters() { - if ( (analysisResults.combRepresentationScale > (2 * overlayParameters.currentBSplineCombRepresentationScale)) || - (analysisResults.combRepresentationScale < (overlayParameters.currentBSplineCombRepresentationScale / 2))) - overlayParameters.currentBSplineCombRepresentationScale = analysisResults.combRepresentationScale ; + if ((analysisResults.combRepresentationScale + > (2 * overlayParameters.currentBSplineCombRepresentationScale)) + || (analysisResults.combRepresentationScale + < (overlayParameters.currentBSplineCombRepresentationScale / 2))) + overlayParameters.currentBSplineCombRepresentationScale = + analysisResults.combRepresentationScale; } -void EditModeCoinManager::processGeometryInformationOverlay(const GeoListFacade & geolistfacade) +void EditModeCoinManager::processGeometryInformationOverlay(const GeoListFacade& geolistfacade) { - if(overlayParameters.rebuildInformationLayer) { + if (overlayParameters.rebuildInformationLayer) { // every time we start with empty information overlay Gui::coinRemoveAllChildren(editModeScenegraphNodes.infoGroup); } - auto ioconv = EditModeInformationOverlayCoinConverter(viewProvider, editModeScenegraphNodes.infoGroup, overlayParameters, drawingParameters); + auto ioconv = EditModeInformationOverlayCoinConverter( + viewProvider, editModeScenegraphNodes.infoGroup, overlayParameters, drawingParameters); - // geometry information layer for bsplines, as they need a second round now that max curvature is known + // geometry information layer for bsplines, as they need a second round now that max curvature + // is known for (auto geoid : analysisResults.bsplineGeoIds) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(geoid); + const Part::Geometry* geo = geolistfacade.getGeometryFromGeoId(geoid); ioconv.convert(geo, geoid); } for (auto geoid : analysisResults.arcGeoIds) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(geoid); + const Part::Geometry* geo = geolistfacade.getGeometryFromGeoId(geoid); ioconv.convert(geo, geoid); } - overlayParameters.visibleInformationChanged = false; // just updated + overlayParameters.visibleInformationChanged = false;// just updated } void EditModeCoinManager::updateAxesLength() { - auto zCrossH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zCross; - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(0,SbVec3f(-analysisResults.boundingBoxMagnitudeOrder, 0.0f, zCrossH)); - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(1,SbVec3f(analysisResults.boundingBoxMagnitudeOrder, 0.0f, zCrossH)); - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(2,SbVec3f(0.0f, -analysisResults.boundingBoxMagnitudeOrder, zCrossH)); - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(3,SbVec3f(0.0f, analysisResults.boundingBoxMagnitudeOrder, zCrossH)); + auto zCrossH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zCross; + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value( + 0, SbVec3f(-analysisResults.boundingBoxMagnitudeOrder, 0.0f, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value( + 1, SbVec3f(analysisResults.boundingBoxMagnitudeOrder, 0.0f, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value( + 2, SbVec3f(0.0f, -analysisResults.boundingBoxMagnitudeOrder, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value( + 3, SbVec3f(0.0f, analysisResults.boundingBoxMagnitudeOrder, zCrossH)); } void EditModeCoinManager::updateColor() @@ -640,7 +798,7 @@ void EditModeCoinManager::updateColor() updateColor(geolistfacade); } -void EditModeCoinManager::updateColor(const GeoListFacade & geolistfacade) +void EditModeCoinManager::updateColor(const GeoListFacade& geolistfacade) { bool sketchinvalid = ViewProviderSketchCoinAttorney::isSketchInvalid(viewProvider); @@ -650,7 +808,7 @@ void EditModeCoinManager::updateColor(const GeoListFacade & geolistfacade) auto constraints = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); - if(ViewProviderSketchCoinAttorney::haveConstraintsInvalidGeometry(viewProvider)) + if (ViewProviderSketchCoinAttorney::haveConstraintsInvalidGeometry(viewProvider)) return; pEditModeConstraintCoinManager->updateConstraintColor(constraints); @@ -671,10 +829,11 @@ void EditModeCoinManager::createEditModeInventorNodes() { // 1 - Create the edit root node editModeScenegraphNodes.EditRoot = new SoSeparator; - editModeScenegraphNodes.EditRoot->ref(); // Node is unref in the destructor of EditModeCoinManager + editModeScenegraphNodes.EditRoot + ->ref();// Node is unref in the destructor of EditModeCoinManager editModeScenegraphNodes.EditRoot->setName("Sketch_EditRoot"); ViewProviderSketchCoinAttorney::addNodeToRoot(viewProvider, editModeScenegraphNodes.EditRoot); - editModeScenegraphNodes.EditRoot->renderCaching = SoSeparator::OFF ; + editModeScenegraphNodes.EditRoot->renderCaching = SoSeparator::OFF; // Create Geometry Coin nodes ++++++++++++++++++++++++++++++++++++++ pEditModeGeometryCoinManager->createEditModeInventorNodes(); @@ -692,13 +851,16 @@ void EditModeCoinManager::createEditModeInventorNodes() editModeScenegraphNodes.RootCrossDrawStyle = new SoDrawStyle; editModeScenegraphNodes.RootCrossDrawStyle->setName("RootCrossDrawStyle"); - editModeScenegraphNodes.RootCrossDrawStyle->lineWidth = 2 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.RootCrossDrawStyle->lineWidth = + 2 * drawingParameters.pixelScalingFactor; crossRoot->addChild(editModeScenegraphNodes.RootCrossDrawStyle); editModeScenegraphNodes.RootCrossMaterials = new SoMaterial; editModeScenegraphNodes.RootCrossMaterials->setName("RootCrossMaterials"); - editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value(0, drawingParameters.CrossColorH); - editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value(1, drawingParameters.CrossColorV); + editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value( + 0, drawingParameters.CrossColorH); + editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value( + 1, drawingParameters.CrossColorV); crossRoot->addChild(editModeScenegraphNodes.RootCrossMaterials); editModeScenegraphNodes.RootCrossCoordinate = new SoCoordinate3; @@ -722,7 +884,8 @@ void EditModeCoinManager::createEditModeInventorNodes() editModeScenegraphNodes.EditCurvesDrawStyle = new SoDrawStyle; editModeScenegraphNodes.EditCurvesDrawStyle->setName("EditCurvesDrawStyle"); - editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = 3 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = + 3 * drawingParameters.pixelScalingFactor; editCurvesRoot->addChild(editModeScenegraphNodes.EditCurvesDrawStyle); editModeScenegraphNodes.EditCurveSet = new SoLineSet; @@ -742,16 +905,18 @@ void EditModeCoinManager::createEditModeInventorNodes() editModeScenegraphNodes.EditMarkersDrawStyle = new SoDrawStyle; editModeScenegraphNodes.EditMarkersDrawStyle->setName("EditMarkersDrawStyle"); - editModeScenegraphNodes.EditMarkersDrawStyle->pointSize = 8 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.EditMarkersDrawStyle->pointSize = + 8 * drawingParameters.pixelScalingFactor; editMarkersRoot->addChild(editModeScenegraphNodes.EditMarkersDrawStyle); editModeScenegraphNodes.EditMarkerSet = new SoMarkerSet; editModeScenegraphNodes.EditMarkerSet->setName("EditMarkerSet"); - editModeScenegraphNodes.EditMarkerSet->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_LINE", drawingParameters.markerSize); + editModeScenegraphNodes.EditMarkerSet->markerIndex = + Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_LINE", drawingParameters.markerSize); editMarkersRoot->addChild(editModeScenegraphNodes.EditMarkerSet); // stuff for the edit coordinates ++++++++++++++++++++++++++++++++++++++ - SoSeparator *Coordsep = new SoSeparator(); + SoSeparator* Coordsep = new SoSeparator(); SoPickStyle* ps = new SoPickStyle(); ps->style.setValue(SoPickStyle::UNPICKABLE); Coordsep->addChild(ps); @@ -785,13 +950,14 @@ void EditModeCoinManager::createEditModeInventorNodes() // group node for the Geometry information visual +++++++++++++++++++++++++++++++++++ MtlBind = new SoMaterialBinding; MtlBind->setName("InformationMaterialBinding"); - MtlBind->value = SoMaterialBinding::OVERALL ; + MtlBind->value = SoMaterialBinding::OVERALL; editModeScenegraphNodes.EditRoot->addChild(MtlBind); // use small line width for the information visual editModeScenegraphNodes.InformationDrawStyle = new SoDrawStyle; editModeScenegraphNodes.InformationDrawStyle->setName("InformationDrawStyle"); - editModeScenegraphNodes.InformationDrawStyle->lineWidth = 1 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.InformationDrawStyle->lineWidth = + 1 * drawingParameters.pixelScalingFactor; editModeScenegraphNodes.EditRoot->addChild(editModeScenegraphNodes.InformationDrawStyle); // add the group where all the information entity has its SoSeparator @@ -802,7 +968,7 @@ void EditModeCoinManager::createEditModeInventorNodes() void EditModeCoinManager::redrawViewProvider() { - viewProvider.draw(false,false); + viewProvider.draw(false, false); } /************************ Delegated constraint public interface **********/ @@ -813,7 +979,7 @@ void EditModeCoinManager::drawConstraintIcons() pEditModeConstraintCoinManager->drawConstraintIcons(); } -void EditModeCoinManager::drawConstraintIcons(const GeoListFacade & geolistfacade) +void EditModeCoinManager::drawConstraintIcons(const GeoListFacade& geolistfacade) { pEditModeConstraintCoinManager->drawConstraintIcons(geolistfacade); } @@ -825,11 +991,13 @@ void EditModeCoinManager::updateVirtualSpace() /************************ Resizing of coin nodes ************************/ -int EditModeCoinManager::defaultApplicationFontSizePixels() const { +int EditModeCoinManager::defaultApplicationFontSizePixels() const +{ return ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(viewProvider); } -int EditModeCoinManager::getApplicationLogicalDPIX() const { +int EditModeCoinManager::getApplicationLogicalDPIX() const +{ return ViewProviderSketchCoinAttorney::getApplicationLogicalDPIX(viewProvider); } @@ -837,18 +1005,28 @@ void EditModeCoinManager::updateInventorNodeSizes() { auto layersconfiguration = viewProvider.VisualLayerList.getValues(); - for(int l = 0; l < geometryLayerParameters.getCoinLayerCount(); l++) { - editModeScenegraphNodes.PointsDrawStyle[l]->pointSize = 8 * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.PointSet[l]->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", drawingParameters.markerSize); - editModeScenegraphNodes.CurvesDrawStyle[l]->lineWidth = layersconfiguration[l].getLineWidth() * drawingParameters.pixelScalingFactor; + for (int l = 0; l < geometryLayerParameters.getCoinLayerCount(); l++) { + editModeScenegraphNodes.PointsDrawStyle[l]->pointSize = + 8 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.PointSet[l]->markerIndex = + Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", + drawingParameters.markerSize); + editModeScenegraphNodes.CurvesDrawStyle[l]->lineWidth = + layersconfiguration[l].getLineWidth() * drawingParameters.pixelScalingFactor; } - editModeScenegraphNodes.RootCrossDrawStyle->lineWidth = 2 * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = 3 * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.EditMarkersDrawStyle->pointSize = 8 * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.EditMarkerSet->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_LINE", drawingParameters.markerSize); - editModeScenegraphNodes.ConstraintDrawStyle->lineWidth = 1 * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.InformationDrawStyle->lineWidth = 1 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.RootCrossDrawStyle->lineWidth = + 2 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = + 3 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.EditMarkersDrawStyle->pointSize = + 8 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.EditMarkerSet->markerIndex = + Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_LINE", drawingParameters.markerSize); + editModeScenegraphNodes.ConstraintDrawStyle->lineWidth = + 1 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.InformationDrawStyle->lineWidth = + 1 * drawingParameters.pixelScalingFactor; editModeScenegraphNodes.textFont->size.setValue(drawingParameters.coinFontSize); @@ -857,8 +1035,10 @@ void EditModeCoinManager::updateInventorNodeSizes() void EditModeCoinManager::updateInventorColors() { - editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value(0, drawingParameters.CrossColorH); - editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value(1, drawingParameters.CrossColorV); + editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value( + 0, drawingParameters.CrossColorH); + editModeScenegraphNodes.RootCrossMaterials->diffuseColor.set1Value( + 1, drawingParameters.CrossColorV); editModeScenegraphNodes.textMaterial->diffuseColor = drawingParameters.CursorTextColor; } diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.h b/src/Mod/Sketcher/Gui/EditModeCoinManager.h index 7ee9b842c2..348eafecb5 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.h @@ -37,25 +37,29 @@ class SoRayPickAction; class SoPickedPoint; class SbVec3s; -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; - class Vector2d; +class Vector2d; - class Placement; +class Placement; +}// namespace Base + +namespace Part +{ +class Geometry; } -namespace Part { - class Geometry; -} +namespace Sketcher +{ +class Constraint; +class PropertyConstraintList; +};// namespace Sketcher -namespace Sketcher { - class Constraint; - class PropertyConstraintList; -}; - -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; class EditModeConstraintCoinManager; @@ -71,7 +75,8 @@ using GeoListFacade = Sketcher::GeoListFacade; * further delegates on other specialised helper classes. Some of them share the * ViewProviderSketchCoinAttorney, which defines the maximum coupling and minimum encapsulation. * - * The most important such delegates are: EditModeGeometryCoinManager and EditModeConstraintCoinManager. + * The most important such delegates are: EditModeGeometryCoinManager and + * EditModeConstraintCoinManager. * * EditModeCoinManager takes over the responsibility of creating the Coin (Inventor) scenograph * and modifying it, including all the drawing of geometry, constraints and overlay layer. This @@ -82,31 +87,35 @@ using GeoListFacade = Sketcher::GeoListFacade; * its responsibility, this access is defined by ViewProviderSketchCoinAttorney. * * EditModeCoinManager is responsible, under the Single Responsibility Principle, to manage the coin - * EditRoot node. This node is ref-ed on creation and unref-ed on destruction to ensure that its lifetime - * matches the one of EditModecoinManager. + * EditRoot node. This node is ref-ed on creation and unref-ed on destruction to ensure that its + * lifetime matches the one of EditModecoinManager. * - * EditRoot is added on request to pcRoot by ViewProviderSketch. The node pcRoot belongs, under the Single - * Responsibility Principle, to ViewProviderSketch. EditModeCoinManager delegates addition and removal of - * child notes of EditRoot to specialised helper classes. + * EditRoot is added on request to pcRoot by ViewProviderSketch. The node pcRoot belongs, under the + * Single Responsibility Principle, to ViewProviderSketch. EditModeCoinManager delegates addition + * and removal of child notes of EditRoot to specialised helper classes. * - * EditModeCoinManager is designed to define the span of time in which ViewProviderSketch is in edit mode. + * EditModeCoinManager is designed to define the span of time in which ViewProviderSketch is in edit + * mode. * - * In addition to the scenograph, EditModeCoinManager is responsible for keeping any necessary mapping between - * indices used at ViewProviderSketch level, and internal indexing used by EditModeCoinManager and its subclasses. + * In addition to the scenograph, EditModeCoinManager is responsible for keeping any necessary + * mapping between indices used at ViewProviderSketch level, and internal indexing used by + * EditModeCoinManager and its subclasses. */ class SketcherGuiExport EditModeCoinManager { - /** @brief Class for monitoring changes in parameters affecting drawing and coin node generation - * @details - * - * This nested class is a helper responsible for attaching to the parameters relevant for - * EditModeCoinManager and its helpers, initialising the EditModeCoinManager to the current configuration - * and handle in real time any change to their values. - */ - class ParameterObserver : public ParameterGrp::ObserverType + /** @brief Class for monitoring changes in parameters affecting drawing and coin node + * generation + * @details + * + * This nested class is a helper responsible for attaching to the parameters relevant for + * EditModeCoinManager and its helpers, initialising the EditModeCoinManager to the current + * configuration and handle in real time any change to their values. + */ + class ParameterObserver: public ParameterGrp::ObserverType { private: - enum class OverlayVisibilityParameter { + enum class OverlayVisibilityParameter + { BSplineDegree, BSplineControlPolygonVisible, BSplineCombVisible, @@ -116,7 +125,7 @@ class SketcherGuiExport EditModeCoinManager }; public: - explicit ParameterObserver(EditModeCoinManager & client); + explicit ParameterObserver(EditModeCoinManager& client); ~ParameterObserver() override; void subscribeToParameters(); @@ -124,23 +133,23 @@ class SketcherGuiExport EditModeCoinManager void unsubscribeToParameters(); /** Observer for parameter group. */ - void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject& rCaller, const char* sReason) override; private: void initParameters(); - void updateCurvedEdgeCountSegmentsParameter(const std::string & parametername); - void updateLineRenderingOrderParameters(const std::string & parametername); - void updateConstraintPresentationParameters(const std::string & parametername); - void updateElementSizeParameters(const std::string & parametername); - void updateColor(SbColor &sbcolor, const std::string ¶metername); - void updateUnit(const std::string ¶metername); + void updateCurvedEdgeCountSegmentsParameter(const std::string& parametername); + void updateLineRenderingOrderParameters(const std::string& parametername); + void updateConstraintPresentationParameters(const std::string& parametername); + void updateElementSizeParameters(const std::string& parametername); + void updateColor(SbColor& sbcolor, const std::string& parametername); + void updateUnit(const std::string& parametername); template - void updateOverlayVisibilityParameter(const std::string & parametername); + void updateOverlayVisibilityParameter(const std::string& parametername); private: - std::map> str2updatefunction; - EditModeCoinManager &Client; + std::map> str2updatefunction; + EditModeCoinManager& Client; }; public: @@ -148,22 +157,27 @@ public: * * @details * - * PointIndex: Only Positive values corresponding to VertexId (are positive for both normal and external geometry) - * GeoIndex: Same values as GeoId of GeoElementId, except for axes which are not included. -1 represents an invalid curve. + * PointIndex: Only Positive values corresponding to VertexId (are positive for both normal and + * external geometry) GeoIndex: Same values as GeoId of GeoElementId, except for axes which are + * not included. -1 represents an invalid curve. * - * In other words valid values are 0,1,2,... for normal geometry and -3,-4,-5,... for external geometry + * In other words valid values are 0,1,2,... for normal geometry and -3,-4,-5,... for external + * geometry * * Cross: Axes and RootPoint values as defined in the enum class. * */ - struct PreselectionResult { - enum SpecialValues { + struct PreselectionResult + { + enum SpecialValues + { InvalidPoint = -1, InvalidCurve = -1, ExternalCurve = -3 }; - enum class Axes { + enum class Axes + { None = -1, RootPoint = 0, HorizontalAxis = 1, @@ -171,11 +185,13 @@ public: }; int PointIndex = InvalidPoint; - int GeoIndex = InvalidCurve; // valid values are 0,1,2,... for normal geometry and -3,-4,-5,... for external geometry + int GeoIndex = InvalidCurve;// valid values are 0,1,2,... for normal geometry and + // -3,-4,-5,... for external geometry Axes Cross = Axes::None; std::set ConstrIndices; - inline void clear() { + inline void clear() + { PointIndex = InvalidPoint; GeoIndex = InvalidCurve; Cross = Axes::None; @@ -184,29 +200,31 @@ public: }; public: - explicit EditModeCoinManager(ViewProviderSketch &vp); + explicit EditModeCoinManager(ViewProviderSketch& vp); ~EditModeCoinManager(); - /** @name Temporary edit curves and markers */ + /** @name Temporary edit curves and markers */ //@{ - void drawEditMarkers(const std::vector &EditMarkers, unsigned int augmentationlevel); - void drawEdit(const std::vector &EditCurve); - void drawEdit(const std::list> &list); - void setPositionText(const Base::Vector2d &Pos, const SbString &txt); - void setPositionText(const Base::Vector2d &Pos); + void drawEditMarkers(const std::vector& EditMarkers, + unsigned int augmentationlevel); + void drawEdit(const std::vector& EditCurve); + void drawEdit(const std::list>& list); + void setPositionText(const Base::Vector2d& Pos, const SbString& txt); + void setPositionText(const Base::Vector2d& Pos); void resetPositionText(); void setAxisPickStyle(bool on); //@} /** @name handle preselection and selection of points */ //@{ - PreselectionResult detectPreselection(SoPickedPoint * Point, const SbVec2s &cursorPos); + PreselectionResult detectPreselection(SoPickedPoint* Point, const SbVec2s& cursorPos); /// The client is responsible for unref-ing the SoGroup to release the memory. SoGroup* getSelectedConstraints(); //@} /** @name update coin nodes*/ - void processGeometryConstraintsInformationOverlay(const GeoListFacade & geolistfacade, bool rebuildinformationlayer); + void processGeometryConstraintsInformationOverlay(const GeoListFacade& geolistfacade, + bool rebuildinformationlayer); void updateVirtualSpace(); @@ -215,7 +233,7 @@ public: void drawConstraintIcons(); // This specific overload is to use a specific geometry list, which may be a temporal one - void drawConstraintIcons(const GeoListFacade & geolistfacade); + void drawConstraintIcons(const GeoListFacade& geolistfacade); void updateGeometryLayersConfiguration(); //@} @@ -227,7 +245,8 @@ public: /** @name update coin colors*/ //@{ void updateColor(); - void updateColor(const GeoListFacade & geolistfacade); // overload to be used with temporal geometry. + void + updateColor(const GeoListFacade& geolistfacade);// overload to be used with temporal geometry. //@} /** @name change constraints selectability*/ @@ -237,11 +256,12 @@ public: private: // This function populates the coin nodes with the information of the current geometry - void processGeometry(const GeoListFacade & geolistfacade); + void processGeometry(const GeoListFacade& geolistfacade); - // This function populates the geometry information layer of coin. It requires the analysis information - // gathered during the processGeometry step, so it is not possible to run both in parallel. - void processGeometryInformationOverlay(const GeoListFacade & geolistfacade); + // This function populates the geometry information layer of coin. It requires the analysis + // information gathered during the processGeometry step, so it is not possible to run both in + // parallel. + void processGeometryInformationOverlay(const GeoListFacade& geolistfacade); // updates the Axes length to extend beyond the calculated bounding box magnitude void updateAxesLength(); @@ -249,7 +269,7 @@ private: // updates the parameters to be used for the Overlay information layer void updateOverlayParameters(); - void updateGeometryColor(const GeoListFacade & geolistfacade, bool issketchinvalid); + void updateGeometryColor(const GeoListFacade& geolistfacade, bool issketchinvalid); // causes the ViewProvider to draw void redrawViewProvider(); @@ -268,7 +288,7 @@ private: private: /// Reference to ViewProviderSketch in order to access the public and the Attorney Interface - ViewProviderSketch & viewProvider; + ViewProviderSketch& viewProvider; /// Observer to track all the needed parameters. std::unique_ptr pObserver; @@ -290,8 +310,7 @@ private: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_EditModeCoinManager_H - +#endif// SKETCHERGUI_EditModeCoinManager_H diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp index 207274c138..aa928f5ac7 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp @@ -27,30 +27,35 @@ using namespace SketcherGui; -SbColor DrawingParameters::InformationColor (0.0f, 1.0f, 0.0f); // #00FF00 -> ( 0,255, 0) -SbColor DrawingParameters::CreateCurveColor (0.8f, 0.8f, 0.8f); // #CCCCCC -> (204,204,204) -SbColor DrawingParameters::CrossColorH (0.8f, 0.4f, 0.4f); // #CC6666 -> (204,102,102) -SbColor DrawingParameters::CrossColorV (0.47f, 1.0f, 0.51f); // #83FF83 -> (120,255,131) -SbColor DrawingParameters::InvalidSketchColor (1.0f, 0.42f, 0.0f); // #FF6D00 -> (255,109, 0) -SbColor DrawingParameters::FullyConstrainedColor (0.0f, 1.0f, 0.0f); // #00FF00 -> ( 0,255, 0) -SbColor DrawingParameters::FullyConstraintInternalAlignmentColor (0.87f, 0.87f, 0.78f); // #DEDEC8 -> (222,222,200) -SbColor DrawingParameters::InternalAlignedGeoColor (0.7f, 0.7f, 0.5f); // #B2B27F -> (178,178,127) -SbColor DrawingParameters::FullyConstraintConstructionPointColor (1.0f, 0.58f, 0.50f); // #FF9580 -> (255,149,128) -SbColor DrawingParameters::VertexColor (1.0f, 0.149f, 0.0f); // #FF2600 -> (255, 38, 0) -SbColor DrawingParameters::FullyConstraintElementColor (0.50f, 0.81f, 0.62f); // #80D0A0 -> (128,208,160) -SbColor DrawingParameters::CurveColor (1.0f, 1.0f, 1.0f); // #FFFFFF -> (255,255,255) -SbColor DrawingParameters::PreselectColor (0.88f, 0.88f, 0.0f); // #E1E100 -> (225,225, 0) -SbColor DrawingParameters::SelectColor (0.11f, 0.68f, 0.11f); // #1CAD1C -> ( 28,173, 28) -SbColor DrawingParameters::PreselectSelectedColor (0.36f, 0.48f, 0.11f); // #5D7B1C -> ( 93,123, 28) -SbColor DrawingParameters::CurveExternalColor (0.8f, 0.2f, 0.6f); // #CC3399 -> (204, 51,153) -SbColor DrawingParameters::CurveDraftColor (0.0f, 0.0f, 0.86f); // #0000DC -> ( 0, 0,220) -SbColor DrawingParameters::FullyConstraintConstructionElementColor (0.56f, 0.66f, 0.99f); // #8FA9FD -> (143,169,253) +SbColor DrawingParameters::InformationColor(0.0f, 1.0f, 0.0f); // #00FF00 -> ( 0,255, 0) +SbColor DrawingParameters::CreateCurveColor(0.8f, 0.8f, 0.8f); // #CCCCCC -> (204,204,204) +SbColor DrawingParameters::CrossColorH(0.8f, 0.4f, 0.4f); // #CC6666 -> (204,102,102) +SbColor DrawingParameters::CrossColorV(0.47f, 1.0f, 0.51f); // #83FF83 -> (120,255,131) +SbColor DrawingParameters::InvalidSketchColor(1.0f, 0.42f, 0.0f); // #FF6D00 -> (255,109, 0) +SbColor DrawingParameters::FullyConstrainedColor(0.0f, 1.0f, 0.0f);// #00FF00 -> ( 0,255, 0) +SbColor DrawingParameters::FullyConstraintInternalAlignmentColor(0.87f, 0.87f, + 0.78f);// #DEDEC8 -> (222,222,200) +SbColor DrawingParameters::InternalAlignedGeoColor(0.7f, 0.7f, 0.5f); // #B2B27F -> (178,178,127) +SbColor DrawingParameters::FullyConstraintConstructionPointColor(1.0f, 0.58f, + 0.50f);// #FF9580 -> (255,149,128) +SbColor DrawingParameters::VertexColor(1.0f, 0.149f, 0.0f); // #FF2600 -> (255, 38, 0) +SbColor DrawingParameters::FullyConstraintElementColor(0.50f, 0.81f, + 0.62f); // #80D0A0 -> (128,208,160) +SbColor DrawingParameters::CurveColor(1.0f, 1.0f, 1.0f); // #FFFFFF -> (255,255,255) +SbColor DrawingParameters::PreselectColor(0.88f, 0.88f, 0.0f); // #E1E100 -> (225,225, 0) +SbColor DrawingParameters::SelectColor(0.11f, 0.68f, 0.11f); // #1CAD1C -> ( 28,173, 28) +SbColor DrawingParameters::PreselectSelectedColor(0.36f, 0.48f, 0.11f);// #5D7B1C -> ( 93,123, 28) +SbColor DrawingParameters::CurveExternalColor(0.8f, 0.2f, 0.6f); // #CC3399 -> (204, 51,153) +SbColor DrawingParameters::CurveDraftColor(0.0f, 0.0f, 0.86f); // #0000DC -> ( 0, 0,220) +SbColor + DrawingParameters::FullyConstraintConstructionElementColor(0.56f, 0.66f, + 0.99f);// #8FA9FD -> (143,169,253) -SbColor DrawingParameters::ConstrDimColor (1.0f, 0.149f, 0.0f); // #FF2600 -> (255, 38, 0) -SbColor DrawingParameters::ConstrIcoColor (1.0f, 0.149f, 0.0f); // #FF2600 -> (255, 38, 0) -SbColor DrawingParameters::NonDrivingConstrDimColor (0.0f, 0.149f, 1.0f); // #0026FF -> ( 0, 38,255) -SbColor DrawingParameters::ExprBasedConstrDimColor (1.0f, 0.5f, 0.149f); // #FF7F26 -> (255, 127,38) -SbColor DrawingParameters::DeactivatedConstrDimColor (0.8f, 0.8f, 0.8f); // #CCCCCC -> (204,204,204) -SbColor DrawingParameters::CursorTextColor (0.0f, 0.0f, 1.0f); // #0000FF -> (0,0,255) +SbColor DrawingParameters::ConstrDimColor(1.0f, 0.149f, 0.0f); // #FF2600 -> (255, 38, 0) +SbColor DrawingParameters::ConstrIcoColor(1.0f, 0.149f, 0.0f); // #FF2600 -> (255, 38, 0) +SbColor DrawingParameters::NonDrivingConstrDimColor(0.0f, 0.149f, 1.0f);// #0026FF -> ( 0, 38,255) +SbColor DrawingParameters::ExprBasedConstrDimColor(1.0f, 0.5f, 0.149f); // #FF7F26 -> (255, 127,38) +SbColor DrawingParameters::DeactivatedConstrDimColor(0.8f, 0.8f, 0.8f); // #CCCCCC -> (204,204,204) +SbColor DrawingParameters::CursorTextColor(0.0f, 0.0f, 1.0f); // #0000FF -> (0,0,255) const MultiFieldId MultiFieldId::Invalid = MultiFieldId(); diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h index d52ffece39..90ae4386eb 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h @@ -29,8 +29,8 @@ #include #include -#include #include +#include #include #include #include @@ -47,39 +47,45 @@ #include "ViewProviderSketchGeometryExtension.h" -namespace Part { - class Geometry; +namespace Part +{ +class Geometry; } -namespace SketcherGui { +namespace SketcherGui +{ /** @brief Struct for storing local drawing parameters * * Parameters based on user preferenced are auto loaded by EditCoinManager observer nested class. */ -struct DrawingParameters { +struct DrawingParameters +{ /// Defines the number of segments to use to draw a curved edge int curvedEdgeCountSegments; - /** @name Rendering Heights - virtual height introduced in the scenegraph to determine what is drawn on top of what*/ + /** @name Rendering Heights - virtual height introduced in the scenegraph to determine what is + * drawn on top of what*/ //@{ - const float zEdit = 0.001f; // Height used by temporal edit curves - const float zCross = 0.001f; // Height used by the Axes - const float zInfo = 0.004f; // Height used by the Overlay information layer - const float zLowLines = 0.005f; // Height used for bottom rendered lines - const float zMidLines = 0.006f; // Height used for in-the-middle rendered lines - const float zHighLines = 0.007f; // Height used for on top rendered lines - const float zHighLine = 0.008f; // Height for highlighted lines (selected/preselected) - const float zConstr = 0.009f; // Height for rendering constraints - const float zRootPoint = 0.010f; // Height used for rendering the root point - const float zLowPoints = 0.011f; // Height used for bottom rendered points - const float zHighPoints = 0.012f; // Height used for in-the-middle rendered points - const float zHighlight = 0.013f; // Height for highlighted points (selected/preselected) - const float zText = 0.013f; // Height for rendered text + const float zEdit = 0.001f; // Height used by temporal edit curves + const float zCross = 0.001f; // Height used by the Axes + const float zInfo = 0.004f; // Height used by the Overlay information layer + const float zLowLines = 0.005f; // Height used for bottom rendered lines + const float zMidLines = 0.006f; // Height used for in-the-middle rendered lines + const float zHighLines = 0.007f; // Height used for on top rendered lines + const float zHighLine = 0.008f; // Height for highlighted lines (selected/preselected) + const float zConstr = 0.009f; // Height for rendering constraints + const float zRootPoint = 0.010f; // Height used for rendering the root point + const float zLowPoints = 0.011f; // Height used for bottom rendered points + const float zHighPoints = 0.012f;// Height used for in-the-middle rendered points + const float zHighlight = 0.013f; // Height for highlighted points (selected/preselected) + const float zText = 0.013f; // Height for rendered text //@} - /// Different categories of geometries that can be selected by the user to be rendered on top, in the middle or in the bottom - enum class GeometryRendering { + /// Different categories of geometries that can be selected by the user to be rendered on top, + /// in the middle or in the bottom + enum class GeometryRendering + { NormalGeometry = 1, Construction = 2, ExternalGeometry = 3 @@ -93,80 +99,93 @@ struct DrawingParameters { /** @name Rendering Coin Colors **/ //@{ - static SbColor InformationColor; // Information Overlay Color - static SbColor CreateCurveColor; // Color for Edit Curves during creation - static SbColor CrossColorH; // Color for the Horizontal Axis - static SbColor CrossColorV; // Color for the Vertical Axis - static SbColor InvalidSketchColor; // Color for rendering an invalid sketch - static SbColor FullyConstrainedColor; // Color for a fully constrained sketch - static SbColor FullyConstraintInternalAlignmentColor; // Color for fully constrained internal alignment geometry - static SbColor InternalAlignedGeoColor; // Color for non-fully constrained internal alignment geometry - static SbColor FullyConstraintConstructionPointColor; // Color for fully constrained construction points - static SbColor VertexColor; // Color for vertices - static SbColor FullyConstraintElementColor; // Color for a fully constrained element - static SbColor CurveColor; // Color for curves - static SbColor PreselectColor; // Color used for pre-selection - static SbColor PreselectSelectedColor; // Color used for pre-selection when geometry is already selected - static SbColor SelectColor; // Color used for selected geometry - static SbColor CurveExternalColor; // Color used for external geometry - static SbColor CurveDraftColor; // Color used for construction geometry - static SbColor FullyConstraintConstructionElementColor; // Color used for a fully constrained construction element - static SbColor ConstrDimColor; // Color used for a dimensional constraints - static SbColor ConstrIcoColor; // Color used for constraint icons - static SbColor NonDrivingConstrDimColor; // Color used for non-driving (reference) dimensional constraints - static SbColor ExprBasedConstrDimColor; // Color used for expression based dimensional constraints - static SbColor DeactivatedConstrDimColor; // Color used for deactivated dimensional constraints - static SbColor CursorTextColor; // Color used by the edit mode cursor + static SbColor InformationColor; // Information Overlay Color + static SbColor CreateCurveColor; // Color for Edit Curves during creation + static SbColor CrossColorH; // Color for the Horizontal Axis + static SbColor CrossColorV; // Color for the Vertical Axis + static SbColor InvalidSketchColor; // Color for rendering an invalid sketch + static SbColor FullyConstrainedColor; // Color for a fully constrained sketch + static SbColor FullyConstraintInternalAlignmentColor;// Color for fully constrained internal + // alignment geometry + static SbColor + InternalAlignedGeoColor;// Color for non-fully constrained internal alignment geometry + static SbColor + FullyConstraintConstructionPointColor; // Color for fully constrained construction points + static SbColor VertexColor; // Color for vertices + static SbColor FullyConstraintElementColor;// Color for a fully constrained element + static SbColor CurveColor; // Color for curves + static SbColor PreselectColor; // Color used for pre-selection + static SbColor + PreselectSelectedColor;// Color used for pre-selection when geometry is already selected + static SbColor SelectColor;// Color used for selected geometry + static SbColor CurveExternalColor; // Color used for external geometry + static SbColor CurveDraftColor; // Color used for construction geometry + static SbColor FullyConstraintConstructionElementColor;// Color used for a fully constrained + // construction element + static SbColor ConstrDimColor;// Color used for a dimensional constraints + static SbColor ConstrIcoColor;// Color used for constraint icons + static SbColor + NonDrivingConstrDimColor;// Color used for non-driving (reference) dimensional constraints + static SbColor + ExprBasedConstrDimColor;// Color used for expression based dimensional constraints + static SbColor DeactivatedConstrDimColor;// Color used for deactivated dimensional constraints + static SbColor CursorTextColor; // Color used by the edit mode cursor //@} /** @name Rendering sizes (also to support HDPI monitors) **/ //@{ - double pixelScalingFactor = 1.0; // Scaling factor to be used for pixels - int coinFontSize = 17; // Font size to be used by coin - int labelFontSize = 17; // Font size to be used by SoDatumLabel, which uses a QPainter and a QFont internally - int constraintIconSize = 15; // Size of constraint icons - int markerSize = 7; // Size used for markers + double pixelScalingFactor = 1.0;// Scaling factor to be used for pixels + int coinFontSize = 17; // Font size to be used by coin + int labelFontSize = + 17;// Font size to be used by SoDatumLabel, which uses a QPainter and a QFont internally + int constraintIconSize = 15;// Size of constraint icons + int markerSize = 7; // Size used for markers //@} }; /** @brief Struct for storing references to the scenegraph nodes necessary for geometry layers */ -struct GeometryLayerNodes { +struct GeometryLayerNodes +{ /** @name Point nodes*/ //@{ - std::vector & PointsMaterials; // The materials for the points/vertices - std::vector& PointsCoordinate; // The coordinates of the points/vertices + std::vector& PointsMaterials; // The materials for the points/vertices + std::vector& PointsCoordinate;// The coordinates of the points/vertices //@} /** @name Curve nodes*/ //@{ - std::vector & CurvesMaterials; // The materials for the curves - std::vector & CurvesCoordinate; // The coordinates of the segments of the curves - std::vector & CurveSet; // The set of curves + std::vector& CurvesMaterials; // The materials for the curves + std::vector& CurvesCoordinate;// The coordinates of the segments of the curves + std::vector& CurveSet; // The set of curves //@} }; /** @brief - * Helper class to store together a field index of a coin multifield object and the coin geometry layer to - * which it belongs. + * Helper class to store together a field index of a coin multifield object and the coin geometry + * layer to which it belongs. * * @details * - * @warning the layer is * not * the logical layer (the one of GeometryFacade), but the coin layer. See GeometryLayerParameters. + * @warning the layer is * not * the logical layer (the one of GeometryFacade), but the coin layer. + * See GeometryLayerParameters. * - * Overloaded operators and specialisation of std::less enable it to be used in containers including ordered - * containers. + * Overloaded operators and specialisation of std::less enable it to be used in containers including + * ordered containers. */ -class MultiFieldId { +class MultiFieldId +{ public: - explicit constexpr MultiFieldId(int fieldindex = -1, int layerid = 0): fieldIndex(fieldindex), - layerId(layerid){} + explicit constexpr MultiFieldId(int fieldindex = -1, int layerid = 0) + : fieldIndex(fieldindex) + , layerId(layerid) + {} - MultiFieldId(const MultiFieldId & ) = default; - MultiFieldId & operator=(const MultiFieldId &) = default; + MultiFieldId(const MultiFieldId&) = default; + MultiFieldId& operator=(const MultiFieldId&) = default; - MultiFieldId(MultiFieldId && ) = default; - MultiFieldId & operator=(MultiFieldId &&) = default; + MultiFieldId(MultiFieldId&&) = default; + MultiFieldId& operator=(MultiFieldId&&) = default; inline bool operator==(const MultiFieldId& obj) const { @@ -185,21 +204,26 @@ public: }; -} // namespace SketcherGui +}// namespace SketcherGui namespace std { - template<> struct less +template<> +struct less +{ + bool operator()(const SketcherGui::MultiFieldId& lhs, + const SketcherGui::MultiFieldId& rhs) const { - bool operator() (const SketcherGui::MultiFieldId& lhs, const SketcherGui::MultiFieldId& rhs) const - { - return (lhs.layerId != rhs.layerId)?(lhs.layerId < rhs.layerId):(static_cast(lhs.fieldIndex) < static_cast(rhs.fieldIndex)); - } - }; -} // namespace std + return (lhs.layerId != rhs.layerId) + ? (lhs.layerId < rhs.layerId) + : (static_cast(lhs.fieldIndex) < static_cast(rhs.fieldIndex)); + } +}; +}// namespace std -namespace SketcherGui { +namespace SketcherGui +{ /** @brief * Helper class to store geometry layers configuration @@ -216,54 +240,65 @@ namespace SketcherGui { * 1. A N:N relationship between logical layers and coin layers. * 2. A M:N relationship between logical layers and coin layers (M bsplineGeoIds; // used for information overlay + */ +struct AnalysisResults +{ // TODO: This needs to be refactored + double combRepresentationScale = 0; // used for information overlay (BSpline comb) + float boundingBoxMagnitudeOrder = 0;// used for grid extension + std::vector bsplineGeoIds; // used for information overlay std::vector arcGeoIds; }; /** @brief Struct adapted to store the parameters necessary to create and update * the information overlay layer. */ -struct OverlayParameters { +struct OverlayParameters +{ bool rebuildInformationLayer = false; bool visibleInformationChanged = true; double currentBSplineCombRepresentationScale = 0; @@ -280,79 +315,81 @@ struct OverlayParameters { /** @brief Struct adapted to store the parameters necessary to create and update * constraints. */ -struct ConstraintParameters { - bool bHideUnits; // whether units should be hidden or not - bool bShowDimensionalName; // whether the name of dimensional constraints should be shown or not - QString sDimensionalStringFormat; // how to code strings of dimensional constraints +struct ConstraintParameters +{ + bool bHideUnits; // whether units should be hidden or not + bool bShowDimensionalName;// whether the name of dimensional constraints should be shown or not + QString sDimensionalStringFormat;// how to code strings of dimensional constraints }; /** @brief Helper struct adapted to store the pointer to edit mode scenegraph objects. */ -struct EditModeScenegraphNodes { +struct EditModeScenegraphNodes +{ /** @name Point nodes*/ //@{ - SoSeparator * EditRoot; - SmSwitchboard * PointsGroup; - std::vector PointsMaterials; - std::vector PointsCoordinate; - std::vector PointsDrawStyle; - std::vector PointSet; + SoSeparator* EditRoot; + SmSwitchboard* PointsGroup; + std::vector PointsMaterials; + std::vector PointsCoordinate; + std::vector PointsDrawStyle; + std::vector PointSet; //@} /** @name Curve nodes*/ //@{ - SmSwitchboard * CurvesGroup; - std::vector CurvesMaterials; - std::vector CurvesCoordinate; - std::vector CurvesDrawStyle; - std::vector CurveSet; + SmSwitchboard* CurvesGroup; + std::vector CurvesMaterials; + std::vector CurvesCoordinate; + std::vector CurvesDrawStyle; + std::vector CurveSet; //@} /** @name Axes nodes*/ /// @warning Root Point is added together with the Point nodes above //@{ - SoMaterial *RootCrossMaterials; - SoCoordinate3 *RootCrossCoordinate; - SoLineSet *RootCrossSet; - SoDrawStyle *RootCrossDrawStyle; + SoMaterial* RootCrossMaterials; + SoCoordinate3* RootCrossCoordinate; + SoLineSet* RootCrossSet; + SoDrawStyle* RootCrossDrawStyle; //@} /** @name Temporal edit curve nodes - For geometry creation */ //@{ - SoMaterial *EditCurvesMaterials; - SoCoordinate3 *EditCurvesCoordinate; - SoLineSet *EditCurveSet; - SoDrawStyle *EditCurvesDrawStyle; - SoPickStyle *pickStyleAxes; + SoMaterial* EditCurvesMaterials; + SoCoordinate3* EditCurvesCoordinate; + SoLineSet* EditCurveSet; + SoDrawStyle* EditCurvesDrawStyle; + SoPickStyle* pickStyleAxes; //@} /** @name Temporal edit markers nodes- For operation rendering, such as trimming green circles*/ //@{ - SoMaterial *EditMarkersMaterials; - SoCoordinate3 *EditMarkersCoordinate; - SoMarkerSet *EditMarkerSet; - SoDrawStyle *EditMarkersDrawStyle; + SoMaterial* EditMarkersMaterials; + SoCoordinate3* EditMarkersCoordinate; + SoMarkerSet* EditMarkerSet; + SoDrawStyle* EditMarkersDrawStyle; //@} /** @name Temporal edit text nodes*/ //@{ - SoText2 *textX; - SoTranslation *textPos; - SoFont *textFont; - SoMaterial *textMaterial; + SoText2* textX; + SoTranslation* textPos; + SoFont* textFont; + SoMaterial* textMaterial; //@} /** @name Constraint nodes*/ //@{ - SmSwitchboard *constrGroup; - SoPickStyle *constrGrpSelect; - SoDrawStyle *ConstraintDrawStyle; + SmSwitchboard* constrGroup; + SoPickStyle* constrGrpSelect; + SoDrawStyle* ConstraintDrawStyle; //@} /** @name Information Overlay Layer nodes*/ //@{ - SoGroup *infoGroup; - SoDrawStyle *InformationDrawStyle; + SoGroup* infoGroup; + SoDrawStyle* InformationDrawStyle; //@} }; @@ -361,24 +398,40 @@ struct EditModeScenegraphNodes { * * These are updated with every draw of the scenegraph. */ -struct CoinMapping { +struct CoinMapping +{ - void clear() { + void clear() + { CurvIdToGeoId.clear(); PointIdToGeoId.clear(); GeoElementId2SetId.clear(); PointIdToVertexId.clear(); }; - /// given the MF index of a curve and the coin layer in which it is drawn returns the GeoId of the curve - int getCurveGeoId(int curveindex, int layerindex) {return CurvIdToGeoId[layerindex][curveindex];} - /// given the MF index of a point and the coin layer in which it is drawn returns the GeoId of the point - int getPointGeoId(int pointindex, int layerindex) {return PointIdToGeoId[layerindex][pointindex];} - /// given the MF index of a point and the coin layer in which it is drawn returns the VertexId of the point - int getPointVertexId(int pointindex, int layerindex) {return PointIdToVertexId[layerindex][pointindex];} + /// given the MF index of a curve and the coin layer in which it is drawn returns the GeoId of + /// the curve + int getCurveGeoId(int curveindex, int layerindex) + { + return CurvIdToGeoId[layerindex][curveindex]; + } + /// given the MF index of a point and the coin layer in which it is drawn returns the GeoId of + /// the point + int getPointGeoId(int pointindex, int layerindex) + { + return PointIdToGeoId[layerindex][pointindex]; + } + /// given the MF index of a point and the coin layer in which it is drawn returns the VertexId + /// of the point + int getPointVertexId(int pointindex, int layerindex) + { + return PointIdToVertexId[layerindex][pointindex]; + } - /// given the {GeoId, PointPos} of a curve or point, returns MultiFieldId containing the MF index and the coin layer of the curve or point - MultiFieldId getIndexLayer(int geoid, Sketcher::PointPos pos) { + /// given the {GeoId, PointPos} of a curve or point, returns MultiFieldId containing the MF + /// index and the coin layer of the curve or point + MultiFieldId getIndexLayer(int geoid, Sketcher::PointPos pos) + { auto indexit = GeoElementId2SetId.find(Sketcher::GeoElementId(geoid, pos)); if (indexit != GeoElementId2SetId.end()) { @@ -388,31 +441,36 @@ struct CoinMapping { return MultiFieldId::Invalid; } - /// given the VertexId of a point, returns MultiFieldId containing the MF index and the coin layer of the point - MultiFieldId getIndexLayer(int vertexId) { + /// given the VertexId of a point, returns MultiFieldId containing the MF index and the coin + /// layer of the point + MultiFieldId getIndexLayer(int vertexId) + { - for(size_t l=0; l> CurvIdToGeoId; // conversion of SoLineSet index to GeoId - std::vector> PointIdToGeoId; // conversion of SoCoordinate3 index to GeoId + std::vector> PointIdToGeoId;// conversion of SoCoordinate3 index to GeoId - //* This maps an MF index (second index) of a point within a coin layer (first index) to a global VertexId */ + //* This maps an MF index (second index) of a point within a coin layer (first index) to a + //global VertexId */ std::vector> PointIdToVertexId; - /// This maps GeoElementId index {GeoId, PointPos} to a {coin layer and MF index} of a curve or point. - std::map GeoElementId2SetId; + /// This maps GeoElementId index {GeoId, PointPos} to a {coin layer and MF index} of a curve or + /// point. + std::map GeoElementId2SetId; }; -} // namespace SketcherGui - -#endif // SKETCHERGUI_EditModeCoinManagerParameters_H +}// namespace SketcherGui +#endif// SKETCHERGUI_EditModeCoinManagerParameters_H diff --git a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp index 8bfe601e9c..fb2ffcb39e 100644 --- a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp @@ -22,24 +22,24 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif// #ifndef _PreComp_ #include #include @@ -47,22 +47,22 @@ #include #include #include -#include -#include #include #include +#include +#include #include +#include +#include +#include #include #include -#include -#include -#include #include "EditModeConstraintCoinManager.h" #include "SoZoomTranslation.h" +#include "Utils.h" #include "ViewProviderSketch.h" #include "ViewProviderSketchCoinAttorney.h" -#include "Utils.h" using namespace Gui; @@ -71,18 +71,16 @@ using namespace Sketcher; //**************************** EditModeConstraintCoinManager class ****************************** -EditModeConstraintCoinManager::EditModeConstraintCoinManager( ViewProviderSketch &vp, - DrawingParameters & drawingParams, - GeometryLayerParameters & geometryLayerParams, - ConstraintParameters & constraintParams, - EditModeScenegraphNodes & editModeScenegraph, - CoinMapping & coinMap): - viewProvider(vp), - drawingParameters(drawingParams), - geometryLayerParameters(geometryLayerParams), - constraintParameters(constraintParams), - editModeScenegraphNodes(editModeScenegraph), - coinMapping(coinMap) +EditModeConstraintCoinManager::EditModeConstraintCoinManager( + ViewProviderSketch& vp, DrawingParameters& drawingParams, + GeometryLayerParameters& geometryLayerParams, ConstraintParameters& constraintParams, + EditModeScenegraphNodes& editModeScenegraph, CoinMapping& coinMap) + : viewProvider(vp) + , drawingParameters(drawingParams) + , geometryLayerParameters(geometryLayerParams) + , constraintParameters(constraintParams) + , editModeScenegraphNodes(editModeScenegraph) + , coinMapping(coinMap) {} EditModeConstraintCoinManager::~EditModeConstraintCoinManager() @@ -90,7 +88,8 @@ EditModeConstraintCoinManager::~EditModeConstraintCoinManager() void EditModeConstraintCoinManager::updateVirtualSpace() { - const std::vector &constrlist = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); + const std::vector& constrlist = + ViewProviderSketchCoinAttorney::getConstraints(viewProvider); bool isshownvirtualspace = ViewProviderSketchCoinAttorney::isShownVirtualSpace(viewProvider); @@ -98,24 +97,26 @@ void EditModeConstraintCoinManager::updateVirtualSpace() editModeScenegraphNodes.constrGroup->enable.setNum(constrlist.size()); - SbBool *sws = editModeScenegraphNodes.constrGroup->enable.startEditing(); + SbBool* sws = editModeScenegraphNodes.constrGroup->enable.startEditing(); for (size_t i = 0; i < constrlist.size(); i++) - sws[i] = !(constrlist[i]->isInVirtualSpace != isshownvirtualspace); // XOR of constraint mode and VP mode + sws[i] = !(constrlist[i]->isInVirtualSpace + != isshownvirtualspace);// XOR of constraint mode and VP mode editModeScenegraphNodes.constrGroup->enable.finishEditing(); } } -void EditModeConstraintCoinManager::processConstraints(const GeoListFacade & geolistfacade) +void EditModeConstraintCoinManager::processConstraints(const GeoListFacade& geolistfacade) { - const auto &constrlist = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); + const auto& constrlist = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); - auto zConstrH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zConstr; + auto zConstrH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zConstr; - // After an undo/redo it can happen that we have an empty geometry list but a non-empty constraint list - // In this case just ignore the constraints. (See bug #0000421) + // After an undo/redo it can happen that we have an empty geometry list but a non-empty + // constraint list In this case just ignore the constraints. (See bug #0000421) if (geolistfacade.geomlist.size() <= 2 && !constrlist.empty()) { rebuildConstraintNodes(geolistfacade); return; @@ -136,18 +137,20 @@ Restart: // update the virtual space updateVirtualSpace(); - auto getNormal = [] (const GeoListFacade & geolistfacade, const int geoid, const Base::Vector3d & pointoncurve) { + auto getNormal = [](const GeoListFacade& geolistfacade, + const int geoid, + const Base::Vector3d& pointoncurve) { auto geom = geolistfacade.getGeometryFromGeoId(geoid); - auto curve = dynamic_cast(geom); + auto curve = dynamic_cast(geom); Base::Vector3d normal; try { if (!(curve && curve->normalAt(pointoncurve, normal))) { - normal = Base::Vector3d(1,0,0); + normal = Base::Vector3d(1, 0, 0); } } catch (const Base::CADKernelError&) { - normal = Base::Vector3d(1,0,0); + normal = Base::Vector3d(1, 0, 0); } return normal; @@ -155,26 +158,28 @@ Restart: // go through the constraints and update the position int i = 0; - for (std::vector::const_iterator it=constrlist.begin(); - it != constrlist.end(); ++it, i++) { + for (std::vector::const_iterator it = constrlist.begin(); + it != constrlist.end(); + ++it, i++) { // check if the type has changed if ((*it)->Type != vConstrType[i]) { // clearing the type vector will force a rebuild of the visual nodes vConstrType.clear(); - //TODO: The 'goto' here is unsafe as it can happen that we cause an endless loop (see bug #0001956). + // TODO: The 'goto' here is unsafe as it can happen that we cause an endless loop (see + // bug #0001956). goto Restart; } - try{//because calculateNormalAtPoint, used in there, can throw + try {// because calculateNormalAtPoint, used in there, can throw // root separator for this constraint - SoSeparator *sep = static_cast(editModeScenegraphNodes.constrGroup->getChild(i)); - const Constraint *Constr = *it; + SoSeparator* sep = + static_cast(editModeScenegraphNodes.constrGroup->getChild(i)); + const Constraint* Constr = *it; if (Constr->First < -extGeoCount || Constr->First >= intGeoCount - || (Constr->Second!=GeoEnum::GeoUndef - && (Constr->Second < -extGeoCount || Constr->Second >= intGeoCount)) - || (Constr->Third!=GeoEnum::GeoUndef - && (Constr->Third < -extGeoCount || Constr->Third >= intGeoCount))) - { + || (Constr->Second != GeoEnum::GeoUndef + && (Constr->Second < -extGeoCount || Constr->Second >= intGeoCount)) + || (Constr->Third != GeoEnum::GeoUndef + && (Constr->Third < -extGeoCount || Constr->Third >= intGeoCount))) { // Constraint can refer to non-existent geometry during undo/redo continue; } @@ -182,1010 +187,1257 @@ Restart: // distinguish different constraint types to build up switch (Constr->Type) { case Block: - case Horizontal: // write the new position of the Horizontal constraint Same as vertical position. - case Vertical: // write the new position of the Vertical constraint - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); - bool alignment = Constr->Type!=Block && Constr->Second != GeoEnum::GeoUndef; + case Horizontal:// write the new position of the Horizontal constraint Same as + // vertical position. + case Vertical: // write the new position of the Vertical constraint + { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + bool alignment = Constr->Type != Block && Constr->Second != GeoEnum::GeoUndef; - // get the geometry - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(Constr->First); + // get the geometry + const Part::Geometry* geo = geolistfacade.getGeometryFromGeoId(Constr->First); - if (!alignment) { - // Vertical & Horiz can only be a GeomLineSegment, but Blocked can be anything. - Base::Vector3d midpos; - Base::Vector3d dir; - Base::Vector3d norm; + if (!alignment) { + // Vertical & Horiz can only be a GeomLineSegment, but Blocked can be + // anything. + Base::Vector3d midpos; + Base::Vector3d dir; + Base::Vector3d norm; - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); + if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg = + static_cast(geo); - // calculate the half distance between the start and endpoint - midpos = ((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); + // calculate the half distance between the start and endpoint + midpos = ((lineSeg->getEndPoint() + lineSeg->getStartPoint()) / 2); - //Get a set of vectors perpendicular and tangential to these - dir = (lineSeg->getEndPoint()-lineSeg->getStartPoint()).Normalize(); + // Get a set of vectors perpendicular and tangential to these + dir = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); - norm = Base::Vector3d(-dir.y,dir.x,0); - } - else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *bsp = static_cast(geo); - midpos = Base::Vector3d(0,0,0); + norm = Base::Vector3d(-dir.y, dir.x, 0); + } + else if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::GeomBSplineCurve* bsp = + static_cast(geo); + midpos = Base::Vector3d(0, 0, 0); - std::vector poles = bsp->getPoles(); + std::vector poles = bsp->getPoles(); - // Move center of gravity towards start not to collide with bspline degree information. - double ws = 1.0 / poles.size(); - double w = 1.0; + // Move center of gravity towards start not to collide with bspline + // degree information. + double ws = 1.0 / poles.size(); + double w = 1.0; - for (std::vector::iterator it = poles.begin(); it != poles.end(); ++it) { - midpos += w*(*it); - w -= ws; - } - - midpos /= poles.size(); - - dir = (bsp->getEndPoint() - bsp->getStartPoint()).Normalize(); - norm = Base::Vector3d(-dir.y,dir.x,0); - } - else { - double ra=0,rb=0; - double angle,angleplus=0.;//angle = rotation of object as a whole; angleplus = arc angle (t parameter for ellipses). - if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo); - ra = circle->getRadius(); - angle = M_PI/4; - midpos = circle->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo); - ra = arc->getRadius(); - double startangle, endangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - angle = (startangle + endangle)/2; - midpos = arc->getCenter(); - } else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - const Part::GeomEllipse *ellipse = static_cast(geo); - ra = ellipse->getMajorRadius(); - rb = ellipse->getMinorRadius(); - Base::Vector3d majdir = ellipse->getMajorAxisDir(); - angle = atan2(majdir.y, majdir.x); - angleplus = M_PI/4; - midpos = ellipse->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *aoe = static_cast(geo); - ra = aoe->getMajorRadius(); - rb = aoe->getMinorRadius(); - double startangle, endangle; - aoe->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = aoe->getMajorAxisDir(); - angle = atan2(majdir.y, majdir.x); - angleplus = (startangle + endangle)/2; - midpos = aoe->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - const Part::GeomArcOfHyperbola *aoh = static_cast(geo); - ra = aoh->getMajorRadius(); - rb = aoh->getMinorRadius(); - double startangle, endangle; - aoh->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = aoh->getMajorAxisDir(); - angle = atan2(majdir.y, majdir.x); - angleplus = (startangle + endangle)/2; - midpos = aoh->getCenter(); - } else if (geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { - const Part::GeomArcOfParabola *aop = static_cast(geo); - ra = aop->getFocal(); - double startangle, endangle; - aop->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = - aop->getXAxisDir(); - angle = atan2(majdir.y, majdir.x); - angleplus = (startangle + endangle)/2; - midpos = aop->getFocus(); - } else - break; - - if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()){ - - Base::Vector3d majDir, minDir, rvec; - majDir = Base::Vector3d(cos(angle),sin(angle),0);//direction of major axis of ellipse - minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse - rvec = (ra*cos(angleplus)) * majDir + (rb*sin(angleplus)) * minDir; - midpos += rvec; - rvec.Normalize(); - norm = rvec; - dir = Base::Vector3d(-rvec.y,rvec.x,0);//DeepSOIC: I'm not sure what dir is supposed to mean. - } - else { - norm = Base::Vector3d(cos(angle),sin(angle),0); - dir = Base::Vector3d(-norm.y,norm.x,0); - midpos += ra*norm; - } + for (std::vector::iterator it = poles.begin(); + it != poles.end(); + ++it) { + midpos += w * (*it); + w -= ws; } - Base::Vector3d relpos = seekConstraintPosition(midpos, norm, dir, 2.5, editModeScenegraphNodes.constrGroup->getChild(i)); + midpos /= poles.size(); - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); - - translation->abPos = SbVec3f(midpos.x, midpos.y, zConstrH); //Absolute Reference - - //Reference Position that is scaled according to zoom - translation->translation = SbVec3f(relpos.x, relpos.y, 0); + dir = (bsp->getEndPoint() - bsp->getStartPoint()).Normalize(); + norm = Base::Vector3d(-dir.y, dir.x, 0); } else { - assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); - assert(Constr->FirstPos != Sketcher::PointPos::none && Constr->SecondPos != Sketcher::PointPos::none); + double ra = 0, rb = 0; + double angle, + angleplus = 0.;// angle = rotation of object as a whole; angleplus = + // arc angle (t parameter for ellipses). + if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo); + ra = circle->getRadius(); + angle = M_PI / 4; + midpos = circle->getCenter(); + } + else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo); + ra = arc->getRadius(); + double startangle, endangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + angle = (startangle + endangle) / 2; + midpos = arc->getCenter(); + } + else if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = + static_cast(geo); + ra = ellipse->getMajorRadius(); + rb = ellipse->getMinorRadius(); + Base::Vector3d majdir = ellipse->getMajorAxisDir(); + angle = atan2(majdir.y, majdir.x); + angleplus = M_PI / 4; + midpos = ellipse->getCenter(); + } + else if (geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoe = + static_cast(geo); + ra = aoe->getMajorRadius(); + rb = aoe->getMinorRadius(); + double startangle, endangle; + aoe->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = aoe->getMajorAxisDir(); + angle = atan2(majdir.y, majdir.x); + angleplus = (startangle + endangle) / 2; + midpos = aoe->getCenter(); + } + else if (geo->getTypeId() + == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = + static_cast(geo); + ra = aoh->getMajorRadius(); + rb = aoh->getMinorRadius(); + double startangle, endangle; + aoh->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = aoh->getMajorAxisDir(); + angle = atan2(majdir.y, majdir.x); + angleplus = (startangle + endangle) / 2; + midpos = aoh->getCenter(); + } + else if (geo->getTypeId() + == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = + static_cast(geo); + ra = aop->getFocal(); + double startangle, endangle; + aop->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = -aop->getXAxisDir(); + angle = atan2(majdir.y, majdir.x); + angleplus = (startangle + endangle) / 2; + midpos = aop->getFocus(); + } + else + break; - Base::Vector3d midpos1, dir1, norm1; - Base::Vector3d midpos2, dir2, norm2; + if (geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - midpos1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); - midpos2 = geolistfacade.getPoint(Constr->Second, Constr->SecondPos); - - dir1 = (midpos2-midpos1).Normalize(); - dir2 = -dir1; - norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); - norm2 = norm1; - - Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); - - translation->abPos = SbVec3f(midpos1.x, midpos1.y, zConstrH); - translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); - - Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - - Base::Vector3d secondPos = midpos2 - midpos1; - - translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondTranslationIndex))); - - translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); - translation->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); + Base::Vector3d majDir, minDir, rvec; + majDir = Base::Vector3d( + cos(angle), sin(angle), 0);// direction of major axis of ellipse + minDir = Base::Vector3d( + -majDir.y, majDir.x, 0);// direction of minor axis of ellipse + rvec = + (ra * cos(angleplus)) * majDir + (rb * sin(angleplus)) * minDir; + midpos += rvec; + rvec.Normalize(); + norm = rvec; + dir = Base::Vector3d( + -rvec.y, + rvec.x, + 0);// DeepSOIC: I'm not sure what dir is supposed to mean. + } + else { + norm = Base::Vector3d(cos(angle), sin(angle), 0); + dir = Base::Vector3d(-norm.y, norm.x, 0); + midpos += ra * norm; + } } + + Base::Vector3d relpos = seekConstraintPosition( + midpos, + norm, + dir, + 2.5, + editModeScenegraphNodes.constrGroup->getChild(i)); + + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); + + translation->abPos = + SbVec3f(midpos.x, midpos.y, zConstrH);// Absolute Reference + + // Reference Position that is scaled according to zoom + translation->translation = SbVec3f(relpos.x, relpos.y, 0); } - break; - case Perpendicular: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + else { assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); - // get the geometry - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); - const Part::Geometry *geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); + assert(Constr->FirstPos != Sketcher::PointPos::none + && Constr->SecondPos != Sketcher::PointPos::none); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; - bool twoIcons = false;//a very local flag. It's set to true to indicate that the second dir+norm are valid and should be used + midpos1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); + midpos2 = geolistfacade.getPoint(Constr->Second, Constr->SecondPos); - if (Constr->Third != GeoEnum::GeoUndef || //perpty via point - Constr->FirstPos != Sketcher::PointPos::none) { //endpoint-to-curve or endpoint-to-endpoint perpty + dir1 = (midpos2 - midpos1).Normalize(); + dir2 = -dir1; + norm1 = Base::Vector3d(-dir1.y, dir1.x, 0.); + norm2 = norm1; - int ptGeoId; - Sketcher::PointPos ptPosId; - do {//dummy loop to use break =) Maybe goto? - ptGeoId = Constr->First; - ptPosId = Constr->FirstPos; - if (ptPosId != Sketcher::PointPos::none) break; - ptGeoId = Constr->Second; - ptPosId = Constr->SecondPos; - if (ptPosId != Sketcher::PointPos::none) break; - ptGeoId = Constr->Third; - ptPosId = Constr->ThirdPos; - if (ptPosId != Sketcher::PointPos::none) break; - assert(0);//no point found! - } while (false); + Base::Vector3d relpos1 = seekConstraintPosition( + midpos1, + norm1, + dir1, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); - midpos1 = geolistfacade.getPoint(ptGeoId, ptPosId); - - norm1 = getNormal(geolistfacade, Constr->Second, midpos1); - - // TODO: Check the method above. This was the old one making use of the solver. - //norm1 = getSolvedSketch().calculateNormalAtPoint(Constr->Second, midpos1.x, midpos1.y); - - norm1.Normalize(); - dir1 = norm1; dir1.RotateZ(-M_PI/2.0); - - } else if (Constr->FirstPos == Sketcher::PointPos::none) { - - if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); - dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); - norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); - } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo1); - double startangle, endangle, midangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - midangle = (startangle + endangle)/2; - norm1 = Base::Vector3d(cos(midangle),sin(midangle),0); - dir1 = Base::Vector3d(-norm1.y,norm1.x,0); - midpos1 = arc->getCenter() + arc->getRadius() * norm1; - } else if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo1); - norm1 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); - dir1 = Base::Vector3d(-norm1.y,norm1.x,0); - midpos1 = circle->getCenter() + circle->getRadius() * norm1; - } else - break; - - if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); - midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); - dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); - norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); - } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo2); - double startangle, endangle, midangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - midangle = (startangle + endangle)/2; - norm2 = Base::Vector3d(cos(midangle),sin(midangle),0); - dir2 = Base::Vector3d(-norm2.y,norm2.x,0); - midpos2 = arc->getCenter() + arc->getRadius() * norm2; - } else if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo2); - norm2 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); - dir2 = Base::Vector3d(-norm2.y,norm2.x,0); - midpos2 = circle->getCenter() + circle->getRadius() * norm2; - } else - break; - twoIcons = true; - } - - Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); translation->abPos = SbVec3f(midpos1.x, midpos1.y, zConstrH); translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); - if (twoIcons) { - Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - - Base::Vector3d secondPos = midpos2 - midpos1; - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondTranslationIndex))); - translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); - translation->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); - } - - } - break; - case Parallel: - case Equal: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); - assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); - // get the geometry - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); - const Part::Geometry *geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); - - Base::Vector3d midpos1, dir1, norm1; - Base::Vector3d midpos2, dir2, norm2; - if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || - geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { - if (Constr->Type == Equal) { - double r1a=0,r1b=0,r2a=0,r2b=0; - double angle1,angle1plus=0., angle2, angle2plus=0.;//angle1 = rotation of object as a whole; angle1plus = arc angle (t parameter for ellipses). - if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo1); - r1a = circle->getRadius(); - angle1 = M_PI/4; - midpos1 = circle->getCenter(); - } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo1); - r1a = arc->getRadius(); - double startangle, endangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - angle1 = (startangle + endangle)/2; - midpos1 = arc->getCenter(); - } else if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - const Part::GeomEllipse *ellipse = static_cast(geo1); - r1a = ellipse->getMajorRadius(); - r1b = ellipse->getMinorRadius(); - Base::Vector3d majdir = ellipse->getMajorAxisDir(); - angle1 = atan2(majdir.y, majdir.x); - angle1plus = M_PI/4; - midpos1 = ellipse->getCenter(); - } else if (geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *aoe = static_cast(geo1); - r1a = aoe->getMajorRadius(); - r1b = aoe->getMinorRadius(); - double startangle, endangle; - aoe->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = aoe->getMajorAxisDir(); - angle1 = atan2(majdir.y, majdir.x); - angle1plus = (startangle + endangle)/2; - midpos1 = aoe->getCenter(); - } else if (geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - const Part::GeomArcOfHyperbola *aoh = static_cast(geo1); - r1a = aoh->getMajorRadius(); - r1b = aoh->getMinorRadius(); - double startangle, endangle; - aoh->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = aoh->getMajorAxisDir(); - angle1 = atan2(majdir.y, majdir.x); - angle1plus = (startangle + endangle)/2; - midpos1 = aoh->getCenter(); - } else if (geo1->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { - const Part::GeomArcOfParabola *aop = static_cast(geo1); - r1a = aop->getFocal(); - double startangle, endangle; - aop->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = - aop->getXAxisDir(); - angle1 = atan2(majdir.y, majdir.x); - angle1plus = (startangle + endangle)/2; - midpos1 = aop->getFocus(); - } else - break; - - if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo2); - r2a = circle->getRadius(); - angle2 = M_PI/4; - midpos2 = circle->getCenter(); - } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo2); - r2a = arc->getRadius(); - double startangle, endangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - angle2 = (startangle + endangle)/2; - midpos2 = arc->getCenter(); - } else if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId()) { - const Part::GeomEllipse *ellipse = static_cast(geo2); - r2a = ellipse->getMajorRadius(); - r2b = ellipse->getMinorRadius(); - Base::Vector3d majdir = ellipse->getMajorAxisDir(); - angle2 = atan2(majdir.y, majdir.x); - angle2plus = M_PI/4; - midpos2 = ellipse->getCenter(); - } else if (geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { - const Part::GeomArcOfEllipse *aoe = static_cast(geo2); - r2a = aoe->getMajorRadius(); - r2b = aoe->getMinorRadius(); - double startangle, endangle; - aoe->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = aoe->getMajorAxisDir(); - angle2 = atan2(majdir.y, majdir.x); - angle2plus = (startangle + endangle)/2; - midpos2 = aoe->getCenter(); - } else if (geo2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - const Part::GeomArcOfHyperbola *aoh = static_cast(geo2); - r2a = aoh->getMajorRadius(); - r2b = aoh->getMinorRadius(); - double startangle, endangle; - aoh->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = aoh->getMajorAxisDir(); - angle2 = atan2(majdir.y, majdir.x); - angle2plus = (startangle + endangle)/2; - midpos2 = aoh->getCenter(); - } else if (geo2->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { - const Part::GeomArcOfParabola *aop = static_cast(geo2); - r2a = aop->getFocal(); - double startangle, endangle; - aop->getRange(startangle, endangle, /*emulateCCW=*/true); - Base::Vector3d majdir = -aop->getXAxisDir(); - angle2 = atan2(majdir.y, majdir.x); - angle2plus = (startangle + endangle)/2; - midpos2 = aop->getFocus(); - } else - break; - - if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo1->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() ){ - - Base::Vector3d majDir, minDir, rvec; - majDir = Base::Vector3d(cos(angle1),sin(angle1),0);//direction of major axis of ellipse - minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse - rvec = (r1a*cos(angle1plus)) * majDir + (r1b*sin(angle1plus)) * minDir; - midpos1 += rvec; - rvec.Normalize(); - norm1 = rvec; - dir1 = Base::Vector3d(-rvec.y,rvec.x,0);//DeepSOIC: I'm not sure what dir is supposed to mean. - } - else { - norm1 = Base::Vector3d(cos(angle1),sin(angle1),0); - dir1 = Base::Vector3d(-norm1.y,norm1.x,0); - midpos1 += r1a*norm1; - } - - - if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() || - geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() || - geo2->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { - - Base::Vector3d majDir, minDir, rvec; - majDir = Base::Vector3d(cos(angle2),sin(angle2),0);//direction of major axis of ellipse - minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse - rvec = (r2a*cos(angle2plus)) * majDir + (r2b*sin(angle2plus)) * minDir; - midpos2 += rvec; - rvec.Normalize(); - norm2 = rvec; - dir2 = Base::Vector3d(-rvec.y,rvec.x,0); - } - else { - norm2 = Base::Vector3d(cos(angle2),sin(angle2),0); - dir2 = Base::Vector3d(-norm2.y,norm2.x,0); - midpos2 += r2a*norm2; - } - - } else // Parallel can only apply to a GeomLineSegment - break; - } else { - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); - - // calculate the half distance between the start and endpoint - midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); - midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); - //Get a set of vectors perpendicular and tangential to these - dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); - dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); - norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); - norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); - } - - Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); - - translation->abPos = SbVec3f(midpos1.x, midpos1.y, zConstrH); //Absolute Reference - - //Reference Position that is scaled according to zoom - translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); + Base::Vector3d relpos2 = seekConstraintPosition( + midpos2, + norm2, + dir2, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); Base::Vector3d secondPos = midpos2 - midpos1; - translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondTranslationIndex))); - - translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); //Absolute Reference - - //Reference Position that is scaled according to zoom - translation->translation = SbVec3f(relpos2.x - relpos1.x, relpos2.y -relpos1.y, 0); + translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondTranslationIndex))); + translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); + translation->translation = + SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); } - break; - case Distance: - case DistanceX: - case DistanceY: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + } break; + case Perpendicular: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); + // get the geometry + const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); + const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); - Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); - if (Constr->SecondPos != Sketcher::PointPos::none) { // point to point distance - pnt1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); - pnt2 = geolistfacade.getPoint(Constr->Second, Constr->SecondPos); - } else if (Constr->Second != GeoEnum::GeoUndef) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(Constr->Second); - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); - Base::Vector3d l2p1 = lineSeg->getStartPoint(); - Base::Vector3d l2p2 = lineSeg->getEndPoint(); - if (Constr->FirstPos != Sketcher::PointPos::none) { // point to line distance - pnt1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); - // calculate the projection of p1 onto line2 - pnt2.ProjectToLine(pnt1-l2p1, l2p2-l2p1); - pnt2 += pnt1; - } else { - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); - if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { // circle to line distance - const Part::GeomCircle *circleSeg = static_cast(geo1); - Base::Vector3d ct = circleSeg->getCenter(); - double radius = circleSeg->getRadius(); - pnt1.ProjectToLine(ct-l2p1, l2p2-l2p1); //project on the line translated to origin - Base::Vector3d dir = pnt1; - dir.Normalize(); - pnt1 += ct; - pnt2 = ct + dir * radius; - } - } + Base::Vector3d midpos1, dir1, norm1; + Base::Vector3d midpos2, dir2, norm2; + bool twoIcons = false;// a very local flag. It's set to true to indicate that + // the second dir+norm are valid and should be used - } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); - if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { // circle to circle distance - const Part::GeomCircle *circleSeg1 = static_cast(geo1); - auto circleSeg2 = static_cast(geo); - GetCirclesMinimalDistance(circleSeg1, circleSeg2, pnt1, pnt2); - } - } else + if (Constr->Third != GeoEnum::GeoUndef ||// perpty via point + Constr->FirstPos + != Sketcher::PointPos::none) {// endpoint-to-curve or + // endpoint-to-endpoint perpty + + int ptGeoId; + Sketcher::PointPos ptPosId; + do {// dummy loop to use break =) Maybe goto? + ptGeoId = Constr->First; + ptPosId = Constr->FirstPos; + if (ptPosId != Sketcher::PointPos::none) break; - } else if (Constr->FirstPos != Sketcher::PointPos::none) { - pnt2 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); - } else if (Constr->First != GeoEnum::GeoUndef) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(Constr->First); - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // segment distance - const Part::GeomLineSegment *lineSeg = static_cast(geo); - pnt1 = lineSeg->getStartPoint(); - pnt2 = lineSeg->getEndPoint(); - } else + ptGeoId = Constr->Second; + ptPosId = Constr->SecondPos; + if (ptPosId != Sketcher::PointPos::none) break; - } else + ptGeoId = Constr->Third; + ptPosId = Constr->ThirdPos; + if (ptPosId != Sketcher::PointPos::none) + break; + assert(0);// no point found! + } while (false); + + midpos1 = geolistfacade.getPoint(ptGeoId, ptPosId); + + norm1 = getNormal(geolistfacade, Constr->Second, midpos1); + + // TODO: Check the method above. This was the old one making use of the + // solver. + // norm1 = getSolvedSketch().calculateNormalAtPoint(Constr->Second, + // midpos1.x, midpos1.y); + + norm1.Normalize(); + dir1 = norm1; + dir1.RotateZ(-M_PI / 2.0); + } + else if (Constr->FirstPos == Sketcher::PointPos::none) { + + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = + static_cast(geo1); + midpos1 = ((lineSeg1->getEndPoint() + lineSeg1->getStartPoint()) / 2); + dir1 = + (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()).Normalize(); + norm1 = Base::Vector3d(-dir1.y, dir1.x, 0.); + } + else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo1); + double startangle, endangle, midangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + midangle = (startangle + endangle) / 2; + norm1 = Base::Vector3d(cos(midangle), sin(midangle), 0); + dir1 = Base::Vector3d(-norm1.y, norm1.x, 0); + midpos1 = arc->getCenter() + arc->getRadius() * norm1; + } + else if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo1); + norm1 = Base::Vector3d(cos(M_PI / 4), sin(M_PI / 4), 0); + dir1 = Base::Vector3d(-norm1.y, norm1.x, 0); + midpos1 = circle->getCenter() + circle->getRadius() * norm1; + } + else break; - SoDatumLabel *asciiText = static_cast(sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - - // Get presentation string (w/o units if option is set) - asciiText->string = SbString( getPresentationString(Constr).toUtf8().constData() ); - - if (Constr->Type == Distance) - asciiText->datumtype = SoDatumLabel::DISTANCE; - else if (Constr->Type == DistanceX) - asciiText->datumtype = SoDatumLabel::DISTANCEX; - else if (Constr->Type == DistanceY) - asciiText->datumtype = SoDatumLabel::DISTANCEY; - - // Assign the Datum Points - asciiText->pnts.setNum(2); - SbVec3f *verts = asciiText->pnts.startEditing(); - - verts[0] = SbVec3f (pnt1.x, pnt1.y, zConstrH); - verts[1] = SbVec3f (pnt2.x, pnt2.y, zConstrH); - - asciiText->pnts.finishEditing(); - - //Assign the Label Distance - asciiText->param1 = Constr->LabelDistance; - asciiText->param2 = Constr->LabelPosition; + if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg2 = + static_cast(geo2); + midpos2 = ((lineSeg2->getEndPoint() + lineSeg2->getStartPoint()) / 2); + dir2 = + (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()).Normalize(); + norm2 = Base::Vector3d(-dir2.y, dir2.x, 0.); + } + else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo2); + double startangle, endangle, midangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + midangle = (startangle + endangle) / 2; + norm2 = Base::Vector3d(cos(midangle), sin(midangle), 0); + dir2 = Base::Vector3d(-norm2.y, norm2.x, 0); + midpos2 = arc->getCenter() + arc->getRadius() * norm2; + } + else if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo2); + norm2 = Base::Vector3d(cos(M_PI / 4), sin(M_PI / 4), 0); + dir2 = Base::Vector3d(-norm2.y, norm2.x, 0); + midpos2 = circle->getCenter() + circle->getRadius() * norm2; + } + else + break; + twoIcons = true; } - break; + + Base::Vector3d relpos1 = + seekConstraintPosition(midpos1, + norm1, + dir1, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); + + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); + + translation->abPos = SbVec3f(midpos1.x, midpos1.y, zConstrH); + translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); + + if (twoIcons) { + Base::Vector3d relpos2 = seekConstraintPosition( + midpos2, + norm2, + dir2, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); + + Base::Vector3d secondPos = midpos2 - midpos1; + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondTranslationIndex))); + translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); + translation->translation = + SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); + } + + } break; + case Parallel: + case Equal: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); + // get the geometry + const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); + const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); + + Base::Vector3d midpos1, dir1, norm1; + Base::Vector3d midpos2, dir2, norm2; + if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() + || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { + if (Constr->Type == Equal) { + double r1a = 0, r1b = 0, r2a = 0, r2b = 0; + double angle1, + angle1plus = 0., angle2, + angle2plus = + 0.;// angle1 = rotation of object as a whole; angle1plus = arc + // angle (t parameter for ellipses). + if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo1); + r1a = circle->getRadius(); + angle1 = M_PI / 4; + midpos1 = circle->getCenter(); + } + else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo1); + r1a = arc->getRadius(); + double startangle, endangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + angle1 = (startangle + endangle) / 2; + midpos1 = arc->getCenter(); + } + else if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = + static_cast(geo1); + r1a = ellipse->getMajorRadius(); + r1b = ellipse->getMinorRadius(); + Base::Vector3d majdir = ellipse->getMajorAxisDir(); + angle1 = atan2(majdir.y, majdir.x); + angle1plus = M_PI / 4; + midpos1 = ellipse->getCenter(); + } + else if (geo1->getTypeId() + == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoe = + static_cast(geo1); + r1a = aoe->getMajorRadius(); + r1b = aoe->getMinorRadius(); + double startangle, endangle; + aoe->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = aoe->getMajorAxisDir(); + angle1 = atan2(majdir.y, majdir.x); + angle1plus = (startangle + endangle) / 2; + midpos1 = aoe->getCenter(); + } + else if (geo1->getTypeId() + == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = + static_cast(geo1); + r1a = aoh->getMajorRadius(); + r1b = aoh->getMinorRadius(); + double startangle, endangle; + aoh->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = aoh->getMajorAxisDir(); + angle1 = atan2(majdir.y, majdir.x); + angle1plus = (startangle + endangle) / 2; + midpos1 = aoh->getCenter(); + } + else if (geo1->getTypeId() + == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = + static_cast(geo1); + r1a = aop->getFocal(); + double startangle, endangle; + aop->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = -aop->getXAxisDir(); + angle1 = atan2(majdir.y, majdir.x); + angle1plus = (startangle + endangle) / 2; + midpos1 = aop->getFocus(); + } + else + break; + + if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo2); + r2a = circle->getRadius(); + angle2 = M_PI / 4; + midpos2 = circle->getCenter(); + } + else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo2); + r2a = arc->getRadius(); + double startangle, endangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + angle2 = (startangle + endangle) / 2; + midpos2 = arc->getCenter(); + } + else if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = + static_cast(geo2); + r2a = ellipse->getMajorRadius(); + r2b = ellipse->getMinorRadius(); + Base::Vector3d majdir = ellipse->getMajorAxisDir(); + angle2 = atan2(majdir.y, majdir.x); + angle2plus = M_PI / 4; + midpos2 = ellipse->getCenter(); + } + else if (geo2->getTypeId() + == Part::GeomArcOfEllipse::getClassTypeId()) { + const Part::GeomArcOfEllipse* aoe = + static_cast(geo2); + r2a = aoe->getMajorRadius(); + r2b = aoe->getMinorRadius(); + double startangle, endangle; + aoe->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = aoe->getMajorAxisDir(); + angle2 = atan2(majdir.y, majdir.x); + angle2plus = (startangle + endangle) / 2; + midpos2 = aoe->getCenter(); + } + else if (geo2->getTypeId() + == Part::GeomArcOfHyperbola::getClassTypeId()) { + const Part::GeomArcOfHyperbola* aoh = + static_cast(geo2); + r2a = aoh->getMajorRadius(); + r2b = aoh->getMinorRadius(); + double startangle, endangle; + aoh->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = aoh->getMajorAxisDir(); + angle2 = atan2(majdir.y, majdir.x); + angle2plus = (startangle + endangle) / 2; + midpos2 = aoh->getCenter(); + } + else if (geo2->getTypeId() + == Part::GeomArcOfParabola::getClassTypeId()) { + const Part::GeomArcOfParabola* aop = + static_cast(geo2); + r2a = aop->getFocal(); + double startangle, endangle; + aop->getRange(startangle, endangle, /*emulateCCW=*/true); + Base::Vector3d majdir = -aop->getXAxisDir(); + angle2 = atan2(majdir.y, majdir.x); + angle2plus = (startangle + endangle) / 2; + midpos2 = aop->getFocus(); + } + else + break; + + if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo1->getTypeId() + == Part::GeomArcOfHyperbola::getClassTypeId()) { + + Base::Vector3d majDir, minDir, rvec; + majDir = Base::Vector3d(cos(angle1), + sin(angle1), + 0);// direction of major axis of ellipse + minDir = Base::Vector3d( + -majDir.y, majDir.x, 0);// direction of minor axis of ellipse + rvec = (r1a * cos(angle1plus)) * majDir + + (r1b * sin(angle1plus)) * minDir; + midpos1 += rvec; + rvec.Normalize(); + norm1 = rvec; + dir1 = Base::Vector3d( + -rvec.y, + rvec.x, + 0);// DeepSOIC: I'm not sure what dir is supposed to mean. + } + else { + norm1 = Base::Vector3d(cos(angle1), sin(angle1), 0); + dir1 = Base::Vector3d(-norm1.y, norm1.x, 0); + midpos1 += r1a * norm1; + } + + + if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo2->getTypeId() + == Part::GeomArcOfHyperbola::getClassTypeId()) { + + Base::Vector3d majDir, minDir, rvec; + majDir = Base::Vector3d(cos(angle2), + sin(angle2), + 0);// direction of major axis of ellipse + minDir = Base::Vector3d( + -majDir.y, majDir.x, 0);// direction of minor axis of ellipse + rvec = (r2a * cos(angle2plus)) * majDir + + (r2b * sin(angle2plus)) * minDir; + midpos2 += rvec; + rvec.Normalize(); + norm2 = rvec; + dir2 = Base::Vector3d(-rvec.y, rvec.x, 0); + } + else { + norm2 = Base::Vector3d(cos(angle2), sin(angle2), 0); + dir2 = Base::Vector3d(-norm2.y, norm2.x, 0); + midpos2 += r2a * norm2; + } + } + else// Parallel can only apply to a GeomLineSegment + break; + } + else { + const Part::GeomLineSegment* lineSeg1 = + static_cast(geo1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geo2); + + // calculate the half distance between the start and endpoint + midpos1 = ((lineSeg1->getEndPoint() + lineSeg1->getStartPoint()) / 2); + midpos2 = ((lineSeg2->getEndPoint() + lineSeg2->getStartPoint()) / 2); + // Get a set of vectors perpendicular and tangential to these + dir1 = (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()).Normalize(); + dir2 = (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()).Normalize(); + norm1 = Base::Vector3d(-dir1.y, dir1.x, 0.); + norm2 = Base::Vector3d(-dir2.y, dir2.x, 0.); + } + + Base::Vector3d relpos1 = + seekConstraintPosition(midpos1, + norm1, + dir1, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); + Base::Vector3d relpos2 = + seekConstraintPosition(midpos2, + norm2, + dir2, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); + + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); + + translation->abPos = + SbVec3f(midpos1.x, midpos1.y, zConstrH);// Absolute Reference + + // Reference Position that is scaled according to zoom + translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); + + Base::Vector3d secondPos = midpos2 - midpos1; + + translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondTranslationIndex))); + + translation->abPos = + SbVec3f(secondPos.x, secondPos.y, zConstrH);// Absolute Reference + + // Reference Position that is scaled according to zoom + translation->translation = + SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); + + } break; + case Distance: + case DistanceX: + case DistanceY: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + + Base::Vector3d pnt1(0., 0., 0.), pnt2(0., 0., 0.); + if (Constr->SecondPos != Sketcher::PointPos::none) {// point to point distance + pnt1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); + pnt2 = geolistfacade.getPoint(Constr->Second, Constr->SecondPos); + } + else if (Constr->Second != GeoEnum::GeoUndef) { + const Part::Geometry* geo = + geolistfacade.getGeometryFromGeoId(Constr->Second); + if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg = + static_cast(geo); + Base::Vector3d l2p1 = lineSeg->getStartPoint(); + Base::Vector3d l2p2 = lineSeg->getEndPoint(); + if (Constr->FirstPos + != Sketcher::PointPos::none) {// point to line distance + pnt1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); + // calculate the projection of p1 onto line2 + pnt2.ProjectToLine(pnt1 - l2p1, l2p2 - l2p1); + pnt2 += pnt1; + } + else { + const Part::Geometry* geo1 = + geolistfacade.getGeometryFromGeoId(Constr->First); + if (geo1->getTypeId() + == Part::GeomCircle::getClassTypeId()) {// circle to line + // distance + const Part::GeomCircle* circleSeg = + static_cast(geo1); + Base::Vector3d ct = circleSeg->getCenter(); + double radius = circleSeg->getRadius(); + pnt1.ProjectToLine( + ct - l2p1, + l2p2 - l2p1);// project on the line translated to origin + Base::Vector3d dir = pnt1; + dir.Normalize(); + pnt1 += ct; + pnt2 = ct + dir * radius; + } + } + } + else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::Geometry* geo1 = + geolistfacade.getGeometryFromGeoId(Constr->First); + if (geo1->getTypeId() + == Part::GeomCircle::getClassTypeId()) {// circle to circle distance + const Part::GeomCircle* circleSeg1 = + static_cast(geo1); + auto circleSeg2 = static_cast(geo); + GetCirclesMinimalDistance(circleSeg1, circleSeg2, pnt1, pnt2); + } + } + else + break; + } + else if (Constr->FirstPos != Sketcher::PointPos::none) { + pnt2 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); + } + else if (Constr->First != GeoEnum::GeoUndef) { + const Part::Geometry* geo = + geolistfacade.getGeometryFromGeoId(Constr->First); + if (geo->getTypeId() + == Part::GeomLineSegment::getClassTypeId()) {// segment distance + const Part::GeomLineSegment* lineSeg = + static_cast(geo); + pnt1 = lineSeg->getStartPoint(); + pnt2 = lineSeg->getEndPoint(); + } + else + break; + } + else + break; + + SoDatumLabel* asciiText = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + + // Get presentation string (w/o units if option is set) + asciiText->string = + SbString(getPresentationString(Constr).toUtf8().constData()); + + if (Constr->Type == Distance) + asciiText->datumtype = SoDatumLabel::DISTANCE; + else if (Constr->Type == DistanceX) + asciiText->datumtype = SoDatumLabel::DISTANCEX; + else if (Constr->Type == DistanceY) + asciiText->datumtype = SoDatumLabel::DISTANCEY; + + // Assign the Datum Points + asciiText->pnts.setNum(2); + SbVec3f* verts = asciiText->pnts.startEditing(); + + verts[0] = SbVec3f(pnt1.x, pnt1.y, zConstrH); + verts[1] = SbVec3f(pnt2.x, pnt2.y, zConstrH); + + asciiText->pnts.finishEditing(); + + // Assign the Label Distance + asciiText->param1 = Constr->LabelDistance; + asciiText->param2 = Constr->LabelPosition; + } break; case PointOnObject: case Tangent: - case SnellsLaw: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); - assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); + case SnellsLaw: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); - Base::Vector3d pos, relPos; - if (Constr->Type == PointOnObject || - Constr->Type == SnellsLaw || - (Constr->Type == Tangent && Constr->Third != GeoEnum::GeoUndef) || //Tangency via point - (Constr->Type == Tangent && Constr->FirstPos != Sketcher::PointPos::none) //endpoint-to-curve or endpoint-to-endpoint tangency - ) { - - //find the point of tangency/point that is on object - //just any point among first/second/third should be OK - int ptGeoId; - Sketcher::PointPos ptPosId; - do {//dummy loop to use break =) Maybe goto? - ptGeoId = Constr->First; - ptPosId = Constr->FirstPos; - if (ptPosId != Sketcher::PointPos::none) break; - ptGeoId = Constr->Second; - ptPosId = Constr->SecondPos; - if (ptPosId != Sketcher::PointPos::none) break; - ptGeoId = Constr->Third; - ptPosId = Constr->ThirdPos; - if (ptPosId != Sketcher::PointPos::none) break; - assert(0);//no point found! - } while (false); - - pos = geolistfacade.getPoint(ptGeoId, ptPosId); - auto norm = getNormal(geolistfacade, Constr->Second, pos); - - // TODO: Check substitution - // Base::Vector3d norm = getSolvedSketch().calculateNormalAtPoint(Constr->Second, pos.x, pos.y); - norm.Normalize(); - Base::Vector3d dir = norm; dir.RotateZ(-M_PI/2.0); - - relPos = seekConstraintPosition(pos, norm, dir, 2.5, editModeScenegraphNodes.constrGroup->getChild(i)); - - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); - - translation->abPos = SbVec3f(pos.x, pos.y, zConstrH); //Absolute Reference - translation->translation = SbVec3f(relPos.x, relPos.y, 0); - } - else if (Constr->Type == Tangent) { - // get the geometry - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); - const Part::Geometry *geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); - - if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); - // tangency between two lines - Base::Vector3d midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); - Base::Vector3d midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); - Base::Vector3d dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); - Base::Vector3d dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); - Base::Vector3d norm1 = Base::Vector3d(-dir1.y,dir1.x,0.f); - Base::Vector3d norm2 = Base::Vector3d(-dir2.y,dir2.x,0.f); - - Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 4.0, editModeScenegraphNodes.constrGroup->getChild(i)); - - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); - - translation->abPos = SbVec3f(midpos1.x, midpos1.y, zConstrH); //Absolute Reference - translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); - - Base::Vector3d secondPos = midpos2 - midpos1; - - translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondTranslationIndex))); - - translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); //Absolute Reference - translation->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); + Base::Vector3d pos, relPos; + if (Constr->Type == PointOnObject || Constr->Type == SnellsLaw + || (Constr->Type == Tangent && Constr->Third != GeoEnum::GeoUndef) + ||// Tangency via point + (Constr->Type == Tangent + && Constr->FirstPos + != Sketcher::PointPos::none)// endpoint-to-curve or + // endpoint-to-endpoint tangency + ) { + // find the point of tangency/point that is on object + // just any point among first/second/third should be OK + int ptGeoId; + Sketcher::PointPos ptPosId; + do {// dummy loop to use break =) Maybe goto? + ptGeoId = Constr->First; + ptPosId = Constr->FirstPos; + if (ptPosId != Sketcher::PointPos::none) break; - } - else if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - std::swap(geo1,geo2); - } + ptGeoId = Constr->Second; + ptPosId = Constr->SecondPos; + if (ptPosId != Sketcher::PointPos::none) + break; + ptGeoId = Constr->Third; + ptPosId = Constr->ThirdPos; + if (ptPosId != Sketcher::PointPos::none) + break; + assert(0);// no point found! + } while (false); - if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo1); - Base::Vector3d dir = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); - Base::Vector3d norm(-dir.y, dir.x, 0); - if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo2); - // tangency between a line and a circle - float length = (circle->getCenter() - lineSeg->getStartPoint())*dir; + pos = geolistfacade.getPoint(ptGeoId, ptPosId); + auto norm = getNormal(geolistfacade, Constr->Second, pos); - pos = lineSeg->getStartPoint() + dir * length; - relPos = norm * 1; //TODO Huh? - } - else if (geo2->getTypeId()== Part::GeomEllipse::getClassTypeId() || - geo2->getTypeId()== Part::GeomArcOfEllipse::getClassTypeId()) { + // TODO: Check substitution + // Base::Vector3d norm = + // getSolvedSketch().calculateNormalAtPoint(Constr->Second, pos.x, pos.y); + norm.Normalize(); + Base::Vector3d dir = norm; + dir.RotateZ(-M_PI / 2.0); - Base::Vector3d center; - if (geo2->getTypeId()== Part::GeomEllipse::getClassTypeId()){ - const Part::GeomEllipse *ellipse = static_cast(geo2); - center=ellipse->getCenter(); - } else { - const Part::GeomArcOfEllipse *aoc = static_cast(geo2); - center=aoc->getCenter(); - } + relPos = seekConstraintPosition( + pos, norm, dir, 2.5, editModeScenegraphNodes.constrGroup->getChild(i)); - // tangency between a line and an ellipse - float length = (center - lineSeg->getStartPoint())*dir; + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); - pos = lineSeg->getStartPoint() + dir * length; - relPos = norm * 1; - } - else if (geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo2); - // tangency between a line and an arc - float length = (arc->getCenter() - lineSeg->getStartPoint())*dir; + translation->abPos = SbVec3f(pos.x, pos.y, zConstrH);// Absolute Reference + translation->translation = SbVec3f(relPos.x, relPos.y, 0); + } + else if (Constr->Type == Tangent) { + // get the geometry + const Part::Geometry* geo1 = + geolistfacade.getGeometryFromGeoId(Constr->First); + const Part::Geometry* geo2 = + geolistfacade.getGeometryFromGeoId(Constr->Second); - pos = lineSeg->getStartPoint() + dir * length; - relPos = norm * 1; //TODO Huh? - } - } + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg1 = + static_cast(geo1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geo2); + // tangency between two lines + Base::Vector3d midpos1 = + ((lineSeg1->getEndPoint() + lineSeg1->getStartPoint()) / 2); + Base::Vector3d midpos2 = + ((lineSeg2->getEndPoint() + lineSeg2->getStartPoint()) / 2); + Base::Vector3d dir1 = + (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()).Normalize(); + Base::Vector3d dir2 = + (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()).Normalize(); + Base::Vector3d norm1 = Base::Vector3d(-dir1.y, dir1.x, 0.f); + Base::Vector3d norm2 = Base::Vector3d(-dir2.y, dir2.x, 0.f); - if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && - geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle1 = static_cast(geo1); - const Part::GeomCircle *circle2 = static_cast(geo2); - // tangency between two cicles - Base::Vector3d dir = (circle2->getCenter() - circle1->getCenter()).Normalize(); - pos = circle1->getCenter() + dir * circle1->getRadius(); - relPos = dir * 1; - } - else if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { - std::swap(geo1,geo2); - } + Base::Vector3d relpos1 = seekConstraintPosition( + midpos1, + norm1, + dir1, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); + Base::Vector3d relpos2 = seekConstraintPosition( + midpos2, + norm2, + dir2, + 4.0, + editModeScenegraphNodes.constrGroup->getChild(i)); - if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && - geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo1); - const Part::GeomArcOfCircle *arc = static_cast(geo2); - // tangency between a circle and an arc - Base::Vector3d dir = (arc->getCenter() - circle->getCenter()).Normalize(); - pos = circle->getCenter() + dir * circle->getRadius(); - relPos = dir * 1; - } - else if (geo1->getTypeId()== Part::GeomArcOfCircle::getClassTypeId() && - geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc1 = static_cast(geo1); - const Part::GeomArcOfCircle *arc2 = static_cast(geo2); - // tangency between two arcs - Base::Vector3d dir = (arc2->getCenter() - arc1->getCenter()).Normalize(); - pos = arc1->getCenter() + dir * arc1->getRadius(); - relPos = dir * 1; - } - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); - translation->abPos = SbVec3f(pos.x, pos.y, zConstrH); //Absolute Reference - translation->translation = SbVec3f(relPos.x, relPos.y, 0); + translation->abPos = + SbVec3f(midpos1.x, midpos1.y, zConstrH);// Absolute Reference + translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); + + Base::Vector3d secondPos = midpos2 - midpos1; + + translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondTranslationIndex))); + + translation->abPos = + SbVec3f(secondPos.x, secondPos.y, zConstrH);// Absolute Reference + translation->translation = + SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); + + break; } + else if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + std::swap(geo1, geo2); + } + + if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg = + static_cast(geo1); + Base::Vector3d dir = + (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); + Base::Vector3d norm(-dir.y, dir.x, 0); + if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo2); + // tangency between a line and a circle + float length = + (circle->getCenter() - lineSeg->getStartPoint()) * dir; + + pos = lineSeg->getStartPoint() + dir * length; + relPos = norm * 1;// TODO Huh? + } + else if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo2->getTypeId() + == Part::GeomArcOfEllipse::getClassTypeId()) { + + Base::Vector3d center; + if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + const Part::GeomEllipse* ellipse = + static_cast(geo2); + center = ellipse->getCenter(); + } + else { + const Part::GeomArcOfEllipse* aoc = + static_cast(geo2); + center = aoc->getCenter(); + } + + // tangency between a line and an ellipse + float length = (center - lineSeg->getStartPoint()) * dir; + + pos = lineSeg->getStartPoint() + dir * length; + relPos = norm * 1; + } + else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo2); + // tangency between a line and an arc + float length = (arc->getCenter() - lineSeg->getStartPoint()) * dir; + + pos = lineSeg->getStartPoint() + dir * length; + relPos = norm * 1;// TODO Huh? + } + } + + if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId() + && geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle1 = + static_cast(geo1); + const Part::GeomCircle* circle2 = + static_cast(geo2); + // tangency between two cicles + Base::Vector3d dir = + (circle2->getCenter() - circle1->getCenter()).Normalize(); + pos = circle1->getCenter() + dir * circle1->getRadius(); + relPos = dir * 1; + } + else if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { + std::swap(geo1, geo2); + } + + if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId() + && geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo1); + const Part::GeomArcOfCircle* arc = + static_cast(geo2); + // tangency between a circle and an arc + Base::Vector3d dir = + (arc->getCenter() - circle->getCenter()).Normalize(); + pos = circle->getCenter() + dir * circle->getRadius(); + relPos = dir * 1; + } + else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + && geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc1 = + static_cast(geo1); + const Part::GeomArcOfCircle* arc2 = + static_cast(geo2); + // tangency between two arcs + Base::Vector3d dir = + (arc2->getCenter() - arc1->getCenter()).Normalize(); + pos = arc1->getCenter() + dir * arc1->getRadius(); + relPos = dir * 1; + } + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); + + translation->abPos = SbVec3f(pos.x, pos.y, zConstrH);// Absolute Reference + translation->translation = SbVec3f(relPos.x, relPos.y, 0); } - break; - case Symmetric: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); - assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); + } break; + case Symmetric: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); - Base::Vector3d pnt1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); - Base::Vector3d pnt2 = geolistfacade.getPoint(Constr->Second, Constr->SecondPos); + Base::Vector3d pnt1 = geolistfacade.getPoint(Constr->First, Constr->FirstPos); + Base::Vector3d pnt2 = geolistfacade.getPoint(Constr->Second, Constr->SecondPos); - SbVec3f p1(pnt1.x, pnt1.y, zConstrH); - SbVec3f p2(pnt2.x, pnt2.y, zConstrH); - SbVec3f dir = (p2-p1); - dir.normalize(); - SbVec3f norm (-dir[1],dir[0],0); + SbVec3f p1(pnt1.x, pnt1.y, zConstrH); + SbVec3f p2(pnt2.x, pnt2.y, zConstrH); + SbVec3f dir = (p2 - p1); + dir.normalize(); + SbVec3f norm(-dir[1], dir[0], 0); - SoDatumLabel *asciiText = static_cast(sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - asciiText->datumtype = SoDatumLabel::SYMMETRIC; + SoDatumLabel* asciiText = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + asciiText->datumtype = SoDatumLabel::SYMMETRIC; - asciiText->pnts.setNum(2); - SbVec3f *verts = asciiText->pnts.startEditing(); + asciiText->pnts.setNum(2); + SbVec3f* verts = asciiText->pnts.startEditing(); - verts[0] = p1; - verts[1] = p2; + verts[0] = p1; + verts[1] = p2; - asciiText->pnts.finishEditing(); + asciiText->pnts.finishEditing(); - auto translation = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); + auto translation = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstTranslationIndex))); - translation->translation = (p1 + p2)/2; - } - break; - case Angle: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); - assert((Constr->Second >= -extGeoCount && Constr->Second < intGeoCount) || - Constr->Second == GeoEnum::GeoUndef); + translation->translation = (p1 + p2) / 2; + } break; + case Angle: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + assert((Constr->Second >= -extGeoCount && Constr->Second < intGeoCount) + || Constr->Second == GeoEnum::GeoUndef); - SbVec3f p0; - double startangle,range,endangle; - if (Constr->Second != GeoEnum::GeoUndef) { - Base::Vector3d dir1, dir2; - if (Constr->Third == GeoEnum::GeoUndef) { //angle between two lines - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); - const Part::Geometry *geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); - if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || - geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) - break; - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); + SbVec3f p0; + double startangle, range, endangle; + if (Constr->Second != GeoEnum::GeoUndef) { + Base::Vector3d dir1, dir2; + if (Constr->Third == GeoEnum::GeoUndef) {// angle between two lines + const Part::Geometry* geo1 = + geolistfacade.getGeometryFromGeoId(Constr->First); + const Part::Geometry* geo2 = + geolistfacade.getGeometryFromGeoId(Constr->Second); + if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() + || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) + break; + const Part::GeomLineSegment* lineSeg1 = + static_cast(geo1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geo2); - bool flip1 = (Constr->FirstPos == PointPos::end); - bool flip2 = (Constr->SecondPos == PointPos::end); - dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); - dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); - Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); - Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); + bool flip1 = (Constr->FirstPos == PointPos::end); + bool flip2 = (Constr->SecondPos == PointPos::end); + dir1 = (flip1 ? -1. : 1.) + * (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()); + dir2 = (flip2 ? -1. : 1.) + * (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()); + Base::Vector3d pnt1 = + flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); + Base::Vector3d pnt2 = + flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); - // line-line intersection - { - double det = dir1.x*dir2.y - dir1.y*dir2.x; - if ((det > 0 ? det : -det) < 1e-10) { - // lines are coincident (or parallel) and in this case the center - // of the point pairs with the shortest distance is used - Base::Vector3d p1[2], p2[2]; - p1[0] = lineSeg1->getStartPoint(); - p1[1] = lineSeg1->getEndPoint(); - p2[0] = lineSeg2->getStartPoint(); - p2[1] = lineSeg2->getEndPoint(); - double length = DBL_MAX; - for (int i=0; i <= 1; i++) { - for (int j=0; j <= 1; j++) { - double tmp = (p2[j]-p1[i]).Length(); - if (tmp < length) { - length = tmp; - p0.setValue((p2[j].x+p1[i].x)/2,(p2[j].y+p1[i].y)/2,0); - } + // line-line intersection + { + double det = dir1.x * dir2.y - dir1.y * dir2.x; + if ((det > 0 ? det : -det) < 1e-10) { + // lines are coincident (or parallel) and in this case the + // center of the point pairs with the shortest distance is used + Base::Vector3d p1[2], p2[2]; + p1[0] = lineSeg1->getStartPoint(); + p1[1] = lineSeg1->getEndPoint(); + p2[0] = lineSeg2->getStartPoint(); + p2[1] = lineSeg2->getEndPoint(); + double length = DBL_MAX; + for (int i = 0; i <= 1; i++) { + for (int j = 0; j <= 1; j++) { + double tmp = (p2[j] - p1[i]).Length(); + if (tmp < length) { + length = tmp; + p0.setValue((p2[j].x + p1[i].x) / 2, + (p2[j].y + p1[i].y) / 2, + 0); } } } - else { - double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; - double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; - double x = (dir1.x*c2 - dir2.x*c1)/det; - double y = (dir1.y*c2 - dir2.y*c1)/det; - p0 = SbVec3f(x,y,0); - } } - - range = Constr->getValue(); // WYSIWYG - startangle = atan2(dir1.y,dir1.x); - } - else {//angle-via-point - Base::Vector3d p = geolistfacade.getPoint(Constr->Third, Constr->ThirdPos); - p0 = SbVec3f(p.x, p.y, 0); - dir1 = getNormal(geolistfacade, Constr->First, p); - // TODO: Check - // dir1 = getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); - dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating - dir2 = getNormal(geolistfacade, Constr->Second, p); - // TODO: Check - // dir2 = getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); - dir2.RotateZ(-M_PI/2); - - startangle = atan2(dir1.y,dir1.x); - range = atan2(dir1.x*dir2.y-dir1.y*dir2.x, - dir1.x*dir2.x+dir1.y*dir2.y); + else { + double c1 = dir1.y * pnt1.x - dir1.x * pnt1.y; + double c2 = dir2.y * pnt2.x - dir2.x * pnt2.y; + double x = (dir1.x * c2 - dir2.x * c1) / det; + double y = (dir1.y * c2 - dir2.y * c1) / det; + p0 = SbVec3f(x, y, 0); + } } + range = Constr->getValue();// WYSIWYG + startangle = atan2(dir1.y, dir1.x); + } + else {// angle-via-point + Base::Vector3d p = + geolistfacade.getPoint(Constr->Third, Constr->ThirdPos); + p0 = SbVec3f(p.x, p.y, 0); + dir1 = getNormal(geolistfacade, Constr->First, p); + // TODO: Check + // dir1 = getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, + // p.y); + dir1.RotateZ(-M_PI / 2);// convert to vector of tangency by rotating + dir2 = getNormal(geolistfacade, Constr->Second, p); + // TODO: Check + // dir2 = getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, + // p.y); + dir2.RotateZ(-M_PI / 2); + + startangle = atan2(dir1.y, dir1.x); + range = atan2(dir1.x * dir2.y - dir1.y * dir2.x, + dir1.x * dir2.x + dir1.y * dir2.y); + } + + endangle = startangle + range; + } + else if (Constr->First != GeoEnum::GeoUndef) { + const Part::Geometry* geo = + geolistfacade.getGeometryFromGeoId(Constr->First); + if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + const Part::GeomLineSegment* lineSeg = + static_cast(geo); + p0 = Base::convertTo( + (lineSeg->getEndPoint() + lineSeg->getStartPoint()) / 2); + + Base::Vector3d dir = lineSeg->getEndPoint() - lineSeg->getStartPoint(); + startangle = 0.; + range = atan2(dir.y, dir.x); endangle = startangle + range; + } + else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo); + p0 = Base::convertTo(arc->getCenter()); - } else if (Constr->First != GeoEnum::GeoUndef) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(Constr->First); - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); - p0 = Base::convertTo((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); - - Base::Vector3d dir = lineSeg->getEndPoint()-lineSeg->getStartPoint(); - startangle = 0.; - range = atan2(dir.y,dir.x); - endangle = startangle + range; - } - else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo); - p0 = Base::convertTo(arc->getCenter()); - - arc->getRange(startangle, endangle,/*emulateCCWXY=*/true); - range = endangle - startangle; - } - else { - break; - } - } else + arc->getRange(startangle, endangle, /*emulateCCWXY=*/true); + range = endangle - startangle; + } + else { break; - - SoDatumLabel *asciiText = static_cast(sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - asciiText->string = SbString(getPresentationString(Constr).toUtf8().constData()); - asciiText->datumtype = SoDatumLabel::ANGLE; - asciiText->param1 = Constr->LabelDistance; - asciiText->param2 = startangle; - asciiText->param3 = range; - - asciiText->pnts.setNum(2); - SbVec3f *verts = asciiText->pnts.startEditing(); - - verts[0] = p0; - - asciiText->pnts.finishEditing(); - + } } - break; - case Diameter: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + else + break; - Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); - if (Constr->First != GeoEnum::GeoUndef) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(Constr->First); + SoDatumLabel* asciiText = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + asciiText->string = + SbString(getPresentationString(Constr).toUtf8().constData()); + asciiText->datumtype = SoDatumLabel::ANGLE; + asciiText->param1 = Constr->LabelDistance; + asciiText->param2 = startangle; + asciiText->param3 = range; - if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo); - double radius = arc->getRadius(); - double angle = (double) Constr->LabelPosition; - if (angle == 10) { - double startangle, endangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - angle = (startangle + endangle)/2; - } - Base::Vector3d center = arc->getCenter(); - pnt1 = center - radius * Base::Vector3d(cos(angle),sin(angle),0.); - pnt2 = center + radius * Base::Vector3d(cos(angle),sin(angle),0.); + asciiText->pnts.setNum(2); + SbVec3f* verts = asciiText->pnts.startEditing(); + + verts[0] = p0; + + asciiText->pnts.finishEditing(); + + } break; + case Diameter: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + + Base::Vector3d pnt1(0., 0., 0.), pnt2(0., 0., 0.); + if (Constr->First != GeoEnum::GeoUndef) { + const Part::Geometry* geo = + geolistfacade.getGeometryFromGeoId(Constr->First); + + if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo); + double radius = arc->getRadius(); + double angle = (double)Constr->LabelPosition; + if (angle == 10) { + double startangle, endangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + angle = (startangle + endangle) / 2; } - else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo); - double radius = circle->getRadius(); - double angle = (double) Constr->LabelPosition; - if (angle == 10) { - angle = 0; - } - Base::Vector3d center = circle->getCenter(); - pnt1 = center - radius * Base::Vector3d(cos(angle),sin(angle),0.); - pnt2 = center + radius * Base::Vector3d(cos(angle),sin(angle),0.); + Base::Vector3d center = arc->getCenter(); + pnt1 = center - radius * Base::Vector3d(cos(angle), sin(angle), 0.); + pnt2 = center + radius * Base::Vector3d(cos(angle), sin(angle), 0.); + } + else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo); + double radius = circle->getRadius(); + double angle = (double)Constr->LabelPosition; + if (angle == 10) { + angle = 0; } - else - break; - } else - break; - - SbVec3f p1(pnt1.x, pnt1.y, zConstrH); - SbVec3f p2(pnt2.x, pnt2.y, zConstrH); - - SoDatumLabel *asciiText = static_cast(sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - - // Get display string with units hidden if so requested - asciiText->string = SbString( getPresentationString(Constr).toUtf8().constData() ); - - asciiText->datumtype = SoDatumLabel::DIAMETER; - asciiText->param1 = Constr->LabelDistance; - asciiText->param2 = Constr->LabelPosition; - - asciiText->pnts.setNum(2); - SbVec3f *verts = asciiText->pnts.startEditing(); - - verts[0] = p1; - verts[1] = p2; - - asciiText->pnts.finishEditing(); - } - break; - case Weight: - case Radius: - { - assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); - - Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); - - if (Constr->First != GeoEnum::GeoUndef) { - const Part::Geometry *geo = geolistfacade.getGeometryFromGeoId(Constr->First); - - if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo); - double radius = arc->getRadius(); - double angle = (double) Constr->LabelPosition; - if (angle == 10) { - double startangle, endangle; - arc->getRange(startangle, endangle, /*emulateCCW=*/true); - angle = (startangle + endangle)/2; - } - pnt1 = arc->getCenter(); - pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); - } - else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo); - auto gf = GeometryFacade::getFacade(geo); - - double radius; - - radius = circle->getRadius(); - - double angle = (double) Constr->LabelPosition; - if (angle == 10) { - angle = 0; - } - pnt1 = circle->getCenter(); - pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); - } - else - break; - } else - break; - - SbVec3f p1(pnt1.x, pnt1.y, zConstrH); - SbVec3f p2(pnt2.x, pnt2.y, zConstrH); - - SoDatumLabel *asciiText = static_cast(sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - - // Get display string with units hidden if so requested - if (Constr->Type == Weight) - asciiText->string = SbString( QString::number(Constr->getValue()).toStdString().c_str()); + Base::Vector3d center = circle->getCenter(); + pnt1 = center - radius * Base::Vector3d(cos(angle), sin(angle), 0.); + pnt2 = center + radius * Base::Vector3d(cos(angle), sin(angle), 0.); + } else - asciiText->string = SbString( getPresentationString(Constr).toUtf8().constData() ); - - asciiText->datumtype = SoDatumLabel::RADIUS; - asciiText->param1 = Constr->LabelDistance; - asciiText->param2 = Constr->LabelPosition; - - asciiText->pnts.setNum(2); - SbVec3f *verts = asciiText->pnts.startEditing(); - - verts[0] = p1; - verts[1] = p2; - - asciiText->pnts.finishEditing(); + break; } - break; - case Coincident: // nothing to do for coincident + else + break; + + SbVec3f p1(pnt1.x, pnt1.y, zConstrH); + SbVec3f p2(pnt2.x, pnt2.y, zConstrH); + + SoDatumLabel* asciiText = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + + // Get display string with units hidden if so requested + asciiText->string = + SbString(getPresentationString(Constr).toUtf8().constData()); + + asciiText->datumtype = SoDatumLabel::DIAMETER; + asciiText->param1 = Constr->LabelDistance; + asciiText->param2 = Constr->LabelPosition; + + asciiText->pnts.setNum(2); + SbVec3f* verts = asciiText->pnts.startEditing(); + + verts[0] = p1; + verts[1] = p2; + + asciiText->pnts.finishEditing(); + } break; + case Weight: + case Radius: { + assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); + + Base::Vector3d pnt1(0., 0., 0.), pnt2(0., 0., 0.); + + if (Constr->First != GeoEnum::GeoUndef) { + const Part::Geometry* geo = + geolistfacade.getGeometryFromGeoId(Constr->First); + + if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = + static_cast(geo); + double radius = arc->getRadius(); + double angle = (double)Constr->LabelPosition; + if (angle == 10) { + double startangle, endangle; + arc->getRange(startangle, endangle, /*emulateCCW=*/true); + angle = (startangle + endangle) / 2; + } + pnt1 = arc->getCenter(); + pnt2 = pnt1 + radius * Base::Vector3d(cos(angle), sin(angle), 0.); + } + else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { + const Part::GeomCircle* circle = + static_cast(geo); + auto gf = GeometryFacade::getFacade(geo); + + double radius; + + radius = circle->getRadius(); + + double angle = (double)Constr->LabelPosition; + if (angle == 10) { + angle = 0; + } + pnt1 = circle->getCenter(); + pnt2 = pnt1 + radius * Base::Vector3d(cos(angle), sin(angle), 0.); + } + else + break; + } + else + break; + + SbVec3f p1(pnt1.x, pnt1.y, zConstrH); + SbVec3f p2(pnt2.x, pnt2.y, zConstrH); + + SoDatumLabel* asciiText = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + + // Get display string with units hidden if so requested + if (Constr->Type == Weight) + asciiText->string = + SbString(QString::number(Constr->getValue()).toStdString().c_str()); + else + asciiText->string = + SbString(getPresentationString(Constr).toUtf8().constData()); + + asciiText->datumtype = SoDatumLabel::RADIUS; + asciiText->param1 = Constr->LabelDistance; + asciiText->param2 = Constr->LabelPosition; + + asciiText->pnts.setNum(2); + SbVec3f* verts = asciiText->pnts.startEditing(); + + verts[0] = p1; + verts[1] = p2; + + asciiText->pnts.finishEditing(); + } break; + case Coincident:// nothing to do for coincident case None: case InternalAlignment: case NumConstraintTypes: break; } - - } catch (Base::Exception &e) { - Base::Console().DeveloperError("EditModeConstraintCoinManager","Exception during draw: %s\n", e.what()); - e.ReportException(); - } catch (...){ - Base::Console().DeveloperError("EditModeConstraintCoinManager","Exception during draw: unknown\n"); } - + catch (Base::Exception& e) { + Base::Console().DeveloperError( + "EditModeConstraintCoinManager", "Exception during draw: %s\n", e.what()); + e.ReportException(); + } + catch (...) { + Base::Console().DeveloperError("EditModeConstraintCoinManager", + "Exception during draw: unknown\n"); + } } } -Base::Vector3d EditModeConstraintCoinManager::seekConstraintPosition(const Base::Vector3d &origPos, - const Base::Vector3d &norm, - const Base::Vector3d &dir, float step, - const SoNode *constraint) +Base::Vector3d EditModeConstraintCoinManager::seekConstraintPosition(const Base::Vector3d& origPos, + const Base::Vector3d& norm, + const Base::Vector3d& dir, + float step, + const SoNode* constraint) { auto rp = ViewProviderSketchCoinAttorney::getRayPickAction(viewProvider); @@ -1207,19 +1459,20 @@ Base::Vector3d EditModeConstraintCoinManager::seekConstraintPosition(const Base: rp->setRadius(0.1f); rp->setPickAll(true); - rp->setRay(SbVec3f(freePos.x, freePos.y, -1.f), SbVec3f(0, 0, 1) ); - //problem - rp->apply(editModeScenegraphNodes.constrGroup); // We could narrow it down to just the SoGroup containing the constraints + rp->setRay(SbVec3f(freePos.x, freePos.y, -1.f), SbVec3f(0, 0, 1)); + // problem + rp->apply(editModeScenegraphNodes.constrGroup);// We could narrow it down to just the + // SoGroup containing the constraints // returns a copy of the point - SoPickedPoint *pp = rp->getPickedPoint(); + SoPickedPoint* pp = rp->getPickedPoint(); const SoPickedPointList ppl = rp->getPickedPointList(); if (ppl.getLength() <= 1 && pp) { - SoPath *path = pp->getPath(); + SoPath* path = pp->getPath(); int length = path->getLength(); - SoNode *tailFather1 = path->getNode(length-2); - SoNode *tailFather2 = path->getNode(length-3); + SoNode* tailFather1 = path->getNode(length - 2); + SoNode* tailFather2 = path->getNode(length - 3); // checking if a constraint is the same as the one selected if (tailFather1 == constraint || tailFather2 == constraint) @@ -1229,86 +1482,90 @@ Base::Vector3d EditModeConstraintCoinManager::seekConstraintPosition(const Base: isConstraintAtPosition = false; } - multiplier *= -1; // search in both sides + multiplier *= -1;// search in both sides if (multiplier >= 0) - multiplier++; // Increment the multiplier + multiplier++;// Increment the multiplier } if (multiplier == 10) - relPos = norm * 0.5f; // no free position found + relPos = norm * 0.5f;// no free position found return relPos * step; } -void EditModeConstraintCoinManager::updateConstraintColor(const std::vector &constraints) +void EditModeConstraintCoinManager::updateConstraintColor( + const std::vector& constraints) { - // Because coincident constraints are selected using the point color, we need to edit the point materials. + // Because coincident constraints are selected using the point color, we need to edit the point + // materials. std::vector PtNum; - std::vector pcolor; // point color + std::vector pcolor;// point color std::vector CurvNum; - std::vector color; // curve color + std::vector color;// curve color - for(int l=0; ldiffuseColor.getNum()); pcolor.push_back(editModeScenegraphNodes.PointsMaterials[l]->diffuseColor.startEditing()); CurvNum.push_back(editModeScenegraphNodes.CurvesMaterials[l]->diffuseColor.getNum()); color.push_back(editModeScenegraphNodes.CurvesMaterials[l]->diffuseColor.startEditing()); } - int maxNumberOfConstraints = std::min(editModeScenegraphNodes.constrGroup->getNumChildren(), static_cast(constraints.size())); + int maxNumberOfConstraints = std::min(editModeScenegraphNodes.constrGroup->getNumChildren(), + static_cast(constraints.size())); // colors of the constraints for (int i = 0; i < maxNumberOfConstraints; i++) { - SoSeparator *s = static_cast(editModeScenegraphNodes.constrGroup->getChild(i)); + SoSeparator* s = + static_cast(editModeScenegraphNodes.constrGroup->getChild(i)); // Check Constraint Type Sketcher::Constraint* constraint = constraints[i]; ConstraintType type = constraint->Type; - // It may happen that color updates are triggered by programmatic selection changes before a command final update. Then - // constraints may have been changed and the color will be updated as part + // It may happen that color updates are triggered by programmatic selection changes before a + // command final update. Then constraints may have been changed and the color will be + // updated as part if (type != vConstrType[i]) break; - bool hasDatumLabel = (type == Sketcher::Angle || - type == Sketcher::Radius || - type == Sketcher::Diameter || - type == Sketcher::Weight || - type == Sketcher::Symmetric || - type == Sketcher::Distance || - type == Sketcher::DistanceX || - type == Sketcher::DistanceY); + bool hasDatumLabel = (type == Sketcher::Angle || type == Sketcher::Radius + || type == Sketcher::Diameter || type == Sketcher::Weight + || type == Sketcher::Symmetric || type == Sketcher::Distance + || type == Sketcher::DistanceX || type == Sketcher::DistanceY); // Non DatumLabel Nodes will have a material excluding coincident bool hasMaterial = false; - SoMaterial *m = nullptr; + SoMaterial* m = nullptr; if (!hasDatumLabel && type != Sketcher::Coincident && type != Sketcher::InternalAlignment) { hasMaterial = true; - m = static_cast(s->getChild(static_cast(ConstraintNodePosition::MaterialIndex))); + m = static_cast( + s->getChild(static_cast(ConstraintNodePosition::MaterialIndex))); } - auto selectpoint = [this, pcolor, PtNum](int geoid, Sketcher::PointPos pos){ + auto selectpoint = [this, pcolor, PtNum](int geoid, Sketcher::PointPos pos) { if (geoid >= 0) { auto multifieldIndex = coinMapping.getIndexLayer(geoid, pos); if (multifieldIndex != MultiFieldId::Invalid) { int index = multifieldIndex.fieldIndex; int layer = multifieldIndex.layerId; - if (layer < static_cast(PtNum.size()) && index >= 0 && index < PtNum[layer]) { + if (layer < static_cast(PtNum.size()) && index >= 0 + && index < PtNum[layer]) { pcolor[layer][index] = drawingParameters.SelectColor; } } } }; - auto selectline = [this, color, CurvNum](int geoid){ + auto selectline = [this, color, CurvNum](int geoid) { if (geoid >= 0) { auto multifieldIndex = coinMapping.getIndexLayer(geoid, Sketcher::PointPos::none); if (multifieldIndex != MultiFieldId::Invalid) { int index = multifieldIndex.fieldIndex; int layer = multifieldIndex.layerId; - if (layer < static_cast(CurvNum.size()) && index >= 0 && index < CurvNum[layer]) { + if (layer < static_cast(CurvNum.size()) && index >= 0 + && index < CurvNum[layer]) { color[layer][index] = drawingParameters.SelectColor; } } @@ -1318,69 +1575,71 @@ void EditModeConstraintCoinManager::updateConstraintColor(const std::vector(s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + SoDatumLabel* l = static_cast( + s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); l->textColor = drawingParameters.SelectColor; - } else if (hasMaterial) { + } + else if (hasMaterial) { m->diffuseColor = drawingParameters.SelectColor; - } else if (type == Sketcher::Coincident) { + } + else if (type == Sketcher::Coincident) { selectpoint(constraint->First, constraint->FirstPos); selectpoint(constraint->Second, constraint->SecondPos); - } else if (type == Sketcher::InternalAlignment) { - switch(constraint->AlignmentType) { + } + else if (type == Sketcher::InternalAlignment) { + switch (constraint->AlignmentType) { case EllipseMajorDiameter: case EllipseMinorDiameter: case HyperbolaMajor: case HyperbolaMinor: - case ParabolaFocalAxis: - { + case ParabolaFocalAxis: { selectline(constraint->First); - } - break; + } break; case EllipseFocus1: case EllipseFocus2: case HyperbolaFocus: case ParabolaFocus: case BSplineControlPoint: - case BSplineKnotPoint: - { + case BSplineKnotPoint: { selectpoint(constraint->First, constraint->FirstPos); - } - break; + } break; default: - break; + break; } } - } else if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider,i)) { + } + else if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider, i)) { if (hasDatumLabel) { - SoDatumLabel *l = static_cast(s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + SoDatumLabel* l = static_cast( + s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); l->textColor = drawingParameters.PreselectColor; - } else if (hasMaterial) { + } + else if (hasMaterial) { m->diffuseColor = drawingParameters.PreselectColor; } } else { if (hasDatumLabel) { - SoDatumLabel *l = static_cast(s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + SoDatumLabel* l = static_cast( + s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - l->textColor = constraint->isActive ? - ViewProviderSketchCoinAttorney::constraintHasExpression(viewProvider, i) ? - drawingParameters.ExprBasedConstrDimColor - :(constraint->isDriving ? - drawingParameters.ConstrDimColor - : drawingParameters.NonDrivingConstrDimColor) - :drawingParameters.DeactivatedConstrDimColor; - - } else if (hasMaterial) { - m->diffuseColor = constraint->isActive ? - (constraint->isDriving ? - drawingParameters.ConstrDimColor - :drawingParameters.NonDrivingConstrDimColor) - :drawingParameters.DeactivatedConstrDimColor; + l->textColor = constraint->isActive + ? ViewProviderSketchCoinAttorney::constraintHasExpression(viewProvider, i) + ? drawingParameters.ExprBasedConstrDimColor + : (constraint->isDriving ? drawingParameters.ConstrDimColor + : drawingParameters.NonDrivingConstrDimColor) + : drawingParameters.DeactivatedConstrDimColor; + } + else if (hasMaterial) { + m->diffuseColor = constraint->isActive + ? (constraint->isDriving ? drawingParameters.ConstrDimColor + : drawingParameters.NonDrivingConstrDimColor) + : drawingParameters.DeactivatedConstrDimColor; } } } - for(int l=0; ldiffuseColor.finishEditing(); editModeScenegraphNodes.CurvesMaterials[l]->diffuseColor.finishEditing(); } @@ -1403,9 +1662,10 @@ void EditModeConstraintCoinManager::setConstraintSelectability(bool enabled /* = } } -void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & geolistfacade) +void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade& geolistfacade) { - const std::vector &constrlist = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); + const std::vector& constrlist = + ViewProviderSketchCoinAttorney::getConstraints(viewProvider); // clean up Gui::coinRemoveAllChildren(editModeScenegraphNodes.constrGroup); @@ -1413,12 +1673,12 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & vConstrType.clear(); // Get sketch normal - Base::Vector3d RN(0,0,1); + Base::Vector3d RN(0, 0, 1); // move to position of Sketch Base::Placement Plz = ViewProviderSketchCoinAttorney::getEditingPlacement(viewProvider); Base::Rotation tmp(Plz.getRotation()); - tmp.multVec(RN,RN); + tmp.multVec(RN, RN); Plz.setRotation(tmp); SbVec3f norm(RN.x, RN.y, RN.z); @@ -1426,24 +1686,27 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & rebuildConstraintNodes(geolistfacade, constrlist, norm); } -void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & geolistfacade, const std::vector constrlist, SbVec3f norm) +void EditModeConstraintCoinManager::rebuildConstraintNodes( + const GeoListFacade& geolistfacade, const std::vector constrlist, + SbVec3f norm) { - for (std::vector::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it) { + for (std::vector::const_iterator it = constrlist.begin(); + it != constrlist.end(); + ++it) { // root separator for one constraint - SoSeparator *sep = new SoSeparator(); + SoSeparator* sep = new SoSeparator(); sep->ref(); // no caching for frequently-changing data structures sep->renderCaching = SoSeparator::OFF; // every constrained visual node gets its own material for preselection and selection - SoMaterial *mat = new SoMaterial; + SoMaterial* mat = new SoMaterial; mat->ref(); - mat->diffuseColor = (*it)->isActive ? - ((*it)->isDriving ? - drawingParameters.ConstrDimColor - :drawingParameters.NonDrivingConstrDimColor) - :drawingParameters.DeactivatedConstrDimColor; + mat->diffuseColor = (*it)->isActive + ? ((*it)->isDriving ? drawingParameters.ConstrDimColor + : drawingParameters.NonDrivingConstrDimColor) + : drawingParameters.DeactivatedConstrDimColor; // distinguish different constraint types to build up @@ -1454,20 +1717,18 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & case Radius: case Diameter: case Weight: - case Angle: - { - SoDatumLabel *text = new SoDatumLabel(); + case Angle: { + SoDatumLabel* text = new SoDatumLabel(); text->norm.setValue(norm); text->string = ""; - text->textColor = (*it)->isActive ? - ((*it)->isDriving ? - drawingParameters.ConstrDimColor - :drawingParameters.NonDrivingConstrDimColor) - :drawingParameters.DeactivatedConstrDimColor; + text->textColor = (*it)->isActive + ? ((*it)->isDriving ? drawingParameters.ConstrDimColor + : drawingParameters.NonDrivingConstrDimColor) + : drawingParameters.DeactivatedConstrDimColor; text->size.setValue(drawingParameters.labelFontSize); text->lineWidth = 2 * drawingParameters.pixelScalingFactor; text->useAntialiasing = false; - SoAnnotation *anno = new SoAnnotation(); + SoAnnotation* anno = new SoAnnotation(); anno->renderCaching = SoSeparator::OFF; anno->addChild(text); // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 @@ -1477,13 +1738,11 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & // nodes not needed sep->unref(); mat->unref(); - continue; // jump to next constraint - } - break; + continue;// jump to next constraint + } break; case Horizontal: case Vertical: - case Block: - { + case Block: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 @@ -1501,15 +1760,13 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & // remember the type of this constraint node vConstrType.push_back((*it)->Type); - } - break; - case Coincident: // no visual for coincident so far + } break; + case Coincident:// no visual for coincident so far vConstrType.push_back(Coincident); break; case Parallel: case Perpendicular: - case Equal: - { + case Equal: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 @@ -1527,12 +1784,10 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & // remember the type of this constraint node vConstrType.push_back((*it)->Type); - } - break; + } break; case PointOnObject: case Tangent: - case SnellsLaw: - { + case SnellsLaw: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 @@ -1543,13 +1798,15 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & sep->addChild(new SoInfo()); if ((*it)->Type == Tangent) { - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId((*it)->First); - const Part::Geometry *geo2 = geolistfacade.getGeometryFromGeoId((*it)->Second); + const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId((*it)->First); + const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId((*it)->Second); if (!geo1 || !geo2) { - Base::Console().DeveloperWarning("EditModeConstraintCoinManager","Tangent constraint references non-existing geometry\n"); + Base::Console().DeveloperWarning( + "EditModeConstraintCoinManager", + "Tangent constraint references non-existing geometry\n"); } - else if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + else if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() + && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 @@ -1560,11 +1817,9 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & } vConstrType.push_back((*it)->Type); - } - break; - case Symmetric: - { - SoDatumLabel *arrows = new SoDatumLabel(); + } break; + case Symmetric: { + SoDatumLabel* arrows = new SoDatumLabel(); arrows->norm.setValue(norm); arrows->string = ""; arrows->textColor = drawingParameters.ConstrDimColor; @@ -1580,13 +1835,10 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & sep->addChild(new SoInfo()); vConstrType.push_back((*it)->Type); - } - break; - case InternalAlignment: - { + } break; + case InternalAlignment: { vConstrType.push_back((*it)->Type); - } - break; + } break; default: vConstrType.push_back((*it)->Type); } @@ -1598,15 +1850,15 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade & } } -QString EditModeConstraintCoinManager::getPresentationString(const Constraint *constraint) +QString EditModeConstraintCoinManager::getPresentationString(const Constraint* constraint) { - QString nameStr; // name parameter string - QString valueStr; // dimensional value string - QString presentationStr; // final return string - QString unitStr; // the actual unit string - QString baseUnitStr; // the expected base unit string - double factor; // unit scaling factor, currently not used - Base::UnitSystem unitSys; // current unit system + QString nameStr; // name parameter string + QString valueStr; // dimensional value string + QString presentationStr; // final return string + QString unitStr; // the actual unit string + QString baseUnitStr; // the expected base unit string + double factor; // unit scaling factor, currently not used + Base::UnitSystem unitSys;// current unit system if (!constraint->isActive) return QString::fromLatin1(" "); @@ -1620,8 +1872,7 @@ QString EditModeConstraintCoinManager::getPresentationString(const Constraint *c // Hide units if user has requested it, is being displayed in the base // units, and the schema being used has a clear base unit in the first // place. Otherwise, display units. - if (constraintParameters.bHideUnits && constraint->Type != Sketcher::Angle) - { + if (constraintParameters.bHideUnits && constraint->Type != Sketcher::Angle) { // Only hide the default length unit. Right now there is not an easy way // to get that from the Unit system so we have to manually add it here. // Hopefully this can be added in the future so this code won't have to @@ -1629,8 +1880,7 @@ QString EditModeConstraintCoinManager::getPresentationString(const Constraint *c unitSys = Base::UnitsApi::getSchema(); // If this is a supported unit system then define what the base unit is. - switch (unitSys) - { + switch (unitSys) { case Base::UnitSystem::SI1: case Base::UnitSystem::MmMin: baseUnitStr = QString::fromLatin1("mm"); @@ -1653,23 +1903,22 @@ QString EditModeConstraintCoinManager::getPresentationString(const Constraint *c break; } - if (!baseUnitStr.isEmpty()) - { + if (!baseUnitStr.isEmpty()) { // expected unit string matches actual unit string. remove. - if (QString::compare(baseUnitStr, unitStr)==0) - { + if (QString::compare(baseUnitStr, unitStr) == 0) { // Example code from: Mod/TechDraw/App/DrawViewDimension.cpp:372 - QRegularExpression rxUnits(QString::fromUtf8(" \\D*$")); //space + any non digits at end of string - valueStr.remove(rxUnits); //getUserString(defaultDecimals) without units + QRegularExpression rxUnits( + QString::fromUtf8(" \\D*$"));// space + any non digits at end of string + valueStr.remove(rxUnits); // getUserString(defaultDecimals) without units } } } - if (constraint->Type == Sketcher::Diameter){ - valueStr.prepend(QChar(216)); // Diameter sign + if (constraint->Type == Sketcher::Diameter) { + valueStr.prepend(QChar(216));// Diameter sign } - else if (constraint->Type == Sketcher::Radius){ - valueStr.prepend(QChar(82)); // Capital letter R + else if (constraint->Type == Sketcher::Radius) { + valueStr.prepend(QChar(82));// Capital letter R } /** @@ -1678,18 +1927,16 @@ QString EditModeConstraintCoinManager::getPresentationString(const Constraint *c %N - the constraint name parameter %V - the value of the dimensional constraint, including any unit characters */ - if (constraintParameters.bShowDimensionalName && !nameStr.isEmpty()) - { - if (constraintParameters.sDimensionalStringFormat.contains(QLatin1String("%V")) || - constraintParameters.sDimensionalStringFormat.contains(QLatin1String("%N"))) - { + if (constraintParameters.bShowDimensionalName && !nameStr.isEmpty()) { + if (constraintParameters.sDimensionalStringFormat.contains(QLatin1String("%V")) + || constraintParameters.sDimensionalStringFormat.contains(QLatin1String("%N"))) { presentationStr = constraintParameters.sDimensionalStringFormat; presentationStr.replace(QLatin1String("%N"), nameStr); presentationStr.replace(QLatin1String("%V"), valueStr); } - else - { - // user defined format string does not contain any valid parameter, using default format "%N = %V" + else { + // user defined format string does not contain any valid parameter, using default format + // "%N = %V" presentationStr = nameStr + QLatin1String(" = ") + valueStr; } @@ -1699,66 +1946,76 @@ QString EditModeConstraintCoinManager::getPresentationString(const Constraint *c return valueStr; } -std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPickedPoint *Point, - const SbVec2s &cursorPos) +std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPickedPoint* Point, + const SbVec2s& cursorPos) { std::set constrIndices; - SoPath *path = Point->getPath(); + SoPath* path = Point->getPath(); // Get the constraints' tail - SoNode *tailFather2 = path->getNode(path->getLength()-3); + SoNode* tailFather2 = path->getNode(path->getLength() - 3); if (tailFather2 != editModeScenegraphNodes.constrGroup) return constrIndices; - SoNode *tail = path->getTail(); - SoNode *tailFather = path->getNode(path->getLength()-2); + SoNode* tail = path->getTail(); + SoNode* tailFather = path->getNode(path->getLength() - 2); - for (int i=0; i < editModeScenegraphNodes.constrGroup->getNumChildren(); ++i) { + for (int i = 0; i < editModeScenegraphNodes.constrGroup->getNumChildren(); ++i) { if (editModeScenegraphNodes.constrGroup->getChild(i) == tailFather) { - SoSeparator *sep = static_cast(tailFather); - if (sep->getNumChildren() > static_cast(ConstraintNodePosition::FirstConstraintIdIndex)) { - SoInfo *constrIds = nullptr; - if (tail == sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex))) { + SoSeparator* sep = static_cast(tailFather); + if (sep->getNumChildren() + > static_cast(ConstraintNodePosition::FirstConstraintIdIndex)) { + SoInfo* constrIds = nullptr; + if (tail + == sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex))) { // First icon was hit - constrIds = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstConstraintIdIndex))); + constrIds = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::FirstConstraintIdIndex))); } else { // Assume second icon was hit - if (static_cast(ConstraintNodePosition::SecondConstraintIdIndex) < sep->getNumChildren()) { - constrIds = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondConstraintIdIndex))); + if (static_cast(ConstraintNodePosition::SecondConstraintIdIndex) + < sep->getNumChildren()) { + constrIds = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondConstraintIdIndex))); } } if (constrIds) { - QString constrIdsStr = QString::fromLatin1(constrIds->string.getValue().getString()); - if (combinedConstrBoxes.count(constrIdsStr) && dynamic_cast(tail)) { + QString constrIdsStr = + QString::fromLatin1(constrIds->string.getValue().getString()); + if (combinedConstrBoxes.count(constrIdsStr) && dynamic_cast(tail)) { // If it's a combined constraint icon // Screen dimensions of the icon - SbVec3s iconSize = getDisplayedSize(static_cast(tail)); + SbVec3s iconSize = getDisplayedSize(static_cast(tail)); // Center of the icon - //SbVec2f iconCoords = viewer->screenCoordsOfPath(path); + // SbVec2f iconCoords = viewer->screenCoordsOfPath(path); - // The use of the Path to get the screen coordinates to get the icon center coordinates - // does not work. + // The use of the Path to get the screen coordinates to get the icon center + // coordinates does not work. // - // This implementation relies on the use of ZoomTranslation to get the absolute and relative - // positions of the icons. + // This implementation relies on the use of ZoomTranslation to get the + // absolute and relative positions of the icons. // - // In the case of second icons (the same constraint has two icons at two different positions), - // the translation vectors have to be added, as the second ZoomTranslation operates on top of - // the first. + // In the case of second icons (the same constraint has two icons at two + // different positions), the translation vectors have to be added, as the + // second ZoomTranslation operates on top of the first. // - // Coordinates are projected on the sketch plane and then to the screen in the interval [0 1] - // Then this result is converted to pixels using the scale factor. + // Coordinates are projected on the sketch plane and then to the screen in + // the interval [0 1] Then this result is converted to pixels using the + // scale factor. SbVec3f absPos; SbVec3f trans; float scaleFactor; - auto translation = static_cast(static_cast(tailFather)->getChild( static_cast(ConstraintNodePosition::FirstTranslationIndex))); + auto translation = static_cast( + static_cast(tailFather) + ->getChild(static_cast( + ConstraintNodePosition::FirstTranslationIndex))); absPos = translation->abPos.getValue(); @@ -1766,10 +2023,15 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi scaleFactor = translation->getScaleFactor(); - if (tail != sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex))) { + if (tail + != sep->getChild( + static_cast(ConstraintNodePosition::FirstIconIndex))) { Base::Console().Log("SecondIcon\n"); - auto translation2 = static_cast(static_cast(tailFather)->getChild( static_cast(ConstraintNodePosition::SecondTranslationIndex))); + auto translation2 = static_cast( + static_cast(tailFather) + ->getChild(static_cast( + ConstraintNodePosition::SecondTranslationIndex))); absPos += translation2->abPos.getValue(); @@ -1778,33 +2040,43 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi scaleFactor = translation2->getScaleFactor(); } - // Only the translation is scaled because this is how SoZoomTranslation works - SbVec3f constrPos = absPos + scaleFactor*trans; + // Only the translation is scaled because this is how SoZoomTranslation + // works + SbVec3f constrPos = absPos + scaleFactor * trans; - SbVec2f iconCoords = ViewProviderSketchCoinAttorney::getScreenCoordinates(viewProvider, SbVec2f(constrPos[0],constrPos[1])); + SbVec2f iconCoords = ViewProviderSketchCoinAttorney::getScreenCoordinates( + viewProvider, SbVec2f(constrPos[0], constrPos[1])); - // cursorPos is SbVec2s in screen coordinates coming from SoEvent in mousemove + // cursorPos is SbVec2s in screen coordinates coming from SoEvent in + // mousemove // // Coordinates of the mouse cursor on the icon, origin at top-left for Qt // but bottom-left for OIV. // The coordinates are needed in Qt format, i.e. from top to bottom. - int iconX = cursorPos[0] - iconCoords[0] + iconSize[0]/2, - iconY = cursorPos[1] - iconCoords[1] + iconSize[1]/2; + int iconX = cursorPos[0] - iconCoords[0] + iconSize[0] / 2, + iconY = cursorPos[1] - iconCoords[1] + iconSize[1] / 2; iconY = iconSize[1] - iconY; - for (ConstrIconBBVec::iterator b = combinedConstrBoxes[constrIdsStr].begin(); - b != combinedConstrBoxes[constrIdsStr].end(); ++b) { + for (ConstrIconBBVec::iterator b = + combinedConstrBoxes[constrIdsStr].begin(); + b != combinedConstrBoxes[constrIdsStr].end(); + ++b) { #ifdef FC_DEBUG - // Useful code to debug coordinates and bounding boxes that does not need to be compiled in for - // any debug operations. + // Useful code to debug coordinates and bounding boxes that does not + // need to be compiled in for any debug operations. - /*Base::Console().Log("Abs(%f,%f),Trans(%f,%f),Coords(%d,%d),iCoords(%f,%f),icon(%d,%d),isize(%d,%d),boundingbox([%d,%d],[%d,%d])\n", absPos[0],absPos[1],trans[0], trans[1], cursorPos[0], cursorPos[1], iconCoords[0], iconCoords[1], iconX, iconY, iconSize[0], iconSize[1], b->first.topLeft().x(),b->first.topLeft().y(),b->first.bottomRight().x(),b->first.bottomRight().y());*/ + /*Base::Console().Log("Abs(%f,%f),Trans(%f,%f),Coords(%d,%d),iCoords(%f,%f),icon(%d,%d),isize(%d,%d),boundingbox([%d,%d],[%d,%d])\n", + * absPos[0],absPos[1],trans[0], trans[1], cursorPos[0], cursorPos[1], + * iconCoords[0], iconCoords[1], iconX, iconY, iconSize[0], iconSize[1], + * b->first.topLeft().x(),b->first.topLeft().y(),b->first.bottomRight().x(),b->first.bottomRight().y());*/ #endif if (b->first.contains(iconX, iconY)) { // We've found a bounding box that contains the mouse pointer! - for (std::set::iterator k = b->second.begin(); k != b->second.end(); ++k) { + for (std::set::iterator k = b->second.begin(); + k != b->second.end(); + ++k) { constrIndices.insert(*k); } } @@ -1816,7 +2088,6 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi while (!constrIdStrings.empty()) { auto constraintid = constrIdStrings.takeAt(0).toInt(); constrIndices.insert(constraintid); - } } } @@ -1833,15 +2104,15 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi return constrIndices; } -SbVec3s EditModeConstraintCoinManager::getDisplayedSize(const SoImage *iconPtr) const +SbVec3s EditModeConstraintCoinManager::getDisplayedSize(const SoImage* iconPtr) const { #if (COIN_MAJOR_VERSION >= 3) SbVec3s iconSize = iconPtr->image.getValue().getSize(); #else SbVec2s size; int nc; - const unsigned char * bytes = iconPtr->image.getValue(size, nc); - SbImage img (bytes, size, nc); + const unsigned char* bytes = iconPtr->image.getValue(size, nc); + SbImage img(bytes, size, nc); SbVec3s iconSize = img.getSize(); #endif if (iconPtr->width.getValue() != -1) @@ -1859,13 +2130,15 @@ void EditModeConstraintCoinManager::drawConstraintIcons() drawConstraintIcons(geolistfacade); } -void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade & geolistfacade) +void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade& geolistfacade) { - const std::vector &constraints = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); + const std::vector& constraints = + ViewProviderSketchCoinAttorney::getConstraints(viewProvider); std::vector iconQueue; - int maxNumberOfConstraints = std::min(editModeScenegraphNodes.constrGroup->getNumChildren(), static_cast(constraints.size())); + int maxNumberOfConstraints = std::min(editModeScenegraphNodes.constrGroup->getNumChildren(), + static_cast(constraints.size())); for (int constrId = 0; constrId < maxNumberOfConstraints; ++constrId) { Sketcher::Constraint* constraint = constraints[constrId]; @@ -1880,65 +2153,68 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade & ge if (constraint->Type != vConstrType[constrId]) break; - switch(constraint->Type) { + switch (constraint->Type) { - case Tangent: - { // second icon is available only for colinear line segments - const Part::Geometry *geo1 = geolistfacade.getGeometryFromGeoId(constraint->First); - const Part::Geometry *geo2 = geolistfacade.getGeometryFromGeoId(constraint->Second); - if (geo1 && geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && - geo2 && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + case Tangent: {// second icon is available only for colinear line segments + const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId(constraint->First); + const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId(constraint->Second); + if (geo1 && geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2 + && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { multipleIcons = true; } - } - break; - case Horizontal: - case Vertical: - { // second icon is available only for point alignment - if (constraint->Second != GeoEnum::GeoUndef && - constraint->FirstPos != Sketcher::PointPos::none && - constraint->SecondPos != Sketcher::PointPos::none) { + } break; + case Horizontal: + case Vertical: {// second icon is available only for point alignment + if (constraint->Second != GeoEnum::GeoUndef + && constraint->FirstPos != Sketcher::PointPos::none + && constraint->SecondPos != Sketcher::PointPos::none) { multipleIcons = true; } - } - break; - case Parallel: - multipleIcons = true; - break; - case Perpendicular: - // second icon is available only when there is no common point - if (constraint->FirstPos == Sketcher::PointPos::none && constraint->Third == GeoEnum::GeoUndef) + } break; + case Parallel: multipleIcons = true; - break; - case Equal: - multipleIcons = true; - break; - default: - break; + break; + case Perpendicular: + // second icon is available only when there is no common point + if (constraint->FirstPos == Sketcher::PointPos::none + && constraint->Third == GeoEnum::GeoUndef) + multipleIcons = true; + break; + case Equal: + multipleIcons = true; + break; + default: + break; } // Double-check that we can safely access the Inventor nodes if (constrId >= editModeScenegraphNodes.constrGroup->getNumChildren()) { - Base::Console().DeveloperWarning("EditModeConstraintManager", "Can't update constraint icons because view is not in sync with sketch\n"); + Base::Console().DeveloperWarning( + "EditModeConstraintManager", + "Can't update constraint icons because view is not in sync with sketch\n"); break; } // Find the Constraint Icon SoImage Node - SoSeparator *sep = static_cast(editModeScenegraphNodes.constrGroup->getChild(constrId)); + SoSeparator* sep = + static_cast(editModeScenegraphNodes.constrGroup->getChild(constrId)); int numChildren = sep->getNumChildren(); SbVec3f absPos; // Somewhat hacky - we use SoZoomTranslations for most types of icon, // but symmetry icons use SoTranslations... - SoTranslation *translationPtr = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); + SoTranslation* translationPtr = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex))); - if (dynamic_cast(translationPtr)) - absPos = static_cast(translationPtr)->abPos.getValue(); + if (dynamic_cast(translationPtr)) + absPos = static_cast(translationPtr)->abPos.getValue(); else absPos = translationPtr->translation.getValue(); - SoImage *coinIconPtr = dynamic_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex))); - SoInfo *infoPtr = static_cast(sep->getChild(static_cast(ConstraintNodePosition::FirstConstraintIdIndex))); + SoImage* coinIconPtr = dynamic_cast( + sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex))); + SoInfo* infoPtr = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::FirstConstraintIdIndex))); constrIconQueueItem thisIcon; thisIcon.type = icoType; @@ -1946,16 +2222,20 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade & ge thisIcon.position = absPos; thisIcon.destination = coinIconPtr; thisIcon.infoPtr = infoPtr; - thisIcon.visible = constraint->isInVirtualSpace == ViewProviderSketchCoinAttorney::isShownVirtualSpace(viewProvider); + thisIcon.visible = constraint->isInVirtualSpace + == ViewProviderSketchCoinAttorney::isShownVirtualSpace(viewProvider); - if (constraint->Type==Symmetric) { - Base::Vector3d startingpoint = geolistfacade.getPoint(constraint->First, constraint->FirstPos); - Base::Vector3d endpoint = geolistfacade.getPoint(constraint->Second, constraint->SecondPos); + if (constraint->Type == Symmetric) { + Base::Vector3d startingpoint = + geolistfacade.getPoint(constraint->First, constraint->FirstPos); + Base::Vector3d endpoint = + geolistfacade.getPoint(constraint->Second, constraint->SecondPos); - SbVec3f pos0(startingpoint.x,startingpoint.y,startingpoint.z); - SbVec3f pos1(endpoint.x,endpoint.y,endpoint.z); + SbVec3f pos0(startingpoint.x, startingpoint.y, startingpoint.z); + SbVec3f pos1(endpoint.x, endpoint.y, endpoint.z); - thisIcon.iconRotation = ViewProviderSketchCoinAttorney::getRotation(viewProvider, pos0, pos1); + thisIcon.iconRotation = + ViewProviderSketchCoinAttorney::getRotation(viewProvider, pos0, pos1); } else { thisIcon.iconRotation = 0; @@ -1973,14 +2253,18 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade & ge // // See note ~30 lines up. if (numChildren > static_cast(ConstraintNodePosition::SecondConstraintIdIndex)) { - translationPtr = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondTranslationIndex))); - if (dynamic_cast(translationPtr)) - thisIcon.position += static_cast(translationPtr)->abPos.getValue(); + translationPtr = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondTranslationIndex))); + if (dynamic_cast(translationPtr)) + thisIcon.position += + static_cast(translationPtr)->abPos.getValue(); else thisIcon.position += translationPtr->translation.getValue(); - thisIcon.destination = dynamic_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondIconIndex))); - thisIcon.infoPtr = static_cast(sep->getChild(static_cast(ConstraintNodePosition::SecondConstraintIdIndex))); + thisIcon.destination = dynamic_cast( + sep->getChild(static_cast(ConstraintNodePosition::SecondIconIndex))); + thisIcon.infoPtr = static_cast(sep->getChild( + static_cast(ConstraintNodePosition::SecondConstraintIdIndex))); } } else { @@ -2004,7 +2288,7 @@ void EditModeConstraintCoinManager::combineConstraintIcons(IconQueue iconQueue) // There's room for optimisation here; we could reuse the combined icons... combinedConstrBoxes.clear(); - while(!iconQueue.empty()) { + while (!iconQueue.empty()) { // A group starts with an item popped off the back of our initial queue IconQueue thisGroup; thisGroup.push_back(iconQueue.back()); @@ -2013,19 +2297,20 @@ void EditModeConstraintCoinManager::combineConstraintIcons(IconQueue iconQueue) // we group only icons not being Symmetry icons, because we want those on the line // and only icons that are visible - if (init.type != QString::fromLatin1("Constraint_Symmetric") && init.visible){ + if (init.type != QString::fromLatin1("Constraint_Symmetric") && init.visible) { IconQueue::iterator i = iconQueue.begin(); - while(i != iconQueue.end()) { + while (i != iconQueue.end()) { if ((*i).visible) { bool addedToGroup = false; - for(IconQueue::iterator j = thisGroup.begin(); - j != thisGroup.end(); ++j) { - float distSquared = pow(i->position[0]-j->position[0],2) + pow(i->position[1]-j->position[1],2); - if (distSquared <= maxDistSquared && (*i).type != QString::fromLatin1("Constraint_Symmetric")) { + for (IconQueue::iterator j = thisGroup.begin(); j != thisGroup.end(); ++j) { + float distSquared = pow(i->position[0] - j->position[0], 2) + + pow(i->position[1] - j->position[1], 2); + if (distSquared <= maxDistSquared + && (*i).type != QString::fromLatin1("Constraint_Symmetric")) { // Found an icon in iconQueue that's close enough to // a member of thisGroup, so move it into thisGroup thisGroup.push_back(*i); @@ -2043,13 +2328,13 @@ void EditModeConstraintCoinManager::combineConstraintIcons(IconQueue iconQueue) // Start looking through the iconQueue again, in case // we have an icon that's now close enough to thisGroup i = iconQueue.begin(); - } else + } + else ++i; } - else // if !visible we skip it - i++; + else// if !visible we skip it + i++; } - } if (thisGroup.size() == 1) { @@ -2063,13 +2348,13 @@ void EditModeConstraintCoinManager::combineConstraintIcons(IconQueue iconQueue) void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueue) { - for(IconQueue::iterator i = iconQueue.begin(); i != iconQueue.end(); ++i) { + for (IconQueue::iterator i = iconQueue.begin(); i != iconQueue.end(); ++i) { clearCoinImage(i->destination); } QImage compositeIcon; - SoImage *thisDest = iconQueue[0].destination; - SoInfo *thisInfo = iconQueue[0].infoPtr; + SoImage* thisDest = iconQueue[0].destination; + SoInfo* thisInfo = iconQueue[0].infoPtr; // Tracks all constraint IDs that are combined into this icon QString idString; @@ -2084,7 +2369,7 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu double iconRotation; ConstrIconBBVec boundingBoxes; - while(!iconQueue.empty()) { + while (!iconQueue.empty()) { IconQueue::iterator i = iconQueue.begin(); labels.clear(); @@ -2097,7 +2382,7 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu iconColor = constrColor(i->constraintId); labelColors.clear(); labelColors.append(iconColor); - iconRotation= i->iconRotation; + iconRotation = i->iconRotation; maxColorPriority = constrColorPriority(i->constraintId); @@ -2106,7 +2391,7 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu idString.append(QString::number(i->constraintId)); i = iconQueue.erase(i); - while(i != iconQueue.end()) { + while (i != iconQueue.end()) { if (i->type != thisType) { ++i; continue; @@ -2118,11 +2403,10 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu if (constrColorPriority(i->constraintId) > maxColorPriority) { maxColorPriority = constrColorPriority(i->constraintId); - iconColor= constrColor(i->constraintId); + iconColor = constrColor(i->constraintId); } - idString.append(QString::fromLatin1(",") + - QString::number(i->constraintId)); + idString.append(QString::fromLatin1(",") + QString::number(i->constraintId)); i = iconQueue.erase(i); } @@ -2140,7 +2424,8 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu iconRotation, &boundingBoxesVec, &lastVPad); - } else { + } + else { int thisVPad; QImage partialIcon = renderConstrIcon(thisType, iconColor, @@ -2160,11 +2445,10 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu // to vary depending on font size too... oldHeight -= std::max(lastVPad - 3, 0); - compositeIcon = compositeIcon.copy(0, 0, - std::max(partialIcon.width(), - compositeIcon.width()), - partialIcon.height() + - compositeIcon.height()); + compositeIcon = compositeIcon.copy(0, + 0, + std::max(partialIcon.width(), compositeIcon.width()), + partialIcon.height() + compositeIcon.height()); QPainter qp(&compositeIcon); qp.drawImage(0, oldHeight, partialIcon); @@ -2175,22 +2459,22 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu // Add bounding boxes for the icon we just rendered to boundingBoxes std::vector::iterator id = ids.begin(); std::set nextIds; - for(std::vector::iterator bb = boundingBoxesVec.begin(); - bb != boundingBoxesVec.end(); ++bb) { + for (std::vector::iterator bb = boundingBoxesVec.begin(); + bb != boundingBoxesVec.end(); + ++bb) { nextIds.clear(); if (bb == boundingBoxesVec.begin()) { // The first bounding box is for the icon at left, so assign // all IDs for that type of constraint to the icon. - for(std::vector::iterator j = ids.begin(); j != ids.end(); ++j) + for (std::vector::iterator j = ids.begin(); j != ids.end(); ++j) nextIds.insert(*j); } else { nextIds.insert(*(id++)); } - ConstrIconBB newBB(bb->adjusted(0, oldHeight, 0, oldHeight), - nextIds); + ConstrIconBB newBB(bb->adjusted(0, oldHeight, 0, oldHeight), nextIds); boundingBoxes.push_back(newBB); } @@ -2204,23 +2488,25 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu /// Note: labels, labelColors, and boundingBoxes are all /// assumed to be the same length. -QImage EditModeConstraintCoinManager::renderConstrIcon(const QString &type, - const QColor &iconColor, - const QStringList &labels, - const QList &labelColors, - double iconRotation, - std::vector *boundingBoxes, - int *vPad) +QImage EditModeConstraintCoinManager::renderConstrIcon(const QString& type, const QColor& iconColor, + const QStringList& labels, + const QList& labelColors, + double iconRotation, + std::vector* boundingBoxes, int* vPad) { // Constants to help create constraint icons QString joinStr = QString::fromLatin1(", "); QPixmap pxMap; std::stringstream constraintName; - constraintName << type.toLatin1().data() << drawingParameters.constraintIconSize; // allow resizing by embedding size - if (! Gui::BitmapFactory().findPixmapInCache(constraintName.str().c_str(), pxMap)) { - pxMap = Gui::BitmapFactory().pixmapFromSvg(type.toLatin1().data(),QSizeF(drawingParameters.constraintIconSize, drawingParameters.constraintIconSize)); - Gui::BitmapFactory().addPixmapToCache(constraintName.str().c_str(), pxMap); // Cache for speed, avoiding pixmapFromSvg + constraintName << type.toLatin1().data() + << drawingParameters.constraintIconSize;// allow resizing by embedding size + if (!Gui::BitmapFactory().findPixmapInCache(constraintName.str().c_str(), pxMap)) { + pxMap = Gui::BitmapFactory().pixmapFromSvg( + type.toLatin1().data(), + QSizeF(drawingParameters.constraintIconSize, drawingParameters.constraintIconSize)); + Gui::BitmapFactory().addPixmapToCache(constraintName.str().c_str(), + pxMap);// Cache for speed, avoiding pixmapFromSvg } QImage icon = pxMap.toImage(); @@ -2240,8 +2526,7 @@ QImage EditModeConstraintCoinManager::renderConstrIcon(const QString &type, rotation.rotate(iconRotation); QImage roticon = icon.transformed(rotation); - QImage image = roticon.copy(0, 0, roticon.width() + labelWidth, - roticon.height() + pxBelowBase); + QImage image = roticon.copy(0, 0, roticon.width() + labelWidth, roticon.height() + pxBelowBase); // Make a bounding box for the icon if (boundingBoxes) @@ -2259,18 +2544,18 @@ QImage EditModeConstraintCoinManager::renderConstrIcon(const QString &type, int cursorOffset = 0; - //In Python: "for label, color in zip(labels, labelColors):" + // In Python: "for label, color in zip(labels, labelColors):" QStringList::const_iterator labelItr; QString labelStr; QList::const_iterator colorItr; QRect labelBB; - for(labelItr = labels.begin(), colorItr = labelColors.begin(); - labelItr != labels.end() && colorItr != labelColors.end(); - ++labelItr, ++colorItr) { + for (labelItr = labels.begin(), colorItr = labelColors.begin(); + labelItr != labels.end() && colorItr != labelColors.end(); + ++labelItr, ++colorItr) { qp.setPen(*colorItr); - if (labelItr + 1 == labels.end()) // if this is the last label + if (labelItr + 1 == labels.end())// if this is the last label labelStr = *labelItr; else labelStr = *labelItr + joinStr; @@ -2295,21 +2580,18 @@ QImage EditModeConstraintCoinManager::renderConstrIcon(const QString &type, return image; } -void EditModeConstraintCoinManager::drawTypicalConstraintIcon(const constrIconQueueItem &i) +void EditModeConstraintCoinManager::drawTypicalConstraintIcon(const constrIconQueueItem& i) { QColor color = constrColor(i.constraintId); - QImage image = renderConstrIcon(i.type, - color, - QStringList(i.label), - QList() << color, - i.iconRotation); + QImage image = renderConstrIcon( + i.type, color, QStringList(i.label), QList() << color, i.iconRotation); i.infoPtr->string.setValue(QString::number(i.constraintId).toLatin1().data()); sendConstraintIconToCoin(image, i.destination); } -QString EditModeConstraintCoinManager::iconTypeFromConstraint(Constraint *constraint) +QString EditModeConstraintCoinManager::iconTypeFromConstraint(Constraint* constraint) { /*! TODO: Consider pushing this functionality up into Constraint * @@ -2317,33 +2599,34 @@ QString EditModeConstraintCoinManager::iconTypeFromConstraint(Constraint *constr does not belong in App, but in Gui. Rather consider refactoring it in a separate class dealing with visualisation of constraints.*/ - switch(constraint->Type) { - case Horizontal: - return QString::fromLatin1("Constraint_Horizontal"); - case Vertical: - return QString::fromLatin1("Constraint_Vertical"); - case PointOnObject: - return QString::fromLatin1("Constraint_PointOnObject"); - case Tangent: - return QString::fromLatin1("Constraint_Tangent"); - case Parallel: - return QString::fromLatin1("Constraint_Parallel"); - case Perpendicular: - return QString::fromLatin1("Constraint_Perpendicular"); - case Equal: - return QString::fromLatin1("Constraint_EqualLength"); - case Symmetric: - return QString::fromLatin1("Constraint_Symmetric"); - case SnellsLaw: - return QString::fromLatin1("Constraint_SnellsLaw"); - case Block: - return QString::fromLatin1("Constraint_Block"); - default: - return QString(); + switch (constraint->Type) { + case Horizontal: + return QString::fromLatin1("Constraint_Horizontal"); + case Vertical: + return QString::fromLatin1("Constraint_Vertical"); + case PointOnObject: + return QString::fromLatin1("Constraint_PointOnObject"); + case Tangent: + return QString::fromLatin1("Constraint_Tangent"); + case Parallel: + return QString::fromLatin1("Constraint_Parallel"); + case Perpendicular: + return QString::fromLatin1("Constraint_Perpendicular"); + case Equal: + return QString::fromLatin1("Constraint_EqualLength"); + case Symmetric: + return QString::fromLatin1("Constraint_Symmetric"); + case SnellsLaw: + return QString::fromLatin1("Constraint_SnellsLaw"); + case Block: + return QString::fromLatin1("Constraint_Block"); + default: + return QString(); } } -void EditModeConstraintCoinManager::sendConstraintIconToCoin(const QImage &icon, SoImage *soImagePtr) +void EditModeConstraintCoinManager::sendConstraintIconToCoin(const QImage& icon, + SoImage* soImagePtr) { SoSFImage icondata = SoSFImage(); @@ -2354,12 +2637,12 @@ void EditModeConstraintCoinManager::sendConstraintIconToCoin(const QImage &icon, int four = 4; soImagePtr->image.setValue(iconSize, 4, icondata.getValue(iconSize, four)); - //Set Image Alignment to Center + // Set Image Alignment to Center soImagePtr->vertAlignment = SoImage::HALF; soImagePtr->horAlignment = SoImage::CENTER; } -void EditModeConstraintCoinManager::clearCoinImage(SoImage *soImagePtr) +void EditModeConstraintCoinManager::clearCoinImage(SoImage* soImagePtr) { soImagePtr->setToDefaults(); } @@ -2367,14 +2650,13 @@ void EditModeConstraintCoinManager::clearCoinImage(SoImage *soImagePtr) QColor EditModeConstraintCoinManager::constrColor(int constraintId) { auto toQColor = [](auto sbcolor) -> QColor { - return QColor( (int)(sbcolor[0] * 255.0f), - (int)(sbcolor[1] * 255.0f), - (int)(sbcolor[2] * 255.0f)); + return QColor( + (int)(sbcolor[0] * 255.0f), (int)(sbcolor[1] * 255.0f), (int)(sbcolor[2] * 255.0f)); }; const auto constraints = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); - if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider,constraintId)) + if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider, constraintId)) return toQColor(drawingParameters.PreselectColor); else if (ViewProviderSketchCoinAttorney::isConstraintSelected(viewProvider, constraintId)) return toQColor(drawingParameters.SelectColor); @@ -2384,12 +2666,11 @@ QColor EditModeConstraintCoinManager::constrColor(int constraintId) return toQColor(drawingParameters.NonDrivingConstrDimColor); else return toQColor(drawingParameters.ConstrIcoColor); - } int EditModeConstraintCoinManager::constrColorPriority(int constraintId) { - if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider,constraintId)) + if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider, constraintId)) return 3; else if (ViewProviderSketchCoinAttorney::isConstraintSelected(viewProvider, constraintId)) return 2; @@ -2397,36 +2678,38 @@ int EditModeConstraintCoinManager::constrColorPriority(int constraintId) return 1; } -SoSeparator * EditModeConstraintCoinManager::getConstraintIdSeparator(int i) +SoSeparator* EditModeConstraintCoinManager::getConstraintIdSeparator(int i) { - return dynamic_cast(editModeScenegraphNodes.constrGroup->getChild(i)); + return dynamic_cast(editModeScenegraphNodes.constrGroup->getChild(i)); } void EditModeConstraintCoinManager::createEditModeInventorNodes() { // group node for the Constraint visual +++++++++++++++++++++++++++++++++++ - SoMaterialBinding *MtlBind = new SoMaterialBinding; + SoMaterialBinding* MtlBind = new SoMaterialBinding; MtlBind->setName("ConstraintMaterialBinding"); - MtlBind->value = SoMaterialBinding::OVERALL ; + MtlBind->value = SoMaterialBinding::OVERALL; editModeScenegraphNodes.EditRoot->addChild(MtlBind); // use small line width for the Constraints editModeScenegraphNodes.ConstraintDrawStyle = new SoDrawStyle; editModeScenegraphNodes.ConstraintDrawStyle->setName("ConstraintDrawStyle"); - editModeScenegraphNodes.ConstraintDrawStyle->lineWidth = 1 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.ConstraintDrawStyle->lineWidth = + 1 * drawingParameters.pixelScalingFactor; editModeScenegraphNodes.EditRoot->addChild(editModeScenegraphNodes.ConstraintDrawStyle); // add the group where all the constraints has its SoSeparator - editModeScenegraphNodes.constrGrpSelect = new SoPickStyle(); // used to toggle constraints selectability + editModeScenegraphNodes.constrGrpSelect = + new SoPickStyle();// used to toggle constraints selectability editModeScenegraphNodes.constrGrpSelect->style.setValue(SoPickStyle::SHAPE); editModeScenegraphNodes.EditRoot->addChild(editModeScenegraphNodes.constrGrpSelect); - setConstraintSelectability(); // Ensure default value; + setConstraintSelectability();// Ensure default value; editModeScenegraphNodes.constrGroup = new SmSwitchboard(); editModeScenegraphNodes.constrGroup->setName("ConstraintGroup"); editModeScenegraphNodes.EditRoot->addChild(editModeScenegraphNodes.constrGroup); - SoPickStyle *ps = new SoPickStyle(); // used to following nodes aren't impacted + SoPickStyle* ps = new SoPickStyle();// used to following nodes aren't impacted ps->style.setValue(SoPickStyle::SHAPE); editModeScenegraphNodes.EditRoot->addChild(ps); } diff --git a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h index e4af4ee127..b4b6e23edc 100644 --- a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h @@ -30,8 +30,8 @@ #include #include -# include -# include +#include +#include #include @@ -43,32 +43,37 @@ class SoRayPickAction; class SoPickedPoint; class SbVec3s; -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; - class Vector2d; +class Vector2d; - class Placement; +class Placement; +}// namespace Base + +namespace Part +{ +class Geometry; } -namespace Part { - class Geometry; -} +namespace Sketcher +{ +class Constraint; +class PropertyConstraintList; +};// namespace Sketcher -namespace Sketcher { - class Constraint; - class PropertyConstraintList; -}; - -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; using GeoList = Sketcher::GeoList; using GeoListFacade = Sketcher::GeoListFacade; -/** @brief Class for managing the Edit mode coin nodes of ViewProviderSketch relating to constraints. +/** @brief Class for managing the Edit mode coin nodes of ViewProviderSketch relating to + * constraints. * @details To be documented. * */ @@ -76,7 +81,8 @@ class SketcherGuiExport EditModeConstraintCoinManager { private: /// Coin Node indices for constraints - enum class ConstraintNodePosition { + enum class ConstraintNodePosition + { MaterialIndex = 0, DatumLabelIndex = 0, FirstTranslationIndex = 1, @@ -86,19 +92,19 @@ private: SecondIconIndex = 5, SecondConstraintIdIndex = 6 }; + public: - explicit EditModeConstraintCoinManager( ViewProviderSketch &vp, - DrawingParameters & drawingParams, - GeometryLayerParameters & geometryLayerParams, - ConstraintParameters & constraintParams, - EditModeScenegraphNodes & editModeScenegraph, - CoinMapping & coinMap); + explicit EditModeConstraintCoinManager(ViewProviderSketch& vp, DrawingParameters& drawingParams, + GeometryLayerParameters& geometryLayerParams, + ConstraintParameters& constraintParams, + EditModeScenegraphNodes& editModeScenegraph, + CoinMapping& coinMap); ~EditModeConstraintCoinManager(); /** @name update coin nodes*/ // geometry list to be used for constraints, which may be a temporal geometry - void processConstraints(const GeoListFacade & geolistfacade); + void processConstraints(const GeoListFacade& geolistfacade); void updateVirtualSpace(); @@ -107,12 +113,12 @@ public: void drawConstraintIcons(); // This specific overload is to use a specific geometry list, which may be a temporal one - void drawConstraintIcons(const GeoListFacade & geolistfacade); + void drawConstraintIcons(const GeoListFacade& geolistfacade); //@} /** @name update coin colors*/ //@{ - void updateConstraintColor(const std::vector & constraints); + void updateConstraintColor(const std::vector& constraints); //@} /** @name coin nodes creation*/ @@ -124,34 +130,33 @@ public: void setConstraintSelectability(bool enabled = true); //@} - std::set detectPreselectionConstr( const SoPickedPoint *Point, - const SbVec2s &cursorPos); + std::set detectPreselectionConstr(const SoPickedPoint* Point, const SbVec2s& cursorPos); - SoSeparator * getConstraintIdSeparator(int i); + SoSeparator* getConstraintIdSeparator(int i); void createEditModeInventorNodes(); private: - void rebuildConstraintNodes(const GeoListFacade & geolistfacade); // with specific geometry + void rebuildConstraintNodes(const GeoListFacade& geolistfacade);// with specific geometry - void rebuildConstraintNodes(const GeoListFacade & geolistfacade, const std::vector constrlist, SbVec3f norm); + void rebuildConstraintNodes(const GeoListFacade& geolistfacade, + const std::vector constrlist, SbVec3f norm); /// finds a free position for placing a constraint icon - Base::Vector3d seekConstraintPosition(const Base::Vector3d &origPos, - const Base::Vector3d &norm, - const Base::Vector3d &dir, float step, - const SoNode *constraint); + Base::Vector3d seekConstraintPosition(const Base::Vector3d& origPos, const Base::Vector3d& norm, + const Base::Vector3d& dir, float step, + const SoNode* constraint); /// Return display string for constraint including hiding units if - //requested. - QString getPresentationString(const Sketcher::Constraint *constraint); + // requested. + QString getPresentationString(const Sketcher::Constraint* constraint); /// Returns the size that Coin should display the indicated image at - SbVec3s getDisplayedSize(const SoImage *) const; + SbVec3s getDisplayedSize(const SoImage*) const; /** @name Protected helpers for drawing constraint icons*/ //@{ - QString iconTypeFromConstraint(Sketcher::Constraint *constraint); + QString iconTypeFromConstraint(Sketcher::Constraint* constraint); /// Returns a QColor object appropriate for constraint with given id /*! In the case of combined icons, the icon color is chosen based on @@ -177,14 +182,15 @@ private: // rendering tree) to a vector of those bounding boxes paired with relevant // constraint IDs. - using ConstrIconBB = std::pair >; + using ConstrIconBB = std::pair>; using ConstrIconBBVec = std::vector; std::map combinedConstrBoxes; /// Internal type used for drawing constraint icons - struct constrIconQueueItem { + struct constrIconQueueItem + { /// Type of constraint the icon represents. Eg: "small/Constraint_PointOnObject_sm" QString type; @@ -199,10 +205,10 @@ private: SbVec3f position; /// Pointer to the SoImage object where the icon should be written - SoImage *destination; + SoImage* destination; /// Pointer to SoInfo object where we store the constraint IDs that the icon refers to - SoInfo *infoPtr; + SoInfo* infoPtr; /// Angle to rotate an icon double iconRotation; @@ -215,48 +221,44 @@ private: void combineConstraintIcons(IconQueue iconQueue); /// Renders an icon for a single constraint and sends it to Coin - void drawTypicalConstraintIcon(const constrIconQueueItem &i); + void drawTypicalConstraintIcon(const constrIconQueueItem& i); /// Combines multiple constraint icons and sends them to Coin void drawMergedConstraintIcons(IconQueue iconQueue); /// Helper for drawMergedConstraintIcons and drawTypicalConstraintIcon - QImage renderConstrIcon(const QString &type, - const QColor &iconColor, - const QStringList &labels, - const QList &labelColors, - double iconRotation, + QImage renderConstrIcon(const QString& type, const QColor& iconColor, const QStringList& labels, + const QList& labelColors, double iconRotation, //! Gets populated with bounding boxes (in icon //! image coordinates) for the icon at left, then //! labels for different constraints. - std::vector *boundingBoxes = nullptr, + std::vector* boundingBoxes = nullptr, //! If not NULL, gets set to the number of pixels //! that the text extends below the icon base. - int *vPad = nullptr); + int* vPad = nullptr); /// Copies a QImage constraint icon into a SoImage* /*! Used by drawTypicalConstraintIcon() and drawMergedConstraintIcons() */ - void sendConstraintIconToCoin(const QImage &icon, SoImage *soImagePtr); + void sendConstraintIconToCoin(const QImage& icon, SoImage* soImagePtr); /// Essentially a version of sendConstraintIconToCoin, with a blank icon - void clearCoinImage(SoImage *soImagePtr); + void clearCoinImage(SoImage* soImagePtr); //@} private: - ViewProviderSketch & viewProvider; + ViewProviderSketch& viewProvider; - DrawingParameters & drawingParameters; - GeometryLayerParameters & geometryLayerParameters; - ConstraintParameters & constraintParameters; + DrawingParameters& drawingParameters; + GeometryLayerParameters& geometryLayerParameters; + ConstraintParameters& constraintParameters; - EditModeScenegraphNodes & editModeScenegraphNodes; + EditModeScenegraphNodes& editModeScenegraphNodes; - CoinMapping & coinMapping; + CoinMapping& coinMapping; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_EditModeConstraintCoinManager_H - +#endif// SKETCHERGUI_EditModeConstraintCoinManager_H diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp index c10857e8c4..46c6d7d20b 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp @@ -25,28 +25,27 @@ #include #include -#include "EditModeGeometryCoinConverter.h" #include "EditModeCoinManagerParameters.h" +#include "EditModeGeometryCoinConverter.h" +#include "Utils.h" #include "ViewProviderSketchCoinAttorney.h" #include "ViewProviderSketchGeometryExtension.h" -#include "Utils.h" using namespace SketcherGui; -EditModeGeometryCoinConverter::EditModeGeometryCoinConverter( ViewProviderSketch & vp, - GeometryLayerNodes & geometrylayernodes, - DrawingParameters & drawingparameters, - GeometryLayerParameters& geometryLayerParams, - CoinMapping & coinMap ): - viewProvider(vp), - geometryLayerNodes(geometrylayernodes), - drawingParameters(drawingparameters), - geometryLayerParameters(geometryLayerParams), - coinMapping(coinMap) +EditModeGeometryCoinConverter::EditModeGeometryCoinConverter( + ViewProviderSketch& vp, GeometryLayerNodes& geometrylayernodes, + DrawingParameters& drawingparameters, GeometryLayerParameters& geometryLayerParams, + CoinMapping& coinMap) + : viewProvider(vp) + , geometryLayerNodes(geometrylayernodes) + , drawingParameters(drawingparameters) + , geometryLayerParameters(geometryLayerParams) + , coinMapping(coinMap) {} -void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade & geolistfacade) +void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geolistfacade) { // measurements @@ -63,7 +62,7 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade & geol pointCounter.clear(); curveCounter.clear(); - for(auto l=0; l 0) // insert the first segment of the curve into the map - coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, - std::forward_as_tuple(geoId, Sketcher::PointPos::none), - std::forward_as_tuple(static_cast(coinMapping.CurvIdToGeoId[coinLayer].size()), coinLayer)); + if (numberCurves > 0)// insert the first segment of the curve into the map + coinMapping.GeoElementId2SetId.emplace( + std::piecewise_construct, + std::forward_as_tuple(geoId, Sketcher::PointPos::none), + std::forward_as_tuple(static_cast(coinMapping.CurvIdToGeoId[coinLayer].size()), + coinLayer)); - for(int i = 0; i < numberCurves; i++) + for (int i = 0; i < numberCurves; i++) coinMapping.CurvIdToGeoId[coinLayer].push_back(geoId); }; - for (size_t i = 0 ; i < geolistfacade.geomlist.size()- 2; i++) { + for (size_t i = 0; i < geolistfacade.geomlist.size() - 2; i++) { const auto GeoId = geolistfacade.getGeoIdFromGeomListIndex(i); const auto geom = geolistfacade.getGeometryFacadeFromGeoId(GeoId); @@ -158,46 +168,53 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade & geol auto coinLayer = geometryLayerParameters.getSafeCoinLayer(layerId); - if (type == Part::GeomPoint::getClassTypeId()) { // add a point - convert< Part::GeomPoint, - EditModeGeometryCoinConverter::PointsMode::InsertSingle, - EditModeGeometryCoinConverter::CurveMode::NoCurve, - EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitude>(geom, GeoId); - setTracking(GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertSingle, 0); + if (type == Part::GeomPoint::getClassTypeId()) {// add a point + convert(geom, GeoId); + setTracking( + GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertSingle, 0); } - else if (type == Part::GeomLineSegment::getClassTypeId()) { // add a line - convert< Part::GeomLineSegment, - EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, - EditModeGeometryCoinConverter::CurveMode::StartEndPointsOnly, - EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitude>(geom, GeoId); - setTracking(GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, 1); + else if (type == Part::GeomLineSegment::getClassTypeId()) {// add a line + convert(geom, GeoId); + setTracking( + GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, 1); } - else if (type.isDerivedFrom(Part::GeomConic::getClassTypeId())) { // add a closed curve conic - convert< Part::GeomConic, - EditModeGeometryCoinConverter::PointsMode::InsertMidOnly, - EditModeGeometryCoinConverter::CurveMode::ClosedCurve, - EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitude>(geom, GeoId); - setTracking(GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertMidOnly, 1); + else if (type.isDerivedFrom(Part::GeomConic::getClassTypeId())) {// add a closed curve conic + convert(geom, GeoId); + setTracking( + GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertMidOnly, 1); } - else if (type.isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) { // add an arc of conic - convert< Part::GeomArcOfConic, - EditModeGeometryCoinConverter::PointsMode::InsertStartEndMid, - EditModeGeometryCoinConverter::CurveMode::OpenCurve, - EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitude>(geom, GeoId); - setTracking(GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertStartEndMid, 1); + else if (type.isDerivedFrom(Part::GeomArcOfConic::getClassTypeId())) {// add an arc of conic + convert(geom, GeoId); + setTracking( + GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertStartEndMid, 1); arcGeoIds.push_back(GeoId); } - else if (type == Part::GeomBSplineCurve::getClassTypeId()) { // add a bspline (a bounded curve that is not a conic) - convert< Part::GeomBSplineCurve, - EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, - EditModeGeometryCoinConverter::CurveMode::OpenCurve, - EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitudeAndBSplineCurvature>(geom, GeoId); - setTracking(GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, 1); + else if (type == Part::GeomBSplineCurve::getClassTypeId()) {// add a bspline (a bounded + // curve that is not a conic) + convert(geom, GeoId); + setTracking( + GeoId, coinLayer, EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, 1); bsplineGeoIds.push_back(GeoId); } } - for(auto l=0 ; l < geometryLayerParameters.getCoinLayerCount() ; l++) { + for (auto l = 0; l < geometryLayerParameters.getCoinLayerCount(); l++) { // Coin Nodes Editing geometryLayerNodes.CurvesCoordinate[l]->point.setNum(Coords[l].size()); @@ -206,23 +223,33 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade & geol geometryLayerNodes.PointsCoordinate[l]->point.setNum(Points[l].size()); geometryLayerNodes.PointsMaterials[l]->diffuseColor.setNum(Points[l].size()); - SbVec3f *verts = geometryLayerNodes.CurvesCoordinate[l]->point.startEditing(); - int32_t *index = geometryLayerNodes.CurveSet[l]->numVertices.startEditing(); - SbVec3f *pverts = geometryLayerNodes.PointsCoordinate[l]->point.startEditing(); + SbVec3f* verts = geometryLayerNodes.CurvesCoordinate[l]->point.startEditing(); + int32_t* index = geometryLayerNodes.CurveSet[l]->numVertices.startEditing(); + SbVec3f* pverts = geometryLayerNodes.PointsCoordinate[l]->point.startEditing(); - int i=0; // setting up the line set - for (std::vector::const_iterator it = Coords[l].begin(); it != Coords[l].end(); ++it,i++) - verts[i].setValue(it->x,it->y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zLowLines); + int i = 0;// setting up the line set + for (std::vector::const_iterator it = Coords[l].begin(); + it != Coords[l].end(); + ++it, i++) + verts[i].setValue(it->x, + it->y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zLowLines); - i=0; // setting up the indexes of the line set - for (std::vector::const_iterator it = Index[l].begin(); it != Index[l].end(); ++it,i++) + i = 0;// setting up the indexes of the line set + for (std::vector::const_iterator it = Index[l].begin(); it != Index[l].end(); + ++it, i++) index[i] = *it; - i=0; // setting up the point set - for (std::vector::const_iterator it = Points[l].begin(); it != Points[l].end(); ++it,i++) - pverts[i].setValue(it->x,it->y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zLowPoints); + i = 0;// setting up the point set + for (std::vector::const_iterator it = Points[l].begin(); + it != Points[l].end(); + ++it, i++) + pverts[i].setValue( + it->x, + it->y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zLowPoints); geometryLayerNodes.CurvesCoordinate[l]->point.finishEditing(); geometryLayerNodes.CurveSet[l]->numVertices.finishEditing(); @@ -230,21 +257,22 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade & geol } } -template < typename GeoType, - EditModeGeometryCoinConverter::PointsMode pointmode, - EditModeGeometryCoinConverter::CurveMode curvemode, - EditModeGeometryCoinConverter::AnalyseMode analysemode > -void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade * geometryfacade, [[maybe_unused]] int geoid) { - auto geo = static_cast(geometryfacade->getGeometry()); +template +void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade* geometryfacade, + [[maybe_unused]] int geoid) +{ + auto geo = static_cast(geometryfacade->getGeometry()); auto layerId = getSafeGeomLayerId(geometryfacade); auto coinLayer = geometryLayerParameters.getSafeCoinLayer(layerId); - auto addPoint = [&dMg = boundingBoxMaxMagnitude] (auto & pushvector, Base::Vector3d point) { - - if constexpr (analysemode == AnalyseMode::BoundingBoxMagnitude || analysemode == AnalyseMode::BoundingBoxMagnitudeAndBSplineCurvature) { - dMg = dMg>std::abs(point.x)?dMg:std::abs(point.x); - dMg = dMg>std::abs(point.y)?dMg:std::abs(point.y); + auto addPoint = [&dMg = boundingBoxMaxMagnitude](auto& pushvector, Base::Vector3d point) { + if constexpr (analysemode == AnalyseMode::BoundingBoxMagnitude + || analysemode == AnalyseMode::BoundingBoxMagnitudeAndBSplineCurvature) { + dMg = dMg > std::abs(point.x) ? dMg : std::abs(point.x); + dMg = dMg > std::abs(point.y) ? dMg : std::abs(point.y); pushvector.push_back(point); } }; @@ -280,32 +308,32 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade * geo double segment = (geo->getLastParameter() - geo->getFirstParameter()) / numSegments; - for (int i=0; i < numSegments; i++) { - Base::Vector3d pnt = geo->value(i*segment); + for (int i = 0; i < numSegments; i++) { + Base::Vector3d pnt = geo->value(i * segment); addPoint(Coords[coinLayer], pnt); } Base::Vector3d pnt = geo->value(0); addPoint(Coords[coinLayer], pnt); - Index[coinLayer].push_back(numSegments+1); + Index[coinLayer].push_back(numSegments + 1); } else if constexpr (curvemode == CurveMode::OpenCurve) { int numSegments = drawingParameters.curvedEdgeCountSegments; if constexpr (std::is_same::value) - numSegments *= (geo->countKnots() - 1); // one less segments than knots + numSegments *= (geo->countKnots() - 1);// one less segments than knots double segment = (geo->getLastParameter() - geo->getFirstParameter()) / numSegments; - for (int i=0; i < numSegments; i++) { - Base::Vector3d pnt = geo->value(geo->getFirstParameter() + i*segment); + for (int i = 0; i < numSegments; i++) { + Base::Vector3d pnt = geo->value(geo->getFirstParameter() + i * segment); addPoint(Coords[coinLayer], pnt); } Base::Vector3d pnt = geo->value(geo->getLastParameter()); - addPoint(Coords[coinLayer], pnt); + addPoint(Coords[coinLayer], pnt); - Index[coinLayer].push_back(numSegments+1); + Index[coinLayer].push_back(numSegments + 1); if constexpr (analysemode == AnalyseMode::BoundingBoxMagnitudeAndBSplineCurvature) { //*************************************************************************************************************** @@ -313,19 +341,20 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade * geo std::vector poles = geo->getPoles(); - Base::Vector3d midp = Base::Vector3d(0,0,0); + Base::Vector3d midp = Base::Vector3d(0, 0, 0); - for (std::vector::iterator it = poles.begin(); it != poles.end(); ++it) { + for (std::vector::iterator it = poles.begin(); it != poles.end(); + ++it) { midp += (*it); } midp /= poles.size(); double firstparam = geo->getFirstParameter(); - double lastparam = geo->getLastParameter(); + double lastparam = geo->getLastParameter(); - const int ndiv = poles.size()>4?poles.size()*16:64; - double step = (lastparam - firstparam ) / (ndiv -1); + const int ndiv = poles.size() > 4 ? poles.size() * 16 : 64; + double step = (lastparam - firstparam) / (ndiv - 1); std::vector paramlist(ndiv); std::vector pointatcurvelist(ndiv); @@ -342,36 +371,36 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade * geo try { curvaturelist[i] = geo->curvatureAt(paramlist[i]); } - catch(Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { // it is "just" a visualisation matter OCC could not calculate the curvature // terminating here would mean that the other shapes would not be drawn. // Solution: Report the issue and set dummy curvature to 0 e.ReportException(); - Base::Console().DeveloperError("EditModeGeometryCoinConverter","Curvature graph for B-Spline with GeoId=%d could not be calculated.\n", geoid); // TODO: Fix identification of curve. + Base::Console().DeveloperError( + "EditModeGeometryCoinConverter", + "Curvature graph for B-Spline with GeoId=%d could not be calculated.\n", + geoid);// TODO: Fix identification of curve. curvaturelist[i] = 0; } if (curvaturelist[i] > maxcurv) maxcurv = curvaturelist[i]; - double tempf = ( pointatcurvelist[i] - midp ).Length(); + double tempf = (pointatcurvelist[i] - midp).Length(); if (tempf > maxdisttocenterofmass) maxdisttocenterofmass = tempf; - } double temprepscale = 0; if (maxcurv > 0) - temprepscale = (0.5 * maxdisttocenterofmass) / maxcurv; // just a factor to make a comb reasonably visible + temprepscale = (0.5 * maxdisttocenterofmass) + / maxcurv;// just a factor to make a comb reasonably visible if (temprepscale > combrepscale) combrepscale = temprepscale; - } - } - } float EditModeGeometryCoinConverter::getBoundingBoxMaxMagnitude() diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h index 06ee5e49d2..aee7eed6c4 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h @@ -28,28 +28,32 @@ #include "ViewProviderSketch.h" -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; - class Vector2d; +class Vector2d; +}// namespace Base + +namespace Sketcher +{ +enum ConstraintType : int; +enum class PointPos : int; +}// namespace Sketcher + +namespace Part +{ +class Geometry; } -namespace Sketcher { - enum ConstraintType : int; - enum class PointPos : int; -} - -namespace Part { - class Geometry; -} - -namespace SketcherGui { - class ViewProviderSketch; - struct GeometryLayerNodes; - struct DrawingParameters; - class GeometryLayerParameters; - struct CoinMapping; +namespace SketcherGui +{ +class ViewProviderSketch; +struct GeometryLayerNodes; +struct DrawingParameters; +class GeometryLayerParameters; +struct CoinMapping; /** @brief Class for creating the Geometry layer into coin nodes * @details @@ -61,31 +65,38 @@ namespace SketcherGui { * Interface: * A single entry point convert(), performing the following flow: * - * [Geometry] => Analysis => construct drawing elements => Create mappings GeoId coin => populate coin nodes + * [Geometry] => Analysis => construct drawing elements => Create mappings GeoId coin => populate + * coin nodes * - * Analysis performs analysis such as maximum boundingbox magnitude of all geometries and maximum curvature of BSplines + * Analysis performs analysis such as maximum boundingbox magnitude of all geometries and maximum + * curvature of BSplines */ -class EditModeGeometryCoinConverter { -// These internal private classes are used to parametrize the conversion of geometry into points and line sets (see template method convert) +class EditModeGeometryCoinConverter +{ + // These internal private classes are used to parametrize the conversion of geometry into points + // and line sets (see template method convert) private: - enum class PointsMode { + enum class PointsMode + { InsertSingle, InsertStartEnd, InsertStartEndMid, InsertMidOnly - }; + }; - enum class CurveMode { + enum class CurveMode + { NoCurve, StartEndPointsOnly, ClosedCurve, OpenCurve - }; + }; - enum class AnalyseMode { + enum class AnalyseMode + { BoundingBoxMagnitude, BoundingBoxMagnitudeAndBSplineCurvature - }; + }; public: /** Constructs an GeometryCoinConverter responsible for @@ -98,50 +109,55 @@ public: * * @param drawingparameters: Parameters for drawing the overlay information */ - EditModeGeometryCoinConverter( ViewProviderSketch & vp, - GeometryLayerNodes & geometrylayernodes, - DrawingParameters & drawingparameters, - GeometryLayerParameters& geometryLayerParams, - CoinMapping & coinMap ); + EditModeGeometryCoinConverter(ViewProviderSketch& vp, GeometryLayerNodes& geometrylayernodes, + DrawingParameters& drawingparameters, + GeometryLayerParameters& geometryLayerParams, + CoinMapping& coinMap); /** - * converts the geometry defined by GeometryLayer into the coin nodes. - * - * @param geometry: the geometry to be processed - */ - void convert(const Sketcher::GeoListFacade & geolistfacade); + * converts the geometry defined by GeometryLayer into the coin nodes. + * + * @param geometry: the geometry to be processed + */ + void convert(const Sketcher::GeoListFacade& geolistfacade); /** - * returns the maximum of the vertical and horizontal magnitudes of the - * coordinates of the points and lines added to coin by this layer (local responsibility). - */ + * returns the maximum of the vertical and horizontal magnitudes of the + * coordinates of the points and lines added to coin by this layer (local responsibility). + */ float getBoundingBoxMaxMagnitude(); /** - * returns the Comb representation scale that should be used to represent - * the B-Splines of this layer (local responsibility). - */ + * returns the Comb representation scale that should be used to represent + * the B-Splines of this layer (local responsibility). + */ double getCombRepresentationScale(); /** - * returns the GeoIds of BSpline geometries - */ - auto getBSplineGeoIds(){ return std::move(bsplineGeoIds);} + * returns the GeoIds of BSpline geometries + */ + auto getBSplineGeoIds() + { + return std::move(bsplineGeoIds); + } /** - * returns the GeoIds of Arc geometries - */ - auto getArcGeoIds(){ return std::move(arcGeoIds);} + * returns the GeoIds of Arc geometries + */ + auto getArcGeoIds() + { + return std::move(arcGeoIds); + } private: - template < typename GeoType, PointsMode pointmode, CurveMode curvemode, AnalyseMode analysemode > - void convert(const Sketcher::GeometryFacade * geometryfacade, [[maybe_unused]] int geoId); + template + void convert(const Sketcher::GeometryFacade* geometryfacade, [[maybe_unused]] int geoId); private: /// Reference to ViewProviderSketch in order to access the public and the Attorney Interface - ViewProviderSketch & viewProvider; + ViewProviderSketch& viewProvider; - GeometryLayerNodes & geometryLayerNodes; + GeometryLayerNodes& geometryLayerNodes; std::vector> Coords; std::vector> Points; @@ -155,22 +171,21 @@ private: int vertexCounter = 0; // Parameters - DrawingParameters & drawingParameters; + DrawingParameters& drawingParameters; GeometryLayerParameters& geometryLayerParameters; // Mappings coin geoId - CoinMapping & coinMapping; + CoinMapping& coinMapping; // measurements float boundingBoxMaxMagnitude = 100; - double combrepscale = 0; // the repscale that would correspond to this comb based only on this calculation. + double combrepscale = + 0;// the repscale that would correspond to this comb based only on this calculation. std::vector bsplineGeoIds; std::vector arcGeoIds; - }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_GeometryCoinConverter_H - +#endif// SKETCHERGUI_GeometryCoinConverter_H diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp index 1cbf51af34..88ccb53866 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp @@ -22,16 +22,16 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include -# include -# include -# include -# include -# include -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#include +#include +#include +#include +#include +#endif// #ifndef _PreComp_ #include #include @@ -41,8 +41,8 @@ #include #include -#include "EditModeGeometryCoinManager.h" #include "EditModeGeometryCoinConverter.h" +#include "EditModeGeometryCoinManager.h" #include "ViewProviderSketchCoinAttorney.h" @@ -51,70 +51,69 @@ using namespace Sketcher; //**************************** EditModeGeometryCoinManager class ****************************** -EditModeGeometryCoinManager::EditModeGeometryCoinManager( ViewProviderSketch &vp, - DrawingParameters & drawingParams, - GeometryLayerParameters & geometryLayerParams, - AnalysisResults & analysisResultStruct, - EditModeScenegraphNodes & editModeScenegraph, - CoinMapping & coinMap): - viewProvider(vp), - drawingParameters(drawingParams), - geometryLayerParameters(geometryLayerParams), - analysisResults(analysisResultStruct), - editModeScenegraphNodes(editModeScenegraph), - coinMapping(coinMap) +EditModeGeometryCoinManager::EditModeGeometryCoinManager( + ViewProviderSketch& vp, DrawingParameters& drawingParams, + GeometryLayerParameters& geometryLayerParams, AnalysisResults& analysisResultStruct, + EditModeScenegraphNodes& editModeScenegraph, CoinMapping& coinMap) + : viewProvider(vp) + , drawingParameters(drawingParams) + , geometryLayerParameters(geometryLayerParams) + , analysisResults(analysisResultStruct) + , editModeScenegraphNodes(editModeScenegraph) + , coinMapping(coinMap) {} EditModeGeometryCoinManager::~EditModeGeometryCoinManager() {} -void EditModeGeometryCoinManager::processGeometry(const GeoListFacade & geolistfacade) +void EditModeGeometryCoinManager::processGeometry(const GeoListFacade& geolistfacade) { // enable all layers editModeScenegraphNodes.PointsGroup->enable.setNum(geometryLayerParameters.getCoinLayerCount()); editModeScenegraphNodes.CurvesGroup->enable.setNum(geometryLayerParameters.getCoinLayerCount()); - SbBool *swsp = editModeScenegraphNodes.PointsGroup->enable.startEditing(); - SbBool *swsc = editModeScenegraphNodes.CurvesGroup->enable.startEditing(); + SbBool* swsp = editModeScenegraphNodes.PointsGroup->enable.startEditing(); + SbBool* swsc = editModeScenegraphNodes.CurvesGroup->enable.startEditing(); auto setEnableLayer = [swsp, swsc](int l, bool enabled) { - swsp[l] = enabled; // layer defaults to enabled - swsc[l] = enabled; // layer defaults to enabled + swsp[l] = enabled;// layer defaults to enabled + swsc[l] = enabled;// layer defaults to enabled }; auto layersconfigurations = viewProvider.VisualLayerList.getValues(); - for(auto l=0; lenable.finishEditing(); editModeScenegraphNodes.CurvesGroup->enable.finishEditing(); // Define the coin nodes that will be filled in with the geometry layers - GeometryLayerNodes geometrylayernodes { - editModeScenegraphNodes.PointsMaterials, - editModeScenegraphNodes.PointsCoordinate, - editModeScenegraphNodes.CurvesMaterials, - editModeScenegraphNodes.CurvesCoordinate, - editModeScenegraphNodes.CurveSet - }; + GeometryLayerNodes geometrylayernodes {editModeScenegraphNodes.PointsMaterials, + editModeScenegraphNodes.PointsCoordinate, + editModeScenegraphNodes.CurvesMaterials, + editModeScenegraphNodes.CurvesCoordinate, + editModeScenegraphNodes.CurveSet}; // process geometry layers - EditModeGeometryCoinConverter gcconv(viewProvider, geometrylayernodes, drawingParameters, geometryLayerParameters, coinMapping); + EditModeGeometryCoinConverter gcconv( + viewProvider, geometrylayernodes, drawingParameters, geometryLayerParameters, coinMapping); gcconv.convert(geolistfacade); // set cross coordinates - editModeScenegraphNodes.RootCrossSet->numVertices.set1Value(0,2); - editModeScenegraphNodes.RootCrossSet->numVertices.set1Value(1,2); + editModeScenegraphNodes.RootCrossSet->numVertices.set1Value(0, 2); + editModeScenegraphNodes.RootCrossSet->numVertices.set1Value(1, 2); analysisResults.combRepresentationScale = gcconv.getCombRepresentationScale(); - analysisResults.boundingBoxMagnitudeOrder = exp(ceil(log(std::abs(gcconv.getBoundingBoxMaxMagnitude())))); + analysisResults.boundingBoxMagnitudeOrder = + exp(ceil(log(std::abs(gcconv.getBoundingBoxMaxMagnitude())))); analysisResults.bsplineGeoIds = gcconv.getBSplineGeoIds(); analysisResults.arcGeoIds = gcconv.getArcGeoIds(); } -void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geolistfacade, bool issketchinvalid) +void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geolistfacade, + bool issketchinvalid) { // Lambdas for convenience retrieval of geometry information auto isConstructionGeom = [&geolistfacade](int GeoId) { @@ -142,13 +141,14 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol auto isFullyConstraintElement = [&geolistfacade](int GeoId) { auto geom = geolistfacade.getGeometryFacadeFromGeoId(GeoId); - if(geom) { - if(geom->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) { + if (geom) { + if (geom->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) { auto solvext = std::static_pointer_cast( - geom->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); + geom->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); - return (solvext->getGeometry() == Sketcher::SolverGeometryExtension::FullyConstraint); + return (solvext->getGeometry() + == Sketcher::SolverGeometryExtension::FullyConstraint); } } return false; @@ -156,30 +156,33 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol // Update Colors - SbColor *crosscolor = editModeScenegraphNodes.RootCrossMaterials->diffuseColor.startEditing(); - auto viewOrientationFactor = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider); + SbColor* crosscolor = editModeScenegraphNodes.RootCrossMaterials->diffuseColor.startEditing(); + auto viewOrientationFactor = + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider); - for(auto l=0; ldiffuseColor.getNum(); - SbColor *pcolor = editModeScenegraphNodes.PointsMaterials[l]->diffuseColor.startEditing(); + SbColor* pcolor = editModeScenegraphNodes.PointsMaterials[l]->diffuseColor.startEditing(); int CurvNum = editModeScenegraphNodes.CurvesMaterials[l]->diffuseColor.getNum(); - SbColor *color = editModeScenegraphNodes.CurvesMaterials[l]->diffuseColor.startEditing(); + SbColor* color = editModeScenegraphNodes.CurvesMaterials[l]->diffuseColor.startEditing(); - SbVec3f *verts = editModeScenegraphNodes.CurvesCoordinate[l]->point.startEditing(); - SbVec3f *pverts = editModeScenegraphNodes.PointsCoordinate[l]->point.startEditing(); + SbVec3f* verts = editModeScenegraphNodes.CurvesCoordinate[l]->point.startEditing(); + SbVec3f* pverts = editModeScenegraphNodes.PointsCoordinate[l]->point.startEditing(); - float x,y,z; + float x, y, z; // colors of the point set - if( issketchinvalid ) { - for (int i=0; i < PtNum; i++) + if (issketchinvalid) { + for (int i = 0; i < PtNum; i++) pcolor[i] = drawingParameters.InvalidSketchColor; } else { - for (int i=0; i < PtNum; i++) { - if ( !(i == 0 && l == 0) && ViewProviderSketchCoinAttorney::isSketchFullyConstrained(viewProvider)) {// root point is not coloured + for (int i = 0; i < PtNum; i++) { + if (!(i == 0 && l == 0) + && ViewProviderSketchCoinAttorney::isSketchFullyConstrained( + viewProvider)) {// root point is not coloured pcolor[i] = drawingParameters.FullyConstrainedColor; } else { @@ -187,21 +190,21 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol bool constrainedElement = isFullyConstraintElement(GeoId); - if(isInternalAlignedGeom(GeoId)) { - if(constrainedElement) + if (isInternalAlignedGeom(GeoId)) { + if (constrainedElement) pcolor[i] = drawingParameters.FullyConstraintInternalAlignmentColor; else pcolor[i] = drawingParameters.InternalAlignedGeoColor; } else { - if(!isDefinedGeomPoint(GeoId)) { - if(constrainedElement) + if (!isDefinedGeomPoint(GeoId)) { + if (constrainedElement) pcolor[i] = drawingParameters.FullyConstraintConstructionPointColor; else pcolor[i] = drawingParameters.VertexColor; } - else { // this is a defined GeomPoint - if(constrainedElement) + else {// this is a defined GeomPoint + if (constrainedElement) pcolor[i] = drawingParameters.FullyConstraintElementColor; else pcolor[i] = drawingParameters.CurveColor; @@ -213,38 +216,42 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol // update rendering height of points - auto getRenderHeight = [this](DrawingParameters::GeometryRendering renderingtype, float toprendering, float midrendering, float lowrendering) { - if(drawingParameters.topRenderingGeometry == renderingtype) + auto getRenderHeight = [this](DrawingParameters::GeometryRendering renderingtype, + float toprendering, + float midrendering, + float lowrendering) { + if (drawingParameters.topRenderingGeometry == renderingtype) return toprendering; - else if(drawingParameters.midRenderingGeometry == renderingtype) + else if (drawingParameters.midRenderingGeometry == renderingtype) return midrendering; else return lowrendering; }; float zNormPoint = getRenderHeight(DrawingParameters::GeometryRendering::NormalGeometry, - drawingParameters.zHighPoints, - drawingParameters.zLowPoints, - drawingParameters.zLowPoints); + drawingParameters.zHighPoints, + drawingParameters.zLowPoints, + drawingParameters.zLowPoints); float zConstrPoint = getRenderHeight(DrawingParameters::GeometryRendering::Construction, - drawingParameters.zHighPoints, - drawingParameters.zLowPoints, - drawingParameters.zLowPoints); + drawingParameters.zHighPoints, + drawingParameters.zLowPoints, + drawingParameters.zLowPoints); - for (int i=0; i < PtNum; i++) { // 0 is the origin - if( i == 0 && l == 0 ) { // reset root point to lowest + for (int i = 0; i < PtNum; i++) {// 0 is the origin + if (i == 0 && l == 0) { // reset root point to lowest pverts[i].setValue(0, 0, viewOrientationFactor * drawingParameters.zRootPoint); } else { - pverts[i].getValue(x,y,z); - auto geom = geolistfacade.getGeometryFacadeFromGeoId(coinMapping.getPointGeoId(i, l)); + pverts[i].getValue(x, y, z); + auto geom = + geolistfacade.getGeometryFacadeFromGeoId(coinMapping.getPointGeoId(i, l)); - if(geom) { - if(geom->getConstruction()) - pverts[i].setValue(x,y,viewOrientationFactor * zConstrPoint); + if (geom) { + if (geom->getConstruction()) + pverts[i].setValue(x, y, viewOrientationFactor * zConstrPoint); else - pverts[i].setValue(x,y,viewOrientationFactor * zNormPoint); + pverts[i].setValue(x, y, viewOrientationFactor * zNormPoint); } } } @@ -253,7 +260,7 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol auto preselectcross = ViewProviderSketchCoinAttorney::getPreselectCross(viewProvider); auto preselectcurve = ViewProviderSketchCoinAttorney::getPreselectCurve(viewProvider); - auto raisePoint = [](SbVec3f & point, float height) { + auto raisePoint = [](SbVec3f& point, float height) { float x, y, z; point.getValue(x, y, z); point.setValue(x, y, height); @@ -261,15 +268,14 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol MultiFieldId preselectpointmfid; - if ( preselectcross == 0) { - if(l == 0) // cross only in layer 0 + if (preselectcross == 0) { + if (l == 0)// cross only in layer 0 pcolor[0] = drawingParameters.PreselectColor; } else if (preselectpoint != -1) { preselectpointmfid = coinMapping.getIndexLayer(preselectpoint); - if (MultiFieldId::Invalid != preselectpointmfid && - preselectpointmfid.layerId == l && - preselectpointmfid.fieldIndex < PtNum) { + if (MultiFieldId::Invalid != preselectpointmfid && preselectpointmfid.layerId == l + && preselectpointmfid.fieldIndex < PtNum) { pcolor[preselectpointmfid.fieldIndex] = drawingParameters.PreselectColor; @@ -277,12 +283,22 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol } } - ViewProviderSketchCoinAttorney::executeOnSelectionPointSet(viewProvider, - [pcolor, pverts, PtNum, preselectpointmfid, layerId = l, &coinMapping = coinMapping, drawingParameters = this->drawingParameters, raisePoint](const int i) { + ViewProviderSketchCoinAttorney::executeOnSelectionPointSet( + viewProvider, + [pcolor, + pverts, + PtNum, + preselectpointmfid, + layerId = l, + &coinMapping = coinMapping, + drawingParameters = this->drawingParameters, + raisePoint](const int i) { auto pointindex = coinMapping.getIndexLayer(i); - if (layerId == pointindex.layerId && pointindex.fieldIndex >= 0 && pointindex.fieldIndex < PtNum) { + if (layerId == pointindex.layerId && pointindex.fieldIndex >= 0 + && pointindex.fieldIndex < PtNum) { pcolor[pointindex.fieldIndex] = (preselectpointmfid == pointindex) - ? drawingParameters.PreselectSelectedColor : drawingParameters.SelectColor; + ? drawingParameters.PreselectSelectedColor + : drawingParameters.SelectColor; raisePoint(pverts[pointindex.fieldIndex], drawingParameters.zHighlight); } @@ -291,26 +307,26 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol // update colors and rendering height of the curves float zNormLine = getRenderHeight(DrawingParameters::GeometryRendering::NormalGeometry, - drawingParameters.zHighLines, - drawingParameters.zMidLines, - drawingParameters.zLowLines); + drawingParameters.zHighLines, + drawingParameters.zMidLines, + drawingParameters.zLowLines); float zConstrLine = getRenderHeight(DrawingParameters::GeometryRendering::Construction, - drawingParameters.zHighLines, - drawingParameters.zMidLines, - drawingParameters.zLowLines); + drawingParameters.zHighLines, + drawingParameters.zMidLines, + drawingParameters.zLowLines); float zExtLine = getRenderHeight(DrawingParameters::GeometryRendering::ExternalGeometry, - drawingParameters.zHighLines, - drawingParameters.zMidLines, - drawingParameters.zLowLines); + drawingParameters.zHighLines, + drawingParameters.zMidLines, + drawingParameters.zLowLines); - int j=0; // vertexindex + int j = 0;// vertexindex - for (int i=0; i < CurvNum; i++) { + for (int i = 0; i < CurvNum; i++) { int GeoId = coinMapping.getCurveGeoId(i, l); // CurvId has several vertices associated to 1 material - //edit->CurveSet->numVertices => [i] indicates number of vertex for line i. + // edit->CurveSet->numVertices => [i] indicates number of vertex for line i. int indexes = (editModeScenegraphNodes.CurveSet[l]->numVertices[i]); bool selected = ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, GeoId); @@ -320,94 +336,96 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade & geol if (selected && preselected) { color[i] = drawingParameters.PreselectSelectedColor; - for (int k=j; jaddChild(editModeScenegraphNodes.CurvesGroup); - } void EditModeGeometryCoinManager::emptyGeometryRootNodes() @@ -479,35 +496,38 @@ void EditModeGeometryCoinManager::emptyGeometryRootNodes() void EditModeGeometryCoinManager::createEditModePointInventorNodes() { - for(int i=0; i < geometryLayerParameters.getCoinLayerCount(); i++) { - SoSeparator * sep = new SoSeparator; + for (int i = 0; i < geometryLayerParameters.getCoinLayerCount(); i++) { + SoSeparator* sep = new SoSeparator; sep->ref(); auto somaterial = new SoMaterial; editModeScenegraphNodes.PointsMaterials.push_back(somaterial); - editModeScenegraphNodes.PointsMaterials[i]->setName(concat("PointsMaterials_",i).c_str()); + editModeScenegraphNodes.PointsMaterials[i]->setName(concat("PointsMaterials_", i).c_str()); sep->addChild(editModeScenegraphNodes.PointsMaterials[i]); - SoMaterialBinding *MtlBind = new SoMaterialBinding; - MtlBind->setName(concat("PointsMaterialBinding",i).c_str()); + SoMaterialBinding* MtlBind = new SoMaterialBinding; + MtlBind->setName(concat("PointsMaterialBinding", i).c_str()); MtlBind->value = SoMaterialBinding::PER_VERTEX; sep->addChild(MtlBind); auto coords = new SoCoordinate3; editModeScenegraphNodes.PointsCoordinate.push_back(coords); - editModeScenegraphNodes.PointsCoordinate[i]->setName(concat("PointsCoordinate",i).c_str()); + editModeScenegraphNodes.PointsCoordinate[i]->setName(concat("PointsCoordinate", i).c_str()); sep->addChild(editModeScenegraphNodes.PointsCoordinate[i]); auto drawstyle = new SoDrawStyle; editModeScenegraphNodes.PointsDrawStyle.push_back(drawstyle); - editModeScenegraphNodes.PointsDrawStyle[i]->setName(concat("PointsDrawStyle",i).c_str()); - editModeScenegraphNodes.PointsDrawStyle[i]->pointSize = 8 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.PointsDrawStyle[i]->setName(concat("PointsDrawStyle", i).c_str()); + editModeScenegraphNodes.PointsDrawStyle[i]->pointSize = + 8 * drawingParameters.pixelScalingFactor; sep->addChild(editModeScenegraphNodes.PointsDrawStyle[i]); auto pointset = new SoMarkerSet; editModeScenegraphNodes.PointSet.push_back(pointset); - editModeScenegraphNodes.PointSet[i]->setName(concat("PointSet",i).c_str()); - editModeScenegraphNodes.PointSet[i]->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", drawingParameters.markerSize); + editModeScenegraphNodes.PointSet[i]->setName(concat("PointSet", i).c_str()); + editModeScenegraphNodes.PointSet[i]->markerIndex = + Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", + drawingParameters.markerSize); sep->addChild(editModeScenegraphNodes.PointSet[i]); editModeScenegraphNodes.PointsGroup->addChild(sep); @@ -519,38 +539,40 @@ void EditModeGeometryCoinManager::createEditModeCurveInventorNodes() { auto layersconfigurations = viewProvider.VisualLayerList.getValue(); - for(int i=0; i < geometryLayerParameters.getCoinLayerCount(); i++) { - SoSeparator * sep = new SoSeparator; + for (int i = 0; i < geometryLayerParameters.getCoinLayerCount(); i++) { + SoSeparator* sep = new SoSeparator; sep->ref(); auto somaterial = new SoMaterial; editModeScenegraphNodes.CurvesMaterials.push_back(somaterial); - editModeScenegraphNodes.CurvesMaterials[i]->setName(concat("CurvesMaterials",i).c_str()); + editModeScenegraphNodes.CurvesMaterials[i]->setName(concat("CurvesMaterials", i).c_str()); sep->addChild(editModeScenegraphNodes.CurvesMaterials[i]); auto MtlBind = new SoMaterialBinding; - MtlBind->setName(concat("CurvesMaterialsBinding",i).c_str()); + MtlBind->setName(concat("CurvesMaterialsBinding", i).c_str()); MtlBind->value = SoMaterialBinding::PER_FACE; sep->addChild(MtlBind); auto coords = new SoCoordinate3; editModeScenegraphNodes.CurvesCoordinate.push_back(coords); - editModeScenegraphNodes.CurvesCoordinate[i]->setName(concat("CurvesCoordinate",i).c_str()); + editModeScenegraphNodes.CurvesCoordinate[i]->setName(concat("CurvesCoordinate", i).c_str()); sep->addChild(editModeScenegraphNodes.CurvesCoordinate[i]); auto drawstyle = new SoDrawStyle; editModeScenegraphNodes.CurvesDrawStyle.push_back(drawstyle); - editModeScenegraphNodes.CurvesDrawStyle[i]->setName(concat("CurvesDrawStyle",i).c_str()); + editModeScenegraphNodes.CurvesDrawStyle[i]->setName(concat("CurvesDrawStyle", i).c_str()); - editModeScenegraphNodes.CurvesDrawStyle[i]->lineWidth = layersconfigurations[i].getLineWidth() * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesDrawStyle[i]->linePattern = layersconfigurations[i].getLinePattern(); + editModeScenegraphNodes.CurvesDrawStyle[i]->lineWidth = + layersconfigurations[i].getLineWidth() * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesDrawStyle[i]->linePattern = + layersconfigurations[i].getLinePattern(); editModeScenegraphNodes.CurvesDrawStyle[i]->linePatternScaleFactor = 5; sep->addChild(editModeScenegraphNodes.CurvesDrawStyle[i]); auto solineset = new SoLineSet; editModeScenegraphNodes.CurveSet.push_back(solineset); - editModeScenegraphNodes.CurveSet[i]->setName(concat("CurvesLineSet",i).c_str()); + editModeScenegraphNodes.CurveSet[i]->setName(concat("CurvesLineSet", i).c_str()); sep->addChild(editModeScenegraphNodes.CurveSet[i]); editModeScenegraphNodes.CurvesGroup->addChild(sep); diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h index e6bf1203ae..b69e98df91 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h @@ -36,25 +36,29 @@ class SoRayPickAction; class SoPickedPoint; class SbVec3s; -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; - class Vector2d; +class Vector2d; - class Placement; +class Placement; +}// namespace Base + +namespace Part +{ +class Geometry; } -namespace Part { - class Geometry; -} +namespace Sketcher +{ +class Constraint; +class PropertyConstraintList; +};// namespace Sketcher -namespace Sketcher { - class Constraint; - class PropertyConstraintList; -}; - -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; class EditModeConstraintCoinManager; @@ -62,10 +66,12 @@ class EditModeConstraintCoinManager; using GeoList = Sketcher::GeoList; using GeoListFacade = Sketcher::GeoListFacade; -/** @brief Class for managing the Edit mode coin nodes of ViewProviderSketch relating to geometry. +/** @brief Class for managing the Edit mode coin nodes of ViewProviderSketch relating to + * geometry. * @details * - * EditModeGeometryCoinManager is a helper of EditModeCoinManager specialised in geometry management. + * EditModeGeometryCoinManager is a helper of EditModeCoinManager specialised in geometry + * management. * * Three main functions are delegated to it: * 1. Creation of Edit mode coin nodes to handle Geometry representation. @@ -80,19 +86,18 @@ class SketcherGuiExport EditModeGeometryCoinManager { public: - explicit EditModeGeometryCoinManager( ViewProviderSketch &vp, - DrawingParameters & drawingParams, - GeometryLayerParameters & geometryLayerParams, - AnalysisResults & analysisResultStruct, - EditModeScenegraphNodes & editModeScenegraph, - CoinMapping & coinMap); + explicit EditModeGeometryCoinManager(ViewProviderSketch& vp, DrawingParameters& drawingParams, + GeometryLayerParameters& geometryLayerParams, + AnalysisResults& analysisResultStruct, + EditModeScenegraphNodes& editModeScenegraph, + CoinMapping& coinMap); ~EditModeGeometryCoinManager(); // This function populates the coin nodes with the information of the current geometry - void processGeometry(const GeoListFacade & geolistfacade); + void processGeometry(const GeoListFacade& geolistfacade); - void updateGeometryColor(const GeoListFacade & geolistfacade, bool issketchinvalid); + void updateGeometryColor(const GeoListFacade& geolistfacade, bool issketchinvalid); void updateGeometryLayersConfiguration(); @@ -107,21 +112,19 @@ private: void createEditModeCurveInventorNodes(); private: - ViewProviderSketch & viewProvider; + ViewProviderSketch& viewProvider; - DrawingParameters & drawingParameters; - GeometryLayerParameters & geometryLayerParameters; - AnalysisResults & analysisResults; + DrawingParameters& drawingParameters; + GeometryLayerParameters& geometryLayerParameters; + AnalysisResults& analysisResults; - EditModeScenegraphNodes & editModeScenegraphNodes; - - CoinMapping & coinMapping; + EditModeScenegraphNodes& editModeScenegraphNodes; + CoinMapping& coinMapping; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_EditModeGeometryCoinManager_H - +#endif// SKETCHERGUI_EditModeGeometryCoinManager_H diff --git a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp index ce4fc1504f..fbd288a8e0 100644 --- a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp +++ b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp @@ -22,43 +22,43 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif // #ifndef _PreComp_ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif// #ifndef _PreComp_ #include #include #include -#include "EditModeInformationOverlayCoinConverter.h" #include "EditModeCoinManagerParameters.h" +#include "EditModeInformationOverlayCoinConverter.h" #include "ViewProviderSketchCoinAttorney.h" using namespace SketcherGui; EditModeInformationOverlayCoinConverter::EditModeInformationOverlayCoinConverter( - ViewProviderSketch & vp, - SoGroup * infogroup, - OverlayParameters & overlayparameters, - DrawingParameters & drawingparameters): viewProvider(vp), - infoGroup(infogroup), - overlayParameters(overlayparameters), - drawingParameters(drawingparameters), - nodeId(0){ + ViewProviderSketch& vp, SoGroup* infogroup, OverlayParameters& overlayparameters, + DrawingParameters& drawingparameters) + : viewProvider(vp) + , infoGroup(infogroup) + , overlayParameters(overlayparameters) + , drawingParameters(drawingparameters) + , nodeId(0) { -}; + }; -void EditModeInformationOverlayCoinConverter::convert(const Part::Geometry * geometry, int geoid) { +void EditModeInformationOverlayCoinConverter::convert(const Part::Geometry* geometry, int geoid) +{ - if (geometry->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()){ + if (geometry->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // at this point all calculations relate to BSplineCurves calculate(geometry, geoid); calculate(geometry, geoid); @@ -71,23 +71,27 @@ void EditModeInformationOverlayCoinConverter::convert(const Part::Geometry * geo addUpdateNode(curvatureComb); addUpdateNode(knotMultiplicity); addUpdateNode(poleWeights); - } else if (geometry->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()){ + } + else if (geometry->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // at this point all calculations relate to ArcOfCircle calculate(geometry, geoid); addUpdateNode(circleHelper); } } -void EditModeInformationOverlayCoinConverter::addToInfoGroup(SoSwitch * sw) { +void EditModeInformationOverlayCoinConverter::addToInfoGroup(SoSwitch* sw) +{ infoGroup->addChild(sw); nodeId++; } -template < EditModeInformationOverlayCoinConverter::CalculationType calculation > -void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * geometry, [[maybe_unused]] int geoid) { +template +void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* geometry, + [[maybe_unused]] int geoid) +{ - if constexpr (calculation == CalculationType::ArcCircleHelper ) { - const Part::GeomArcOfCircle *arc = static_cast(geometry); + if constexpr (calculation == CalculationType::ArcCircleHelper) { + const Part::GeomArcOfCircle* arc = static_cast(geometry); clearCalculation(circleHelper); Base::Vector3d center = arc->getCenter(); @@ -100,15 +104,16 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g circleHelper.coordinates.reserve(ndiv); for (int i = 0; i < ndiv; i++) { - double param = i * std::atan(1) * 8 / ndiv; - circleHelper.coordinates.emplace_back(circle.value(param)); + double param = i * std::atan(1) * 8 / ndiv; + circleHelper.coordinates.emplace_back(circle.value(param)); } - circleHelper.coordinates.emplace_back(circle.value(0.0)); + circleHelper.coordinates.emplace_back(circle.value(0.0)); circleHelper.indices.push_back(ndiv + 1); - } else { - const Part::GeomBSplineCurve *spline = static_cast(geometry); + } + else { + const Part::GeomBSplineCurve* spline = static_cast(geometry); - if constexpr (calculation == CalculationType::BSplineDegree ) { + if constexpr (calculation == CalculationType::BSplineDegree) { clearCalculation(degree); std::vector poles = spline->getPoles(); @@ -116,7 +121,7 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g degree.strings.clear(); degree.positions.clear(); - Base::Vector3d midp = Base::Vector3d(0,0,0); + Base::Vector3d midp = Base::Vector3d(0, 0, 0); for (auto val : poles) midp += val; @@ -126,7 +131,7 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g degree.strings.emplace_back(std::to_string(spline->getDegree())); degree.positions.emplace_back(midp); } - else if constexpr (calculation == CalculationType::BSplineControlPolygon ) { + else if constexpr (calculation == CalculationType::BSplineControlPolygon) { clearCalculation(controlPolygon); @@ -138,21 +143,22 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g size_t nvertices; if (spline->isPeriodic()) - nvertices = poles.size()+1; + nvertices = poles.size() + 1; else nvertices = poles.size(); controlPolygon.coordinates.reserve(nvertices); - for (auto & v : poles) + for (auto& v : poles) controlPolygon.coordinates.emplace_back(v); if (spline->isPeriodic()) controlPolygon.coordinates.emplace_back(poles[0]); - controlPolygon.indices.push_back(nvertices); // single continuous polygon starting at index 0 + controlPolygon.indices.push_back( + nvertices);// single continuous polygon starting at index 0 } - else if constexpr (calculation == CalculationType::BSplineCurvatureComb ) { + else if constexpr (calculation == CalculationType::BSplineCurvatureComb) { clearCalculation(curvatureComb); // curvature graph -------------------------------------------------------- @@ -165,7 +171,7 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g auto knots = spline->getKnots(); auto mults = spline->getMultiplicities(); - const int ndivPerPiece = 64; // heuristic of number of division to fill in + const int ndivPerPiece = 64;// heuristic of number of division to fill in const int ndiv = ndivPerPiece * (knots.size() - 1); std::vector pointatcurvelist; @@ -177,10 +183,13 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g normallist.reserve(ndiv); // go through the polynomial pieces (i.e. from one knot to next) - for (size_t k = 0; k < knots.size()-1; ++k) { - // first and last params are a little off to account for possible discontinuity at knots - double firstparam = knots[k] + Precision::Approximation()*(knots[k + 1] - knots[k]); - double lastparam = knots[k + 1] - Precision::Approximation()*(knots[k + 1] - knots[k]); + for (size_t k = 0; k < knots.size() - 1; ++k) { + // first and last params are a little off to account for possible discontinuity at + // knots + double firstparam = + knots[k] + Precision::Approximation() * (knots[k + 1] - knots[k]); + double lastparam = + knots[k + 1] - Precision::Approximation() * (knots[k + 1] - knots[k]); // TODO: Maybe this can be improved, specifically adapted for each piece double step = (lastparam - firstparam) / (ndivPerPiece - 1); @@ -192,12 +201,15 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g try { curvaturelist.emplace_back(spline->curvatureAt(param)); } - catch(Base::CADKernelError &e) { + catch (Base::CADKernelError& e) { // it is "just" a visualisation matter OCC could not calculate the curvature // terminating here would mean that the other shapes would not be drawn. // Solution: Report the issue and set dummy curvature to 0 e.ReportException(); - Base::Console().DeveloperError("EditModeInformationOverlayCoinConverter","Curvature graph for B-Spline with GeoId=%d could not be calculated.\n", geoid); + Base::Console().DeveloperError( + "EditModeInformationOverlayCoinConverter", + "Curvature graph for B-Spline with GeoId=%d could not be calculated.\n", + geoid); curvaturelist.emplace_back(0); } @@ -206,8 +218,8 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g spline->normalAt(param, normal); normallist.emplace_back(normal); } - catch(Base::Exception&) { - normallist.emplace_back(0,0,0); + catch (Base::Exception&) { + normallist.emplace_back(0, 0, 0); } } } @@ -216,52 +228,64 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry * g pointatcomblist.reserve(ndiv); for (int i = 0; i < ndiv; i++) { - pointatcomblist.emplace_back(pointatcurvelist[i] - overlayParameters.currentBSplineCombRepresentationScale * curvaturelist[i] * normallist[i]); + pointatcomblist.emplace_back( + pointatcurvelist[i] + - overlayParameters.currentBSplineCombRepresentationScale * curvaturelist[i] + * normallist[i]); } - curvatureComb.coordinates.reserve(3*ndiv); // 2*ndiv +1 points of ndiv separate segments + ndiv points for last segment - curvatureComb.indices.reserve(ndiv+1); // ndiv separate segments of radials + 1 segment connecting at comb end + curvatureComb.coordinates.reserve( + 3 + * ndiv);// 2*ndiv +1 points of ndiv separate segments + ndiv points for last segment + curvatureComb.indices.reserve( + ndiv + 1);// ndiv separate segments of radials + 1 segment connecting at comb end - auto zInfoH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zInfo; + auto zInfoH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zInfo; for (int i = 0; i < ndiv; i++) { // note emplace emplaces on the position BEFORE the iterator given. - curvatureComb.coordinates.emplace_back(pointatcurvelist[i].x, pointatcurvelist[i].y, zInfoH); // radials - curvatureComb.coordinates.emplace_back(pointatcomblist[i].x, pointatcomblist[i].y, zInfoH); // radials + curvatureComb.coordinates.emplace_back( + pointatcurvelist[i].x, pointatcurvelist[i].y, zInfoH);// radials + curvatureComb.coordinates.emplace_back( + pointatcomblist[i].x, pointatcomblist[i].y, zInfoH);// radials - curvatureComb.indices.emplace_back(2); // line + curvatureComb.indices.emplace_back(2);// line } for (int i = 0; i < ndiv; i++) - curvatureComb.coordinates.emplace_back(pointatcomblist[i].x, pointatcomblist[i].y, zInfoH); // // comb endpoint closing segment + curvatureComb.coordinates.emplace_back(pointatcomblist[i].x, + pointatcomblist[i].y, + zInfoH);// // comb endpoint closing segment - curvatureComb.indices.emplace_back(ndiv); // Comb line + curvatureComb.indices.emplace_back(ndiv);// Comb line } - else if constexpr (calculation == CalculationType::BSplineKnotMultiplicity ) { + else if constexpr (calculation == CalculationType::BSplineKnotMultiplicity) { clearCalculation(knotMultiplicity); std::vector knots = spline->getKnots(); std::vector mult = spline->getMultiplicities(); - for (size_t i=0; ipointAtParameter(knots[i])); std::ostringstream stringStream; stringStream << "(" << mult[i] << ")"; - knotMultiplicity.strings.emplace_back( stringStream.str()); + knotMultiplicity.strings.emplace_back(stringStream.str()); } } - else if constexpr (calculation == CalculationType::BSplinePoleWeight ) { + else if constexpr (calculation == CalculationType::BSplinePoleWeight) { clearCalculation(poleWeights); std::vector poles = spline->getPoles(); auto weights = spline->getWeights(); - for (size_t i=0; i -void EditModeInformationOverlayCoinConverter::addUpdateNode(const Result & result) { +template +void EditModeInformationOverlayCoinConverter::addUpdateNode(const Result& result) +{ if (overlayParameters.rebuildInformationLayer) addNode(result); @@ -278,40 +303,46 @@ void EditModeInformationOverlayCoinConverter::addUpdateNode(const Result & resul updateNode(result); } -template < EditModeInformationOverlayCoinConverter::CalculationType calculation > -bool EditModeInformationOverlayCoinConverter::isVisible() { - if constexpr ( calculation == CalculationType::BSplineDegree ) { +template +bool EditModeInformationOverlayCoinConverter::isVisible() +{ + if constexpr (calculation == CalculationType::BSplineDegree) { return overlayParameters.bSplineDegreeVisible; } - else if constexpr ( calculation == CalculationType::BSplineControlPolygon ) { + else if constexpr (calculation == CalculationType::BSplineControlPolygon) { return overlayParameters.bSplineControlPolygonVisible; } - else if constexpr ( calculation == CalculationType::BSplineCurvatureComb ) { + else if constexpr (calculation == CalculationType::BSplineCurvatureComb) { return overlayParameters.bSplineCombVisible; } - else if constexpr ( calculation == CalculationType::BSplineKnotMultiplicity ) { + else if constexpr (calculation == CalculationType::BSplineKnotMultiplicity) { return overlayParameters.bSplineKnotMultiplicityVisible; } - else if constexpr ( calculation == CalculationType::BSplinePoleWeight ) { + else if constexpr (calculation == CalculationType::BSplinePoleWeight) { return overlayParameters.bSplinePoleWeightVisible; } - else if constexpr ( calculation == CalculationType::ArcCircleHelper ) { + else if constexpr (calculation == CalculationType::ArcCircleHelper) { return overlayParameters.arcCircleHelperVisible; } } -template < typename Result > -void EditModeInformationOverlayCoinConverter::setPolygon(const Result & result, SoLineSet *polygonlineset, SoCoordinate3 *polygoncoords) { +template +void EditModeInformationOverlayCoinConverter::setPolygon(const Result& result, + SoLineSet* polygonlineset, + SoCoordinate3* polygoncoords) +{ polygoncoords->point.setNum(result.coordinates.size()); polygonlineset->numVertices.setNum(result.indices.size()); - int32_t *index = polygonlineset->numVertices.startEditing(); - SbVec3f *vts = polygoncoords->point.startEditing(); + int32_t* index = polygonlineset->numVertices.startEditing(); + SbVec3f* vts = polygoncoords->point.startEditing(); for (size_t i = 0; i < result.coordinates.size(); i++) - vts[i].setValue(result.coordinates[i].x, result.coordinates[i].y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zInfo); + vts[i].setValue(result.coordinates[i].x, + result.coordinates[i].y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zInfo); for (size_t i = 0; i < result.indices.size(); i++) index[i] = result.indices[i]; @@ -320,8 +351,9 @@ void EditModeInformationOverlayCoinConverter::setPolygon(const Result & result, polygonlineset->numVertices.finishEditing(); } -template < int line > -void EditModeInformationOverlayCoinConverter::setText(const std::string & string, SoText2 * text) { +template +void EditModeInformationOverlayCoinConverter::setText(const std::string& string, SoText2* text) +{ if constexpr (line == 1) { text->string = SbString(string.c_str()); @@ -329,65 +361,72 @@ void EditModeInformationOverlayCoinConverter::setText(const std::string & string else { assert(line > 1); SoMFString label; - for ( int l = 0; l < (line - 1) ; l++) + for (int l = 0; l < (line - 1); l++) label.set1Value(l, SbString("")); - label.set1Value(line-1, SbString(string.c_str())); + label.set1Value(line - 1, SbString(string.c_str())); text->string = label; } } -template < typename Result > -void EditModeInformationOverlayCoinConverter::clearCalculation(Result & result) { - if constexpr (Result::visualisationType == VisualisationType::Text) { +template +void EditModeInformationOverlayCoinConverter::clearCalculation(Result& result) +{ + if constexpr (Result::visualisationType == VisualisationType::Text) { result.positions.clear(); result.strings.clear(); - } - else if constexpr (Result::visualisationType == VisualisationType::Polygon) { + } + else if constexpr (Result::visualisationType == VisualisationType::Polygon) { result.coordinates.clear(); result.indices.clear(); - } + } } -template < typename Result> -void EditModeInformationOverlayCoinConverter::addNode(const Result & result) { +template +void EditModeInformationOverlayCoinConverter::addNode(const Result& result) +{ if constexpr (Result::visualisationType == VisualisationType::Text) { - for(size_t i = 0; i < result.strings.size(); i++) { + for (size_t i = 0; i < result.strings.size(); i++) { - SoSwitch *sw = new SoSwitch(); + SoSwitch* sw = new SoSwitch(); - sw->whichChild = isVisible()?SO_SWITCH_ALL:SO_SWITCH_NONE; + sw->whichChild = isVisible() ? SO_SWITCH_ALL : SO_SWITCH_NONE; - SoSeparator *sep = new SoSeparator(); + SoSeparator* sep = new SoSeparator(); sep->ref(); // no caching for frequently-changing data structures sep->renderCaching = SoSeparator::OFF; - // every information visual node gets its own material for to-be-implemented preselection and selection - SoMaterial *mat = new SoMaterial; + // every information visual node gets its own material for to-be-implemented + // preselection and selection + SoMaterial* mat = new SoMaterial; mat->ref(); mat->diffuseColor = drawingParameters.InformationColor; - SoTranslation *translate = new SoTranslation; + SoTranslation* translate = new SoTranslation; - translate->translation.setValue(result.positions[i].x, result.positions[i].y, - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zInfo); + translate->translation.setValue( + result.positions[i].x, + result.positions[i].y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zInfo); - SoFont *font = new SoFont; + SoFont* font = new SoFont; font->name.setValue("Helvetica"); font->size.setValue(drawingParameters.coinFontSize); - SoText2 *text = new SoText2; + SoText2* text = new SoText2; // since the first and last control point of a spline is also treated as knot and thus - // can also have a displayed multiplicity, we must assure the multiplicity is not visibly overwritten - // therefore be output the weight in a second line + // can also have a displayed multiplicity, we must assure the multiplicity is not + // visibly overwritten therefore be output the weight in a second line // - // This could be made into a more generic form, but it is probably not worth the effort at this time. - if constexpr ( Result::calculationType == CalculationType::BSplinePoleWeight ) + // This could be made into a more generic form, but it is probably not worth the effort + // at this time. + if constexpr (Result::calculationType == CalculationType::BSplinePoleWeight) setText<2>(result.strings[i], text); else setText(result.strings[i], text); @@ -406,23 +445,24 @@ void EditModeInformationOverlayCoinConverter::addNode(const Result & result) { } else if constexpr (Result::visualisationType == VisualisationType::Polygon) { - SoSwitch *sw = new SoSwitch(); + SoSwitch* sw = new SoSwitch(); // hGrpsk->GetBool("BSplineControlPolygonVisible", true) - sw->whichChild = isVisible()?SO_SWITCH_ALL:SO_SWITCH_NONE; + sw->whichChild = isVisible() ? SO_SWITCH_ALL : SO_SWITCH_NONE; - SoSeparator *sep = new SoSeparator(); + SoSeparator* sep = new SoSeparator(); sep->ref(); // no caching for frequently-changing data structures sep->renderCaching = SoSeparator::OFF; - // every information visual node gets its own material for to-be-implemented preselection and selection - SoMaterial *mat = new SoMaterial; + // every information visual node gets its own material for to-be-implemented preselection + // and selection + SoMaterial* mat = new SoMaterial; mat->ref(); mat->diffuseColor = drawingParameters.InformationColor; - SoLineSet *polygonlineset = new SoLineSet; - SoCoordinate3 *polygoncoords = new SoCoordinate3; + SoLineSet* polygonlineset = new SoLineSet; + SoCoordinate3* polygoncoords = new SoCoordinate3; setPolygon(result, polygonlineset, polygoncoords); @@ -438,47 +478,61 @@ void EditModeInformationOverlayCoinConverter::addNode(const Result & result) { } } -template < typename Result > -void EditModeInformationOverlayCoinConverter::updateNode(const Result & result) { +template +void EditModeInformationOverlayCoinConverter::updateNode(const Result& result) +{ - if constexpr (Result::visualisationType == VisualisationType::Text ) { + if constexpr (Result::visualisationType == VisualisationType::Text) { - for(size_t i = 0; i < result.strings.size(); i++) { - SoSwitch *sw = static_cast(infoGroup->getChild(nodeId)); + for (size_t i = 0; i < result.strings.size(); i++) { + SoSwitch* sw = static_cast(infoGroup->getChild(nodeId)); if (overlayParameters.visibleInformationChanged) - sw->whichChild = isVisible()?SO_SWITCH_ALL:SO_SWITCH_NONE; + sw->whichChild = + isVisible() ? SO_SWITCH_ALL : SO_SWITCH_NONE; - SoSeparator *sep = static_cast(sw->getChild(0)); + SoSeparator* sep = static_cast(sw->getChild(0)); - static_cast(sep->getChild(static_cast(TextNodePosition::TextCoordinates)))->translation.setValue(result.positions[i].x, result.positions[i].y, ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zInfo); + static_cast( + sep->getChild(static_cast(TextNodePosition::TextCoordinates))) + ->translation.setValue( + result.positions[i].x, + result.positions[i].y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zInfo); // since the first and last control point of a spline is also treated as knot and thus - // can also have a displayed multiplicity, we must assure the multiplicity is not visibly overwritten - // therefore be output the weight in a second line + // can also have a displayed multiplicity, we must assure the multiplicity is not + // visibly overwritten therefore be output the weight in a second line // - // This could be made into a more generic form, but it is probably not worth the effort at this time. - if constexpr ( Result::calculationType == CalculationType::BSplinePoleWeight ) - setText<2>(result.strings[i], static_cast(sep->getChild(static_cast(TextNodePosition::TextInformation)))); + // This could be made into a more generic form, but it is probably not worth the effort + // at this time. + if constexpr (Result::calculationType == CalculationType::BSplinePoleWeight) + setText<2>(result.strings[i], + static_cast( + sep->getChild(static_cast(TextNodePosition::TextInformation)))); else - setText(result.strings[i], static_cast(sep->getChild(static_cast(TextNodePosition::TextInformation)))); + setText(result.strings[i], + static_cast( + sep->getChild(static_cast(TextNodePosition::TextInformation)))); nodeId++; } - } else if constexpr (Result::visualisationType == VisualisationType::Polygon) { - SoSwitch *sw = static_cast(infoGroup->getChild(nodeId)); + SoSwitch* sw = static_cast(infoGroup->getChild(nodeId)); - if(overlayParameters.visibleInformationChanged) - sw->whichChild = isVisible()?SO_SWITCH_ALL:SO_SWITCH_NONE; + if (overlayParameters.visibleInformationChanged) + sw->whichChild = isVisible() ? SO_SWITCH_ALL : SO_SWITCH_NONE; - SoSeparator *sep = static_cast(sw->getChild(0)); + SoSeparator* sep = static_cast(sw->getChild(0)); - SoCoordinate3 *polygoncoords = static_cast(sep->getChild(static_cast(PolygonNodePosition::PolygonCoordinates))); + SoCoordinate3* polygoncoords = static_cast( + sep->getChild(static_cast(PolygonNodePosition::PolygonCoordinates))); - SoLineSet *polygonlineset = static_cast(sep->getChild(static_cast(PolygonNodePosition::PolygonLineSet))); + SoLineSet* polygonlineset = static_cast( + sep->getChild(static_cast(PolygonNodePosition::PolygonLineSet))); setPolygon(result, polygonlineset, polygoncoords); diff --git a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.h b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.h index ba9af8a173..c74f636228 100644 --- a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.h +++ b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.h @@ -28,21 +28,24 @@ #include "ViewProviderSketch.h" -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; - class Vector2d; +class Vector2d; +}// namespace Base + +namespace Part +{ +class Geometry; } -namespace Part { - class Geometry; -} - -namespace SketcherGui { - class ViewProviderSketch; - struct OverlayParameters; - struct DrawingParameters; +namespace SketcherGui +{ +class ViewProviderSketch; +struct OverlayParameters; +struct DrawingParameters; /** @brief Class for creating the Overlay information layer * @details @@ -57,24 +60,27 @@ namespace SketcherGui { * * [Geometry] => Calculate => addUpdateNode * - * Calculate is responsible for generating information directly usable by Coin (but with standard types that - * would enable portability) in a predetermined internal Node structure format (e.g. StringNode, PolygonNode) - * that can generically be used by the addUpdateNode. + * Calculate is responsible for generating information directly usable by Coin (but with standard + * types that would enable portability) in a predetermined internal Node structure format (e.g. + * StringNode, PolygonNode) that can generically be used by the addUpdateNode. * - * addUpdateNode is responsible for creating or updating the node structure (depending on overlayParameters.rebuildInformationLayer) + * addUpdateNode is responsible for creating or updating the node structure (depending on + * overlayParameters.rebuildInformationLayer) * * Supported: - * Currently it only supports information of Part::Geometry objects and implements calculations only for GeomBSplineCurve and GeomArc. + * Currently it only supports information of Part::Geometry objects and implements calculations only + * for GeomBSplineCurve and GeomArc. * * Caveats: - * - This class relies on the order of creation to perform the update. Any parallel execution that does not deterministically - * maintain the order will result in undefined behaviour. This provides a reasonable tradeoff between complexity and the fact that - * currently the information layer is generally so small that no parallel execution would actually result in a performance gain. + * - This class relies on the order of creation to perform the update. Any parallel execution that + * does not deterministically maintain the order will result in undefined behaviour. This provides a + * reasonable tradeoff between complexity and the fact that currently the information layer is + * generally so small that no parallel execution would actually result in a performance gain. * */ -class EditModeInformationOverlayCoinConverter { +class EditModeInformationOverlayCoinConverter +{ private: - enum class CalculationType { BSplineDegree, @@ -102,32 +108,37 @@ private: // // a struct Node template enables to define the VisualisationType and // the CalculationType so that uniform treatment can be provided - template< VisualisationType vtype, CalculationType ctype > - struct Node { + template + struct Node + { static constexpr VisualisationType visualisationType = vtype; static constexpr CalculationType calculationType = ctype; }; - template< CalculationType ctype > - struct NodeText : public Node { + template + struct NodeText: public Node + { std::vector strings; std::vector positions; }; - template< CalculationType ctype > - struct NodePolygon: public Node { + template + struct NodePolygon: public Node + { std::vector coordinates; std::vector indices; }; private: // Node Position in the Coin Scenograph for the different types of nodes - enum class TextNodePosition { + enum class TextNodePosition + { TextCoordinates = 0, TextInformation = 3 }; - enum class PolygonNodePosition { + enum class PolygonNodePosition + { PolygonCoordinates = 1, PolygonLineSet = 2 }; @@ -143,53 +154,52 @@ public: * @param overlayparameters: Parameters for controlling the overlay * @param drawingparameters: Parameters for drawing the overlay information */ - EditModeInformationOverlayCoinConverter( ViewProviderSketch &vp, - SoGroup * infogroup, - OverlayParameters & overlayparameters, - DrawingParameters & drawingparameters); + EditModeInformationOverlayCoinConverter(ViewProviderSketch& vp, SoGroup* infogroup, + OverlayParameters& overlayparameters, + DrawingParameters& drawingparameters); /** - * extracts information from the geometry and converts it into an information overlay in the - * SoGroup provided in the constructor. - * - * @param geometry: the geometry to be processed - */ - void convert(const Part::Geometry * geometry, int geoid); + * extracts information from the geometry and converts it into an information overlay in the + * SoGroup provided in the constructor. + * + * @param geometry: the geometry to be processed + */ + void convert(const Part::Geometry* geometry, int geoid); private: - template < CalculationType calculation > - void calculate(const Part::Geometry * geometry, [[maybe_unused]] int geoid); + template + void calculate(const Part::Geometry* geometry, [[maybe_unused]] int geoid); - template - void addUpdateNode(const Result & result); + template + void addUpdateNode(const Result& result); - template < CalculationType calculation > + template bool isVisible(); - template < typename Result > - void setPolygon(const Result & result, SoLineSet *polygonlineset, SoCoordinate3 *polygoncoords); + template + void setPolygon(const Result& result, SoLineSet* polygonlineset, SoCoordinate3* polygoncoords); - template < int line = 1 > - void setText(const std::string & string, SoText2 * text); + template + void setText(const std::string& string, SoText2* text); - void addToInfoGroup(SoSwitch * sw); + void addToInfoGroup(SoSwitch* sw); - template < typename Result > - void clearCalculation(Result & result); + template + void clearCalculation(Result& result); - template < typename Result> - void addNode(const Result & result); + template + void addNode(const Result& result); - template < typename Result > - void updateNode(const Result & result); + template + void updateNode(const Result& result); private: /// Reference to ViewProviderSketch in order to access the public and the Attorney Interface - ViewProviderSketch & viewProvider; + ViewProviderSketch& viewProvider; - SoGroup * infoGroup; - OverlayParameters & overlayParameters; - DrawingParameters & drawingParameters; + SoGroup* infoGroup; + OverlayParameters& overlayParameters; + DrawingParameters& drawingParameters; // Calculations NodeText degree; @@ -204,8 +214,7 @@ private: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_InformationOverlayCoinConverter_H - +#endif// SKETCHERGUI_InformationOverlayCoinConverter_H diff --git a/src/Mod/Sketcher/Gui/GeometryCreationMode.h b/src/Mod/Sketcher/Gui/GeometryCreationMode.h index 60b3c80f09..60f059be63 100644 --- a/src/Mod/Sketcher/Gui/GeometryCreationMode.h +++ b/src/Mod/Sketcher/Gui/GeometryCreationMode.h @@ -26,10 +26,11 @@ /***** Creation Mode ************/ namespace SketcherGui { - enum GeometryCreationMode { - Normal, - Construction - }; +enum GeometryCreationMode +{ + Normal, + Construction +}; } -#endif //SKETCHERGUI_GEOMETRYCREATIONMODE_H +#endif// SKETCHERGUI_GEOMETRYCREATIONMODE_H diff --git a/src/Mod/Sketcher/Gui/PreCompiled.cpp b/src/Mod/Sketcher/Gui/PreCompiled.cpp index 942976f8be..cde4369c5b 100644 --- a/src/Mod/Sketcher/Gui/PreCompiled.cpp +++ b/src/Mod/Sketcher/Gui/PreCompiled.cpp @@ -20,4 +20,4 @@ * * ***************************************************************************/ -#include "PreCompiled.h" +#include "PreCompiled.h" diff --git a/src/Mod/Sketcher/Gui/PreCompiled.h b/src/Mod/Sketcher/Gui/PreCompiled.h index 01322f9cb4..d0e9863c9b 100644 --- a/src/Mod/Sketcher/Gui/PreCompiled.h +++ b/src/Mod/Sketcher/Gui/PreCompiled.h @@ -26,7 +26,7 @@ #include #ifdef _MSC_VER -# pragma warning(disable : 4005) +#pragma warning(disable : 4005) #endif #ifdef _PreComp_ @@ -45,41 +45,41 @@ #include // Boost -#include #include +#include #ifdef FC_OS_WIN32 -# define NOMINMAX -# include +#define NOMINMAX +#include #endif // OpenCasCade #include #include -#include #include #include -#include -#include #include #include +#include +#include #include #include #include #include +#include // Qt #ifndef __QtAll__ -# include +#include #endif #include // all of Inventor #ifndef __InventorAll__ -# include +#include #endif -#endif //_PreComp_ +#endif//_PreComp_ -#endif // __PRECOMPILED_GUI__ +#endif// __PRECOMPILED_GUI__ diff --git a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp index 726d8c3fb8..d428ac6a96 100644 --- a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp +++ b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp @@ -1,30 +1,30 @@ /*************************************************************************** -* Copyright (c) 2014 Abdullah Tahiri * -* * -* This file is part of the FreeCAD CAx development system. * -* * -* This library is free software; you can redistribute it and/or * -* modify it under the terms of the GNU Library General Public * -* License as published by the Free Software Foundation; either * -* version 2 of the License, or (at your option) any later version. * -* * -* This library is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Library General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this library; see the file COPYING.LIB. If not, * -* write to the Free Software Foundation, Inc., 59 Temple Place, * -* Suite 330, Boston, MA 02111-1307, USA * -* * -***************************************************************************/ + * Copyright (c) 2014 Abdullah Tahiri * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU Library General Public License for more details. * + * * + * You should have received a copy of the GNU Library General Public * + * License along with this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include @@ -45,12 +45,11 @@ PropertyConstraintListItem::PropertyConstraintListItem() } PropertyConstraintListItem::~PropertyConstraintListItem() -{ -} +{} QVariant PropertyConstraintListItem::toString(const QVariant& prop) const { - const QList& value = prop.value< QList >(); + const QList& value = prop.value>(); QString str; QTextStream out(&str); out << "["; @@ -65,21 +64,21 @@ QVariant PropertyConstraintListItem::toString(const QVariant& prop) const void PropertyConstraintListItem::initialize() { - const Sketcher::PropertyConstraintList* list = static_cast(getPropertyData()[0]); - const std::vector< Sketcher::Constraint * > &vals = list->getValues(); + const Sketcher::PropertyConstraintList* list = + static_cast(getPropertyData()[0]); + const std::vector& vals = list->getValues(); int id = 1; int iNamed = 0; - std::vector unnamed; + std::vector unnamed; - for (std::vector< Sketcher::Constraint* >::const_iterator it = vals.begin();it != vals.end(); ++it, ++id) { - if ((*it)->Type == Sketcher::Distance || // Datum constraint - (*it)->Type == Sketcher::DistanceX || - (*it)->Type == Sketcher::DistanceY || - (*it)->Type == Sketcher::Radius || - (*it)->Type == Sketcher::Diameter || - (*it)->Type == Sketcher::Angle ) { + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++id) { + if ((*it)->Type == Sketcher::Distance ||// Datum constraint + (*it)->Type == Sketcher::DistanceX || (*it)->Type == Sketcher::DistanceY + || (*it)->Type == Sketcher::Radius || (*it)->Type == Sketcher::Diameter + || (*it)->Type == Sketcher::Angle) { PropertyUnitItem* item = static_cast(PropertyUnitItem::create()); @@ -108,7 +107,7 @@ void PropertyConstraintListItem::initialize() this->appendChild(item); } - item->bind(list->createPath(id-1)); + item->bind(list->createPath(id - 1)); item->setAutoApply(false); } } @@ -116,7 +115,9 @@ void PropertyConstraintListItem::initialize() // now deal with the unnamed if (iNamed == 0) { onlyUnnamed = true; - for (std::vector< PropertyUnitItem* >::const_iterator it = unnamed.begin();it != unnamed.end(); ++it) { + for (std::vector::const_iterator it = unnamed.begin(); + it != unnamed.end(); + ++it) { (*it)->setParent(this); this->appendChild((*it)); } @@ -124,12 +125,15 @@ void PropertyConstraintListItem::initialize() else { onlyUnnamed = false; if (!unnamed.empty()) { - PropertyConstraintListItem* item = static_cast(PropertyConstraintListItem::create()); + PropertyConstraintListItem* item = + static_cast(PropertyConstraintListItem::create()); item->setParent(this); item->setPropertyName(tr("Unnamed")); this->appendChild(item); - for (std::vector< PropertyUnitItem* >::const_iterator it = unnamed.begin();it != unnamed.end(); ++it) { + for (std::vector::const_iterator it = unnamed.begin(); + it != unnamed.end(); + ++it) { (*it)->setParent(item); item->appendChild((*it)); } @@ -145,8 +149,9 @@ void PropertyConstraintListItem::assignProperty(const App::Property* prop) if (!prop->getTypeId().isDerivedFrom(Sketcher::PropertyConstraintList::getClassTypeId())) return; - const Sketcher::PropertyConstraintList* list = static_cast(prop); - const std::vector< Sketcher::Constraint * > &vals = list->getValues(); + const Sketcher::PropertyConstraintList* list = + static_cast(prop); + const std::vector& vals = list->getValues(); // search for the group of unnamed items if available and take it out int numUnnamed = 0; @@ -166,19 +171,19 @@ void PropertyConstraintListItem::assignProperty(const App::Property* prop) int numNamed = this->childCount(); this->onlyUnnamed = true; - for (std::vector< Sketcher::Constraint* >::const_iterator it = vals.begin();it != vals.end(); ++it, ++id) { - if ((*it)->Type == Sketcher::Distance || // Datum constraint - (*it)->Type == Sketcher::DistanceX || - (*it)->Type == Sketcher::DistanceY || - (*it)->Type == Sketcher::Radius || - (*it)->Type == Sketcher::Diameter || - (*it)->Type == Sketcher::Angle ) { + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++id) { + if ((*it)->Type == Sketcher::Distance ||// Datum constraint + (*it)->Type == Sketcher::DistanceX || (*it)->Type == Sketcher::DistanceY + || (*it)->Type == Sketcher::Radius || (*it)->Type == Sketcher::Diameter + || (*it)->Type == Sketcher::Angle) { PropertyUnitItem* child = nullptr; if ((*it)->Name.empty()) { // search inside the group item for unnamed constraints if (!unnamed) { - unnamed = static_cast(PropertyConstraintListItem::create()); + unnamed = static_cast( + PropertyConstraintListItem::create()); unnamed->setPropertyName(tr("Unnamed")); } @@ -217,7 +222,7 @@ void PropertyConstraintListItem::assignProperty(const App::Property* prop) child->setPropertyName(name); child->setObjectName(internalName); - child->bind(list->createPath(id-1)); + child->bind(list->createPath(id - 1)); child->setAutoApply(false); } } @@ -232,7 +237,8 @@ void PropertyConstraintListItem::assignProperty(const App::Property* prop) QVariant PropertyConstraintListItem::value(const App::Property* prop) const { - assert(prop && prop->getTypeId().isDerivedFrom(Sketcher::PropertyConstraintList::getClassTypeId())); + assert(prop + && prop->getTypeId().isDerivedFrom(Sketcher::PropertyConstraintList::getClassTypeId())); PropertyConstraintListItem* self = const_cast(this); @@ -242,17 +248,17 @@ QVariant PropertyConstraintListItem::value(const App::Property* prop) const QList subquantities; bool onlyNamed = true; - const std::vector< Sketcher::Constraint * > &vals = static_cast(prop)->getValues(); - for (std::vector< Sketcher::Constraint* >::const_iterator it = vals.begin();it != vals.end(); ++it, ++id) { - if ((*it)->Type == Sketcher::Distance || // Datum constraint - (*it)->Type == Sketcher::DistanceX || - (*it)->Type == Sketcher::DistanceY || - (*it)->Type == Sketcher::Radius || - (*it)->Type == Sketcher::Diameter || - (*it)->Type == Sketcher::Angle ) { + const std::vector& vals = + static_cast(prop)->getValues(); + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++id) { + if ((*it)->Type == Sketcher::Distance ||// Datum constraint + (*it)->Type == Sketcher::DistanceX || (*it)->Type == Sketcher::DistanceY + || (*it)->Type == Sketcher::Radius || (*it)->Type == Sketcher::Diameter + || (*it)->Type == Sketcher::Angle) { Base::Quantity quant; - if ((*it)->Type == Sketcher::Angle ) { + if ((*it)->Type == Sketcher::Angle) { double datum = Base::toDegrees((*it)->getValue()); quant.setUnit(Base::Unit::Angle); quant.setValue(datum); @@ -271,11 +277,13 @@ QVariant PropertyConstraintListItem::value(const App::Property* prop) const if ((*it)->Name.empty() && !onlyUnnamed) { onlyNamed = false; subquantities.append(quant); - PropertyItem* child = self->child(self->childCount()-1); - PropertyConstraintListItem* unnamednode = qobject_cast(child); + PropertyItem* child = self->child(self->childCount() - 1); + PropertyConstraintListItem* unnamednode = + qobject_cast(child); if (unnamednode) { unnamednode->blockEvent = true; - unnamednode->setProperty(internalName.toLatin1(), QVariant::fromValue(quant)); + unnamednode->setProperty(internalName.toLatin1(), + QVariant::fromValue(quant)); unnamednode->blockEvent = false; } else { @@ -285,7 +293,8 @@ QVariant PropertyConstraintListItem::value(const App::Property* prop) const } else { self->blockEvent = true; - self->setProperty(internalName.toLatin1(), QVariant::fromValue(quant)); + self->setProperty(internalName.toLatin1(), + QVariant::fromValue(quant)); self->blockEvent = false; } } @@ -294,14 +303,14 @@ QVariant PropertyConstraintListItem::value(const App::Property* prop) const // The quantities of unnamed constraints are only needed for display purposes inside toString() if (!onlyUnnamed && !onlyNamed) { self->blockEvent = true; - self->setProperty("Unnamed", QVariant::fromValue< QList >(subquantities)); + self->setProperty("Unnamed", QVariant::fromValue>(subquantities)); self->blockEvent = false; } - return QVariant::fromValue< QList >(quantities); + return QVariant::fromValue>(quantities); } -bool PropertyConstraintListItem::event (QEvent* ev) +bool PropertyConstraintListItem::event(QEvent* ev) { if (ev->type() == QEvent::DynamicPropertyChange) { if (!blockEvent) { @@ -315,23 +324,24 @@ bool PropertyConstraintListItem::event (QEvent* ev) int id = 0; if (dynamic_cast(this->parent())) { - item = static_cast(this->parent()->getFirstProperty()); + item = static_cast( + this->parent()->getFirstProperty()); } else { item = static_cast(getFirstProperty()); } - const std::vector< Sketcher::Constraint * > &vals = item->getValues(); - for (std::vector< Sketcher::Constraint* >::const_iterator it = vals.begin();it != vals.end(); ++it, ++id) { - if ((*it)->Type == Sketcher::Distance || // Datum constraint - (*it)->Type == Sketcher::DistanceX || - (*it)->Type == Sketcher::DistanceY || - (*it)->Type == Sketcher::Radius || - (*it)->Type == Sketcher::Diameter || - (*it)->Type == Sketcher::Angle ) { + const std::vector& vals = item->getValues(); + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it, ++id) { + if ((*it)->Type == Sketcher::Distance ||// Datum constraint + (*it)->Type == Sketcher::DistanceX || (*it)->Type == Sketcher::DistanceY + || (*it)->Type == Sketcher::Radius || (*it)->Type == Sketcher::Diameter + || (*it)->Type == Sketcher::Angle) { // Get the internal name - QString internalName = QString::fromLatin1("Constraint%1").arg(id+1); + QString internalName = QString::fromLatin1("Constraint%1").arg(id + 1); if (internalName == propName) { double datum = quant.getValue(); if ((*it)->Type == Sketcher::Angle) @@ -355,25 +365,26 @@ void PropertyConstraintListItem::setValue(const QVariant& value) Q_UNUSED(value); } -QWidget* PropertyConstraintListItem::createEditor(QWidget* parent, const QObject* receiver, const char* method) const +QWidget* PropertyConstraintListItem::createEditor(QWidget* parent, const QObject* receiver, + const char* method) const { Q_UNUSED(receiver); Q_UNUSED(method); - QLineEdit *le = new QLineEdit(parent); + QLineEdit* le = new QLineEdit(parent); le->setFrame(false); le->setReadOnly(true); return le; } -void PropertyConstraintListItem::setEditorData(QWidget *editor, const QVariant& data) const +void PropertyConstraintListItem::setEditorData(QWidget* editor, const QVariant& data) const { QLineEdit* le = qobject_cast(editor); le->setText(toString(data).toString()); } -QVariant PropertyConstraintListItem::editorData(QWidget *editor) const +QVariant PropertyConstraintListItem::editorData(QWidget* editor) const { - QLineEdit *le = qobject_cast(editor); + QLineEdit* le = qobject_cast(editor); return QVariant(le->text()); } diff --git a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h index ad3f4fcb7d..23315b01cc 100644 --- a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h +++ b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h @@ -1,34 +1,35 @@ /*************************************************************************** -* Copyright (c) 2014 Abdullah Tahiri * -* * -* This file is part of the FreeCAD CAx development system. * -* * -* This library is free software; you can redistribute it and/or * -* modify it under the terms of the GNU Library General Public * -* License as published by the Free Software Foundation; either * -* version 2 of the License, or (at your option) any later version. * -* * -* This library is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Library General Public License for more details. * -* * -* You should have received a copy of the GNU Library General Public * -* License along with this library; see the file COPYING.LIB. If not, * -* write to the Free Software Foundation, Inc., 59 Temple Place, * -* Suite 330, Boston, MA 02111-1307, USA * -* * -***************************************************************************/ + * Copyright (c) 2014 Abdullah Tahiri * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU Library General Public License for more details. * + * * + * You should have received a copy of the GNU Library General Public * + * License along with this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ #ifndef PROPERTYCONSTRAINTLISTITEM_H #define PROPERTYCONSTRAINTLISTITEM_H -#include #include +#include #include -namespace SketcherGui { +namespace SketcherGui +{ class PropertyConstraintListItem: public Gui::PropertyEditor::PropertyItem { @@ -37,15 +38,16 @@ class PropertyConstraintListItem: public Gui::PropertyEditor::PropertyItem ~PropertyConstraintListItem() override; void assignProperty(const App::Property* prop) override; - QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; - void setEditorData(QWidget *editor, const QVariant& data) const override; - QVariant editorData(QWidget *editor) const override; + QWidget* createEditor(QWidget* parent, const QObject* receiver, + const char* method) const override; + void setEditorData(QWidget* editor, const QVariant& data) const override; + QVariant editorData(QWidget* editor) const override; protected: QVariant toString(const QVariant&) const override; QVariant value(const App::Property*) const override; void setValue(const QVariant&) override; - bool event (QEvent* ev) override; + bool event(QEvent* ev) override; void initialize() override; @@ -55,7 +57,7 @@ protected: bool onlyUnnamed; }; -} //namespace SketcherGui +}// namespace SketcherGui #endif diff --git a/src/Mod/Sketcher/Gui/PropertyVisualLayerList.cpp b/src/Mod/Sketcher/Gui/PropertyVisualLayerList.cpp index 0e78f38641..2f35d2b9f2 100644 --- a/src/Mod/Sketcher/Gui/PropertyVisualLayerList.cpp +++ b/src/Mod/Sketcher/Gui/PropertyVisualLayerList.cpp @@ -23,9 +23,9 @@ #include "PreCompiled.h" #include +#include #include #include -#include #include "PropertyVisualLayerList.h" @@ -36,7 +36,7 @@ using namespace std; using namespace SketcherGui; -TYPESYSTEM_SOURCE(SketcherGui::PropertyVisualLayerList , App::PropertyLists) +TYPESYSTEM_SOURCE(SketcherGui::PropertyVisualLayerList, App::PropertyLists) //************************************************************************** // Construction/Destruction @@ -48,29 +48,30 @@ PropertyVisualLayerList::~PropertyVisualLayerList() = default; //************************************************************************** // Base class implementer -PyObject *PropertyVisualLayerList::getPyObject() +PyObject* PropertyVisualLayerList::getPyObject() { THROWM(Base::NotImplementedError, "PropertyVisualLayerList has no python counterpart"); } -VisualLayer PropertyVisualLayerList::getPyValue(PyObject *item) const { +VisualLayer PropertyVisualLayerList::getPyValue(PyObject* item) const +{ - (void) item; + (void)item; THROWM(Base::NotImplementedError, "PropertyVisualLayerList has no python counterpart"); } -void PropertyVisualLayerList::Save (Base::Writer &writer) const +void PropertyVisualLayerList::Save(Base::Writer& writer) const { - writer.Stream() << writer.ind() << "" << endl; + writer.Stream() << writer.ind() << "" << endl; writer.incInd(); for (int i = 0; i < getSize(); i++) { _lValueList[i].Save(writer); } writer.decInd(); - writer.Stream() << writer.ind() << "" << endl ; + writer.Stream() << writer.ind() << "" << endl; } -void PropertyVisualLayerList::Restore(Base::XMLReader &reader) +void PropertyVisualLayerList::Restore(Base::XMLReader& reader) { reader.readElement("VisualLayerList"); // get the value of my attribute @@ -90,19 +91,19 @@ void PropertyVisualLayerList::Restore(Base::XMLReader &reader) setValues(std::move(layers)); } -Property *PropertyVisualLayerList::Copy() const +Property* PropertyVisualLayerList::Copy() const { - PropertyVisualLayerList *p= new PropertyVisualLayerList(); + PropertyVisualLayerList* p = new PropertyVisualLayerList(); p->_lValueList = _lValueList; return p; } -void PropertyVisualLayerList::Paste(const Property &from) +void PropertyVisualLayerList::Paste(const Property& from) { setValues(dynamic_cast(from)._lValueList); } -unsigned int PropertyVisualLayerList::getMemSize () const +unsigned int PropertyVisualLayerList::getMemSize() const { return static_cast(_lValueList.size() * sizeof(VisualLayer)); } diff --git a/src/Mod/Sketcher/Gui/PropertyVisualLayerList.h b/src/Mod/Sketcher/Gui/PropertyVisualLayerList.h index ec893f4c2f..dcbb05c2c8 100644 --- a/src/Mod/Sketcher/Gui/PropertyVisualLayerList.h +++ b/src/Mod/Sketcher/Gui/PropertyVisualLayerList.h @@ -32,7 +32,8 @@ #include "VisualLayer.h" -namespace Base { +namespace Base +{ class Writer; } @@ -44,7 +45,6 @@ class SketcherGuiExport PropertyVisualLayerList: public App::PropertyListsT +#include #endif #include "ShortcutListener.h" @@ -32,27 +32,26 @@ using namespace SketcherGui; // ******************** ViewProvider attorney *********************************************// -inline void ViewProviderSketchShortcutListenerAttorney::deleteSelected(ViewProviderSketch & vp) +inline void ViewProviderSketchShortcutListenerAttorney::deleteSelected(ViewProviderSketch& vp) { vp.deleteSelected(); }; // ******************** ShortcutListener *********************************************// -ShortcutListener::ShortcutListener(ViewProviderSketch * vp) +ShortcutListener::ShortcutListener(ViewProviderSketch* vp) { pViewProvider = vp; } ShortcutListener::~ShortcutListener() -{ -} +{} -bool ShortcutListener::eventFilter(QObject *obj, QEvent *event) { +bool ShortcutListener::eventFilter(QObject* obj, QEvent* event) +{ if (event->type() == QEvent::ShortcutOverride) { - QKeyEvent * kevent = static_cast(event); - if (kevent->modifiers() == Qt::NoModifier || - kevent->modifiers() == Qt::ShiftModifier || - kevent->modifiers() == Qt::KeypadModifier) { + QKeyEvent* kevent = static_cast(event); + if (kevent->modifiers() == Qt::NoModifier || kevent->modifiers() == Qt::ShiftModifier + || kevent->modifiers() == Qt::KeypadModifier) { switch (kevent->key()) { case Qt::Key_Delete: kevent->accept(); diff --git a/src/Mod/Sketcher/Gui/ShortcutListener.h b/src/Mod/Sketcher/Gui/ShortcutListener.h index 6bd4ab3796..6991859f90 100644 --- a/src/Mod/Sketcher/Gui/ShortcutListener.h +++ b/src/Mod/Sketcher/Gui/ShortcutListener.h @@ -26,13 +26,15 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; -class ViewProviderSketchShortcutListenerAttorney { +class ViewProviderSketchShortcutListenerAttorney +{ private: - static inline void deleteSelected(ViewProviderSketch &vp); + static inline void deleteSelected(ViewProviderSketch& vp); friend class ShortcutListener; @@ -40,20 +42,19 @@ private: class ShortcutListener: public QObject { - //Q_OBJECT + // Q_OBJECT public: - explicit ShortcutListener(ViewProviderSketch * vp); + explicit ShortcutListener(ViewProviderSketch* vp); ~ShortcutListener() override; protected: - bool eventFilter(QObject *obj, QEvent *event) override; + bool eventFilter(QObject* obj, QEvent* event) override; - ViewProviderSketch * pViewProvider; + ViewProviderSketch* pViewProvider; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_SHORTCUTLISTENER_H - +#endif// SKETCHERGUI_SHORTCUTLISTENER_H diff --git a/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp b/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp index 44884a7f70..33714f8f6c 100644 --- a/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp @@ -22,43 +22,42 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include -#include "ui_SketchMirrorDialog.h" #include "SketchMirrorDialog.h" +#include "ui_SketchMirrorDialog.h" using namespace SketcherGui; SketchMirrorDialog::SketchMirrorDialog() - : QDialog(Gui::getMainWindow()) - , RefGeoid(-1) - , RefPosid(Sketcher::PointPos::none) - , ui(new Ui_SketchMirrorDialog) + : QDialog(Gui::getMainWindow()) + , RefGeoid(-1) + , RefPosid(Sketcher::PointPos::none) + , ui(new Ui_SketchMirrorDialog) { ui->setupUi(this); } SketchMirrorDialog::~SketchMirrorDialog() -{ -} +{} void SketchMirrorDialog::accept() { if (ui->XAxisRadioButton->isChecked()) { - RefGeoid=Sketcher::GeoEnum::HAxis; - RefPosid=Sketcher::PointPos::none; + RefGeoid = Sketcher::GeoEnum::HAxis; + RefPosid = Sketcher::PointPos::none; } else if (ui->YAxisRadioButton->isChecked()) { - RefGeoid=Sketcher::GeoEnum::VAxis; - RefPosid=Sketcher::PointPos::none; + RefGeoid = Sketcher::GeoEnum::VAxis; + RefPosid = Sketcher::PointPos::none; } else if (ui->OriginRadioButton->isChecked()) { - RefGeoid=Sketcher::GeoEnum::RtPnt; - RefPosid=Sketcher::PointPos::start; + RefGeoid = Sketcher::GeoEnum::RtPnt; + RefPosid = Sketcher::PointPos::start; } QDialog::accept(); diff --git a/src/Mod/Sketcher/Gui/SketchMirrorDialog.h b/src/Mod/Sketcher/Gui/SketchMirrorDialog.h index c0cc513cf4..e8e00a61d6 100644 --- a/src/Mod/Sketcher/Gui/SketchMirrorDialog.h +++ b/src/Mod/Sketcher/Gui/SketchMirrorDialog.h @@ -28,10 +28,11 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ class Ui_SketchMirrorDialog; -class SketchMirrorDialog : public QDialog +class SketchMirrorDialog: public QDialog { Q_OBJECT @@ -48,6 +49,6 @@ private: std::unique_ptr ui; }; -} +}// namespace SketcherGui -#endif // SKETCHERGUI_SketchMirrorDialog_H +#endif// SKETCHERGUI_SketchMirrorDialog_H diff --git a/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp b/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp index 7c7469b672..5c7d84e3b8 100644 --- a/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp @@ -22,34 +22,34 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include #include -#include "ui_SketchOrientationDialog.h" #include "SketchOrientationDialog.h" +#include "ui_SketchOrientationDialog.h" using namespace SketcherGui; SketchOrientationDialog::SketchOrientationDialog() - : QDialog(Gui::getMainWindow()), ui(new Ui_SketchOrientationDialog) + : QDialog(Gui::getMainWindow()) + , ui(new Ui_SketchOrientationDialog) { DirType = 0; ui->setupUi(this); onPreview(); connect(ui->Reverse_checkBox, &QCheckBox::clicked, this, &SketchOrientationDialog::onPreview); - connect(ui->XY_radioButton , &QRadioButton::clicked, this, &SketchOrientationDialog::onPreview); - connect(ui->XZ_radioButton , &QRadioButton::clicked, this, &SketchOrientationDialog::onPreview); - connect(ui->YZ_radioButton , &QRadioButton::clicked, this, &SketchOrientationDialog::onPreview); + connect(ui->XY_radioButton, &QRadioButton::clicked, this, &SketchOrientationDialog::onPreview); + connect(ui->XZ_radioButton, &QRadioButton::clicked, this, &SketchOrientationDialog::onPreview); + connect(ui->YZ_radioButton, &QRadioButton::clicked, this, &SketchOrientationDialog::onPreview); } SketchOrientationDialog::~SketchOrientationDialog() -{ -} +{} void SketchOrientationDialog::accept() { @@ -57,31 +57,32 @@ void SketchOrientationDialog::accept() bool reverse = ui->Reverse_checkBox->isChecked(); if (ui->XY_radioButton->isChecked()) { if (reverse) { - Pos = Base::Placement(Base::Vector3d(0,0,offset),Base::Rotation(1.0,0.0,0.0,0.0)); + Pos = Base::Placement(Base::Vector3d(0, 0, offset), Base::Rotation(1.0, 0.0, 0.0, 0.0)); DirType = 1; } else { - Pos = Base::Placement(Base::Vector3d(0,0,offset),Base::Rotation()); + Pos = Base::Placement(Base::Vector3d(0, 0, offset), Base::Rotation()); DirType = 0; } } else if (ui->XZ_radioButton->isChecked()) { if (reverse) { - Pos = Base::Placement(Base::Vector3d(0,offset,0),Base::Rotation(0.0,1.0,1.0,0.0)); + Pos = Base::Placement(Base::Vector3d(0, offset, 0), Base::Rotation(0.0, 1.0, 1.0, 0.0)); DirType = 3; } else { - Pos = Base::Placement(Base::Vector3d(0,offset,0),Base::Rotation(1.0,0.0,0.0,1.0)); + Pos = Base::Placement(Base::Vector3d(0, offset, 0), Base::Rotation(1.0, 0.0, 0.0, 1.0)); DirType = 2; } } else if (ui->YZ_radioButton->isChecked()) { if (reverse) { - Pos = Base::Placement(Base::Vector3d(offset,0,0),Base::Rotation(-1.0,1.0,1.0,-1.0)); + Pos = + Base::Placement(Base::Vector3d(offset, 0, 0), Base::Rotation(-1.0, 1.0, 1.0, -1.0)); DirType = 5; } else { - Pos = Base::Placement(Base::Vector3d(offset,0,0),Base::Rotation(1.0,1.0,1.0,1.0)); + Pos = Base::Placement(Base::Vector3d(offset, 0, 0), Base::Rotation(1.0, 1.0, 1.0, 1.0)); DirType = 4; } } @@ -113,8 +114,7 @@ void SketchOrientationDialog::onPreview() } ui->previewLabel->setPixmap( - Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), - ui->previewLabel->size())); + Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size())); } #include "moc_SketchOrientationDialog.cpp" diff --git a/src/Mod/Sketcher/Gui/SketchOrientationDialog.h b/src/Mod/Sketcher/Gui/SketchOrientationDialog.h index 4ba415b3b1..0713329536 100644 --- a/src/Mod/Sketcher/Gui/SketchOrientationDialog.h +++ b/src/Mod/Sketcher/Gui/SketchOrientationDialog.h @@ -29,10 +29,11 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ class Ui_SketchOrientationDialog; -class SketcherGuiExport SketchOrientationDialog : public QDialog +class SketcherGuiExport SketchOrientationDialog: public QDialog { Q_OBJECT @@ -41,7 +42,7 @@ public: ~SketchOrientationDialog() override; Base::Placement Pos; - int DirType; + int DirType; void accept() override; @@ -52,6 +53,6 @@ private: std::unique_ptr ui; }; -} +}// namespace SketcherGui -#endif // SKETCHERGUI_SketchOrientationDialog_H +#endif// SKETCHERGUI_SketchOrientationDialog_H diff --git a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp index 2e747b2f2f..d7ec332f87 100644 --- a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp @@ -22,34 +22,34 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include -#include "ui_SketchRectangularArrayDialog.h" #include "SketchRectangularArrayDialog.h" +#include "ui_SketchRectangularArrayDialog.h" using namespace SketcherGui; SketchRectangularArrayDialog::SketchRectangularArrayDialog() - : QDialog(Gui::getMainWindow()), ui(new Ui_SketchRectangularArrayDialog) + : QDialog(Gui::getMainWindow()) + , ui(new Ui_SketchRectangularArrayDialog) { ui->setupUi(this); - + ui->RowsQuantitySpinBox->onRestore(); ui->ColsQuantitySpinBox->onRestore(); ui->ConstraintSeparationCheckBox->onRestore(); ui->EqualVerticalHorizontalSpacingCheckBox->onRestore(); ui->CloneCheckBox->onRestore(); - + updateValues(); } SketchRectangularArrayDialog::~SketchRectangularArrayDialog() -{ -} +{} void SketchRectangularArrayDialog::accept() { @@ -58,9 +58,9 @@ void SketchRectangularArrayDialog::accept() ui->ConstraintSeparationCheckBox->onSave(); ui->EqualVerticalHorizontalSpacingCheckBox->onSave(); ui->CloneCheckBox->onSave(); - + updateValues(); - + QDialog::accept(); } @@ -70,7 +70,7 @@ void SketchRectangularArrayDialog::updateValues() Cols = ui->ColsQuantitySpinBox->value(); ConstraintSeparation = ui->ConstraintSeparationCheckBox->isChecked(); EqualVerticalHorizontalSpacing = ui->EqualVerticalHorizontalSpacingCheckBox->isChecked(); - Clone = ui->CloneCheckBox->isChecked(); + Clone = ui->CloneCheckBox->isChecked(); } #include "moc_SketchRectangularArrayDialog.cpp" diff --git a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h index 269f9cc057..b2f7ad7253 100644 --- a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h +++ b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h @@ -26,10 +26,11 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ class Ui_SketchRectangularArrayDialog; -class SketchRectangularArrayDialog : public QDialog +class SketchRectangularArrayDialog: public QDialog { Q_OBJECT @@ -38,7 +39,7 @@ public: ~SketchRectangularArrayDialog() override; void accept() override; - + int Rows; int Cols; bool ConstraintSeparation; @@ -47,10 +48,11 @@ public: protected: void updateValues(); + private: std::unique_ptr ui; }; -} +}// namespace SketcherGui -#endif // SKETCHERGUI_SketchRectangularArrayDialog_H +#endif// SKETCHERGUI_SketchRectangularArrayDialog_H diff --git a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp index 7757cd1b45..eeb6895524 100644 --- a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp @@ -22,19 +22,20 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include -#include "ui_SketcherRegularPolygonDialog.h" #include "SketcherRegularPolygonDialog.h" +#include "ui_SketcherRegularPolygonDialog.h" using namespace SketcherGui; SketcherRegularPolygonDialog::SketcherRegularPolygonDialog() -: QDialog(Gui::getMainWindow()), ui(new Ui_SketcherRegularPolygonDialog) + : QDialog(Gui::getMainWindow()) + , ui(new Ui_SketcherRegularPolygonDialog) { ui->setupUi(this); @@ -44,8 +45,7 @@ SketcherRegularPolygonDialog::SketcherRegularPolygonDialog() } SketcherRegularPolygonDialog::~SketcherRegularPolygonDialog() -{ -} +{} void SketcherRegularPolygonDialog::accept() { diff --git a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h index 0001898f49..2bd78100c1 100644 --- a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h +++ b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h @@ -26,10 +26,11 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ class Ui_SketcherRegularPolygonDialog; -class SketcherRegularPolygonDialog : public QDialog +class SketcherRegularPolygonDialog: public QDialog { Q_OBJECT @@ -43,10 +44,11 @@ public: protected: void updateValues(); + private: std::unique_ptr ui; }; -} +}// namespace SketcherGui -#endif // SKETCHERGUI_SketcherRegularPolygonDialog_H +#endif// SKETCHERGUI_SketcherRegularPolygonDialog_H diff --git a/src/Mod/Sketcher/Gui/SketcherSettings.cpp b/src/Mod/Sketcher/Gui/SketcherSettings.cpp index 38b30c3a46..0381280338 100644 --- a/src/Mod/Sketcher/Gui/SketcherSettings.cpp +++ b/src/Mod/Sketcher/Gui/SketcherSettings.cpp @@ -22,9 +22,9 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +#include +#include +#include #endif #include @@ -34,10 +34,9 @@ #include "SketcherSettings.h" #include "ui_SketcherSettings.h" -#include "ui_SketcherSettingsGrid.h" -#include "ui_SketcherSettingsDisplay.h" #include "ui_SketcherSettingsColors.h" #include "ui_SketcherSettingsDisplay.h" +#include "ui_SketcherSettingsGrid.h" using namespace SketcherGui; @@ -45,7 +44,8 @@ using namespace SketcherGui; /* TRANSLATOR SketcherGui::SketcherSettings */ SketcherSettings::SketcherSettings(QWidget* parent) - : PreferencePage(parent), ui(new Ui_SketcherSettings) + : PreferencePage(parent) + , ui(new Ui_SketcherSettings) { ui->setupUi(this); } @@ -81,7 +81,7 @@ void SketcherSettings::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void SketcherSettings::changeEvent(QEvent *e) +void SketcherSettings::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -94,18 +94,18 @@ void SketcherSettings::changeEvent(QEvent *e) /* TRANSLATOR SketcherGui::SketcherSettingsGrid */ SketcherSettingsGrid::SketcherSettingsGrid(QWidget* parent) - : PreferencePage(parent), ui(new Ui_SketcherSettingsGrid) + : PreferencePage(parent) + , ui(new Ui_SketcherSettingsGrid) { ui->setupUi(this); - QList < QPair > styles; - styles << qMakePair(Qt::SolidLine, 0xffff) - << qMakePair(Qt::DashLine, 0x0f0f) - << qMakePair(Qt::DotLine, 0xaaaa); + QList> styles; + styles << qMakePair(Qt::SolidLine, 0xffff) << qMakePair(Qt::DashLine, 0x0f0f) + << qMakePair(Qt::DotLine, 0xaaaa); ui->gridLinePattern->setIconSize(QSize(80, 12)); ui->gridDivLinePattern->setIconSize(QSize(80, 12)); - for (QList < QPair >::iterator it = styles.begin(); it != styles.end(); ++it) { + for (QList>::iterator it = styles.begin(); it != styles.end(); ++it) { QPixmap px(ui->gridLinePattern->iconSize()); px.fill(Qt::transparent); QBrush brush(Qt::black); @@ -141,7 +141,8 @@ void SketcherSettingsGrid::saveSettings() ui->gridDivLineWidth->onSave(); ui->gridNumberSubdivision->onSave(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); QVariant data = ui->gridLinePattern->itemData(ui->gridLinePattern->currentIndex()); int pattern = data.toInt(); hGrp->SetInt("GridLinePattern", pattern); @@ -163,14 +164,17 @@ void SketcherSettingsGrid::loadSettings() ui->gridDivLineWidth->onRestore(); ui->gridNumberSubdivision->onRestore(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); int pattern = hGrp->GetInt("GridLinePattern", 0x0f0f); int index = ui->gridLinePattern->findData(QVariant(pattern)); - if (index < 0) index = 1; + if (index < 0) + index = 1; ui->gridLinePattern->setCurrentIndex(index); pattern = hGrp->GetInt("GridDivLinePattern", 0xffff); index = ui->gridDivLinePattern->findData(QVariant(pattern)); - if (index < 0) index = 0; + if (index < 0) + index = 0; ui->gridDivLinePattern->setCurrentIndex(index); } @@ -190,11 +194,13 @@ void SketcherSettingsGrid::changeEvent(QEvent* e) /* TRANSLATOR SketcherGui::SketcherSettingsDisplay */ SketcherSettingsDisplay::SketcherSettingsDisplay(QWidget* parent) - : PreferencePage(parent), ui(new Ui_SketcherSettingsDisplay) + : PreferencePage(parent) + , ui(new Ui_SketcherSettingsDisplay) { ui->setupUi(this); - connect(ui->btnTVApply, &QPushButton::clicked, this, &SketcherSettingsDisplay::onBtnTVApplyClicked); + connect( + ui->btnTVApply, &QPushButton::clicked, this, &SketcherSettingsDisplay::onBtnTVApplyClicked); } /** @@ -251,7 +257,7 @@ void SketcherSettingsDisplay::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void SketcherSettingsDisplay::changeEvent(QEvent *e) +void SketcherSettingsDisplay::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -264,40 +270,42 @@ void SketcherSettingsDisplay::changeEvent(QEvent *e) void SketcherSettingsDisplay::onBtnTVApplyClicked(bool) { QString errMsg; - try{ + try { Gui::Command::doCommand(Gui::Command::Gui, - "for name,doc in App.listDocuments().items():\n" - " for sketch in doc.findObjects('Sketcher::SketchObject'):\n" - " sketch.ViewObject.HideDependent = %s\n" - " sketch.ViewObject.ShowLinks = %s\n" - " sketch.ViewObject.ShowSupport = %s\n" - " sketch.ViewObject.RestoreCamera = %s\n" - " sketch.ViewObject.ForceOrtho = %s\n" - " sketch.ViewObject.SectionView = %s\n", - this->ui->checkBoxTVHideDependent->isChecked() ? "True": "False", - this->ui->checkBoxTVShowLinks->isChecked() ? "True": "False", - this->ui->checkBoxTVShowSupport->isChecked() ? "True": "False", - this->ui->checkBoxTVRestoreCamera->isChecked() ? "True": "False", - this->ui->checkBoxTVForceOrtho->isChecked() ? "True": "False", - this->ui->checkBoxTVSectionView->isChecked() ? "True": "False"); - } catch (Base::PyException &e){ + "for name,doc in App.listDocuments().items():\n" + " for sketch in doc.findObjects('Sketcher::SketchObject'):\n" + " sketch.ViewObject.HideDependent = %s\n" + " sketch.ViewObject.ShowLinks = %s\n" + " sketch.ViewObject.ShowSupport = %s\n" + " sketch.ViewObject.RestoreCamera = %s\n" + " sketch.ViewObject.ForceOrtho = %s\n" + " sketch.ViewObject.SectionView = %s\n", + this->ui->checkBoxTVHideDependent->isChecked() ? "True" : "False", + this->ui->checkBoxTVShowLinks->isChecked() ? "True" : "False", + this->ui->checkBoxTVShowSupport->isChecked() ? "True" : "False", + this->ui->checkBoxTVRestoreCamera->isChecked() ? "True" : "False", + this->ui->checkBoxTVForceOrtho->isChecked() ? "True" : "False", + this->ui->checkBoxTVSectionView->isChecked() ? "True" : "False"); + } + catch (Base::PyException& e) { Base::Console().DeveloperError("SketcherSettings", "error in onBtnTVApplyClicked:\n"); e.ReportException(); errMsg = QString::fromLatin1(e.what()); - } catch (...) { + } + catch (...) { errMsg = tr("Unexpected C++ exception"); } - if(errMsg.length()>0){ - QMessageBox::warning(this, tr("Sketcher"),errMsg); + if (errMsg.length() > 0) { + QMessageBox::warning(this, tr("Sketcher"), errMsg); } } - /* TRANSLATOR SketcherGui::SketcherSettingsColors */ SketcherSettingsColors::SketcherSettingsColors(QWidget* parent) - : PreferencePage(parent), ui(new Ui_SketcherSettingsColors) + : PreferencePage(parent) + , ui(new Ui_SketcherSettingsColors) { ui->setupUi(this); } @@ -369,7 +377,7 @@ void SketcherSettingsColors::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void SketcherSettingsColors::changeEvent(QEvent *e) +void SketcherSettingsColors::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -380,4 +388,3 @@ void SketcherSettingsColors::changeEvent(QEvent *e) } #include "moc_SketcherSettings.cpp" - diff --git a/src/Mod/Sketcher/Gui/SketcherSettings.h b/src/Mod/Sketcher/Gui/SketcherSettings.h index bc441a8e16..3a65ca1243 100644 --- a/src/Mod/Sketcher/Gui/SketcherSettings.h +++ b/src/Mod/Sketcher/Gui/SketcherSettings.h @@ -23,11 +23,12 @@ #ifndef SKETCHERGUI_SKETCHERSETTINGS_H #define SKETCHERGUI_SKETCHERSETTINGS_H -#include #include +#include -namespace SketcherGui { +namespace SketcherGui +{ class Ui_SketcherSettings; class Ui_SketcherSettingsGrid; class Ui_SketcherSettingsDisplay; @@ -37,7 +38,7 @@ class SketcherGeneralWidget; * The SketcherSettings class implements a preference page to change sketcher settings. * @author Werner Mayer */ -class SketcherSettings : public Gui::Dialog::PreferencePage +class SketcherSettings: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -49,7 +50,7 @@ public: void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; @@ -58,7 +59,7 @@ private: /** * The SketcherSettings class implements a preference page to change sketcher grid settings. */ -class SketcherSettingsGrid : public Gui::Dialog::PreferencePage +class SketcherSettingsGrid: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -70,7 +71,7 @@ public: void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; @@ -80,7 +81,7 @@ private: * The SketcherSettings class implements a preference page to change sketcher display settings. * @author Werner Mayer */ -class SketcherSettingsDisplay : public Gui::Dialog::PreferencePage +class SketcherSettingsDisplay: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -92,7 +93,7 @@ public: void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private Q_SLOTS: void onBtnTVApplyClicked(bool); @@ -105,7 +106,7 @@ private: * The SketcherSettings class implements a preference page to change sketcher settings. * @author Werner Mayer */ -class SketcherSettingsColors : public Gui::Dialog::PreferencePage +class SketcherSettingsColors: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -117,12 +118,12 @@ public: void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_SKETCHERSETTINGS_H +#endif// SKETCHERGUI_SKETCHERSETTINGS_H diff --git a/src/Mod/Sketcher/Gui/SnapManager.cpp b/src/Mod/Sketcher/Gui/SnapManager.cpp index 0b0e8fa587..d12793cf29 100644 --- a/src/Mod/Sketcher/Gui/SnapManager.cpp +++ b/src/Mod/Sketcher/Gui/SnapManager.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ #include -#endif // #ifndef _PreComp_ +#endif// #ifndef _PreComp_ #include @@ -52,7 +52,8 @@ inline int ViewProviderSketchSnapAttorney::getPreselectCurve(const ViewProviderS } /**************************** ParameterObserver nested class *****************************/ -SnapManager::ParameterObserver::ParameterObserver(SnapManager& client) : client(client) +SnapManager::ParameterObserver::ParameterObserver(SnapManager& client) + : client(client) { initParameters(); subscribeToParameters(); @@ -71,13 +72,21 @@ void SnapManager::ParameterObserver::initParameters() // key->second => Update function to be called for the parameter, str2updatefunction = { {"Snap", - [this](const std::string& param) {updateSnapParameter(param); }}, + [this](const std::string& param) { + updateSnapParameter(param); + }}, {"SnapToObjects", - [this](const std::string& param) {updateSnapToObjectParameter(param); }}, + [this](const std::string& param) { + updateSnapToObjectParameter(param); + }}, {"SnapToGrid", - [this](const std::string& param) {updateSnapToGridParameter(param); }}, + [this](const std::string& param) { + updateSnapToGridParameter(param); + }}, {"SnapAngle", - [this](const std::string& param) {updateSnapAngleParameter(param); }}, + [this](const std::string& param) { + updateSnapAngleParameter(param); + }}, }; for (auto& val : str2updatefunction) { @@ -122,7 +131,8 @@ void SnapManager::ParameterObserver::subscribeToParameters() ParameterGrp::handle hGrp = getParameterGrpHandle(); hGrp->Attach(this); } - catch (const Base::ValueError& e) { // ensure that if parameter strings are not well-formed, the exception is not propagated + catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the + // exception is not propagated Base::Console().DeveloperError("SnapManager", "Malformed parameter string: %s\n", e.what()); } } @@ -133,12 +143,15 @@ void SnapManager::ParameterObserver::unsubscribeToParameters() ParameterGrp::handle hGrp = getParameterGrpHandle(); hGrp->Detach(this); } - catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the program is not terminated when calling the noexcept destructor. + catch (const Base::ValueError& + e) {// ensure that if parameter strings are not well-formed, the program is not + // terminated when calling the noexcept destructor. Base::Console().DeveloperError("SnapManager", "Malformed parameter string: %s\n", e.what()); } } -void SnapManager::ParameterObserver::OnChange(Base::Subject& rCaller, const char* sReason) +void SnapManager::ParameterObserver::OnChange(Base::Subject& rCaller, + const char* sReason) { (void)rCaller; @@ -153,27 +166,32 @@ void SnapManager::ParameterObserver::OnChange(Base::Subject& rCalle ParameterGrp::handle SnapManager::ParameterObserver::getParameterGrpHandle() { - return App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); + return App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); } //**************************** SnapManager class ****************************** -SnapManager::SnapManager(ViewProviderSketch &vp):viewProvider(vp), angleSnapRequested(false), referencePoint(Base::Vector2d(0.,0.)), lastMouseAngle(0.0) +SnapManager::SnapManager(ViewProviderSketch& vp) + : viewProvider(vp) + , angleSnapRequested(false) + , referencePoint(Base::Vector2d(0., 0.)) + , lastMouseAngle(0.0) { // Create parameter observer and initialise watched parameters pObserver = std::make_unique(*this); } -SnapManager::~SnapManager() {} +SnapManager::~SnapManager() +{} bool SnapManager::snap(double& x, double& y) { - if (!snapRequested) - { + if (!snapRequested) { return false; } - //In order of priority : + // In order of priority : // 1 - Snap at an angle if (angleSnapRequested && QApplication::keyboardModifiers() == Qt::ControlModifier) { @@ -184,13 +202,14 @@ bool SnapManager::snap(double& x, double& y) } // 2 - Snap to objects - if (snapToObjectsRequested - && snapToObject(x, y)) { + if (snapToObjectsRequested && snapToObject(x, y)) { return true; } - + // 3 - Snap to grid - if (snapToGridRequested /*&& viewProvider.ShowGrid.getValue() */ ) { //Snap to grid is enabled even if the grid is not visible. + if (snapToGridRequested /*&& viewProvider.ShowGrid.getValue() */) {// Snap to grid is enabled + // even if the grid is not + // visible. return snapToGrid(x, y); } @@ -237,15 +256,15 @@ bool SnapManager::snapToObject(double& x, double& y) y = Obj->getPoint(geoId, posId).y; return true; } - else if (CrsId == 1) { //H_Axis + else if (CrsId == 1) {// H_Axis y = 0; return true; } - else if (CrsId == 2) { //V_Axis + else if (CrsId == 2) {// V_Axis x = 0; return true; } - else if (CrvId >= 0 || CrvId <= Sketcher::GeoEnum::RefExt) { //Curves + else if (CrvId >= 0 || CrvId <= Sketcher::GeoEnum::RefExt) {// Curves const Part::Geometry* geo = Obj->getGeometry(CrvId); @@ -263,13 +282,13 @@ bool SnapManager::snapToObject(double& x, double& y) return false; } - //If it is a line, then we check if we need to snap to the middle. + // If it is a line, then we check if we need to snap to the middle. if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment* line = static_cast(geo); snapToLineMiddle(pointToOverride, line); } - //If it is an arc, then we check if we need to snap to the middle (not the center). + // If it is an arc, then we check if we need to snap to the middle (not the center). if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle* arc = static_cast(geo); snapToArcMiddle(pointToOverride, arc); @@ -298,26 +317,27 @@ bool SnapManager::snapToGrid(double& x, double& y) // Check if x within snap tolerance if (x < tmpX + snapTol && x > tmpX - snapTol) { - x = tmpX; // Snap X Mouse Position + x = tmpX;// Snap X Mouse Position snapped = true; } - // Check if y within snap tolerance + // Check if y within snap tolerance if (y < tmpY + snapTol && y > tmpY - snapTol) { - y = tmpY; // Snap Y Mouse Position + y = tmpY;// Snap Y Mouse Position snapped = true; } return snapped; } -bool SnapManager::snapToLineMiddle(Base::Vector3d& pointToOverride, const Part::GeomLineSegment* line) +bool SnapManager::snapToLineMiddle(Base::Vector3d& pointToOverride, + const Part::GeomLineSegment* line) { Base::Vector3d startPoint = line->getStartPoint(); Base::Vector3d endPoint = line->getEndPoint(); Base::Vector3d midPoint = (startPoint + endPoint) / 2; - //Check if we are at middle of the line and if so snap to it. + // Check if we are at middle of the line and if so snap to it. if ((pointToOverride - midPoint).Length() < (endPoint - startPoint).Length() * 0.05) { pointToOverride = midPoint; return true; @@ -353,8 +373,9 @@ bool SnapManager::snapToArcMiddle(Base::Vector3d& pointToOverride, const Part::G int revert = angle < M_PI ? 1 : -1; /*To know if we are close to the middle of the arc, we are going to compare the angle of the - * (mouse cursor - center) to the angle of the middle of the arc. If it's less than 10% of the arc angle, then we snap. - */ + * (mouse cursor - center) to the angle of the middle of the arc. If it's less than 10% of the + * arc angle, then we snap. + */ if (fabs(pVec.Angle() - (revert * mVec).Angle()) < 0.10 * angle) { pointToOverride = centerPoint + middleVec * revert; return true; diff --git a/src/Mod/Sketcher/Gui/SnapManager.h b/src/Mod/Sketcher/Gui/SnapManager.h index 8fc4a7134a..a02936b11c 100644 --- a/src/Mod/Sketcher/Gui/SnapManager.h +++ b/src/Mod/Sketcher/Gui/SnapManager.h @@ -28,14 +28,15 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; -class ViewProviderSketchSnapAttorney { +class ViewProviderSketchSnapAttorney +{ private: - static inline int getPreselectPoint(const ViewProviderSketch& vp); static inline int getPreselectCross(const ViewProviderSketch& vp); static inline int getPreselectCurve(const ViewProviderSketch& vp); @@ -44,23 +45,23 @@ private: }; /* This class is used to manage the overriding of mouse pointer coordinates in Sketcher -* (in Edit-Mode) depending on the situation. Those situations are in priority order : -* 1 - Snap at angle: For tools like Slot, Arc, Line, Ellipse, this enables to constrain the angle at steps of 5° (or customized angle). -* This is useful to make features at a certain angle (45° for example) -* 2 - Snap to object: This snaps the mouse pointer onto objects. -* 3 - Snap to grid: This snaps the mouse pointer on the grid. -*/ + * (in Edit-Mode) depending on the situation. Those situations are in priority order : + * 1 - Snap at angle: For tools like Slot, Arc, Line, Ellipse, this enables to constrain the angle + * at steps of 5° (or customized angle). This is useful to make features at a certain angle (45° for + * example) 2 - Snap to object: This snaps the mouse pointer onto objects. 3 - Snap to grid: This + * snaps the mouse pointer on the grid. + */ class SnapManager { /** @brief Class for monitoring changes in parameters affecting Snapping - * @details - * - * This nested class is a helper responsible for attaching to the parameters relevant for - * SnapManager, initialising the SnapManager to the current configuration - * and handle in real time any change to their values. - */ - class ParameterObserver : public ParameterGrp::ObserverType + * @details + * + * This nested class is a helper responsible for attaching to the parameters relevant for + * SnapManager, initialising the SnapManager to the current configuration + * and handle in real time any change to their values. + */ + class ParameterObserver: public ParameterGrp::ObserverType { public: explicit ParameterObserver(SnapManager& client); @@ -88,7 +89,7 @@ class SnapManager }; public: - explicit SnapManager(ViewProviderSketch &vp); + explicit SnapManager(ViewProviderSketch& vp); ~SnapManager(); bool snap(double& x, double& y); @@ -103,7 +104,7 @@ public: private: /// Reference to ViewProviderSketch in order to access the public and the Attorney Interface - ViewProviderSketch & viewProvider; + ViewProviderSketch& viewProvider; bool angleSnapRequested; bool snapRequested; @@ -120,8 +121,7 @@ private: }; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_SnapManager_H - +#endif// SKETCHERGUI_SnapManager_H diff --git a/src/Mod/Sketcher/Gui/SoZoomTranslation.cpp b/src/Mod/Sketcher/Gui/SoZoomTranslation.cpp index 1f19dc20f5..c1981f7a68 100644 --- a/src/Mod/Sketcher/Gui/SoZoomTranslation.cpp +++ b/src/Mod/Sketcher/Gui/SoZoomTranslation.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 #endif #include "SoZoomTranslation.h" @@ -71,28 +71,31 @@ float SoZoomTranslation::calculateScaleFactor(SoAction* action) const // Dividing by 5 seems to work well SbViewVolume vv = SoViewVolumeElement::get(action->getState()); float aspectRatio = SoViewportRegionElement::get(action->getState()).getViewportAspectRatio(); - scaleFactor = vv.getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) / (5*aspectRatio); + scaleFactor = vv.getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) / (5 * aspectRatio); return scaleFactor; } -SoZoomTranslation::SoZoomTranslation(): scaleFactor(0) +SoZoomTranslation::SoZoomTranslation() + : scaleFactor(0) { SO_NODE_CONSTRUCTOR(SoZoomTranslation); - SO_NODE_ADD_FIELD(abPos, (SbVec3f(0.f,0.f,0.f))); + SO_NODE_ADD_FIELD(abPos, (SbVec3f(0.f, 0.f, 0.f))); } -void SoZoomTranslation::GLRender(SoGLRenderAction * action) +void SoZoomTranslation::GLRender(SoGLRenderAction* action) { - SoZoomTranslation::doAction((SoAction *)action); + SoZoomTranslation::doAction((SoAction*)action); } // Doc in superclass. -void SoZoomTranslation::doAction(SoAction * action) +void SoZoomTranslation::doAction(SoAction* action) { SbVec3f v; - if (this->translation.getValue() == SbVec3f(0.0f, 0.0f, 0.0f) && this->abPos.getValue() == SbVec3f(0.0f, 0.0f, 0.0f)) { + if (this->translation.getValue() == SbVec3f(0.0f, 0.0f, 0.0f) + && this->abPos.getValue() == SbVec3f(0.0f, 0.0f, 0.0f)) { return; - } else { + } + else { SbVec3f absVtr = this->abPos.getValue(); SbVec3f relVtr = this->translation.getValue(); @@ -107,19 +110,21 @@ void SoZoomTranslation::doAction(SoAction * action) SoModelMatrixElement::translateBy(action->getState(), this, v); } -void SoZoomTranslation::getMatrix(SoGetMatrixAction * action) +void SoZoomTranslation::getMatrix(SoGetMatrixAction* action) { SbVec3f v; - if (this->translation.getValue() == SbVec3f(0.0f, 0.0f, 0.0f) && this->abPos.getValue() == SbVec3f(0.0f, 0.0f, 0.0f)) { + if (this->translation.getValue() == SbVec3f(0.0f, 0.0f, 0.0f) + && this->abPos.getValue() == SbVec3f(0.0f, 0.0f, 0.0f)) { return; - } else { + } + else { SbVec3f absVtr = this->abPos.getValue(); SbVec3f relVtr = this->translation.getValue(); float sf = this->calculateScaleFactor(action); // For Sketcher Keep Z value the same - relVtr[0] = (relVtr[0] != 0) ? sf * relVtr[0] : 0; - relVtr[1] = (relVtr[1] != 0) ? sf * relVtr[1] : 0; + relVtr[0] = (relVtr[0] != 0) ? sf * relVtr[0] : 0; + relVtr[1] = (relVtr[1] != 0) ? sf * relVtr[1] : 0; v = absVtr + relVtr; } @@ -131,23 +136,23 @@ void SoZoomTranslation::getMatrix(SoGetMatrixAction * action) action->getInverse().multRight(m); } -void SoZoomTranslation::callback(SoCallbackAction * action) +void SoZoomTranslation::callback(SoCallbackAction* action) { - SoZoomTranslation::doAction((SoAction *)action); + SoZoomTranslation::doAction((SoAction*)action); } -void SoZoomTranslation::getBoundingBox(SoGetBoundingBoxAction * action) +void SoZoomTranslation::getBoundingBox(SoGetBoundingBoxAction* action) { - SoZoomTranslation::doAction((SoAction *)action); + SoZoomTranslation::doAction((SoAction*)action); } -void SoZoomTranslation::pick(SoPickAction * action) +void SoZoomTranslation::pick(SoPickAction* action) { - SoZoomTranslation::doAction((SoAction *)action); + SoZoomTranslation::doAction((SoAction*)action); } // Doc in superclass. -void SoZoomTranslation::getPrimitiveCount(SoGetPrimitiveCountAction * action) +void SoZoomTranslation::getPrimitiveCount(SoGetPrimitiveCountAction* action) { - SoZoomTranslation::doAction((SoAction *)action); + SoZoomTranslation::doAction((SoAction*)action); } diff --git a/src/Mod/Sketcher/Gui/SoZoomTranslation.h b/src/Mod/Sketcher/Gui/SoZoomTranslation.h index c1afbc0e32..a951b0b105 100644 --- a/src/Mod/Sketcher/Gui/SoZoomTranslation.h +++ b/src/Mod/Sketcher/Gui/SoZoomTranslation.h @@ -28,9 +28,11 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ -class SketcherGuiExport SoZoomTranslation : public SoTranslation { +class SketcherGuiExport SoZoomTranslation: public SoTranslation +{ using inherited = SoTranslation; SO_NODE_HEADER(SoZoomTranslation); @@ -39,21 +41,25 @@ public: static void initClass(); SoZoomTranslation(); SoSFVec3f abPos; - float getScaleFactor() const { return scaleFactor;} + float getScaleFactor() const + { + return scaleFactor; + } protected: - ~SoZoomTranslation() override {} - void doAction(SoAction * action) override; - void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; - void getMatrix(SoGetMatrixAction * action) override; - void GLRender(SoGLRenderAction *action) override; - void getBoundingBox(SoGetBoundingBoxAction * action) override; - void callback(SoCallbackAction * action) override; - void pick(SoPickAction * action) override; - float calculateScaleFactor (SoAction * action) const; + ~SoZoomTranslation() override + {} + void doAction(SoAction* action) override; + void getPrimitiveCount(SoGetPrimitiveCountAction* action) override; + void getMatrix(SoGetMatrixAction* action) override; + void GLRender(SoGLRenderAction* action) override; + void getBoundingBox(SoGetBoundingBoxAction* action) override; + void callback(SoCallbackAction* action) override; + void pick(SoPickAction* action) override; + float calculateScaleFactor(SoAction* action) const; mutable float scaleFactor; }; -} -#endif // SKETCHERGUI_SOZOOMTRANSLATION_H +}// namespace SketcherGui +#endif// SKETCHERGUI_SOZOOMTRANSLATION_H diff --git a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp index 108831ed4d..0912c4b54b 100644 --- a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp +++ b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp @@ -35,8 +35,9 @@ using namespace SketcherGui; // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgEditSketch::TaskDlgEditSketch(ViewProviderSketch *sketchView) - : TaskDialog(),sketchView(sketchView) +TaskDlgEditSketch::TaskDlgEditSketch(ViewProviderSketch* sketchView) + : TaskDialog() + , sketchView(sketchView) { assert(sketchView); Constraints = new TaskSketcherConstraints(sketchView); @@ -44,25 +45,26 @@ TaskDlgEditSketch::TaskDlgEditSketch(ViewProviderSketch *sketchView) Messages = new TaskSketcherMessages(sketchView); SolverAdvanced = new TaskSketcherSolverAdvanced(sketchView); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); setEscapeButtonEnabled(hGrp->GetBool("LeaveSketchWithEscape", true)); Content.push_back(Messages); - if (hGrp->GetBool("ShowSolverAdvancedWidget",false)) { + if (hGrp->GetBool("ShowSolverAdvancedWidget", false)) { Content.push_back(SolverAdvanced); } Content.push_back(Constraints); Content.push_back(Elements); - if (!hGrp->GetBool("ExpandedMessagesWidget",true)) + if (!hGrp->GetBool("ExpandedMessagesWidget", true)) Messages->hideGroupBox(); - if (!hGrp->GetBool("ExpandedSolverAdvancedWidget",false)) + if (!hGrp->GetBool("ExpandedSolverAdvancedWidget", false)) SolverAdvanced->hideGroupBox(); - if (!hGrp->GetBool("ExpandedConstraintsWidget",true)) + if (!hGrp->GetBool("ExpandedConstraintsWidget", true)) Constraints->hideGroupBox(); - if (!hGrp->GetBool("ExpandedElementsWidget",true)) + if (!hGrp->GetBool("ExpandedElementsWidget", true)) Elements->hideGroupBox(); } @@ -79,14 +81,10 @@ TaskDlgEditSketch::~TaskDlgEditSketch() void TaskDlgEditSketch::open() -{ - -} +{} void TaskDlgEditSketch::clicked(int) -{ - -} +{} bool TaskDlgEditSketch::accept() { @@ -95,15 +93,18 @@ bool TaskDlgEditSketch::accept() bool TaskDlgEditSketch::reject() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - hGrp->SetBool("ExpandedMessagesWidget",Messages->isGroupVisible()); - hGrp->SetBool("ExpandedSolverAdvancedWidget",SolverAdvanced->isGroupVisible()); - hGrp->SetBool("ExpandedConstraintsWidget",Constraints->isGroupVisible()); - hGrp->SetBool("ExpandedElementsWidget",Elements->isGroupVisible()); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + hGrp->SetBool("ExpandedMessagesWidget", Messages->isGroupVisible()); + hGrp->SetBool("ExpandedSolverAdvancedWidget", SolverAdvanced->isGroupVisible()); + hGrp->SetBool("ExpandedConstraintsWidget", Constraints->isGroupVisible()); + hGrp->SetBool("ExpandedElementsWidget", Elements->isGroupVisible()); - std::string document = getDocumentName(); // needed because resetEdit() deletes this instance - Gui::Command::doCommand(Gui::Command::Gui,"Gui.getDocument('%s').resetEdit()", document.c_str()); - Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument('%s').recompute()", document.c_str()); + std::string document = getDocumentName();// needed because resetEdit() deletes this instance + Gui::Command::doCommand( + Gui::Command::Gui, "Gui.getDocument('%s').resetEdit()", document.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, "App.getDocument('%s').recompute()", document.c_str()); return true; } diff --git a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h index e29cc35c7e..55c1b7a3d6 100644 --- a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h +++ b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h @@ -36,19 +36,22 @@ using Connection = boost::signals2::connection; -namespace SketcherGui { +namespace SketcherGui +{ /// simulation dialog for the TaskView -class SketcherGuiExport TaskDlgEditSketch : public Gui::TaskView::TaskDialog +class SketcherGuiExport TaskDlgEditSketch: public Gui::TaskView::TaskDialog { Q_OBJECT public: - explicit TaskDlgEditSketch(ViewProviderSketch *sketchView); + explicit TaskDlgEditSketch(ViewProviderSketch* sketchView); ~TaskDlgEditSketch() override; ViewProviderSketch* getSketchView() const - { return sketchView; } + { + return sketchView; + } public: /// is called the TaskView when the dialog is opened @@ -60,26 +63,29 @@ public: /// is called by the framework if the dialog is rejected (Cancel) bool reject() override; bool isAllowedAlterDocument() const override - { return false; } + { + return false; + } /// returns for Close and Help button QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Close; } + { + return QDialogButtonBox::Close; + } protected: void slotUndoDocument(const App::Document&); void slotRedoDocument(const App::Document&); protected: - ViewProviderSketch *sketchView; - TaskSketcherConstraints *Constraints; - TaskSketcherElements *Elements; - TaskSketcherMessages *Messages; - TaskSketcherSolverAdvanced *SolverAdvanced; + ViewProviderSketch* sketchView; + TaskSketcherConstraints* Constraints; + TaskSketcherElements* Elements; + TaskSketcherMessages* Messages; + TaskSketcherSolverAdvanced* SolverAdvanced; }; +}// namespace SketcherGui -} //namespace SketcherGui - -#endif // SKETCHERGUI_TaskDlgEditSketch_H +#endif// SKETCHERGUI_TaskDlgEditSketch_H diff --git a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp index d328c08fdf..d7fb24474b 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp @@ -22,17 +22,17 @@ #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 #endif #include @@ -49,11 +49,11 @@ #include #include -#include "TaskSketcherConstraints.h" -#include "ui_TaskSketcherConstraints.h" #include "EditDatumDialog.h" +#include "TaskSketcherConstraints.h" #include "Utils.h" #include "ViewProviderSketch.h" +#include "ui_TaskSketcherConstraints.h" using namespace SketcherGui; @@ -71,34 +71,43 @@ QT_TRANSLATE_NOOP("SketcherGui::ConstraintView", "Select Elements"); /// CMDSTR is the string registered in the commandManager /// FUNC is the name of the member function to be executed on selection of the menu item /// ACTSONSELECTION is a true/false value to activate the command only if a selection is made -#define CONTEXT_ITEM(ICONSTR,NAMESTR,CMDSTR,FUNC,ACTSONSELECTION) \ -QIcon icon_ ## FUNC( Gui::BitmapFactory().pixmap(ICONSTR) ); \ - QAction* constr_ ## FUNC = menu.addAction(icon_ ## FUNC,tr(NAMESTR), this, SLOT(FUNC()), \ - QKeySequence(QString::fromUtf8(Gui::Application::Instance->commandManager().getCommandByName(CMDSTR)->getAccel()))); \ - if(ACTSONSELECTION) constr_ ## FUNC->setEnabled(!items.isEmpty()); else constr_ ## FUNC->setEnabled(true); +#define CONTEXT_ITEM(ICONSTR, NAMESTR, CMDSTR, FUNC, ACTSONSELECTION) \ + QIcon icon_##FUNC(Gui::BitmapFactory().pixmap(ICONSTR)); \ + QAction* constr_##FUNC = menu.addAction( \ + icon_##FUNC, \ + tr(NAMESTR), \ + this, \ + SLOT(FUNC()), \ + QKeySequence(QString::fromUtf8( \ + Gui::Application::Instance->commandManager().getCommandByName(CMDSTR)->getAccel()))); \ + if (ACTSONSELECTION) \ + constr_##FUNC->setEnabled(!items.isEmpty()); \ + else \ + constr_##FUNC->setEnabled(true); /// Defines the member function corresponding to the CONTEXT_ITEM macro -#define CONTEXT_MEMBER_DEF(CMDSTR,FUNC) \ -void ConstraintView::FUNC(){ \ - Gui::Application::Instance->commandManager().runCommandByName(CMDSTR);} +#define CONTEXT_MEMBER_DEF(CMDSTR, FUNC) \ + void ConstraintView::FUNC() \ + { \ + Gui::Application::Instance->commandManager().runCommandByName(CMDSTR); \ + } // helper class to store additional information about the listWidget entry. -class ConstraintItem : public QListWidgetItem +class ConstraintItem: public QListWidgetItem { public: - ConstraintItem(const Sketcher::SketchObject * s, ViewProviderSketch *sketchview, int ConstNbr) - : QListWidgetItem(QString()), - sketch(s), - sketchView(sketchview), - ConstraintNbr(ConstNbr) + ConstraintItem(const Sketcher::SketchObject* s, ViewProviderSketch* sketchview, int ConstNbr) + : QListWidgetItem(QString()) + , sketch(s) + , sketchView(sketchview) + , ConstraintNbr(ConstNbr) { this->setFlags(this->flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable); updateVirtualSpaceStatus(); } ~ConstraintItem() override - { - } - void setData(int role, const QVariant & value) override + {} + void setData(int role, const QVariant& value) override { if (role == Qt::EditRole) this->value = value; @@ -106,12 +115,12 @@ public: QListWidgetItem::setData(role, value); } - QVariant data (int role) const override + QVariant data(int role) const override { if (ConstraintNbr < 0 || ConstraintNbr >= sketch->Constraints.getSize()) return QVariant(); - const Sketcher::Constraint * constraint = sketch->Constraints[ConstraintNbr]; + const Sketcher::Constraint* constraint = sketch->Constraints[ConstraintNbr]; // it can happen that the geometry of the sketch is tmp. invalid and thus // the index operator returns null. @@ -123,109 +132,150 @@ public: if (value.isValid()) return value; else - return Base::Tools::fromStdString(Sketcher::PropertyConstraintList::getConstraintName(constraint->Name, ConstraintNbr)); + return Base::Tools::fromStdString( + Sketcher::PropertyConstraintList::getConstraintName(constraint->Name, + ConstraintNbr)); } else if (role == Qt::DisplayRole) { - QString name = Base::Tools::fromStdString(Sketcher::PropertyConstraintList::getConstraintName(constraint->Name, ConstraintNbr)); + QString name = + Base::Tools::fromStdString(Sketcher::PropertyConstraintList::getConstraintName( + constraint->Name, ConstraintNbr)); switch (constraint->Type) { - case Sketcher::Horizontal: - case Sketcher::Vertical: - case Sketcher::Coincident: - case Sketcher::PointOnObject: - case Sketcher::Parallel: - case Sketcher::Perpendicular: - case Sketcher::Tangent: - case Sketcher::Equal: - case Sketcher::Symmetric: - case Sketcher::Block: - break; - case Sketcher::Distance: - case Sketcher::DistanceX: - case Sketcher::DistanceY: - case Sketcher::Radius: - case Sketcher::Weight: - case Sketcher::Diameter: - case Sketcher::Angle: - name = QString::fromLatin1("%1 (%2)").arg(name, constraint->getPresentationValue().getUserString()); - break; - case Sketcher::SnellsLaw: { - double v = constraint->getPresentationValue().getValue(); - double n1 = 1.0; - double n2 = 1.0; - if (fabs(v) >= 1) { - n2 = v; - } else { - n1 = 1/v; + case Sketcher::Horizontal: + case Sketcher::Vertical: + case Sketcher::Coincident: + case Sketcher::PointOnObject: + case Sketcher::Parallel: + case Sketcher::Perpendicular: + case Sketcher::Tangent: + case Sketcher::Equal: + case Sketcher::Symmetric: + case Sketcher::Block: + break; + case Sketcher::Distance: + case Sketcher::DistanceX: + case Sketcher::DistanceY: + case Sketcher::Radius: + case Sketcher::Weight: + case Sketcher::Diameter: + case Sketcher::Angle: + name = QString::fromLatin1("%1 (%2)").arg( + name, constraint->getPresentationValue().getUserString()); + break; + case Sketcher::SnellsLaw: { + double v = constraint->getPresentationValue().getValue(); + double n1 = 1.0; + double n2 = 1.0; + if (fabs(v) >= 1) { + n2 = v; + } + else { + n1 = 1 / v; + } + name = QString::fromLatin1("%1 (%2/%3)").arg(name).arg(n2).arg(n1); + break; } - name = QString::fromLatin1("%1 (%2/%3)").arg(name).arg(n2).arg(n1); - break; - } - case Sketcher::InternalAlignment: - break; - default: - break; + case Sketcher::InternalAlignment: + break; + default: + break; } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool extended = hGrp->GetBool("ExtendedConstraintInformation",false); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool extended = hGrp->GetBool("ExtendedConstraintInformation", false); - if(extended) { - if(constraint->Second == Sketcher::GeoEnum::GeoUndef) { - name = QString::fromLatin1("%1 [(%2,%3)]").arg(name).arg(constraint->First).arg(static_cast(constraint->FirstPos)); + if (extended) { + if (constraint->Second == Sketcher::GeoEnum::GeoUndef) { + name = QString::fromLatin1("%1 [(%2,%3)]") + .arg(name) + .arg(constraint->First) + .arg(static_cast(constraint->FirstPos)); } - else if(constraint->Third == Sketcher::GeoEnum::GeoUndef) { - name = QString::fromLatin1("%1 [(%2,%3),(%4,%5)]").arg(name).arg(constraint->First).arg(static_cast(constraint->FirstPos)).arg(constraint->Second).arg(static_cast(constraint->SecondPos)); + else if (constraint->Third == Sketcher::GeoEnum::GeoUndef) { + name = QString::fromLatin1("%1 [(%2,%3),(%4,%5)]") + .arg(name) + .arg(constraint->First) + .arg(static_cast(constraint->FirstPos)) + .arg(constraint->Second) + .arg(static_cast(constraint->SecondPos)); } else { - name = QString::fromLatin1("%1 [(%2,%3),(%4,%5),(%6,%7)]").arg(name).arg(constraint->First).arg(static_cast(constraint->FirstPos)).arg(constraint->Second).arg(static_cast(constraint->SecondPos)).arg(constraint->Third).arg(static_cast(constraint->ThirdPos)); + name = QString::fromLatin1("%1 [(%2,%3),(%4,%5),(%6,%7)]") + .arg(name) + .arg(constraint->First) + .arg(static_cast(constraint->FirstPos)) + .arg(constraint->Second) + .arg(static_cast(constraint->SecondPos)) + .arg(constraint->Third) + .arg(static_cast(constraint->ThirdPos)); } } return name; } else if (role == Qt::DecorationRole) { - static QIcon hdist( Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance") ); - static QIcon vdist( Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance") ); - static QIcon horiz( Gui::BitmapFactory().iconFromTheme("Constraint_Horizontal") ); - static QIcon vert ( Gui::BitmapFactory().iconFromTheme("Constraint_Vertical") ); - //static QIcon lock ( Gui::BitmapFactory().iconFromTheme("Constraint_Lock") ); - static QIcon block ( Gui::BitmapFactory().iconFromTheme("Constraint_Block") ); - static QIcon coinc( Gui::BitmapFactory().iconFromTheme("Constraint_PointOnPoint") ); - static QIcon para ( Gui::BitmapFactory().iconFromTheme("Constraint_Parallel") ); - static QIcon perp ( Gui::BitmapFactory().iconFromTheme("Constraint_Perpendicular") ); - static QIcon tang ( Gui::BitmapFactory().iconFromTheme("Constraint_Tangent") ); - static QIcon dist ( Gui::BitmapFactory().iconFromTheme("Constraint_Length") ); - static QIcon radi ( Gui::BitmapFactory().iconFromTheme("Constraint_Radius") ); - static QIcon dia ( Gui::BitmapFactory().iconFromTheme("Constraint_Diameter") ); - //static QIcon majradi ( Gui::BitmapFactory().iconFromTheme("Constraint_Ellipse_Major_Radius") ); - //static QIcon minradi ( Gui::BitmapFactory().iconFromTheme("Constraint_Ellipse_Minor_Radius") ); - static QIcon angl ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle") ); - //static QIcon ellipseXUAngl ( Gui::BitmapFactory().iconFromTheme("Constraint_Ellipse_Axis_Angle") ); - static QIcon equal( Gui::BitmapFactory().iconFromTheme("Constraint_EqualLength") ); - static QIcon pntoo( Gui::BitmapFactory().iconFromTheme("Constraint_PointOnObject") ); - static QIcon symm ( Gui::BitmapFactory().iconFromTheme("Constraint_Symmetric") ); - static QIcon snell ( Gui::BitmapFactory().iconFromTheme("Constraint_SnellsLaw") ); - static QIcon iaellipseminoraxis ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment_Ellipse_MinorAxis") ); - static QIcon iaellipsemajoraxis ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment_Ellipse_MajorAxis") ); - static QIcon iaellipsefocus1 ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment_Ellipse_Focus1") ); - static QIcon iaellipsefocus2 ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment_Ellipse_Focus2") ); - static QIcon iaellipseother ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment") ); + static QIcon hdist(Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance")); + static QIcon vdist(Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance")); + static QIcon horiz(Gui::BitmapFactory().iconFromTheme("Constraint_Horizontal")); + static QIcon vert(Gui::BitmapFactory().iconFromTheme("Constraint_Vertical")); + // static QIcon lock ( Gui::BitmapFactory().iconFromTheme("Constraint_Lock") ); + static QIcon block(Gui::BitmapFactory().iconFromTheme("Constraint_Block")); + static QIcon coinc(Gui::BitmapFactory().iconFromTheme("Constraint_PointOnPoint")); + static QIcon para(Gui::BitmapFactory().iconFromTheme("Constraint_Parallel")); + static QIcon perp(Gui::BitmapFactory().iconFromTheme("Constraint_Perpendicular")); + static QIcon tang(Gui::BitmapFactory().iconFromTheme("Constraint_Tangent")); + static QIcon dist(Gui::BitmapFactory().iconFromTheme("Constraint_Length")); + static QIcon radi(Gui::BitmapFactory().iconFromTheme("Constraint_Radius")); + static QIcon dia(Gui::BitmapFactory().iconFromTheme("Constraint_Diameter")); + // static QIcon majradi ( + // Gui::BitmapFactory().iconFromTheme("Constraint_Ellipse_Major_Radius") ); static QIcon + // minradi ( Gui::BitmapFactory().iconFromTheme("Constraint_Ellipse_Minor_Radius") ); + static QIcon angl(Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle")); + // static QIcon ellipseXUAngl ( + // Gui::BitmapFactory().iconFromTheme("Constraint_Ellipse_Axis_Angle") ); + static QIcon equal(Gui::BitmapFactory().iconFromTheme("Constraint_EqualLength")); + static QIcon pntoo(Gui::BitmapFactory().iconFromTheme("Constraint_PointOnObject")); + static QIcon symm(Gui::BitmapFactory().iconFromTheme("Constraint_Symmetric")); + static QIcon snell(Gui::BitmapFactory().iconFromTheme("Constraint_SnellsLaw")); + static QIcon iaellipseminoraxis(Gui::BitmapFactory().iconFromTheme( + "Constraint_InternalAlignment_Ellipse_MinorAxis")); + static QIcon iaellipsemajoraxis(Gui::BitmapFactory().iconFromTheme( + "Constraint_InternalAlignment_Ellipse_MajorAxis")); + static QIcon iaellipsefocus1( + Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment_Ellipse_Focus1")); + static QIcon iaellipsefocus2( + Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment_Ellipse_Focus2")); + static QIcon iaellipseother( + Gui::BitmapFactory().iconFromTheme("Constraint_InternalAlignment")); - static QIcon hdist_driven ( Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance_Driven") ); - static QIcon vdist_driven( Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance_Driven") ); - static QIcon dist_driven ( Gui::BitmapFactory().iconFromTheme("Constraint_Length_Driven") ); - static QIcon radi_driven ( Gui::BitmapFactory().iconFromTheme("Constraint_Radius_Driven") ); - static QIcon dia_driven ( Gui::BitmapFactory().iconFromTheme("Constraint_Diameter_Driven") ); - static QIcon angl_driven ( Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle_Driven") ); - static QIcon snell_driven ( Gui::BitmapFactory().iconFromTheme("Constraint_SnellsLaw_Driven") ); + static QIcon hdist_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_HorizontalDistance_Driven")); + static QIcon vdist_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_VerticalDistance_Driven")); + static QIcon dist_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_Length_Driven")); + static QIcon radi_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_Radius_Driven")); + static QIcon dia_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_Diameter_Driven")); + static QIcon angl_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_InternalAngle_Driven")); + static QIcon snell_driven( + Gui::BitmapFactory().iconFromTheme("Constraint_SnellsLaw_Driven")); - auto selicon = [](const Sketcher::Constraint * constr, const QIcon & normal, const QIcon & driven) -> QIcon { - if(!constr->isActive) { + auto selicon = [](const Sketcher::Constraint* constr, + const QIcon& normal, + const QIcon& driven) -> QIcon { + if (!constr->isActive) { QIcon darkIcon; int w = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize); - darkIcon.addPixmap(normal.pixmap(w, w, QIcon::Disabled, QIcon::Off), QIcon::Normal, QIcon::Off); - darkIcon.addPixmap(normal.pixmap(w, w, QIcon::Disabled, QIcon::On ), QIcon::Normal, QIcon::On ); + darkIcon.addPixmap(normal.pixmap(w, w, QIcon::Disabled, QIcon::Off), + QIcon::Normal, + QIcon::Off); + darkIcon.addPixmap( + normal.pixmap(w, w, QIcon::Disabled, QIcon::On), QIcon::Normal, QIcon::On); return darkIcon; } else if (constr->isDriving) { @@ -236,58 +286,58 @@ public: } }; - switch(constraint->Type){ - case Sketcher::Horizontal: - return selicon(constraint,horiz,horiz); - case Sketcher::Vertical: - return selicon(constraint,vert,vert); - case Sketcher::Coincident: - return selicon(constraint,coinc,coinc); - case Sketcher::Block: - return selicon(constraint,block,block); - case Sketcher::PointOnObject: - return selicon(constraint,pntoo,pntoo); - case Sketcher::Parallel: - return selicon(constraint,para,para); - case Sketcher::Perpendicular: - return selicon(constraint,perp,perp); - case Sketcher::Tangent: - return selicon(constraint,tang,tang); - case Sketcher::Equal: - return selicon(constraint,equal,equal); - case Sketcher::Symmetric: - return selicon(constraint,symm,symm); - case Sketcher::Distance: - return selicon(constraint,dist,dist_driven); - case Sketcher::DistanceX: - return selicon(constraint,hdist,hdist_driven); - case Sketcher::DistanceY: - return selicon(constraint,vdist,vdist_driven); - case Sketcher::Radius: - case Sketcher::Weight: - return selicon(constraint,radi,radi_driven); - case Sketcher::Diameter: - return selicon(constraint,dia,dia_driven); - case Sketcher::Angle: - return selicon(constraint,angl,angl_driven); - case Sketcher::SnellsLaw: - return selicon(constraint,snell,snell_driven); - case Sketcher::InternalAlignment: - switch(constraint->AlignmentType){ - case Sketcher::EllipseMajorDiameter: - return selicon(constraint,iaellipsemajoraxis,iaellipsemajoraxis); - case Sketcher::EllipseMinorDiameter: - return selicon(constraint,iaellipseminoraxis,iaellipseminoraxis); - case Sketcher::EllipseFocus1: - return selicon(constraint,iaellipsefocus1,iaellipsefocus1); - case Sketcher::EllipseFocus2: - return selicon(constraint,iaellipsefocus2,iaellipsefocus2); - case Sketcher::Undef: + switch (constraint->Type) { + case Sketcher::Horizontal: + return selicon(constraint, horiz, horiz); + case Sketcher::Vertical: + return selicon(constraint, vert, vert); + case Sketcher::Coincident: + return selicon(constraint, coinc, coinc); + case Sketcher::Block: + return selicon(constraint, block, block); + case Sketcher::PointOnObject: + return selicon(constraint, pntoo, pntoo); + case Sketcher::Parallel: + return selicon(constraint, para, para); + case Sketcher::Perpendicular: + return selicon(constraint, perp, perp); + case Sketcher::Tangent: + return selicon(constraint, tang, tang); + case Sketcher::Equal: + return selicon(constraint, equal, equal); + case Sketcher::Symmetric: + return selicon(constraint, symm, symm); + case Sketcher::Distance: + return selicon(constraint, dist, dist_driven); + case Sketcher::DistanceX: + return selicon(constraint, hdist, hdist_driven); + case Sketcher::DistanceY: + return selicon(constraint, vdist, vdist_driven); + case Sketcher::Radius: + case Sketcher::Weight: + return selicon(constraint, radi, radi_driven); + case Sketcher::Diameter: + return selicon(constraint, dia, dia_driven); + case Sketcher::Angle: + return selicon(constraint, angl, angl_driven); + case Sketcher::SnellsLaw: + return selicon(constraint, snell, snell_driven); + case Sketcher::InternalAlignment: + switch (constraint->AlignmentType) { + case Sketcher::EllipseMajorDiameter: + return selicon(constraint, iaellipsemajoraxis, iaellipsemajoraxis); + case Sketcher::EllipseMinorDiameter: + return selicon(constraint, iaellipseminoraxis, iaellipseminoraxis); + case Sketcher::EllipseFocus1: + return selicon(constraint, iaellipsefocus1, iaellipsefocus1); + case Sketcher::EllipseFocus2: + return selicon(constraint, iaellipsefocus2, iaellipsefocus2); + case Sketcher::Undef: + default: + return selicon(constraint, iaellipseother, iaellipseother); + } default: - return selicon(constraint,iaellipseother,iaellipseother); - } - default: - return QVariant(); + return QVariant(); } } else if (role == Qt::ToolTipRole) { @@ -303,92 +353,106 @@ public: return QListWidgetItem::data(role); } - Sketcher::ConstraintType constraintType() const { + Sketcher::ConstraintType constraintType() const + { assert(ConstraintNbr >= 0 && ConstraintNbr < sketch->Constraints.getSize()); return sketch->Constraints[ConstraintNbr]->Type; } - bool isEnforceable() const { + bool isEnforceable() const + { assert(ConstraintNbr >= 0 && ConstraintNbr < sketch->Constraints.getSize()); - const Sketcher::Constraint * constraint = sketch->Constraints[ConstraintNbr]; + const Sketcher::Constraint* constraint = sketch->Constraints[ConstraintNbr]; switch (constraint->Type) { - case Sketcher::None: - case Sketcher::NumConstraintTypes: - assert( false ); - return false; - case Sketcher::Horizontal: - case Sketcher::Vertical: - case Sketcher::Coincident: - case Sketcher::Block: - case Sketcher::PointOnObject: - case Sketcher::Parallel: - case Sketcher::Perpendicular: - case Sketcher::Tangent: - case Sketcher::Equal: - case Sketcher::Symmetric: - return true; - case Sketcher::Distance: - case Sketcher::DistanceX: - case Sketcher::DistanceY: - case Sketcher::Radius: - case Sketcher::Diameter: - case Sketcher::Weight: - case Sketcher::Angle: - case Sketcher::SnellsLaw: - return ( constraint->First >= 0 || constraint->Second >= 0 || constraint->Third >= 0 ); - case Sketcher::InternalAlignment: - return true; + case Sketcher::None: + case Sketcher::NumConstraintTypes: + assert(false); + return false; + case Sketcher::Horizontal: + case Sketcher::Vertical: + case Sketcher::Coincident: + case Sketcher::Block: + case Sketcher::PointOnObject: + case Sketcher::Parallel: + case Sketcher::Perpendicular: + case Sketcher::Tangent: + case Sketcher::Equal: + case Sketcher::Symmetric: + return true; + case Sketcher::Distance: + case Sketcher::DistanceX: + case Sketcher::DistanceY: + case Sketcher::Radius: + case Sketcher::Diameter: + case Sketcher::Weight: + case Sketcher::Angle: + case Sketcher::SnellsLaw: + return (constraint->First >= 0 || constraint->Second >= 0 + || constraint->Third >= 0); + case Sketcher::InternalAlignment: + return true; } return false; } - bool isDimensional() const { + bool isDimensional() const + { assert(ConstraintNbr >= 0 && ConstraintNbr < sketch->Constraints.getSize()); return (sketch->Constraints[ConstraintNbr])->isDimensional(); } - bool isDriving() const { + bool isDriving() const + { assert(ConstraintNbr >= 0 && ConstraintNbr < sketch->Constraints.getSize()); return sketch->Constraints[ConstraintNbr]->isDriving; } - bool isInVirtualSpace() const { + bool isInVirtualSpace() const + { assert(ConstraintNbr >= 0 && ConstraintNbr < sketch->Constraints.getSize()); return sketch->Constraints[ConstraintNbr]->isInVirtualSpace; } - bool isActive() const { + bool isActive() const + { assert(ConstraintNbr >= 0 && ConstraintNbr < sketch->Constraints.getSize()); return sketch->Constraints[ConstraintNbr]->isActive; } - void updateVirtualSpaceStatus() { - this->setCheckState((this->isInVirtualSpace() != sketchView->getIsShownVirtualSpace())?Qt::Unchecked:Qt::Checked); + void updateVirtualSpaceStatus() + { + this->setCheckState((this->isInVirtualSpace() != sketchView->getIsShownVirtualSpace()) + ? Qt::Unchecked + : Qt::Checked); } - const Sketcher::SketchObject * sketch; - const ViewProviderSketch *sketchView; + const Sketcher::SketchObject* sketch; + const ViewProviderSketch* sketchView; int ConstraintNbr; QVariant value; }; -class ExpressionDelegate : public QStyledItemDelegate +class ExpressionDelegate: public QStyledItemDelegate { public: - explicit ExpressionDelegate(QListWidget * _view) : QStyledItemDelegate(_view), view(_view) { } + explicit ExpressionDelegate(QListWidget* _view) + : QStyledItemDelegate(_view) + , view(_view) + {} + protected: QPixmap getIcon(const char* name, const QSize& size) const { QString key = QString::fromLatin1("%1_%2x%3") - .arg(QString::fromLatin1(name)) - .arg(size.width()) - .arg(size.height()); + .arg(QString::fromLatin1(name)) + .arg(size.width()) + .arg(size.height()); QPixmap icon; if (QPixmapCache::find(key, &icon)) return icon; @@ -399,13 +463,15 @@ protected: return icon; } - void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const override { + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const override + { QStyleOptionViewItem options = option; initStyleOption(&options, index); options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); - ConstraintItem * item = dynamic_cast(view->item(index.row())); + ConstraintItem* item = dynamic_cast(view->item(index.row())); if (!item || item->sketch->Constraints.getSize() <= item->ConstraintNbr) return; @@ -429,26 +495,25 @@ protected: } } - QListWidget * view; + QListWidget* view; }; /* ConstraintView list widget ------------------------------*/ -ConstraintView::ConstraintView(QWidget *parent) +ConstraintView::ConstraintView(QWidget* parent) : QListWidget(parent) { - ExpressionDelegate * delegate = new ExpressionDelegate(this); + ExpressionDelegate* delegate = new ExpressionDelegate(this); setItemDelegate(delegate); } ConstraintView::~ConstraintView() -{ -} +{} -void ConstraintView::contextMenuEvent (QContextMenuEvent* event) +void ConstraintView::contextMenuEvent(QContextMenuEvent* event) { QMenu menu; QListWidgetItem* item = currentItem(); - QList items = selectedItems(); + QList items = selectedItems(); // Cancel any in-progress operation Gui::Document* doc = Gui::Application::Instance->activeDocument(); @@ -457,17 +522,22 @@ void ConstraintView::contextMenuEvent (QContextMenuEvent* event) // Sync the FreeCAD selection with the selection in the ConstraintView widget if (didRelease && item) { Gui::Selection().clearSelection(); - std::string doc_name = static_cast(item)->sketchView->getSketchObject()->getDocument()->getName(); - std::string obj_name = static_cast(item)->sketchView->getSketchObject()->getNameInDocument(); + std::string doc_name = static_cast(item) + ->sketchView->getSketchObject() + ->getDocument() + ->getName(); + std::string obj_name = + static_cast(item)->sketchView->getSketchObject()->getNameInDocument(); std::vector constraintSubNames; for (auto&& it : items) { auto ci = static_cast(it); - std::string constraint_name = Sketcher::PropertyConstraintList::getConstraintName(ci->ConstraintNbr); + std::string constraint_name = + Sketcher::PropertyConstraintList::getConstraintName(ci->ConstraintNbr); constraintSubNames.emplace_back(constraint_name.c_str()); } - if(!constraintSubNames.empty()) + if (!constraintSubNames.empty()) Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), constraintSubNames); } @@ -476,7 +546,7 @@ void ConstraintView::contextMenuEvent (QContextMenuEvent* event) bool isActive = true; // Non-driving-constraints/measurements - ConstraintItem *it = dynamic_cast(item); + ConstraintItem* it = dynamic_cast(item); if (it) { // if its the right constraint if (it->isDimensional()) { @@ -489,15 +559,18 @@ void ConstraintView::contextMenuEvent (QContextMenuEvent* event) isActive = it->isActive(); } - // This does the same as a double-click and thus it should be the first action and with bold text + // This does the same as a double-click and thus it should be the first action and with bold + // text QAction* change = menu.addAction(tr("Change value"), this, &ConstraintView::modifyCurrentItem); change->setEnabled(isQuantity); menu.setDefaultAction(change); - QAction* driven = menu.addAction(tr("Toggle to/from reference"), this, &ConstraintView::updateDrivingStatus); + QAction* driven = + menu.addAction(tr("Toggle to/from reference"), this, &ConstraintView::updateDrivingStatus); driven->setEnabled(isToggleDriving); - QAction* activate = menu.addAction(isActive ? tr("Deactivate") : tr("Activate"), this, &ConstraintView::updateActiveStatus); + QAction* activate = menu.addAction( + isActive ? tr("Deactivate") : tr("Activate"), this, &ConstraintView::updateActiveStatus); activate->setEnabled(!items.isEmpty()); menu.addSeparator(); @@ -507,35 +580,46 @@ void ConstraintView::contextMenuEvent (QContextMenuEvent* event) hide->setEnabled(!items.isEmpty()); menu.addSeparator(); - CONTEXT_ITEM("Sketcher_SelectElementsAssociatedWithConstraints","Select Elements","Sketcher_SelectElementsAssociatedWithConstraints",doSelectConstraints,true) + CONTEXT_ITEM("Sketcher_SelectElementsAssociatedWithConstraints", + "Select Elements", + "Sketcher_SelectElementsAssociatedWithConstraints", + doSelectConstraints, + true) - QAction* rename = menu.addAction(tr("Rename"), this, &ConstraintView::renameCurrentItem -#ifndef Q_OS_MAC // on Mac F2 doesn't seem to trigger an edit signal - ,QKeySequence(Qt::Key_F2) + QAction* rename = menu.addAction(tr("Rename"), + this, + &ConstraintView::renameCurrentItem +#ifndef Q_OS_MAC// on Mac F2 doesn't seem to trigger an edit signal + , + QKeySequence(Qt::Key_F2) #endif - ); + ); rename->setEnabled(item != nullptr); - QAction* center = menu.addAction(tr("Center sketch"), this, &ConstraintView::centerSelectedItems); + QAction* center = + menu.addAction(tr("Center sketch"), this, &ConstraintView::centerSelectedItems); center->setEnabled(item != nullptr); - QAction* remove = menu.addAction(tr("Delete"), this, &ConstraintView::deleteSelectedItems, - QKeySequence(QKeySequence::Delete)); + QAction* remove = menu.addAction(tr("Delete"), + this, + &ConstraintView::deleteSelectedItems, + QKeySequence(QKeySequence::Delete)); remove->setEnabled(!items.isEmpty()); - QAction* swap = menu.addAction(tr("Swap constraint names"), this, &ConstraintView::swapNamedOfSelectedItems); + QAction* swap = menu.addAction( + tr("Swap constraint names"), this, &ConstraintView::swapNamedOfSelectedItems); swap->setEnabled(items.size() == 2); menu.exec(event->globalPos()); } -CONTEXT_MEMBER_DEF("Sketcher_SelectElementsAssociatedWithConstraints",doSelectConstraints) +CONTEXT_MEMBER_DEF("Sketcher_SelectElementsAssociatedWithConstraints", doSelectConstraints) void ConstraintView::updateDrivingStatus() { QListWidgetItem* item = currentItem(); - ConstraintItem *it = dynamic_cast(item); + ConstraintItem* it = dynamic_cast(item); if (it) { Q_EMIT onUpdateDrivingStatus(item, !it->isDriving()); } @@ -545,7 +629,7 @@ void ConstraintView::updateActiveStatus() { QListWidgetItem* item = currentItem(); - ConstraintItem *it = dynamic_cast(item); + ConstraintItem* it = dynamic_cast(item); if (it) { Q_EMIT onUpdateActiveStatus(item, !it->isActive()); } @@ -598,25 +682,28 @@ void ConstraintView::deleteSelectedItems() void ConstraintView::swapNamedOfSelectedItems() { - QList items = selectedItems(); + QList items = selectedItems(); if (items.size() != 2) return; - ConstraintItem * item1 = static_cast(items[0]); - std::string escapedstr1 = Base::Tools::escapedUnicodeFromUtf8(item1->sketch->Constraints[item1->ConstraintNbr]->Name.c_str()); - ConstraintItem * item2 = static_cast(items[1]); - std::string escapedstr2 = Base::Tools::escapedUnicodeFromUtf8(item2->sketch->Constraints[item2->ConstraintNbr]->Name.c_str()); + ConstraintItem* item1 = static_cast(items[0]); + std::string escapedstr1 = Base::Tools::escapedUnicodeFromUtf8( + item1->sketch->Constraints[item1->ConstraintNbr]->Name.c_str()); + ConstraintItem* item2 = static_cast(items[1]); + std::string escapedstr2 = Base::Tools::escapedUnicodeFromUtf8( + item2->sketch->Constraints[item2->ConstraintNbr]->Name.c_str()); - // In commit 67800ec8c (21 Jul 2015) the implementation of on_listWidgetConstraints_itemChanged() - // has changed ensuring that a name of a constraint cannot be reset any more. - // This leads to some inconsistencies when trying to swap "empty" names. + // In commit 67800ec8c (21 Jul 2015) the implementation of + // on_listWidgetConstraints_itemChanged() has changed ensuring that a name of a constraint + // cannot be reset any more. This leads to some inconsistencies when trying to swap "empty" + // names. // // If names are empty then nothing should be done if (escapedstr1.empty() || escapedstr2.empty()) { Gui::TranslatedUserWarning(item1->sketch, - tr("Unnamed constraint"), - tr("Only the names of named constraints can be swapped.")); + tr("Unnamed constraint"), + tr("Only the names of named constraints can be swapped.")); return; } @@ -626,12 +713,12 @@ void ConstraintView::swapNamedOfSelectedItems() std::string tmpname = ss.str(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Swap constraint names")); - Gui::cmdAppObjectArgs(item1->sketch, "renameConstraint(%d, u'%s')", - item1->ConstraintNbr, tmpname.c_str()); - Gui::cmdAppObjectArgs(item2->sketch, "renameConstraint(%d, u'%s')", - item2->ConstraintNbr, escapedstr1.c_str()); - Gui::cmdAppObjectArgs(item1->sketch, "renameConstraint(%d, u'%s')", - item1->ConstraintNbr, escapedstr2.c_str()); + Gui::cmdAppObjectArgs( + item1->sketch, "renameConstraint(%d, u'%s')", item1->ConstraintNbr, tmpname.c_str()); + Gui::cmdAppObjectArgs( + item2->sketch, "renameConstraint(%d, u'%s')", item2->ConstraintNbr, escapedstr1.c_str()); + Gui::cmdAppObjectArgs( + item1->sketch, "renameConstraint(%d, u'%s')", item1->ConstraintNbr, escapedstr2.c_str()); Gui::Command::commitCommand(); } @@ -639,10 +726,12 @@ void ConstraintView::swapNamedOfSelectedItems() ConstraintFilterList::ConstraintFilterList(QWidget* parent) : QListWidget(parent) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - int filterState = hGrp->GetInt("ConstraintFilterState", INT_MAX); //INT_MAX = 1111111111111111111111111111111 in binary. + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + int filterState = hGrp->GetInt("ConstraintFilterState", + INT_MAX);// INT_MAX = 1111111111111111111111111111111 in binary. - normalFilterCount = filterItems.size() - 2; //All filter but selected and associated + normalFilterCount = filterItems.size() - 2;// All filter but selected and associated selectedFilterIndex = normalFilterCount; associatedFilterIndex = normalFilterCount + 1; @@ -652,9 +741,9 @@ ConstraintFilterList::ConstraintFilterList(QWidget* parent) it->setFlags(it->flags() | Qt::ItemIsUserCheckable); addItem(it); - bool isChecked = static_cast(filterState & 1); //get the first bit of filterState + bool isChecked = static_cast(filterState & 1);// get the first bit of filterState it->setCheckState(isChecked ? Qt::Checked : Qt::Unchecked); - filterState = filterState >> 1; //shift right to get rid of the used bit. + filterState = filterState >> 1;// shift right to get rid of the used bit. } languageChange(); @@ -662,8 +751,7 @@ ConstraintFilterList::ConstraintFilterList(QWidget* parent) } ConstraintFilterList::~ConstraintFilterList() -{ -} +{} void ConstraintFilterList::changeEvent(QEvent* e) { @@ -678,9 +766,9 @@ void ConstraintFilterList::languageChange() assert(static_cast(filterItems.size()) == count()); int i = 0; for (auto const& filterItem : filterItems) { - auto text = QStringLiteral(" ").repeated(filterItem.second - 1) + - (filterItem.second > 0 ? QStringLiteral("- ") : QStringLiteral("")) + - tr(filterItem.first); + auto text = QStringLiteral(" ").repeated(filterItem.second - 1) + + (filterItem.second > 0 ? QStringLiteral("- ") : QStringLiteral("")) + + tr(filterItem.first); item(i++)->setText(text); } } @@ -688,8 +776,9 @@ void ConstraintFilterList::languageChange() void ConstraintFilterList::setPartiallyChecked() { /* If a group is partially checked or unchecked then we apply Qt::PartiallyChecked. - The for-loop index is starting from the end. This way sub-groups are first set, which enables the bigger group to be set correctly after. - Example: If we go from 0 to count, then the loop starts at 'All' group, which check state of 'Geometric' which is not updated yet.*/ + The for-loop index is starting from the end. This way sub-groups are first set, which enables + the bigger group to be set correctly after. Example: If we go from 0 to count, then the loop + starts at 'All' group, which check state of 'Geometric' which is not updated yet.*/ for (int i = normalFilterCount - 1; i >= 0; i--) { bool mustBeChecked = true; bool mustBeUnchecked = true; @@ -699,13 +788,13 @@ void ConstraintFilterList::setPartiallyChecked() if (i == j) continue; - if (filterAggregates[i][j]) { // if it is in group + if (filterAggregates[i][j]) {// if it is in group numberOfFilterInGroup++; mustBeChecked = mustBeChecked && item(j)->checkState() == Qt::Checked; mustBeUnchecked = mustBeUnchecked && item(j)->checkState() == Qt::Unchecked; } } - if (numberOfFilterInGroup > 1) { //avoid groups of single filters. + if (numberOfFilterInGroup > 1) {// avoid groups of single filters. if (mustBeChecked) item(i)->setCheckState(Qt::Checked); else if (mustBeUnchecked) @@ -732,10 +821,11 @@ FilterValueBitset ConstraintFilterList::getMultiFilter() // ---------------------------------------------------------------------------- -TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) : - TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Constraints"), true, nullptr), - sketchView(sketchView), inEditMode(false), - ui(new Ui_TaskSketcherConstraints) +TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch* sketchView) + : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Constraints"), true, nullptr) + , sketchView(sketchView) + , inEditMode(false) + , ui(new Ui_TaskSketcherConstraints) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -743,7 +833,8 @@ TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) ui->listWidgetConstraints->setSelectionMode(QAbstractItemView::ExtendedSelection); ui->listWidgetConstraints->setEditTriggers(QListWidget::EditKeyPressed); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); ui->filterBox->setChecked(hGrp->GetBool("ConstraintFilterEnabled", true)); ui->filterButton->setEnabled(ui->filterBox->isChecked()); @@ -768,7 +859,8 @@ TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) action4->setCheckable(true); action5->setCheckable(true); - hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); { QSignalBlocker block(this); action1->setChecked(sketchView->Autoconstraints.getValue()); @@ -789,78 +881,77 @@ TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) // connect needed signals + QObject::connect(ui->listWidgetConstraints, + &ConstraintView::itemSelectionChanged, + this, + &TaskSketcherConstraints::onListWidgetConstraintsItemSelectionChanged); + QObject::connect(ui->listWidgetConstraints, + &ConstraintView::itemActivated, + this, + &TaskSketcherConstraints::onListWidgetConstraintsItemActivated); + QObject::connect(ui->listWidgetConstraints, + &ConstraintView::itemChanged, + this, + &TaskSketcherConstraints::onListWidgetConstraintsItemChanged); + QObject::connect(ui->listWidgetConstraints, + &ConstraintView::emitCenterSelectedItems, + this, + &TaskSketcherConstraints::onListWidgetConstraintsEmitCenterSelectedItems); + QObject::connect(ui->listWidgetConstraints, + &ConstraintView::onUpdateDrivingStatus, + this, + &TaskSketcherConstraints::onListWidgetConstraintsUpdateDrivingStatus); + QObject::connect(ui->listWidgetConstraints, + &ConstraintView::onUpdateActiveStatus, + this, + &TaskSketcherConstraints::onListWidgetConstraintsUpdateActiveStatus); QObject::connect( - ui->listWidgetConstraints, &ConstraintView::itemSelectionChanged, - this, &TaskSketcherConstraints::onListWidgetConstraintsItemSelectionChanged - ); + ui->listWidgetConstraints, + &ConstraintView::emitHideSelection3DVisibility, + this, + &TaskSketcherConstraints::onListWidgetConstraintsEmitHideSelection3DVisibility); QObject::connect( - ui->listWidgetConstraints, &ConstraintView::itemActivated, - this, &TaskSketcherConstraints::onListWidgetConstraintsItemActivated - ); + ui->listWidgetConstraints, + &ConstraintView::emitShowSelection3DVisibility, + this, + &TaskSketcherConstraints::onListWidgetConstraintsEmitShowSelection3DVisibility); + QObject::connect(ui->filterBox, + &QCheckBox::stateChanged, + this, + &TaskSketcherConstraints::onFilterBoxStateChanged); QObject::connect( - ui->listWidgetConstraints, &ConstraintView::itemChanged, - this, &TaskSketcherConstraints::onListWidgetConstraintsItemChanged - ); + ui->filterButton, &QToolButton::clicked, ui->filterButton, &QToolButton::showMenu); + QObject::connect(ui->showHideButton, + &QToolButton::clicked, + this, + &TaskSketcherConstraints::onShowHideButtonClicked); QObject::connect( - ui->listWidgetConstraints, &ConstraintView::emitCenterSelectedItems, - this, &TaskSketcherConstraints::onListWidgetConstraintsEmitCenterSelectedItems - ); - QObject::connect( - ui->listWidgetConstraints, &ConstraintView::onUpdateDrivingStatus, - this, &TaskSketcherConstraints::onListWidgetConstraintsUpdateDrivingStatus - ); - QObject::connect( - ui->listWidgetConstraints, &ConstraintView::onUpdateActiveStatus, - this, &TaskSketcherConstraints::onListWidgetConstraintsUpdateActiveStatus - ); - QObject::connect( - ui->listWidgetConstraints, &ConstraintView::emitHideSelection3DVisibility, - this, &TaskSketcherConstraints::onListWidgetConstraintsEmitHideSelection3DVisibility - ); - QObject::connect( - ui->listWidgetConstraints, &ConstraintView::emitShowSelection3DVisibility, - this, &TaskSketcherConstraints::onListWidgetConstraintsEmitShowSelection3DVisibility - ); - QObject::connect( - ui->filterBox, &QCheckBox::stateChanged, - this, &TaskSketcherConstraints::onFilterBoxStateChanged - ); - QObject::connect( - ui->filterButton, &QToolButton::clicked, - ui->filterButton, &QToolButton::showMenu - ); - QObject::connect( - ui->showHideButton, &QToolButton::clicked, - this, &TaskSketcherConstraints::onShowHideButtonClicked - ); - QObject::connect( - ui->settingsButton, &QToolButton::clicked, - ui->settingsButton, &QToolButton::showMenu - ); - QObject::connect( - action1, &QAction::triggered, // 'triggered' is emitted only on user action. This is defensive. See if 'toggled' is needed - this, &TaskSketcherConstraints::onSettingsAutoConstraintsChanged - ); - QObject::connect( - action2, &QAction::triggered, - this, &TaskSketcherConstraints::onSettingsAutoRemoveRedundantChanged - ); - QObject::connect( - action3, &QAction::triggered, - this, &TaskSketcherConstraints::onSettingsRestrictVisibilityChanged - ); - QObject::connect( - action4, &QAction::triggered, - this, &TaskSketcherConstraints::onSettingsExtendedInformationChanged - ); - QObject::connect( - action5, &QAction::triggered, - this, &TaskSketcherConstraints::onSettingsHideInternalAligmentChanged - ); - QObject::connect( - filterList, &ConstraintFilterList::itemChanged, - this, &TaskSketcherConstraints::onFilterListItemChanged - ); + ui->settingsButton, &QToolButton::clicked, ui->settingsButton, &QToolButton::showMenu); + QObject::connect(action1, + &QAction::triggered,// 'triggered' is emitted only on user action. This is + // defensive. See if 'toggled' is needed + this, + &TaskSketcherConstraints::onSettingsAutoConstraintsChanged); + QObject::connect(action2, + &QAction::triggered, + this, + &TaskSketcherConstraints::onSettingsAutoRemoveRedundantChanged); + QObject::connect(action3, + &QAction::triggered, + this, + &TaskSketcherConstraints::onSettingsRestrictVisibilityChanged); + QObject::connect(action4, + &QAction::triggered, + this, + &TaskSketcherConstraints::onSettingsExtendedInformationChanged); + QObject::connect(action5, + &QAction::triggered, + this, + &TaskSketcherConstraints::onSettingsHideInternalAligmentChanged); + QObject::connect(filterList, + &ConstraintFilterList::itemChanged, + this, + &TaskSketcherConstraints::onFilterListItemChanged); connectionConstraintsChanged = sketchView->signalConstraintsChanged.connect( boost::bind(&SketcherGui::TaskSketcherConstraints::slotConstraintsChanged, this)); @@ -872,12 +963,12 @@ TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) ui->listWidgetConstraints->setStyleSheet(QString::fromLatin1("margin-top: 0px")); Gui::Application* app = Gui::Application::Instance; - changedSketchView = app->signalChangedObject.connect(boost::bind - (&TaskSketcherConstraints::onChangedSketchView, this, bp::_1, bp::_2)); + changedSketchView = app->signalChangedObject.connect( + boost::bind(&TaskSketcherConstraints::onChangedSketchView, this, bp::_1, bp::_2)); - slotConstraintsChanged(); // Populate constraints list + slotConstraintsChanged();// Populate constraints list // Initialize special filters - for (int i = filterList->normalFilterCount ; i < filterList->count() ; i++) { + for (int i = filterList->normalFilterCount; i < filterList->count(); i++) { onFilterListItemChanged(filterList->item(i)); } } @@ -885,12 +976,15 @@ TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) TaskSketcherConstraints::~TaskSketcherConstraints() { connectionConstraintsChanged.disconnect(); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher")->Detach(this); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher") + ->Detach(this); } void TaskSketcherConstraints::onSettingsExtendedInformationChanged(bool value) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); if (hGrp->GetBool("ExtendedConstraintInformation", false) != value) { hGrp->SetBool("ExtendedConstraintInformation", value); @@ -902,7 +996,8 @@ void TaskSketcherConstraints::onSettingsExtendedInformationChanged(bool value) void TaskSketcherConstraints::onSettingsHideInternalAligmentChanged(bool value) { // synchronise parameter - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); if (hGrp->GetBool("HideInternalAlignment", false) != value) { hGrp->SetBool("HideInternalAlignment", value); @@ -914,7 +1009,8 @@ void TaskSketcherConstraints::onSettingsHideInternalAligmentChanged(bool value) void TaskSketcherConstraints::onSettingsRestrictVisibilityChanged(bool value) { // synchronise VisualisationTrackingFilter parameter - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); if (hGrp->GetBool("VisualisationTrackingFilter", false) != value) { hGrp->SetBool("VisualisationTrackingFilter", value); @@ -927,7 +1023,8 @@ void TaskSketcherConstraints::onSettingsRestrictVisibilityChanged(bool value) void TaskSketcherConstraints::onSettingsAutoConstraintsChanged(bool value) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); Base::ConnectionBlocker block(changedSketchView); sketchView->Autoconstraints.setValue(value); @@ -935,26 +1032,31 @@ void TaskSketcherConstraints::onSettingsAutoConstraintsChanged(bool value) void TaskSketcherConstraints::onSettingsAutoRemoveRedundantChanged(bool value) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); if (hGrp->GetBool("AutoRemoveRedundants", false) != value) { hGrp->SetBool("AutoRemoveRedundants", value); } } -void TaskSketcherConstraints::onChangedSketchView(const Gui::ViewProvider& vp, const App::Property& prop) +void TaskSketcherConstraints::onChangedSketchView(const Gui::ViewProvider& vp, + const App::Property& prop) { if (sketchView == &vp) { if (&sketchView->Autoconstraints == &prop) { QSignalBlocker block(qAsConst(ui->settingsButton)->actions()[0]); - qAsConst(ui->settingsButton)->actions()[0]->setChecked(sketchView->Autoconstraints.getValue()); + qAsConst(ui->settingsButton) + ->actions()[0] + ->setChecked(sketchView->Autoconstraints.getValue()); } } } void TaskSketcherConstraints::onFilterBoxStateChanged(int val) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrp->SetBool("ConstraintFilterEnabled", val == Qt::Checked); ui->filterButton->setEnabled(val == Qt::Checked); @@ -966,7 +1068,7 @@ void TaskSketcherConstraints::onShowHideButtonClicked(bool val) { Q_UNUSED(val) bool allSelected = true; - for (int i = 0; i < ui->listWidgetConstraints->count(); ++i){ + for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { QListWidgetItem* it = ui->listWidgetConstraints->item(i); if (!(it->isHidden()) && it->checkState() == Qt::Unchecked) { allSelected = false; @@ -995,8 +1097,7 @@ void TaskSketcherConstraints::changeFilteredVisibility(bool show, ActionTarget t std::vector constrIds; - for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) - { + for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { QListWidgetItem* item = ui->listWidgetConstraints->item(i); bool processItem = false; @@ -1009,15 +1110,16 @@ void TaskSketcherConstraints::changeFilteredVisibility(bool show, ActionTarget t processItem = true; } - if (processItem) { // The item is shown in the filtered list + if (processItem) {// The item is shown in the filtered list const ConstraintItem* it = dynamic_cast(item); if (!it) continue; - // must change state is shown and is to be hidden or hidden and must change state is shown - if ((it->isInVirtualSpace() == sketchView->getIsShownVirtualSpace() && !show) || - (it->isInVirtualSpace() != sketchView->getIsShownVirtualSpace() && show)) { + // must change state is shown and is to be hidden or hidden and must change state is + // shown + if ((it->isInVirtualSpace() == sketchView->getIsShownVirtualSpace() && !show) + || (it->isInVirtualSpace() != sketchView->getIsShownVirtualSpace() && show)) { constrIds.push_back(it->ConstraintNbr); } @@ -1026,7 +1128,8 @@ void TaskSketcherConstraints::changeFilteredVisibility(bool show, ActionTarget t if (!constrIds.empty()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); std::stringstream stream; @@ -1040,45 +1143,45 @@ void TaskSketcherConstraints::changeFilteredVisibility(bool show, ActionTarget t std::string constrIdList = stream.str(); try { - Gui::cmdAppObjectArgs(sketch, "setVirtualSpace(%s, %s)", - constrIdList, - show ? "False" : "True"); - + Gui::cmdAppObjectArgs( + sketch, "setVirtualSpace(%s, %s)", constrIdList, show ? "False" : "True"); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); - Gui::TranslatedUserError(sketch, - tr("Error"), - tr("Impossible to update visibility tracking")); + Gui::TranslatedUserError( + sketch, tr("Error"), tr("Impossible to update visibility tracking")); return; } Gui::Command::commitCommand(); } - } -void TaskSketcherConstraints::onListWidgetConstraintsUpdateDrivingStatus(QListWidgetItem* item, bool status) +void TaskSketcherConstraints::onListWidgetConstraintsUpdateDrivingStatus(QListWidgetItem* item, + bool status) { Q_UNUSED(status); ConstraintItem* citem = dynamic_cast(item); if (!citem) return; - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_ToggleDrivingConstraint"); + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_ToggleDrivingConstraint"); slotConstraintsChanged(); } -void TaskSketcherConstraints::onListWidgetConstraintsUpdateActiveStatus(QListWidgetItem* item, bool status) +void TaskSketcherConstraints::onListWidgetConstraintsUpdateActiveStatus(QListWidgetItem* item, + bool status) { Q_UNUSED(status); ConstraintItem* citem = dynamic_cast(item); if (!citem) return; - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_ToggleActiveConstraint"); + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_ToggleActiveConstraint"); slotConstraintsChanged(); } @@ -1107,51 +1210,52 @@ void TaskSketcherConstraints::onListWidgetConstraintsItemChanged(QListWidgetItem assert(sketchView); const Sketcher::SketchObject* sketch = sketchView->getSketchObject(); - const std::vector< Sketcher::Constraint* >& vals = sketch->Constraints.getValues(); + const std::vector& vals = sketch->Constraints.getValues(); const Sketcher::Constraint* v = vals[it->ConstraintNbr]; const std::string currConstraintName = v->Name; const std::string basename = Base::Tools::toStdString(it->data(Qt::EditRole).toString()); - std::string newName(Sketcher::PropertyConstraintList::getConstraintName(basename, it->ConstraintNbr)); + std::string newName( + Sketcher::PropertyConstraintList::getConstraintName(basename, it->ConstraintNbr)); // we only start a rename if we are really sure the name has changed, which is: // a) that the name generated by the constraints is different from the text in the widget item // b) that the text in the widget item, basename, is not "" - // otherwise a checkbox change will trigger a rename on the first execution, bloating the constraint icons with the - // default constraint name "constraint1, constraint2" + // otherwise a checkbox change will trigger a rename on the first execution, bloating the + // constraint icons with the default constraint name "constraint1, constraint2" if (newName != currConstraintName && !basename.empty()) { std::string escapedstr = Base::Tools::escapedUnicodeFromUtf8(newName.c_str()); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Rename sketch constraint")); try { - Gui::cmdAppObjectArgs(sketch, "renameConstraint(%d, u'%s')", - it->ConstraintNbr, escapedstr.c_str()); + Gui::cmdAppObjectArgs( + sketch, "renameConstraint(%d, u'%s')", it->ConstraintNbr, escapedstr.c_str()); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); - Gui::NotifyUserError(sketch, - QT_TRANSLATE_NOOP("Notifications", "Value Error"), - e.what()); + Gui::NotifyUserError( + sketch, QT_TRANSLATE_NOOP("Notifications", "Value Error"), e.what()); } } // update constraint virtual space status Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); try { - Gui::cmdAppObjectArgs(sketch, "setVirtualSpace(%d, %s)", + Gui::cmdAppObjectArgs( + sketch, + "setVirtualSpace(%d, %s)", it->ConstraintNbr, - ((item->checkState() == Qt::Checked) != sketchView->getIsShownVirtualSpace()) ? "False" : "True"); + ((item->checkState() == Qt::Checked) != sketchView->getIsShownVirtualSpace()) ? "False" + : "True"); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); - Gui::NotifyUserError(sketch, - QT_TRANSLATE_NOOP("Notifications", "Value Error"), - e.what()); + Gui::NotifyUserError(sketch, QT_TRANSLATE_NOOP("Notifications", "Value Error"), e.what()); } inEditMode = false; @@ -1164,7 +1268,7 @@ void TaskSketcherConstraints::updateSelectionFilter() selectionFilter.clear(); - for(const auto & item : items) + for (const auto& item : items) selectionFilter.push_back(static_cast(item)->ConstraintNbr); } @@ -1183,22 +1287,23 @@ void TaskSketcherConstraints::updateAssociatedConstraintsFilter() } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); - const Sketcher::SketchObject * Obj = sketchView->getSketchObject(); - const std::vector< Sketcher::Constraint * > &vals = Obj->Constraints.getValues(); + const std::vector& SubNames = selection[0].getSubNames(); + const Sketcher::SketchObject* Obj = sketchView->getSketchObject(); + const std::vector& vals = Obj->Constraints.getValues(); std::vector constraintSubNames; // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { // only handle edges - if (it->size() > 4 && it->substr(0,4) == "Edge") { - int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + int GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; // push all the constraints int i = 0; - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); - it != vals.end(); ++it,++i) - { + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it, ++i) { if ((*it)->First == GeoId || (*it)->Second == GeoId || (*it)->Third == GeoId) { associatedConstraintsFilter.push_back(i); } @@ -1209,14 +1314,17 @@ void TaskSketcherConstraints::updateAssociatedConstraintsFilter() void TaskSketcherConstraints::updateList() { - multiFilterStatus = filterList->getMultiFilter(); //moved here in case the filter is changed programmatically. + multiFilterStatus = + filterList->getMultiFilter();// moved here in case the filter is changed programmatically. // enforce constraint visibility - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool visibilityTracksFilter = hGrp->GetBool("VisualisationTrackingFilter",false); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool visibilityTracksFilter = hGrp->GetBool("VisualisationTrackingFilter", false); - if(visibilityTracksFilter) - change3DViewVisibilityToTrackFilter(); // it will call slotConstraintChanged via update mechanism + if (visibilityTracksFilter) + change3DViewVisibilityToTrackFilter();// it will call slotConstraintChanged via update + // mechanism else slotConstraintsChanged(); } @@ -1231,10 +1339,10 @@ void TaskSketcherConstraints::onSelectionChanged(const Gui::SelectionChanges& ms ui->listWidgetConstraints->clearSelection(); ui->listWidgetConstraints->blockSignals(tmpBlock); - if(specialFilterMode == SpecialFilterType::Selected) { + if (specialFilterMode == SpecialFilterType::Selected) { updateSelectionFilter(); - bool block = this->blockSelection(true); // avoid to be notified by itself + bool block = this->blockSelection(true);// avoid to be notified by itself updateList(); this->blockSelection(block); } @@ -1243,25 +1351,25 @@ void TaskSketcherConstraints::onSelectionChanged(const Gui::SelectionChanges& ms updateList(); } } - else if (msg.Type == Gui::SelectionChanges::AddSelection || - msg.Type == Gui::SelectionChanges::RmvSelection) { + else if (msg.Type == Gui::SelectionChanges::AddSelection + || msg.Type == Gui::SelectionChanges::RmvSelection) { bool select = (msg.Type == Gui::SelectionChanges::AddSelection); // is it this object?? - if (strcmp(msg.pDocName,sketchView->getSketchObject()->getDocument()->getName())==0 && - strcmp(msg.pObjectName,sketchView->getSketchObject()->getNameInDocument())== 0) { + if (strcmp(msg.pDocName, sketchView->getSketchObject()->getDocument()->getName()) == 0 + && strcmp(msg.pObjectName, sketchView->getSketchObject()->getNameInDocument()) == 0) { if (msg.pSubName) { QRegularExpression rx(QString::fromLatin1("^Constraint(\\d+)$")); QRegularExpressionMatch match; QString expr = QString::fromLatin1(msg.pSubName); boost::ignore_unused(expr.indexOf(rx, 0, &match)); - if (match.hasMatch()) { // is a constraint + if (match.hasMatch()) {// is a constraint bool ok; int ConstrId = match.captured(1).toInt(&ok) - 1; if (ok) { int countItems = ui->listWidgetConstraints->count(); - for (int i=0; i < countItems; i++) { - ConstraintItem* item = static_cast - (ui->listWidgetConstraints->item(i)); + for (int i = 0; i < countItems; i++) { + ConstraintItem* item = + static_cast(ui->listWidgetConstraints->item(i)); if (item->ConstraintNbr == ConstrId) { auto tmpBlock = ui->listWidgetConstraints->blockSignals(true); item->setSelected(select); @@ -1270,23 +1378,26 @@ void TaskSketcherConstraints::onSelectionChanged(const Gui::SelectionChanges& ms } } - if(specialFilterMode == SpecialFilterType::Selected) { + if (specialFilterMode == SpecialFilterType::Selected) { updateSelectionFilter(); - bool block = this->blockSelection(true); // avoid to be notified by itself + bool block = + this->blockSelection(true);// avoid to be notified by itself updateList(); this->blockSelection(block); } } } - else if(specialFilterMode == SpecialFilterType::Associated) { // is NOT a constraint + else if (specialFilterMode == SpecialFilterType::Associated) {// is NOT a constraint int geoid = Sketcher::GeoEnum::GeoUndef; Sketcher::PointPos pointpos = Sketcher::PointPos::none; getSelectionGeoId(expr, geoid, pointpos); - if(geoid != Sketcher::GeoEnum::GeoUndef && pointpos == Sketcher::PointPos::none){ - // It is not possible to update on single addition/removal of a geometric element, - // as one removal may imply removing a constraint that should be added by a different element - // that is still selected. The necessary checks outweigh a full rebuild of the filter. + if (geoid != Sketcher::GeoEnum::GeoUndef + && pointpos == Sketcher::PointPos::none) { + // It is not possible to update on single addition/removal of a geometric + // element, as one removal may imply removing a constraint that should be + // added by a different element that is still selected. The necessary checks + // outweigh a full rebuild of the filter. updateAssociatedConstraintsFilter(); updateList(); } @@ -1299,11 +1410,12 @@ void TaskSketcherConstraints::onSelectionChanged(const Gui::SelectionChanges& ms } } -void TaskSketcherConstraints::OnChange(Base::Subject &rCaller,const char* rcReason) +void TaskSketcherConstraints::OnChange(Base::Subject& rCaller, const char* rcReason) { Q_UNUSED(rCaller); int actNum = -1; - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); if (strcmp(rcReason, "AutoRemoveRedundants") == 0) { actNum = 1; } @@ -1322,7 +1434,8 @@ void TaskSketcherConstraints::OnChange(Base::Subject &rCaller,const } } -void TaskSketcherConstraints::getSelectionGeoId(QString expr, int & geoid, Sketcher::PointPos & pointpos) +void TaskSketcherConstraints::getSelectionGeoId(QString expr, int& geoid, + Sketcher::PointPos& pointpos) { QRegularExpression rxEdge(QString::fromLatin1("^Edge(\\d+)$")); QRegularExpressionMatch match; @@ -1345,7 +1458,7 @@ void TaskSketcherConstraints::getSelectionGeoId(QString expr, int & geoid, Sketc bool ok; int vertexId = match.captured(1).toInt(&ok) - 1; if (ok) { - const Sketcher::SketchObject * sketch = sketchView->getSketchObject(); + const Sketcher::SketchObject* sketch = sketchView->getSketchObject(); sketch->getGeoVertexIndex(vertexId, geoid, pointpos); } } @@ -1362,17 +1475,18 @@ void TaskSketcherConstraints::onListWidgetConstraintsItemSelectionChanged() std::string doc_name = sketchView->getSketchObject()->getDocument()->getName(); std::string obj_name = sketchView->getSketchObject()->getNameInDocument(); - bool block = this->blockSelection(true); // avoid to be notified by itself + bool block = this->blockSelection(true);// avoid to be notified by itself Gui::Selection().clearSelection(); std::vector constraintSubNames; - QList items = ui->listWidgetConstraints->selectedItems(); - for (QList::iterator it = items.begin(); it != items.end(); ++it) { - std::string constraint_name(Sketcher::PropertyConstraintList::getConstraintName(static_cast(*it)->ConstraintNbr)); + QList items = ui->listWidgetConstraints->selectedItems(); + for (QList::iterator it = items.begin(); it != items.end(); ++it) { + std::string constraint_name(Sketcher::PropertyConstraintList::getConstraintName( + static_cast(*it)->ConstraintNbr)); constraintSubNames.push_back(constraint_name); } - if(!constraintSubNames.empty()) + if (!constraintSubNames.empty()) Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), constraintSubNames); this->blockSelection(block); @@ -1382,54 +1496,54 @@ void TaskSketcherConstraints::change3DViewVisibilityToTrackFilter() { assert(sketchView); // Build up ListView with the constraints - const Sketcher::SketchObject * sketch = sketchView->getSketchObject(); - const std::vector< Sketcher::Constraint * > &vals = sketch->Constraints.getValues(); + const Sketcher::SketchObject* sketch = sketchView->getSketchObject(); + const std::vector& vals = sketch->Constraints.getValues(); std::vector constrIdsToVirtualSpace; std::vector constrIdsToCurrentSpace; - for(std::size_t i = 0; i < vals.size(); ++i) { - ConstraintItem * it = static_cast(ui->listWidgetConstraints->item(i)); + for (std::size_t i = 0; i < vals.size(); ++i) { + ConstraintItem* it = static_cast(ui->listWidgetConstraints->item(i)); bool visible = !isConstraintFiltered(it); // If the constraint is filteredout and it was previously shown in 3D view - if( !visible && it->isInVirtualSpace() == sketchView->getIsShownVirtualSpace()) { + if (!visible && it->isInVirtualSpace() == sketchView->getIsShownVirtualSpace()) { constrIdsToVirtualSpace.push_back(it->ConstraintNbr); } - else if( visible && it->isInVirtualSpace() != sketchView->getIsShownVirtualSpace() ) { + else if (visible && it->isInVirtualSpace() != sketchView->getIsShownVirtualSpace()) { constrIdsToCurrentSpace.push_back(it->ConstraintNbr); } } - if(!constrIdsToVirtualSpace.empty() || !constrIdsToCurrentSpace.empty()) { + if (!constrIdsToVirtualSpace.empty() || !constrIdsToCurrentSpace.empty()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space")); - auto doSetVirtualSpace = [&sketch](const std::vector & constrIds, bool isvirtualspace) { + auto doSetVirtualSpace = [&sketch](const std::vector& constrIds, bool isvirtualspace) { std::stringstream stream; stream << '['; - for(size_t i = 0; i < constrIds.size()-1; i++) { + for (size_t i = 0; i < constrIds.size() - 1; i++) { stream << constrIds[i] << ","; } - stream << constrIds[constrIds.size()-1] << ']'; + stream << constrIds[constrIds.size() - 1] << ']'; std::string constrIdList = stream.str(); try { - Gui::cmdAppObjectArgs(sketch, "setVirtualSpace(%s, %s)", - constrIdList, - isvirtualspace?"True":"False"); - + Gui::cmdAppObjectArgs(sketch, + "setVirtualSpace(%s, %s)", + constrIdList, + isvirtualspace ? "True" : "False"); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { Gui::Command::abortCommand(); - Gui::TranslatedUserError(sketch, - tr("Error"), - tr("Impossible to update visibility tracking: ")); + Gui::TranslatedUserError( + sketch, tr("Error"), tr("Impossible to update visibility tracking: ")); return false; } @@ -1438,108 +1552,112 @@ void TaskSketcherConstraints::change3DViewVisibilityToTrackFilter() }; - if(!constrIdsToVirtualSpace.empty()) { + if (!constrIdsToVirtualSpace.empty()) { bool ret = doSetVirtualSpace(constrIdsToVirtualSpace, true); - if(!ret) + if (!ret) return; } - if(!constrIdsToCurrentSpace.empty()) { + if (!constrIdsToCurrentSpace.empty()) { bool ret = doSetVirtualSpace(constrIdsToCurrentSpace, false); - if(!ret) + if (!ret) return; } Gui::Command::commitCommand(); - } - } -bool TaskSketcherConstraints::isConstraintFiltered(QListWidgetItem * item) +bool TaskSketcherConstraints::isConstraintFiltered(QListWidgetItem* item) { assert(sketchView); - const Sketcher::SketchObject * sketch = sketchView->getSketchObject(); - const std::vector< Sketcher::Constraint * > &vals = sketch->Constraints.getValues(); - ConstraintItem * it = static_cast(item); - const Sketcher::Constraint * constraint = vals[it->ConstraintNbr]; + const Sketcher::SketchObject* sketch = sketchView->getSketchObject(); + const std::vector& vals = sketch->Constraints.getValues(); + ConstraintItem* it = static_cast(item); + const Sketcher::Constraint* constraint = vals[it->ConstraintNbr]; - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool hideInternalAlignment = hGrp->GetBool("HideInternalAlignment",false); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + bool hideInternalAlignment = hGrp->GetBool("HideInternalAlignment", false); bool visible = true; - if(ui->filterBox->checkState() == Qt::Checked) { - //First select only the filtered one. + if (ui->filterBox->checkState() == Qt::Checked) { + // First select only the filtered one. switch (constraint->Type) { - case Sketcher::Horizontal: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Horizontal); - break; - case Sketcher::Vertical: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Vertical); - break; - case Sketcher::Coincident: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Coincident); - break; - case Sketcher::PointOnObject: - visible = checkFilterBitset(multiFilterStatus, FilterValue::PointOnObject); - break; - case Sketcher::Parallel: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Parallel); - break; - case Sketcher::Perpendicular: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Perpendicular); - break; - case Sketcher::Tangent: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Tangent); - break; - case Sketcher::Equal: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Equality); - break; - case Sketcher::Symmetric: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Symmetric); - break; - case Sketcher::Block: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Block); - break; - case Sketcher::Distance: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Distance); - break; - case Sketcher::DistanceX: - visible = checkFilterBitset(multiFilterStatus, FilterValue::HorizontalDistance); - break; - case Sketcher::DistanceY: - visible = checkFilterBitset(multiFilterStatus, FilterValue::VerticalDistance); - break; - case Sketcher::Radius: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Radius); - break; - case Sketcher::Weight: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Weight); - break; - case Sketcher::Diameter: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Diameter); - break; - case Sketcher::Angle: - visible = checkFilterBitset(multiFilterStatus, FilterValue::Angle); - break; - case Sketcher::SnellsLaw: - visible = checkFilterBitset(multiFilterStatus, FilterValue::SnellsLaw); - break; - case Sketcher::InternalAlignment: - visible = checkFilterBitset(multiFilterStatus, FilterValue::InternalAlignment) && !hideInternalAlignment; - default: - break; + case Sketcher::Horizontal: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Horizontal); + break; + case Sketcher::Vertical: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Vertical); + break; + case Sketcher::Coincident: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Coincident); + break; + case Sketcher::PointOnObject: + visible = checkFilterBitset(multiFilterStatus, FilterValue::PointOnObject); + break; + case Sketcher::Parallel: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Parallel); + break; + case Sketcher::Perpendicular: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Perpendicular); + break; + case Sketcher::Tangent: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Tangent); + break; + case Sketcher::Equal: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Equality); + break; + case Sketcher::Symmetric: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Symmetric); + break; + case Sketcher::Block: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Block); + break; + case Sketcher::Distance: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Distance); + break; + case Sketcher::DistanceX: + visible = checkFilterBitset(multiFilterStatus, FilterValue::HorizontalDistance); + break; + case Sketcher::DistanceY: + visible = checkFilterBitset(multiFilterStatus, FilterValue::VerticalDistance); + break; + case Sketcher::Radius: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Radius); + break; + case Sketcher::Weight: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Weight); + break; + case Sketcher::Diameter: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Diameter); + break; + case Sketcher::Angle: + visible = checkFilterBitset(multiFilterStatus, FilterValue::Angle); + break; + case Sketcher::SnellsLaw: + visible = checkFilterBitset(multiFilterStatus, FilterValue::SnellsLaw); + break; + case Sketcher::InternalAlignment: + visible = checkFilterBitset(multiFilterStatus, FilterValue::InternalAlignment) + && !hideInternalAlignment; + default: + break; } - //Then we re-filter based on selected/associated if such mode selected. + // Then we re-filter based on selected/associated if such mode selected. if (visible && specialFilterMode == SpecialFilterType::Selected) { - visible = (std::find(selectionFilter.begin(), selectionFilter.end(), it->ConstraintNbr) != selectionFilter.end()); + visible = (std::find(selectionFilter.begin(), selectionFilter.end(), it->ConstraintNbr) + != selectionFilter.end()); } else if (visible && specialFilterMode == SpecialFilterType::Associated) { - visible = (std::find(associatedConstraintsFilter.begin(), associatedConstraintsFilter.end(), it->ConstraintNbr) != associatedConstraintsFilter.end()); + visible = (std::find(associatedConstraintsFilter.begin(), + associatedConstraintsFilter.end(), + it->ConstraintNbr) + != associatedConstraintsFilter.end()); } } else if (constraint->Type == Sketcher::InternalAlignment) { @@ -1553,12 +1671,12 @@ void TaskSketcherConstraints::slotConstraintsChanged() { assert(sketchView); // Build up ListView with the constraints - const Sketcher::SketchObject * sketch = sketchView->getSketchObject(); - const std::vector< Sketcher::Constraint * > &vals = sketch->Constraints.getValues(); + const Sketcher::SketchObject* sketch = sketchView->getSketchObject(); + const std::vector& vals = sketch->Constraints.getValues(); /* Update constraint number and virtual space check status */ - for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { - ConstraintItem * it = dynamic_cast(ui->listWidgetConstraints->item(i)); + for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { + ConstraintItem* it = dynamic_cast(ui->listWidgetConstraints->item(i)); assert(it); @@ -1576,16 +1694,16 @@ void TaskSketcherConstraints::slotConstraintsChanged() /* Update the states */ auto tmpBlock = ui->listWidgetConstraints->blockSignals(true); - for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { - ConstraintItem * it = static_cast(ui->listWidgetConstraints->item(i)); + for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { + ConstraintItem* it = static_cast(ui->listWidgetConstraints->item(i)); it->updateVirtualSpaceStatus(); } ui->listWidgetConstraints->blockSignals(tmpBlock); /* Update filtering */ - for(std::size_t i = 0; i < vals.size(); ++i) { - const Sketcher::Constraint * constraint = vals[i]; - ConstraintItem * it = static_cast(ui->listWidgetConstraints->item(i)); + for (std::size_t i = 0; i < vals.size(); ++i) { + const Sketcher::Constraint* constraint = vals[i]; + ConstraintItem* it = static_cast(ui->listWidgetConstraints->item(i)); bool visible = !isConstraintFiltered(it); @@ -1598,11 +1716,10 @@ void TaskSketcherConstraints::slotConstraintsChanged() it->setHidden(!visible); it->setData(Qt::EditRole, Base::Tools::fromStdString(constraint->Name)); model->blockSignals(tmpBlock); - } } -void TaskSketcherConstraints::changeEvent(QEvent *e) +void TaskSketcherConstraints::changeEvent(QEvent* e) { TaskBox::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -1621,29 +1738,32 @@ void TaskSketcherConstraints::onFilterListItemChanged(QListWidgetItem* item) auto itemAggregate = filterAggregates[filterindex]; - /*First, if this is a group, we need to set the same state to all of its children. + /*First, if this is a group, we need to set the same state to all of its children. ie any filter comprised on the filter of the activated item, gets the same check state.*/ for (int i = 0; i < filterList->normalFilterCount; i++) { if (itemAggregate[i]) filterList->item(i)->setCheckState(item->checkState()); } - /* Now we also need to see if any modified group is all checked or all unchecked and set their status accordingly*/ + /* Now we also need to see if any modified group is all checked or all unchecked and set + * their status accordingly*/ filterList->setPartiallyChecked(); } - else if (filterindex == filterList->selectedFilterIndex) { //Selected constraints + else if (filterindex == filterList->selectedFilterIndex) {// Selected constraints if (item->checkState() == Qt::Checked) { specialFilterMode = SpecialFilterType::Selected; - filterList->item(filterList->associatedFilterIndex)->setCheckState(Qt::Unchecked); //Disable 'associated' + filterList->item(filterList->associatedFilterIndex) + ->setCheckState(Qt::Unchecked);// Disable 'associated' updateSelectionFilter(); } else specialFilterMode = SpecialFilterType::None; } - else { //Associated constraints + else {// Associated constraints if (item->checkState() == Qt::Checked) { specialFilterMode = SpecialFilterType::Associated; - filterList->item(filterList->selectedFilterIndex)->setCheckState(Qt::Unchecked); //Disable 'selected' + filterList->item(filterList->selectedFilterIndex) + ->setCheckState(Qt::Unchecked);// Disable 'selected' updateAssociatedConstraintsFilter(); } else @@ -1652,20 +1772,22 @@ void TaskSketcherConstraints::onFilterListItemChanged(QListWidgetItem* item) filterList->blockSignals(tmpBlock); - //Save the state of the filter. + // Save the state of the filter. int filterState = 0; for (int i = filterList->count() - 1; i >= 0; i--) { bool isChecked = filterList->item(i)->checkState() == Qt::Checked; - filterState = filterState << 1; //we shift left first, else the list is shifted at the end. + filterState = filterState << 1;// we shift left first, else the list is shifted at the end. filterState = filterState | isChecked; } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrp->SetInt("ConstraintFilterState", filterState); - // if tracking, it will call slotConstraintChanged via update mechanism as Multi Filter affects not only visibility, but also filtered list content, if not tracking will still update the list to match the multi-filter. + // if tracking, it will call slotConstraintChanged via update mechanism as Multi Filter affects + // not only visibility, but also filtered list content, if not tracking will still update the + // list to match the multi-filter. updateList(); } #include "moc_TaskSketcherConstraints.cpp" - diff --git a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h index 33c298ebe5..3072162c59 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h @@ -33,35 +33,38 @@ #include "ConstraintFilters.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { - class ViewProvider; +namespace Gui +{ +class ViewProvider; } -namespace SketcherGui { +namespace SketcherGui +{ using namespace ConstraintFilter; class ViewProviderSketch; class Ui_TaskSketcherConstraints; -class ConstraintView : public QListWidget +class ConstraintView: public QListWidget { Q_OBJECT public: - explicit ConstraintView(QWidget *parent = nullptr); + explicit ConstraintView(QWidget* parent = nullptr); ~ConstraintView() override; protected: - void contextMenuEvent (QContextMenuEvent* event) override; + void contextMenuEvent(QContextMenuEvent* event) override; Q_SIGNALS: - void onUpdateDrivingStatus(QListWidgetItem *item, bool status); - void onUpdateActiveStatus(QListWidgetItem *item, bool status); + void onUpdateDrivingStatus(QListWidgetItem* item, bool status); + void onUpdateActiveStatus(QListWidgetItem* item, bool status); void emitCenterSelectedItems(); void emitHideSelection3DVisibility(); void emitShowSelection3DVisibility(); @@ -79,7 +82,7 @@ protected Q_SLOTS: void hideConstraints(); }; -class ConstraintFilterList : public QListWidget +class ConstraintFilterList: public QListWidget { Q_OBJECT @@ -91,7 +94,7 @@ public: FilterValueBitset getMultiFilter(); - int normalFilterCount; //All filters but selected and associated + int normalFilterCount;// All filters but selected and associated int selectedFilterIndex; int associatedFilterIndex; @@ -100,82 +103,84 @@ protected: virtual void languageChange(); private: - using filterItemRepr = std::pair; // {filter item text, filter item level} + using filterItemRepr = + std::pair;// {filter item text, filter item level} inline static const std::vector filterItems = { - {QT_TR_NOOP("All"),0}, - {QT_TR_NOOP("Geometric"),0}, - {QT_TR_NOOP("Coincident"),1}, - {QT_TR_NOOP("Point on Object"),1}, - {QT_TR_NOOP("Vertical"),1}, - {QT_TR_NOOP("Horizontal"),1}, - {QT_TR_NOOP("Parallel"),1}, - {QT_TR_NOOP("Perpendicular"),1}, - {QT_TR_NOOP("Tangent"),1}, - {QT_TR_NOOP("Equality"),1}, - {QT_TR_NOOP("Symmetric"),1}, - {QT_TR_NOOP("Block"),1}, - {QT_TR_NOOP("Internal Alignment"),1}, - {QT_TR_NOOP("Datums"),0}, - {QT_TR_NOOP("Horizontal Distance"),1}, - {QT_TR_NOOP("Vertical Distance"),1}, - {QT_TR_NOOP("Distance"),1}, - {QT_TR_NOOP("Radius"),1}, - {QT_TR_NOOP("Weight"),1}, - {QT_TR_NOOP("Diameter"),1}, - {QT_TR_NOOP("Angle"),1}, - {QT_TR_NOOP("Snell's Law"),1}, - {QT_TR_NOOP("Named"),0}, - {QT_TR_NOOP("Reference"),0}, - {QT_TR_NOOP("Selected constraints"),0}, - {QT_TR_NOOP("Associated constraints"),0}, + {QT_TR_NOOP("All"), 0}, + {QT_TR_NOOP("Geometric"), 0}, + {QT_TR_NOOP("Coincident"), 1}, + {QT_TR_NOOP("Point on Object"), 1}, + {QT_TR_NOOP("Vertical"), 1}, + {QT_TR_NOOP("Horizontal"), 1}, + {QT_TR_NOOP("Parallel"), 1}, + {QT_TR_NOOP("Perpendicular"), 1}, + {QT_TR_NOOP("Tangent"), 1}, + {QT_TR_NOOP("Equality"), 1}, + {QT_TR_NOOP("Symmetric"), 1}, + {QT_TR_NOOP("Block"), 1}, + {QT_TR_NOOP("Internal Alignment"), 1}, + {QT_TR_NOOP("Datums"), 0}, + {QT_TR_NOOP("Horizontal Distance"), 1}, + {QT_TR_NOOP("Vertical Distance"), 1}, + {QT_TR_NOOP("Distance"), 1}, + {QT_TR_NOOP("Radius"), 1}, + {QT_TR_NOOP("Weight"), 1}, + {QT_TR_NOOP("Diameter"), 1}, + {QT_TR_NOOP("Angle"), 1}, + {QT_TR_NOOP("Snell's Law"), 1}, + {QT_TR_NOOP("Named"), 0}, + {QT_TR_NOOP("Reference"), 0}, + {QT_TR_NOOP("Selected constraints"), 0}, + {QT_TR_NOOP("Associated constraints"), 0}, }; }; -class TaskSketcherConstraints : - public Gui::TaskView::TaskBox, - public Gui::SelectionObserver, - public ParameterGrp::ObserverType +class TaskSketcherConstraints: public Gui::TaskView::TaskBox, + public Gui::SelectionObserver, + public ParameterGrp::ObserverType { Q_OBJECT - enum class ActionTarget { + enum class ActionTarget + { All, Selected }; - enum class SpecialFilterType { + enum class SpecialFilterType + { None, Associated, Selected }; public: - explicit TaskSketcherConstraints(ViewProviderSketch *sketchView); + explicit TaskSketcherConstraints(ViewProviderSketch* sketchView); ~TaskSketcherConstraints() override; /// Observer message from the Selection void onSelectionChanged(const Gui::SelectionChanges& msg) override; - void OnChange(Base::Subject &rCaller,const char* rcReason) override; + void OnChange(Base::Subject& rCaller, const char* rcReason) override; SpecialFilterType specialFilterMode; private: void slotConstraintsChanged(); - bool isConstraintFiltered(QListWidgetItem * item); + bool isConstraintFiltered(QListWidgetItem* item); void change3DViewVisibilityToTrackFilter(); void changeFilteredVisibility(bool show, ActionTarget target = ActionTarget::All); void updateSelectionFilter(); void updateAssociatedConstraintsFilter(); void updateList(); - void getSelectionGeoId(QString expr, int & geoid, Sketcher::PointPos & pos); + void getSelectionGeoId(QString expr, int& geoid, Sketcher::PointPos& pos); public: void onListWidgetConstraintsItemSelectionChanged(); - void onListWidgetConstraintsItemActivated(QListWidgetItem *item); - void onListWidgetConstraintsItemChanged(QListWidgetItem * item); - void onListWidgetConstraintsUpdateDrivingStatus(QListWidgetItem *item, bool status); - void onListWidgetConstraintsUpdateActiveStatus(QListWidgetItem *item, bool status); + void onListWidgetConstraintsItemActivated(QListWidgetItem* item); + void onListWidgetConstraintsItemChanged(QListWidgetItem* item); + void onListWidgetConstraintsUpdateDrivingStatus(QListWidgetItem* item, bool status); + void onListWidgetConstraintsUpdateActiveStatus(QListWidgetItem* item, bool status); void onListWidgetConstraintsEmitCenterSelectedItems(); void onListWidgetConstraintsEmitShowSelection3DVisibility(); void onListWidgetConstraintsEmitHideSelection3DVisibility(); @@ -189,8 +194,8 @@ public: void onFilterListItemChanged(QListWidgetItem* item); protected: - void changeEvent(QEvent *e) override; - ViewProviderSketch *sketchView; + void changeEvent(QEvent* e) override; + ViewProviderSketch* sketchView; using Connection = boost::signals2::connection; Connection connectionConstraintsChanged; @@ -201,14 +206,17 @@ private: QWidget* proxy; bool inEditMode; std::unique_ptr ui; - ConstraintFilter::FilterValueBitset multiFilterStatus; // Stores the filters to be aggregated to form the multifilter. - std::vector selectionFilter; // holds the constraint ids of the selected constraints - std::vector associatedConstraintsFilter; // holds the constraint ids of the constraints associated with the selected geometry + ConstraintFilter::FilterValueBitset + multiFilterStatus;// Stores the filters to be aggregated to form the multifilter. + std::vector + selectionFilter;// holds the constraint ids of the selected constraints + std::vector + associatedConstraintsFilter;// holds the constraint ids of the constraints associated with + // the selected geometry ConstraintFilterList* filterList; boost::signals2::scoped_connection changedSketchView; - }; -} //namespace SketcherGui +}// namespace SketcherGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif// GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp index 646641c422..e41fdaed16 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -32,55 +32,52 @@ using namespace Gui::TaskView; -TaskSketcherCreateCommands::TaskSketcherCreateCommands(QWidget *parent) - : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Appearance"),true, parent) +TaskSketcherCreateCommands::TaskSketcherCreateCommands(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); - //ui = new Ui_TaskAppearance(); - //ui->setupUi(proxy); - //ui->textLabel1_3->hide(); - //ui->changePlot->hide(); - //QMetaObject::connectSlotsByName(this); + // proxy = new QWidget(this); + // ui = new Ui_TaskAppearance(); + // ui->setupUi(proxy); + // ui->textLabel1_3->hide(); + // ui->changePlot->hide(); + // QMetaObject::connectSlotsByName(this); - //this->groupLayout()->addWidget(proxy); + // this->groupLayout()->addWidget(proxy); - //std::vector views; - //setDisplayModes(views); - //setPointSize(views); - //setLineWidth(views); - //setTransparency(views); + // std::vector views; + // setDisplayModes(views); + // setPointSize(views); + // setLineWidth(views); + // setTransparency(views); Gui::Selection().Attach(this); } TaskSketcherCreateCommands::~TaskSketcherCreateCommands() { - //delete ui; + // delete ui; Gui::Selection().Detach(this); } -void TaskSketcherCreateCommands::changeEvent(QEvent *e) +void TaskSketcherCreateCommands::changeEvent(QEvent* e) { TaskBox::changeEvent(e); - //if (e->type() == QEvent::LanguageChange) { - // ui->retranslateUi(proxy); - //} + // if (e->type() == QEvent::LanguageChange) { + // ui->retranslateUi(proxy); + // } } /// @cond DOXERR -void TaskSketcherCreateCommands::OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason) +void TaskSketcherCreateCommands::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) { - } + if (Reason.Type == SelectionChanges::AddSelection + || Reason.Type == SelectionChanges::RmvSelection + || Reason.Type == SelectionChanges::SetSelection + || Reason.Type == SelectionChanges::ClrSelection) {} } /// @endcond DOXERR - - #include "moc_TaskSketcherCreateCommands.cpp" diff --git a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h index 3e96ac6389..69c47e39e7 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h @@ -27,38 +27,40 @@ #include -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; -namespace TaskView { +namespace TaskView +{ - -class TaskSketcherCreateCommands : public TaskBox, public Gui::SelectionSingleton::ObserverType +class TaskSketcherCreateCommands: public TaskBox, public Gui::SelectionSingleton::ObserverType { Q_OBJECT public: - explicit TaskSketcherCreateCommands(QWidget *parent = nullptr); + explicit TaskSketcherCreateCommands(QWidget* parent = nullptr); ~TaskSketcherCreateCommands() override; /// Observer message from the Selection - void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, + void OnChange(Gui::SelectionSingleton::SubjectType& rCaller, Gui::SelectionSingleton::MessageType Reason) override; private Q_SLOTS: - + protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: - //QWidget* proxy; + // QWidget* proxy; }; -} //namespace TaskView -} //namespace Gui +}// namespace TaskView +}// namespace Gui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif// GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp b/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp index 9929fb39b3..378f25f6dc 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp @@ -22,17 +22,17 @@ #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 #endif #include @@ -49,9 +49,9 @@ #include #include "TaskSketcherElements.h" -#include "ui_TaskSketcherElements.h" -#include "ViewProviderSketch.h" #include "Utils.h" +#include "ViewProviderSketch.h" +#include "ui_TaskSketcherElements.h" using namespace SketcherGui; using namespace Gui::TaskView; @@ -89,36 +89,49 @@ QT_TRANSLATE_NOOP("SketcherGui::ElementView", "Select Vertical Axis"); /// CMDSTR is the string registered in the commandManager /// FUNC is the name of the member function to be executed on selection of the menu item /// ACTSONSELECTION is a true/false value to activate the command only if a selection is made -#define CONTEXT_ITEM(ICONSTR,NAMESTR,CMDSTR,FUNC,ACTSONSELECTION) \ -QIcon icon_ ## FUNC( Gui::BitmapFactory().pixmap(ICONSTR) ); \ - QAction* constr_ ## FUNC = menu.addAction(icon_ ## FUNC,tr(NAMESTR), this, SLOT(FUNC()), \ - QKeySequence(QString::fromUtf8(Gui::Application::Instance->commandManager().getCommandByName(CMDSTR)->getAccel()))); \ - if(ACTSONSELECTION) constr_ ## FUNC->setEnabled(!items.isEmpty()); else constr_ ## FUNC->setEnabled(true); +#define CONTEXT_ITEM(ICONSTR, NAMESTR, CMDSTR, FUNC, ACTSONSELECTION) \ + QIcon icon_##FUNC(Gui::BitmapFactory().pixmap(ICONSTR)); \ + QAction* constr_##FUNC = menu.addAction( \ + icon_##FUNC, \ + tr(NAMESTR), \ + this, \ + SLOT(FUNC()), \ + QKeySequence(QString::fromUtf8( \ + Gui::Application::Instance->commandManager().getCommandByName(CMDSTR)->getAccel()))); \ + if (ACTSONSELECTION) \ + constr_##FUNC->setEnabled(!items.isEmpty()); \ + else \ + constr_##FUNC->setEnabled(true); /// Defines the member function corresponding to the CONTEXT_ITEM macro -#define CONTEXT_MEMBER_DEF(CMDSTR,FUNC) \ -void ElementView::FUNC(){ \ - Gui::Application::Instance->commandManager().runCommandByName(CMDSTR);} +#define CONTEXT_MEMBER_DEF(CMDSTR, FUNC) \ + void ElementView::FUNC() \ + { \ + Gui::Application::Instance->commandManager().runCommandByName(CMDSTR); \ + } -namespace SketcherGui { +namespace SketcherGui +{ -class ElementItemDelegate : public QStyledItemDelegate +class ElementItemDelegate: public QStyledItemDelegate { Q_OBJECT public: explicit ElementItemDelegate(ElementView* parent); ~ElementItemDelegate() override; - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) override; + void paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const override; + bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, + const QModelIndex& index) override; ElementItem* getElementtItem(const QModelIndex& index) const; - const int border = 1; //1px, looks good around buttons. - const int leftMargin = 4; //4px on the left of icons, looks good. + const int border = 1; // 1px, looks good around buttons. + const int leftMargin = 4;// 4px on the left of icons, looks good. mutable int customIconsMargin = 4; - const int textBottomMargin = 5; //5px center the text. + const int textBottomMargin = 5;// 5px center the text. Q_SIGNALS: void itemHovered(QModelIndex); @@ -126,26 +139,28 @@ Q_SIGNALS: }; // helper class to store additional information about the listWidget entry. -class ElementItem : public QListWidgetItem +class ElementItem: public QListWidgetItem { - public: - - enum class GeometryState { +public: + enum class GeometryState + { Normal, Construction, InternalAlignment, External }; - enum class Layer { + enum class Layer + { Default = 0, Discontinuous = 1, Hidden = 2, }; ElementItem(int elementnr, int startingVertex, int midVertex, int endVertex, - Base::Type geometryType, GeometryState state, const QString & lab, ViewProviderSketch *sketchView) : - ElementNbr(elementnr) + Base::Type geometryType, GeometryState state, const QString& lab, + ViewProviderSketch* sketchView) + : ElementNbr(elementnr) , StartingVertex(startingVertex) , MidVertex(midVertex) , EndVertex(endVertex) @@ -160,18 +175,17 @@ class ElementItem : public QListWidgetItem , rightClicked(false) , label(lab) , sketchView(sketchView) + {} + + ~ElementItem() override + {} + + bool isVisible() { - } - - ~ElementItem() override { - } - - bool isVisible() { - - if(State != GeometryState::External) { + if (State != GeometryState::External) { const auto geo = sketchView->getSketchObject()->getGeometry(ElementNbr); - if(geo) { + if (geo) { auto layer = getSafeGeomLayerId(geo); return layer != static_cast(Layer::Hidden); @@ -204,11 +218,11 @@ class ElementItem : public QListWidgetItem QString label; - private: - ViewProviderSketch *sketchView; +private: + ViewProviderSketch* sketchView; }; -class ElementFilterList : public QListWidget +class ElementFilterList: public QListWidget { Q_OBJECT @@ -221,28 +235,28 @@ protected: virtual void languageChange(); private: - using filterItemRepr = std::pair; // {filter item text, filter item level} + using filterItemRepr = + std::pair;// {filter item text, filter item level} inline static const std::vector filterItems = { - {QT_TR_NOOP("Normal"),0}, - {QT_TR_NOOP("Construction"),0}, - {QT_TR_NOOP("Internal"),0}, - {QT_TR_NOOP("External"),0}, - {QT_TR_NOOP("All types"),0}, - {QT_TR_NOOP("Point"),1}, - {QT_TR_NOOP("Line"),1}, - {QT_TR_NOOP("Circle"),1}, - {QT_TR_NOOP("Ellipse"),1}, - {QT_TR_NOOP("Arc of circle"),1}, - {QT_TR_NOOP("Arc of ellipse"),1}, - {QT_TR_NOOP("Arc of hyperbola"),1}, - {QT_TR_NOOP("Arc of parabola"),1}, - {QT_TR_NOOP("B-Spline"),1} - }; - + {QT_TR_NOOP("Normal"), 0}, + {QT_TR_NOOP("Construction"), 0}, + {QT_TR_NOOP("Internal"), 0}, + {QT_TR_NOOP("External"), 0}, + {QT_TR_NOOP("All types"), 0}, + {QT_TR_NOOP("Point"), 1}, + {QT_TR_NOOP("Line"), 1}, + {QT_TR_NOOP("Circle"), 1}, + {QT_TR_NOOP("Ellipse"), 1}, + {QT_TR_NOOP("Arc of circle"), 1}, + {QT_TR_NOOP("Arc of ellipse"), 1}, + {QT_TR_NOOP("Arc of hyperbola"), 1}, + {QT_TR_NOOP("Arc of parabola"), 1}, + {QT_TR_NOOP("B-Spline"), 1}}; }; -} // SketcherGui +}// namespace SketcherGui -class ElementWidgetIcons { +class ElementWidgetIcons +{ private: ElementWidgetIcons() @@ -251,112 +265,157 @@ private: } public: - ElementWidgetIcons(const ElementWidgetIcons &) = delete; - ElementWidgetIcons(ElementWidgetIcons &&) = delete; - ElementWidgetIcons & operator=(const ElementWidgetIcons &) = delete; - ElementWidgetIcons & operator=(ElementWidgetIcons &&) = delete; + ElementWidgetIcons(const ElementWidgetIcons&) = delete; + ElementWidgetIcons(ElementWidgetIcons&&) = delete; + ElementWidgetIcons& operator=(const ElementWidgetIcons&) = delete; + ElementWidgetIcons& operator=(ElementWidgetIcons&&) = delete; - static const QIcon & getIcon(Base::Type type, Sketcher::PointPos pos, ElementItem::GeometryState icontype = ElementItem::GeometryState::Normal) { + static const QIcon& + getIcon(Base::Type type, Sketcher::PointPos pos, + ElementItem::GeometryState icontype = ElementItem::GeometryState::Normal) + { static ElementWidgetIcons elementicons; return elementicons.getIconImpl(type, pos, icontype); } private: - void initIcons() { + void initIcons() + { - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomArcOfCircle::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Arc_Edge") }, - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_Arc_StartingPoint") }, - { Sketcher::PointPos::end , getMultIcon("Sketcher_Element_Arc_EndPoint") }, - { Sketcher::PointPos::mid , getMultIcon("Sketcher_Element_Arc_MidPoint") } - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomArcOfCircle::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Arc_Edge")}, + {Sketcher::PointPos::start, getMultIcon("Sketcher_Element_Arc_StartingPoint")}, + {Sketcher::PointPos::end, getMultIcon("Sketcher_Element_Arc_EndPoint")}, + {Sketcher::PointPos::mid, getMultIcon("Sketcher_Element_Arc_MidPoint")}})); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomCircle::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Circle_Edge") }, - { Sketcher::PointPos::mid , getMultIcon("Sketcher_Element_Circle_MidPoint") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomCircle::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Circle_Edge")}, + {Sketcher::PointPos::mid, getMultIcon("Sketcher_Element_Circle_MidPoint")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomLineSegment::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Line_Edge") }, - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_Line_StartingPoint") }, - { Sketcher::PointPos::end , getMultIcon("Sketcher_Element_Line_EndPoint") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomLineSegment::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Line_Edge")}, + {Sketcher::PointPos::start, getMultIcon("Sketcher_Element_Line_StartingPoint")}, + {Sketcher::PointPos::end, getMultIcon("Sketcher_Element_Line_EndPoint")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomPoint::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_Point_StartingPoint") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomPoint::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::start, + getMultIcon("Sketcher_Element_Point_StartingPoint")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomEllipse::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Ellipse_Edge_2") }, - { Sketcher::PointPos::mid , getMultIcon("Sketcher_Element_Ellipse_CentrePoint") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomEllipse::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Ellipse_Edge_2")}, + {Sketcher::PointPos::mid, getMultIcon("Sketcher_Element_Ellipse_CentrePoint")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomArcOfEllipse::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Elliptical_Arc_Edge") }, - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_Elliptical_Arc_Start_Point") }, - { Sketcher::PointPos::end , getMultIcon("Sketcher_Element_Elliptical_Arc_End_Point") }, - { Sketcher::PointPos::mid , getMultIcon("Sketcher_Element_Elliptical_Arc_Centre_Point") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomArcOfEllipse::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Elliptical_Arc_Edge")}, + {Sketcher::PointPos::start, + getMultIcon("Sketcher_Element_Elliptical_Arc_Start_Point")}, + {Sketcher::PointPos::end, + getMultIcon("Sketcher_Element_Elliptical_Arc_End_Point")}, + {Sketcher::PointPos::mid, + getMultIcon("Sketcher_Element_Elliptical_Arc_Centre_Point")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomArcOfHyperbola::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Hyperbolic_Arc_Edge") }, - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_Hyperbolic_Arc_Start_Point") }, - { Sketcher::PointPos::end , getMultIcon("Sketcher_Element_Hyperbolic_Arc_End_Point") }, - { Sketcher::PointPos::mid , getMultIcon("Sketcher_Element_Hyperbolic_Arc_Centre_Point") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomArcOfHyperbola::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Hyperbolic_Arc_Edge")}, + {Sketcher::PointPos::start, + getMultIcon("Sketcher_Element_Hyperbolic_Arc_Start_Point")}, + {Sketcher::PointPos::end, + getMultIcon("Sketcher_Element_Hyperbolic_Arc_End_Point")}, + {Sketcher::PointPos::mid, + getMultIcon("Sketcher_Element_Hyperbolic_Arc_Centre_Point")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomArcOfParabola::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_Parabolic_Arc_Edge") }, - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_Parabolic_Arc_Start_Point") }, - { Sketcher::PointPos::end , getMultIcon("Sketcher_Element_Parabolic_Arc_End_Point") }, - { Sketcher::PointPos::mid , getMultIcon("Sketcher_Element_Parabolic_Arc_Centre_Point") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomArcOfParabola::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_Parabolic_Arc_Edge")}, + {Sketcher::PointPos::start, + getMultIcon("Sketcher_Element_Parabolic_Arc_Start_Point")}, + {Sketcher::PointPos::end, + getMultIcon("Sketcher_Element_Parabolic_Arc_End_Point")}, + {Sketcher::PointPos::mid, + getMultIcon("Sketcher_Element_Parabolic_Arc_Centre_Point")}, + })); - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Part::GeomBSplineCurve::getClassTypeId()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_BSpline_Edge") }, - { Sketcher::PointPos::start , getMultIcon("Sketcher_Element_BSpline_StartPoint") }, - { Sketcher::PointPos::end , getMultIcon("Sketcher_Element_BSpline_EndPoint") }, - })); - - icons.emplace(std::piecewise_construct, - std::forward_as_tuple(Base::Type::badType()), - std::forward_as_tuple(std::initializer_list>> { - { Sketcher::PointPos::none , getMultIcon("Sketcher_Element_SelectionTypeInvalid") }, - })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Part::GeomBSplineCurve::getClassTypeId()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, getMultIcon("Sketcher_Element_BSpline_Edge")}, + {Sketcher::PointPos::start, getMultIcon("Sketcher_Element_BSpline_StartPoint")}, + {Sketcher::PointPos::end, getMultIcon("Sketcher_Element_BSpline_EndPoint")}, + })); + icons.emplace( + std::piecewise_construct, + std::forward_as_tuple(Base::Type::badType()), + std::forward_as_tuple( + std::initializer_list< + std::pair>> { + {Sketcher::PointPos::none, + getMultIcon("Sketcher_Element_SelectionTypeInvalid")}, + })); } - const QIcon & getIconImpl(Base::Type type, Sketcher::PointPos pos, ElementItem::GeometryState icontype) { + const QIcon& getIconImpl(Base::Type type, Sketcher::PointPos pos, + ElementItem::GeometryState icontype) + { auto typekey = icons.find(type); - if( typekey == icons.end()) { // Not supported Geometry Type - Defaults to invalid icon + if (typekey == icons.end()) {// Not supported Geometry Type - Defaults to invalid icon typekey = icons.find(Base::Type::badType()); pos = Sketcher::PointPos::none; } auto poskey = typekey->second.find(pos); - if ( poskey == typekey->second.end()) { // invalid PointPos for type - Provide Invalid icon + if (poskey == typekey->second.end()) {// invalid PointPos for type - Provide Invalid icon typekey = icons.find(Base::Type::badType()); pos = Sketcher::PointPos::none; poskey = typekey->second.find(pos); @@ -368,7 +427,7 @@ private: return std::get<1>(poskey->second); else if (icontype == ElementItem::GeometryState::External) return std::get<2>(poskey->second); - else //internal alignment + else// internal alignment return std::get<3>(poskey->second); // We should never arrive here, as badtype, PointPos::none must exist. @@ -383,26 +442,29 @@ private: QImage imgExt(imgConstr); QImage imgInt(imgConstr); - //Create construction/external/internal icons by changing colors. - for(int ix=0 ; ix 127 && hue >= 0) { - if (sat > 127 && (hue > 330 || hue < 30)) { //change the color of red points. + if (sat > 127 && (hue > 330 || hue < 30)) {// change the color of red points. clr.setHsv((hue + 240) % 360, sat, val, alp); imgConstr.setPixelColor(ix, iy, clr); clr.setHsv((hue + 300) % 360, sat, val, alp); imgExt.setPixelColor(ix, iy, clr); - clr.setHsv((hue + 60) % 360, (int) (sat / 3), std::min((int) (val * 8 / 7), 255), alp); + clr.setHsv((hue + 60) % 360, + (int)(sat / 3), + std::min((int)(val * 8 / 7), 255), + alp); imgInt.setPixelColor(ix, iy, clr); } - else if (sat < 64 && val > 192) { //change the color of white edges. - clr.setHsv(240, (255-sat), val, alp); + else if (sat < 64 && val > 192) {// change the color of white edges. + clr.setHsv(240, (255 - sat), val, alp); imgConstr.setPixel(ix, iy, clr.rgba()); - clr.setHsv(300, (255-sat), val, alp); + clr.setHsv(300, (255 - sat), val, alp); imgExt.setPixel(ix, iy, clr.rgba()); - clr.setHsv(60, (int) (255-sat) / 2, val, alp); + clr.setHsv(60, (int)(255 - sat) / 2, val, alp); imgInt.setPixel(ix, iy, clr.rgba()); } } @@ -416,29 +478,25 @@ private: } private: - std::map>> icons; - + std::map>> + icons; }; -ElementView::ElementView(QWidget *parent) : QListWidget(parent) +ElementView::ElementView(QWidget* parent) + : QListWidget(parent) { ElementItemDelegate* elementItemDelegate = new ElementItemDelegate(this); setItemDelegate(elementItemDelegate); QObject::connect( - elementItemDelegate, &ElementItemDelegate::itemHovered, - this, &ElementView::onIndexHovered - ); + elementItemDelegate, &ElementItemDelegate::itemHovered, this, &ElementView::onIndexHovered); QObject::connect( - elementItemDelegate, &ElementItemDelegate::itemChecked, - this, &ElementView::onIndexChecked - ); + elementItemDelegate, &ElementItemDelegate::itemChecked, this, &ElementView::onIndexChecked); } ElementView::~ElementView() -{ -} +{} void ElementView::changeLayer(int layer) { @@ -449,7 +507,7 @@ void ElementView::changeLayer(int layer) doc->openTransaction("Geometry Layer Change"); std::vector sel = Gui::Selection().getSelectionEx(doc->getName()); for (std::vector::iterator ft = sel.begin(); ft != sel.end(); ++ft) { - auto sketchobject = dynamic_cast(ft->getObject()); + auto sketchobject = dynamic_cast(ft->getObject()); auto geoids = getGeoIdsOfEdgesFromNames(sketchobject, ft->getSubNames()); @@ -458,10 +516,11 @@ void ElementView::changeLayer(int layer) auto newgeometry(geometry); bool anychanged = false; - for(auto geoid : geoids) { - if(geoid >= 0) { // currently only internal geometry can be changed from one layer to another + for (auto geoid : geoids) { + if (geoid + >= 0) {// currently only internal geometry can be changed from one layer to another auto currentlayer = getSafeGeomLayerId(geometry[geoid]); - if( currentlayer != layer) { + if (currentlayer != layer) { auto geo = geometry[geoid]->clone(); setSafeGeomLayerId(geo, layer); newgeometry[geoid] = geo; @@ -469,13 +528,15 @@ void ElementView::changeLayer(int layer) } } else { - Gui::TranslatedUserWarning(sketchobject, - QObject::tr("Unsupported visual layer operation"), - QObject::tr("It is currently unsupported to move external geometry to another visual layer. External geometry will be omitted")); + Gui::TranslatedUserWarning( + sketchobject, + QObject::tr("Unsupported visual layer operation"), + QObject::tr("It is currently unsupported to move external geometry to another " + "visual layer. External geometry will be omitted")); } } - if(anychanged) { + if (anychanged) { sketchobject->Geometry.setValues(std::move(newgeometry)); sketchobject->solve(); } @@ -483,52 +544,137 @@ void ElementView::changeLayer(int layer) doc->commitTransaction(); } -void ElementView::contextMenuEvent (QContextMenuEvent* event) +void ElementView::contextMenuEvent(QContextMenuEvent* event) { QMenu menu; - QList items = selectedItems(); + QList items = selectedItems(); // NOTE: If extending this context menu, be sure to add the items to the translation block at // the top of this file // CONTEXT_ITEM(ICONSTR,NAMESTR,CMDSTR,FUNC,ACTSONSELECTION) - CONTEXT_ITEM("Constraint_PointOnPoint","Point Coincidence","Sketcher_ConstrainCoincident",doPointCoincidence,true) - CONTEXT_ITEM("Constraint_PointOnObject","Point on Object","Sketcher_ConstrainPointOnObject",doPointOnObjectConstraint,true) - CONTEXT_ITEM("Constraint_Vertical","Vertical Constraint","Sketcher_ConstrainVertical", doVerticalConstraint,true) - CONTEXT_ITEM("Constraint_Horizontal","Horizontal Constraint","Sketcher_ConstrainHorizontal",doHorizontalConstraint,true) - CONTEXT_ITEM("Constraint_Parallel","Parallel Constraint","Sketcher_ConstrainParallel",doParallelConstraint,true) - CONTEXT_ITEM("Constraint_Perpendicular","Perpendicular Constraint","Sketcher_ConstrainPerpendicular",doPerpendicularConstraint,true) - CONTEXT_ITEM("Constraint_Tangent","Tangent Constraint","Sketcher_ConstrainTangent",doTangentConstraint,true) - CONTEXT_ITEM("Constraint_EqualLength","Equal Length","Sketcher_ConstrainEqual",doEqualConstraint,true) - CONTEXT_ITEM("Constraint_Symmetric","Symmetric","Sketcher_ConstrainSymmetric",doSymmetricConstraint,true) - CONTEXT_ITEM("Constraint_Block","Block Constraint","Sketcher_ConstrainBlock",doBlockConstraint,true) + CONTEXT_ITEM("Constraint_PointOnPoint", + "Point Coincidence", + "Sketcher_ConstrainCoincident", + doPointCoincidence, + true) + CONTEXT_ITEM("Constraint_PointOnObject", + "Point on Object", + "Sketcher_ConstrainPointOnObject", + doPointOnObjectConstraint, + true) + CONTEXT_ITEM("Constraint_Vertical", + "Vertical Constraint", + "Sketcher_ConstrainVertical", + doVerticalConstraint, + true) + CONTEXT_ITEM("Constraint_Horizontal", + "Horizontal Constraint", + "Sketcher_ConstrainHorizontal", + doHorizontalConstraint, + true) + CONTEXT_ITEM("Constraint_Parallel", + "Parallel Constraint", + "Sketcher_ConstrainParallel", + doParallelConstraint, + true) + CONTEXT_ITEM("Constraint_Perpendicular", + "Perpendicular Constraint", + "Sketcher_ConstrainPerpendicular", + doPerpendicularConstraint, + true) + CONTEXT_ITEM("Constraint_Tangent", + "Tangent Constraint", + "Sketcher_ConstrainTangent", + doTangentConstraint, + true) + CONTEXT_ITEM("Constraint_EqualLength", + "Equal Length", + "Sketcher_ConstrainEqual", + doEqualConstraint, + true) + CONTEXT_ITEM("Constraint_Symmetric", + "Symmetric", + "Sketcher_ConstrainSymmetric", + doSymmetricConstraint, + true) + CONTEXT_ITEM( + "Constraint_Block", "Block Constraint", "Sketcher_ConstrainBlock", doBlockConstraint, true) - CONTEXT_ITEM("Constraint_Lock","Lock Constraint","Sketcher_ConstrainLock",doLockConstraint,true) - CONTEXT_ITEM("Constraint_HorizontalDistance","Horizontal Distance","Sketcher_ConstrainDistanceX",doHorizontalDistance,true) - CONTEXT_ITEM("Constraint_VerticalDistance","Vertical Distance","Sketcher_ConstrainDistanceY",doVerticalDistance,true) - CONTEXT_ITEM("Constraint_Length","Length Constraint","Sketcher_ConstrainDistance",doLengthConstraint,true) - CONTEXT_ITEM("Constraint_Radius","Radius Constraint","Sketcher_ConstrainRadius",doRadiusConstraint,true) - CONTEXT_ITEM("Constraint_Diameter","Diameter Constraint","Sketcher_ConstrainDiameter",doDiameterConstraint,true) - CONTEXT_ITEM("Constraint_Radiam","Radiam Constraint","Sketcher_ConstrainRadiam",doRadiamConstraint,true) - CONTEXT_ITEM("Constraint_InternalAngle","Angle Constraint","Sketcher_ConstrainAngle",doAngleConstraint,true) + CONTEXT_ITEM( + "Constraint_Lock", "Lock Constraint", "Sketcher_ConstrainLock", doLockConstraint, true) + CONTEXT_ITEM("Constraint_HorizontalDistance", + "Horizontal Distance", + "Sketcher_ConstrainDistanceX", + doHorizontalDistance, + true) + CONTEXT_ITEM("Constraint_VerticalDistance", + "Vertical Distance", + "Sketcher_ConstrainDistanceY", + doVerticalDistance, + true) + CONTEXT_ITEM("Constraint_Length", + "Length Constraint", + "Sketcher_ConstrainDistance", + doLengthConstraint, + true) + CONTEXT_ITEM("Constraint_Radius", + "Radius Constraint", + "Sketcher_ConstrainRadius", + doRadiusConstraint, + true) + CONTEXT_ITEM("Constraint_Diameter", + "Diameter Constraint", + "Sketcher_ConstrainDiameter", + doDiameterConstraint, + true) + CONTEXT_ITEM("Constraint_Radiam", + "Radiam Constraint", + "Sketcher_ConstrainRadiam", + doRadiamConstraint, + true) + CONTEXT_ITEM("Constraint_InternalAngle", + "Angle Constraint", + "Sketcher_ConstrainAngle", + doAngleConstraint, + true) menu.addSeparator(); - CONTEXT_ITEM("Sketcher_ToggleConstruction","Toggle construction geometry","Sketcher_ToggleConstruction",doToggleConstruction,true) + CONTEXT_ITEM("Sketcher_ToggleConstruction", + "Toggle construction geometry", + "Sketcher_ToggleConstruction", + doToggleConstruction, + true) menu.addSeparator(); - CONTEXT_ITEM("Sketcher_SelectConstraints","Select Constraints","Sketcher_SelectConstraints",doSelectConstraints,true) - CONTEXT_ITEM("Sketcher_SelectOrigin","Select Origin","Sketcher_SelectOrigin",doSelectOrigin,false) - CONTEXT_ITEM("Sketcher_SelectHorizontalAxis","Select Horizontal Axis","Sketcher_SelectHorizontalAxis",doSelectHAxis,false) - CONTEXT_ITEM("Sketcher_SelectVerticalAxis","Select Vertical Axis","Sketcher_SelectVerticalAxis",doSelectVAxis,false) + CONTEXT_ITEM("Sketcher_SelectConstraints", + "Select Constraints", + "Sketcher_SelectConstraints", + doSelectConstraints, + true) + CONTEXT_ITEM( + "Sketcher_SelectOrigin", "Select Origin", "Sketcher_SelectOrigin", doSelectOrigin, false) + CONTEXT_ITEM("Sketcher_SelectHorizontalAxis", + "Select Horizontal Axis", + "Sketcher_SelectHorizontalAxis", + doSelectHAxis, + false) + CONTEXT_ITEM("Sketcher_SelectVerticalAxis", + "Select Vertical Axis", + "Sketcher_SelectVerticalAxis", + doSelectVAxis, + false) menu.addSeparator(); auto submenu = menu.addMenu(tr("Layer")); - auto addLayerAction = [submenu, this, items](auto && name, int layernumber){ - auto action = submenu->addAction(std::forward(name), [this, layernumber](){changeLayer(layernumber);}); + auto addLayerAction = [submenu, this, items](auto&& name, int layernumber) { + auto action = submenu->addAction(std::forward(name), [this, layernumber]() { + changeLayer(layernumber); + }); action->setEnabled(!items.isEmpty()); return action; }; @@ -540,8 +686,8 @@ void ElementView::contextMenuEvent (QContextMenuEvent* event) menu.addSeparator(); - QAction* remove = menu.addAction(tr("Delete"), this, &ElementView::deleteSelectedItems, - QKeySequence(QKeySequence::Delete)); + QAction* remove = menu.addAction( + tr("Delete"), this, &ElementView::deleteSelectedItems, QKeySequence(QKeySequence::Delete)); remove->setEnabled(!items.isEmpty()); menu.menuAction()->setIconVisibleInMenu(true); @@ -549,32 +695,32 @@ void ElementView::contextMenuEvent (QContextMenuEvent* event) menu.exec(event->globalPos()); } -CONTEXT_MEMBER_DEF("Sketcher_ConstrainCoincident",doPointCoincidence) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainPointOnObject",doPointOnObjectConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainVertical",doVerticalConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainHorizontal",doHorizontalConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainParallel",doParallelConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainPerpendicular",doPerpendicularConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainTangent",doTangentConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainEqual",doEqualConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainSymmetric",doSymmetricConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainBlock",doBlockConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainCoincident", doPointCoincidence) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainPointOnObject", doPointOnObjectConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainVertical", doVerticalConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainHorizontal", doHorizontalConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainParallel", doParallelConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainPerpendicular", doPerpendicularConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainTangent", doTangentConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainEqual", doEqualConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainSymmetric", doSymmetricConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainBlock", doBlockConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainLock",doLockConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainDistanceX",doHorizontalDistance) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainDistanceY",doVerticalDistance) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainDistance",doLengthConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainRadius",doRadiusConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainDiameter",doDiameterConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainRadiam",doRadiamConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ConstrainAngle",doAngleConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainLock", doLockConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainDistanceX", doHorizontalDistance) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainDistanceY", doVerticalDistance) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainDistance", doLengthConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainRadius", doRadiusConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainDiameter", doDiameterConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainRadiam", doRadiamConstraint) +CONTEXT_MEMBER_DEF("Sketcher_ConstrainAngle", doAngleConstraint) -CONTEXT_MEMBER_DEF("Sketcher_ToggleConstruction",doToggleConstruction) +CONTEXT_MEMBER_DEF("Sketcher_ToggleConstruction", doToggleConstruction) -CONTEXT_MEMBER_DEF("Sketcher_SelectConstraints",doSelectConstraints) -CONTEXT_MEMBER_DEF("Sketcher_SelectOrigin",doSelectOrigin) -CONTEXT_MEMBER_DEF("Sketcher_SelectHorizontalAxis",doSelectHAxis) -CONTEXT_MEMBER_DEF("Sketcher_SelectVerticalAxis",doSelectVAxis) +CONTEXT_MEMBER_DEF("Sketcher_SelectConstraints", doSelectConstraints) +CONTEXT_MEMBER_DEF("Sketcher_SelectOrigin", doSelectOrigin) +CONTEXT_MEMBER_DEF("Sketcher_SelectHorizontalAxis", doSelectHAxis) +CONTEXT_MEMBER_DEF("Sketcher_SelectVerticalAxis", doSelectVAxis) void ElementView::deleteSelectedItems() { @@ -593,12 +739,14 @@ void ElementView::deleteSelectedItems() doc->commitTransaction(); } -void ElementView::onIndexHovered(QModelIndex index) { +void ElementView::onIndexHovered(QModelIndex index) +{ Q_EMIT onItemHovered(itemFromIndex(index)); } -void ElementView::onIndexChecked(QModelIndex, Qt::CheckState state) { - if(state == Qt::Checked) { +void ElementView::onIndexChecked(QModelIndex, Qt::CheckState state) +{ + if (state == Qt::Checked) { changeLayer(static_cast(ElementItem::Layer::Default)); } else { @@ -606,22 +754,24 @@ void ElementView::onIndexChecked(QModelIndex, Qt::CheckState state) { } } -ElementItem* ElementView::itemFromIndex(const QModelIndex& index) { +ElementItem* ElementView::itemFromIndex(const QModelIndex& index) +{ return static_cast(QListWidget::itemFromIndex(index)); } /* ElementItem delegate ---------------------------------------------------- */ -ElementItemDelegate::ElementItemDelegate(ElementView* parent) : QStyledItemDelegate(parent) -{ // This class relies on the parent being an ElementView, see getElementtItem +ElementItemDelegate::ElementItemDelegate(ElementView* parent) + : QStyledItemDelegate(parent) +{// This class relies on the parent being an ElementView, see getElementtItem } ElementItemDelegate::~ElementItemDelegate() -{ -} +{} -void ElementItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +void ElementItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const { ElementItem* item = getElementtItem(index); @@ -632,33 +782,38 @@ void ElementItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o checkboxstyle.state |= QStyle::State_Enabled; - if(item->isVisible()) + if (item->isVisible()) checkboxstyle.state |= QStyle::State_On; else checkboxstyle.state |= QStyle::State_Off; - QRect checkboxrect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle); + QRect checkboxrect = + QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle); customIconsMargin = leftMargin + checkboxrect.width(); QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxstyle, painter); int height = option.rect.height(); - int width = height; //icons are square. + int width = height;// icons are square. int x0 = option.rect.x() + customIconsMargin; int iconsize = height - 2 * border; int btny = option.rect.y() + border; - if (item->isLineSelected || item->isStartingPointSelected || item->isEndPointSelected || item->isMidPointSelected) { //option.state & QStyle::State_Selected + if (item->isLineSelected || item->isStartingPointSelected || item->isEndPointSelected + || item->isMidPointSelected) {// option.state & QStyle::State_Selected - auto unselecticon = [&](int iconnumber){ - QRect rect{ x0 + border + width*iconnumber, btny, iconsize, iconsize }; + auto unselecticon = [&](int iconnumber) { + QRect rect {x0 + border + width * iconnumber, btny, iconsize, iconsize}; painter->fillRect(rect, option.palette.base()); }; - QRect selection = QRect(customIconsMargin, option.rect.y(), option.rect.width()-customIconsMargin, option.rect.height()); + QRect selection = QRect(customIconsMargin, + option.rect.y(), + option.rect.width() - customIconsMargin, + option.rect.height()); - painter->fillRect(selection, option.palette.highlight()); // paint the item as selected + painter->fillRect(selection, option.palette.highlight());// paint the item as selected // Repaint individual icons if (!item->isLineSelected) @@ -674,34 +829,40 @@ void ElementItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o unselecticon(3); } - auto & iconEdge = ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::none, item->State); - auto & iconStart = ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::start, item->State); - auto & iconEnd = ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::end, item->State); - auto & iconMid = ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::mid, item->State); - //getIcon(item->GeometryType); + auto& iconEdge = + ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::none, item->State); + auto& iconStart = + ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::start, item->State); + auto& iconEnd = + ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::end, item->State); + auto& iconMid = + ElementWidgetIcons::getIcon(item->GeometryType, Sketcher::PointPos::mid, item->State); + // getIcon(item->GeometryType); - painter->drawPixmap(x0 + border , btny, iconEdge.pixmap(iconsize, iconsize)); - painter->drawPixmap(x0 + border + width , btny, iconStart.pixmap(iconsize, iconsize)); - painter->drawPixmap(x0 + border + width * 2 , btny, iconEnd.pixmap(iconsize, iconsize)); - painter->drawPixmap(x0 + border + width * 3 , btny, iconMid.pixmap(iconsize, iconsize)); - - //Label : - painter->drawText(x0 + width * 4 + 3 * border, option.rect.y() + height - textBottomMargin, item->label); + painter->drawPixmap(x0 + border, btny, iconEdge.pixmap(iconsize, iconsize)); + painter->drawPixmap(x0 + border + width, btny, iconStart.pixmap(iconsize, iconsize)); + painter->drawPixmap(x0 + border + width * 2, btny, iconEnd.pixmap(iconsize, iconsize)); + painter->drawPixmap(x0 + border + width * 3, btny, iconMid.pixmap(iconsize, iconsize)); + // Label : + painter->drawText( + x0 + width * 4 + 3 * border, option.rect.y() + height - textBottomMargin, item->label); } } -bool ElementItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) +bool ElementItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, + const QStyleOptionViewItem& option, const QModelIndex& index) { auto getSubElementType = [&](ElementItem* item, int xPos, int width) { - bool label = (xPos > option.rect.x() + customIconsMargin + width * 4 + border); - if((xPos < option.rect.x() + customIconsMargin + width + border) || ( item->GeometryType != Part::GeomPoint::getClassTypeId() && label)) + if ((xPos < option.rect.x() + customIconsMargin + width + border) + || (item->GeometryType != Part::GeomPoint::getClassTypeId() && label)) return SubElementType::edge; - if(xPos < option.rect.x() + customIconsMargin + width * 2 + border || ( item->GeometryType == Part::GeomPoint::getClassTypeId() && label)) + if (xPos < option.rect.x() + customIconsMargin + width * 2 + border + || (item->GeometryType == Part::GeomPoint::getClassTypeId() && label)) return SubElementType::start; - if(xPos < option.rect.x() + customIconsMargin + width * 3 + border) + if (xPos < option.rect.x() + customIconsMargin + width * 3 + border) return SubElementType::end; else if (xPos < option.rect.x() + customIconsMargin + width * 4 + border) return SubElementType::mid; @@ -714,24 +875,25 @@ bool ElementItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, ElementItem* item = getElementtItem(index); int xPos = mEvent->pos().x(); - int width = option.rect.height(); //icons are square + int width = option.rect.height();// icons are square item->clickedOn = getSubElementType(item, xPos, width); if (mEvent->button() == Qt::RightButton) item->rightClicked = true; - QRect checkboxrect = QRect(leftMargin, option.rect.y(), customIconsMargin-leftMargin, option.rect.height()); + QRect checkboxrect = QRect( + leftMargin, option.rect.y(), customIconsMargin - leftMargin, option.rect.height()); if (mEvent->button() == Qt::LeftButton && checkboxrect.contains(mEvent->pos())) { - Q_EMIT itemChecked(index, item->isVisible()?Qt::Unchecked:Qt::Checked); + Q_EMIT itemChecked(index, item->isVisible() ? Qt::Unchecked : Qt::Checked); } } else if (event->type() == QEvent::MouseMove) { SubElementType typeUnderMouse; QMouseEvent* mEvent = static_cast(event); int xPos = mEvent->pos().x(); - int width = option.rect.height(); //icons are square + int width = option.rect.height();// icons are square ElementItem* item = getElementtItem(index); @@ -744,14 +906,16 @@ bool ElementItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, return QStyledItemDelegate::editorEvent(event, model, option, index); } -ElementItem* ElementItemDelegate::getElementtItem(const QModelIndex& index) const{ +ElementItem* ElementItemDelegate::getElementtItem(const QModelIndex& index) const +{ ElementView* elementView = static_cast(parent()); return elementView->itemFromIndex(index); } /* Filter element list widget ------------------------------------------------------ */ -enum class GeoFilterType { +enum class GeoFilterType +{ NormalGeos, ConstructionGeos, InternalGeos, @@ -768,28 +932,30 @@ enum class GeoFilterType { BSplineGeos }; -ElementFilterList::ElementFilterList(QWidget* parent) : QListWidget(parent) +ElementFilterList::ElementFilterList(QWidget* parent) + : QListWidget(parent) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - int filterState = hGrp->GetInt("ElementFilterState", INT_MAX); //INT_MAX = 1111111111111111111111111111111 in binary. + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + int filterState = hGrp->GetInt("ElementFilterState", + INT_MAX);// INT_MAX = 1111111111111111111111111111111 in binary. - for (auto const &filterItem:filterItems) { + for (auto const& filterItem : filterItems) { Q_UNUSED(filterItem); auto it = new QListWidgetItem(); it->setFlags(it->flags() | Qt::ItemIsUserCheckable); - bool isChecked = static_cast(filterState & 1); //get the first bit of filterState + bool isChecked = static_cast(filterState & 1);// get the first bit of filterState it->setCheckState(isChecked ? Qt::Checked : Qt::Unchecked); - filterState = filterState >> 1; //shift right to get rid of the used bit. + filterState = filterState >> 1;// shift right to get rid of the used bit. addItem(it); } languageChange(); - //We need to fix the state of 'All' group checkbox in case it is partially checked. + // We need to fix the state of 'All' group checkbox in case it is partially checked. int indexOfAllTypes = static_cast(GeoFilterType::AllGeosTypes); - if(item(indexOfAllTypes)->checkState() == Qt::Unchecked) - { + if (item(indexOfAllTypes)->checkState() == Qt::Unchecked) { bool allUnchecked = true; for (int i = indexOfAllTypes + 1; i < count(); i++) { if (item(i)->checkState() == Qt::Checked) { @@ -803,8 +969,7 @@ ElementFilterList::ElementFilterList(QWidget* parent) : QListWidget(parent) } ElementFilterList::~ElementFilterList() -{ -} +{} void ElementFilterList::changeEvent(QEvent* e) { @@ -817,11 +982,11 @@ void ElementFilterList::changeEvent(QEvent* e) void ElementFilterList::languageChange() { assert(static_cast(filterItems.size()) == count()); - int i=0; - for (auto const &filterItem:filterItems) { - auto text = QStringLiteral(" ").repeated(filterItem.second-1) + - (filterItem.second > 0 ? QStringLiteral("- ") : QStringLiteral("")) + - tr(filterItem.first); + int i = 0; + for (auto const& filterItem : filterItems) { + auto text = QStringLiteral(" ").repeated(filterItem.second - 1) + + (filterItem.second > 0 ? QStringLiteral("- ") : QStringLiteral("")) + + tr(filterItem.first); item(i++)->setText(text); } } @@ -829,8 +994,8 @@ void ElementFilterList::languageChange() /* TRANSLATOR SketcherGui::TaskSketcherElements */ -TaskSketcherElements::TaskSketcherElements(ViewProviderSketch *sketchView) - : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Elements"),true, nullptr) +TaskSketcherElements::TaskSketcherElements(ViewProviderSketch* sketchView) + : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Elements"), true, nullptr) , sketchView(sketchView) , ui(new Ui_TaskSketcherElements()) , focusItemIndex(-1) @@ -843,7 +1008,7 @@ TaskSketcherElements::TaskSketcherElements(ViewProviderSketch *sketchView) proxy = new QWidget(this); ui->setupUi(proxy); #ifdef Q_OS_MAC - QString cmdKey = QString::fromUtf8("\xe2\x8c\x98"); // U+2318 + QString cmdKey = QString::fromUtf8("\xe2\x8c\x98");// U+2318 #else // translate the text (it's offered by Qt's translation files) // but avoid being picked up by lupdate @@ -863,7 +1028,8 @@ TaskSketcherElements::TaskSketcherElements(ViewProviderSketch *sketchView) this->groupLayout()->addWidget(proxy); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); ui->filterBox->setChecked(hGrp->GetBool("ElementFilterEnabled", true)); ui->filterButton->setEnabled(ui->filterBox->isChecked()); @@ -878,38 +1044,34 @@ TaskSketcherElements::~TaskSketcherElements() void TaskSketcherElements::connectSignals() { // connecting the needed signals + QObject::connect(ui->listWidgetElements, + &ElementView::itemPressed, + this, + &TaskSketcherElements::onListWidgetElementsItemPressed); + QObject::connect(ui->listWidgetElements, + &ElementView::itemEntered, + this, + &TaskSketcherElements::onListWidgetElementsItemEntered); + QObject::connect(ui->listWidgetElements, + &ElementView::onItemHovered, + this, + &TaskSketcherElements::onListWidgetElementsMouseMoveOnItem); + QObject::connect(filterList, + &QListWidget::itemChanged, + this, + &TaskSketcherElements::onListMultiFilterItemChanged); + QObject::connect(ui->filterBox, + &QCheckBox::stateChanged, + this, + &TaskSketcherElements::onFilterBoxStateChanged); QObject::connect( - ui->listWidgetElements, &ElementView::itemPressed, - this, &TaskSketcherElements::onListWidgetElementsItemPressed - ); + ui->settingsButton, &QToolButton::clicked, ui->settingsButton, &QToolButton::showMenu); + QObject::connect(qAsConst(ui->settingsButton)->actions()[0], + &QAction::changed, + this, + &TaskSketcherElements::onSettingsExtendedInformationChanged); QObject::connect( - ui->listWidgetElements, &ElementView::itemEntered, - this, &TaskSketcherElements::onListWidgetElementsItemEntered - ); - QObject::connect( - ui->listWidgetElements, &ElementView::onItemHovered, - this, &TaskSketcherElements::onListWidgetElementsMouseMoveOnItem - ); - QObject::connect( - filterList, &QListWidget::itemChanged, - this, &TaskSketcherElements::onListMultiFilterItemChanged - ); - QObject::connect( - ui->filterBox, &QCheckBox::stateChanged, - this, &TaskSketcherElements::onFilterBoxStateChanged - ); - QObject::connect( - ui->settingsButton, &QToolButton::clicked, - ui->settingsButton, &QToolButton::showMenu - ); - QObject::connect( - qAsConst(ui->settingsButton)->actions()[0], &QAction::changed, - this, &TaskSketcherElements::onSettingsExtendedInformationChanged - ); - QObject::connect( - ui->filterButton, &QToolButton::clicked, - ui->filterButton, &QToolButton::showMenu - ); + ui->filterButton, &QToolButton::clicked, ui->filterButton, &QToolButton::showMenu); connectionElementsChanged = sketchView->signalElementsChanged.connect( boost::bind(&SketcherGui::TaskSketcherElements::slotElementsChanged, this)); @@ -928,7 +1090,8 @@ void TaskSketcherElements::createFilterButtonActions() void TaskSketcherElements::onFilterBoxStateChanged(int val) { Q_UNUSED(val); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrp->SetBool("ElementFilterEnabled", ui->filterBox->checkState() == Qt::Checked); ui->filterButton->setEnabled(ui->filterBox->checkState() == Qt::Checked); @@ -960,21 +1123,22 @@ void TaskSketcherElements::onListMultiFilterItemChanged(QListWidgetItem* item) } if (atLeastOneChecked && atLeastOneUnchecked) filterList->item(indexOfAllTypes)->setCheckState(Qt::PartiallyChecked); - else if(atLeastOneUnchecked) + else if (atLeastOneUnchecked) filterList->item(indexOfAllTypes)->setCheckState(Qt::Unchecked); - else if(atLeastOneChecked) + else if (atLeastOneChecked) filterList->item(indexOfAllTypes)->setCheckState(Qt::Checked); } } - //Save the state of the filter. - int filterState = INT_MIN; //INT_MIN = 000000000000000000000000000000 in binary. - for (int i = filterList->count() - 1; i >= 0 ; i--) { + // Save the state of the filter. + int filterState = INT_MIN;// INT_MIN = 000000000000000000000000000000 in binary. + for (int i = filterList->count() - 1; i >= 0; i--) { bool isChecked = filterList->item(i)->checkState() == Qt::Checked; - filterState = filterState << 1; //we shift left first, else the list is shifted at the end. + filterState = filterState << 1;// we shift left first, else the list is shifted at the end. filterState = filterState | isChecked; } - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrp->SetInt("ElementFilterState", filterState); updateVisibility(); @@ -984,26 +1148,52 @@ void TaskSketcherElements::setItemVisibility(QListWidgetItem* it) { ElementItem* item = static_cast(it); - if (ui->filterBox->checkState() == Qt::Unchecked) { item->setHidden(false); + if (ui->filterBox->checkState() == Qt::Unchecked) { + item->setHidden(false); return; } using GeometryState = ElementItem::GeometryState; - if ((filterList->item(static_cast(GeoFilterType::NormalGeos))->checkState() == Qt::Unchecked && item->State == GeometryState::Normal) || - (filterList->item(static_cast(GeoFilterType::ConstructionGeos))->checkState() == Qt::Unchecked && item->State == GeometryState::Construction) || - (filterList->item(static_cast(GeoFilterType::InternalGeos))->checkState() == Qt::Unchecked && item->State == GeometryState::InternalAlignment) || - (filterList->item(static_cast(GeoFilterType::ExternalGeos))->checkState() == Qt::Unchecked && item->State == GeometryState::External) || - (filterList->item(static_cast(GeoFilterType::PointGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomPoint::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::LineGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomLineSegment::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::CircleGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomCircle::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::EllipseGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomEllipse::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::ArcGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomArcOfCircle::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::ArcOfEllipseGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::HyperbolaGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::ParabolaGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomArcOfParabola::getClassTypeId()) || - (filterList->item(static_cast(GeoFilterType::BSplineGeos))->checkState() == Qt::Unchecked && item->GeometryType == Part::GeomBSplineCurve::getClassTypeId()) ) - { + if ((filterList->item(static_cast(GeoFilterType::NormalGeos))->checkState() + == Qt::Unchecked + && item->State == GeometryState::Normal) + || (filterList->item(static_cast(GeoFilterType::ConstructionGeos))->checkState() + == Qt::Unchecked + && item->State == GeometryState::Construction) + || (filterList->item(static_cast(GeoFilterType::InternalGeos))->checkState() + == Qt::Unchecked + && item->State == GeometryState::InternalAlignment) + || (filterList->item(static_cast(GeoFilterType::ExternalGeos))->checkState() + == Qt::Unchecked + && item->State == GeometryState::External) + || (filterList->item(static_cast(GeoFilterType::PointGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomPoint::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::LineGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomLineSegment::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::CircleGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomCircle::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::EllipseGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomEllipse::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::ArcGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomArcOfCircle::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::ArcOfEllipseGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::HyperbolaGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::ParabolaGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomArcOfParabola::getClassTypeId()) + || (filterList->item(static_cast(GeoFilterType::BSplineGeos))->checkState() + == Qt::Unchecked + && item->GeometryType == Part::GeomBSplineCurve::getClassTypeId())) { item->setHidden(true); return; } @@ -1024,17 +1214,17 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) if (msg.Type == Gui::SelectionChanges::ClrSelection) { clearWidget(); } - else if (msg.Type == Gui::SelectionChanges::AddSelection || - msg.Type == Gui::SelectionChanges::RmvSelection) { + else if (msg.Type == Gui::SelectionChanges::AddSelection + || msg.Type == Gui::SelectionChanges::RmvSelection) { bool select = (msg.Type == Gui::SelectionChanges::AddSelection); // is it this object?? - if (strcmp(msg.pDocName,sketchView->getSketchObject()->getDocument()->getName())==0 && - strcmp(msg.pObjectName,sketchView->getSketchObject()->getNameInDocument())== 0) { + if (strcmp(msg.pDocName, sketchView->getSketchObject()->getDocument()->getName()) == 0 + && strcmp(msg.pObjectName, sketchView->getSketchObject()->getNameInDocument()) == 0) { if (msg.pSubName) { QString expr = QString::fromLatin1(msg.pSubName); std::string shapetype(msg.pSubName); // if-else edge vertex - if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { + if (shapetype.size() > 4 && shapetype.substr(0, 4) == "Edge") { QRegularExpression rx(QString::fromLatin1("^Edge(\\d+)$")); QRegularExpressionMatch match; boost::ignore_unused(expr.indexOf(rx, 0, &match)); @@ -1043,8 +1233,9 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) int ElementId = match.captured(1).toInt(&ok) - 1; if (ok) { int countItems = ui->listWidgetElements->count(); - for (int i=0; i < countItems; i++) { - ElementItem* item = static_cast(ui->listWidgetElements->item(i)); + for (int i = 0; i < countItems; i++) { + ElementItem* item = + static_cast(ui->listWidgetElements->item(i)); if (item->ElementNbr == ElementId) { item->isLineSelected = select; break; @@ -1053,7 +1244,7 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) } } } - else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex"){ + else if (shapetype.size() > 6 && shapetype.substr(0, 6) == "Vertex") { QRegularExpression rx(QString::fromLatin1("^Vertex(\\d+)$")); QRegularExpressionMatch match; boost::ignore_unused(expr.indexOf(rx, 0, &match)); @@ -1064,25 +1255,26 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) // Get the GeoID&Pos int GeoId; Sketcher::PointPos PosId; - sketchView->getSketchObject()->getGeoVertexIndex(ElementId,GeoId, PosId); + sketchView->getSketchObject()->getGeoVertexIndex( + ElementId, GeoId, PosId); int countItems = ui->listWidgetElements->count(); - for (int i=0; i < countItems; i++) { - ElementItem* item = static_cast(ui->listWidgetElements->item(i)); + for (int i = 0; i < countItems; i++) { + ElementItem* item = + static_cast(ui->listWidgetElements->item(i)); if (item->ElementNbr == GeoId) { - switch(PosId) - { - case Sketcher::PointPos::start: - item->isStartingPointSelected=select; - break; - case Sketcher::PointPos::end: - item->isEndPointSelected=select; - break; - case Sketcher::PointPos::mid: - item->isMidPointSelected=select; - break; - default: - break; + switch (PosId) { + case Sketcher::PointPos::start: + item->isStartingPointSelected = select; + break; + case Sketcher::PointPos::end: + item->isEndPointSelected = select; + break; + case Sketcher::PointPos::mid: + item->isMidPointSelected = select; + break; + default: + break; } break; } @@ -1094,10 +1286,14 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) { QSignalBlocker sigblk(ui->listWidgetElements); for (int i = 0; i < ui->listWidgetElements->count(); i++) { - ElementItem* item = static_cast(ui->listWidgetElements->item(i)); - if(item->isSelected()) - item->setSelected(false); //if already selected, we need to reset setSelected or it won't draw subelements correctly if selecting several. - item->setSelected(item->isLineSelected || item->isStartingPointSelected || item->isEndPointSelected || item->isMidPointSelected); + ElementItem* item = + static_cast(ui->listWidgetElements->item(i)); + if (item->isSelected()) + item->setSelected( + false);// if already selected, we need to reset setSelected or it + // won't draw subelements correctly if selecting several. + item->setSelected(item->isLineSelected || item->isStartingPointSelected + || item->isEndPointSelected || item->isMidPointSelected); } } } @@ -1108,15 +1304,19 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) } } -void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) { - //We use itemPressed instead of previously used ItemSelectionChanged because if user click on already selected item, ItemSelectionChanged didn't trigger. +void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) +{ + // We use itemPressed instead of previously used ItemSelectionChanged because if user click on + // already selected item, ItemSelectionChanged didn't trigger. if (!it) return; ElementItem* itf = static_cast(it); - bool rightClickOnSelected = itf->rightClicked && (itf->isLineSelected || itf->isStartingPointSelected || itf->isEndPointSelected || itf->isMidPointSelected); + bool rightClickOnSelected = itf->rightClicked + && (itf->isLineSelected || itf->isStartingPointSelected || itf->isEndPointSelected + || itf->isMidPointSelected); itf->rightClicked = false; - if (rightClickOnSelected) //if user right clicked on a selected item, change nothing. + if (rightClickOnSelected)// if user right clicked on a selected item, change nothing. return; { @@ -1129,7 +1329,8 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) if (QApplication::keyboardModifiers() == Qt::ShiftModifier) multipleconsecutiveselection = true; - if (multipleselection && multipleconsecutiveselection) { // ctrl takes priority over shift functionality + if (multipleselection + && multipleconsecutiveselection) {// ctrl takes priority over shift functionality multipleselection = true; multipleconsecutiveselection = false; } @@ -1138,14 +1339,15 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) std::string doc_name = sketchView->getSketchObject()->getDocument()->getName(); std::string obj_name = sketchView->getSketchObject()->getNameInDocument(); - bool block = this->blockSelection(true); // avoid to be notified by itself + bool block = this->blockSelection(true);// avoid to be notified by itself Gui::Selection().clearSelection(); for (int i = 0; i < ui->listWidgetElements->count(); i++) { ElementItem* item = static_cast(ui->listWidgetElements->item(i)); - if (!multipleselection && !multipleconsecutiveselection ) { - //if not multiple selection, then all are disabled but the one that was just selected + if (!multipleselection && !multipleconsecutiveselection) { + // if not multiple selection, then all are disabled but the one that was just + // selected item->isLineSelected = false; item->isStartingPointSelected = false; item->isEndPointSelected = false; @@ -1163,33 +1365,35 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) || item->GeometryType == Part::GeomEllipse::getClassTypeId())) { item->isMidPointSelected = !item->isMidPointSelected; } - else if (item->clickedOn == SubElementType::start && - (item->GeometryType == Part::GeomPoint::getClassTypeId() - || item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() - || item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId() - || item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId() - || item->GeometryType == Part::GeomArcOfParabola::getClassTypeId() - || item->GeometryType == Part::GeomLineSegment::getClassTypeId() - || item->GeometryType == Part::GeomBSplineCurve::getClassTypeId())) { + else if (item->clickedOn == SubElementType::start + && (item->GeometryType == Part::GeomPoint::getClassTypeId() + || item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() + || item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId() + || item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId() + || item->GeometryType == Part::GeomArcOfParabola::getClassTypeId() + || item->GeometryType == Part::GeomLineSegment::getClassTypeId() + || item->GeometryType == Part::GeomBSplineCurve::getClassTypeId())) { item->isStartingPointSelected = !item->isStartingPointSelected; } - else if (item->clickedOn == SubElementType::end && - (item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() - || item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId() - || item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId() - || item->GeometryType == Part::GeomArcOfParabola::getClassTypeId() - || item->GeometryType == Part::GeomLineSegment::getClassTypeId() - || item->GeometryType == Part::GeomBSplineCurve::getClassTypeId())) { + else if (item->clickedOn == SubElementType::end + && (item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() + || item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId() + || item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId() + || item->GeometryType == Part::GeomArcOfParabola::getClassTypeId() + || item->GeometryType == Part::GeomLineSegment::getClassTypeId() + || item->GeometryType == Part::GeomBSplineCurve::getClassTypeId())) { item->isEndPointSelected = !item->isEndPointSelected; } - else if (item->clickedOn == SubElementType::edge && - item->GeometryType != Part::GeomPoint::getClassTypeId()){ + else if (item->clickedOn == SubElementType::edge + && item->GeometryType != Part::GeomPoint::getClassTypeId()) { item->isLineSelected = !item->isLineSelected; } item->clickedOn = SubElementType::none; } - else if (multipleconsecutiveselection && previouslySelectedItemIndex >= 0 && !rightClickOnSelected && - ((i > focusItemIndex && i < previouslySelectedItemIndex) || (ipreviouslySelectedItemIndex))) { + else if (multipleconsecutiveselection && previouslySelectedItemIndex >= 0 + && !rightClickOnSelected + && ((i > focusItemIndex && i < previouslySelectedItemIndex) + || (i < focusItemIndex && i > previouslySelectedItemIndex))) { if (item->GeometryType == Part::GeomPoint::getClassTypeId()) { item->isStartingPointSelected = true; } @@ -1198,14 +1402,18 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) } } - // first update the listwidget. Item is selected if at least one element of the geo is selected. - bool selected = item->isLineSelected || item->isStartingPointSelected || item->isEndPointSelected || item->isMidPointSelected; + // first update the listwidget. Item is selected if at least one element of the geo is + // selected. + bool selected = item->isLineSelected || item->isStartingPointSelected + || item->isEndPointSelected || item->isMidPointSelected; { QSignalBlocker sigblk(ui->listWidgetElements); if (item->isSelected() && selected) { - item->setSelected(false);// if already selected and changing or adding subelement, ensure selection change is triggered, which ensures timely repaint + item->setSelected( + false);// if already selected and changing or adding subelement, ensure + // selection change is triggered, which ensures timely repaint item->setSelected(selected); } else { @@ -1222,7 +1430,7 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) elementSubNames.push_back(ss.str()); } - auto selectVertex = [&ss, &elementSubNames] (bool subelementselected, int vertexid) { + auto selectVertex = [&ss, &elementSubNames](bool subelementselected, int vertexid) { if (subelementselected) { int vertex; ss.str(std::string()); @@ -1237,7 +1445,6 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) selectVertex(item->isStartingPointSelected, item->StartingVertex); selectVertex(item->isEndPointSelected, item->EndVertex); selectVertex(item->isMidPointSelected, item->MidVertex); - } if (!elementSubNames.empty()) { @@ -1253,17 +1460,20 @@ void TaskSketcherElements::onListWidgetElementsItemPressed(QListWidgetItem* it) ui->listWidgetElements->repaint(); } -void TaskSketcherElements::onListWidgetElementsItemEntered(QListWidgetItem *item) +void TaskSketcherElements::onListWidgetElementsItemEntered(QListWidgetItem* item) { ui->listWidgetElements->setFocus(); focusItemIndex = ui->listWidgetElements->row(item); } -void TaskSketcherElements::onListWidgetElementsMouseMoveOnItem(QListWidgetItem* it) { +void TaskSketcherElements::onListWidgetElementsMouseMoveOnItem(QListWidgetItem* it) +{ ElementItem* item = static_cast(it); - if (!item || (ui->listWidgetElements->row(item) == previouslyHoveredItemIndex && item->hovered == previouslyHoveredType) ) + if (!item + || (ui->listWidgetElements->row(item) == previouslyHoveredItemIndex + && item->hovered == previouslyHoveredType)) return; Gui::Selection().rmvPreselect(); @@ -1276,8 +1486,8 @@ void TaskSketcherElements::onListWidgetElementsMouseMoveOnItem(QListWidgetItem* || item->GeometryType == Part::GeomCircle::getClassTypeId() || item->GeometryType == Part::GeomEllipse::getClassTypeId()); - bool validstartpoint = item->hovered == SubElementType::start && - (item->GeometryType == Part::GeomPoint::getClassTypeId() + bool validstartpoint = item->hovered == SubElementType::start + && (item->GeometryType == Part::GeomPoint::getClassTypeId() || item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() || item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId() || item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId() @@ -1285,16 +1495,16 @@ void TaskSketcherElements::onListWidgetElementsMouseMoveOnItem(QListWidgetItem* || item->GeometryType == Part::GeomLineSegment::getClassTypeId() || item->GeometryType == Part::GeomBSplineCurve::getClassTypeId()); - bool validendpoint = item->hovered == SubElementType::end && - (item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() + bool validendpoint = item->hovered == SubElementType::end + && (item->GeometryType == Part::GeomArcOfCircle::getClassTypeId() || item->GeometryType == Part::GeomArcOfEllipse::getClassTypeId() || item->GeometryType == Part::GeomArcOfHyperbola::getClassTypeId() || item->GeometryType == Part::GeomArcOfParabola::getClassTypeId() || item->GeometryType == Part::GeomLineSegment::getClassTypeId() || item->GeometryType == Part::GeomBSplineCurve::getClassTypeId()); - bool validedge = item->hovered == SubElementType::edge && - item->GeometryType != Part::GeomPoint::getClassTypeId(); + bool validedge = item->hovered == SubElementType::edge + && item->GeometryType != Part::GeomPoint::getClassTypeId(); if (validmid || validstartpoint || validendpoint || validedge) { std::string doc_name = sketchView->getSketchObject()->getDocument()->getName(); @@ -1320,14 +1530,13 @@ void TaskSketcherElements::onListWidgetElementsMouseMoveOnItem(QListWidgetItem* ss << "Edge" << item->ElementNbr + 1; Gui::Selection().setPreselect(doc_name.c_str(), obj_name.c_str(), ss.str().c_str()); } - } previouslyHoveredItemIndex = ui->listWidgetElements->row(item); previouslyHoveredType = item->hovered; } -void TaskSketcherElements::leaveEvent (QEvent * event) +void TaskSketcherElements::leaveEvent(QEvent* event) { Q_UNUSED(event); Gui::Selection().rmvPreselect(); @@ -1338,15 +1547,16 @@ void TaskSketcherElements::slotElementsChanged(void) { assert(sketchView); // Build up ListView with the elements - Sketcher::SketchObject *sketch = sketchView->getSketchObject(); - const std::vector< Part::Geometry * > &vals = sketch->Geometry.getValues(); + Sketcher::SketchObject* sketch = sketchView->getSketchObject(); + const std::vector& vals = sketch->Geometry.getValues(); ui->listWidgetElements->clear(); using GeometryState = ElementItem::GeometryState; - int i=1; - for(std::vector< Part::Geometry * >::const_iterator it= vals.begin();it!=vals.end();++it,++i){ + int i = 1; + for (std::vector::const_iterator it = vals.begin(); it != vals.end(); + ++it, ++i) { Base::Type type = (*it)->getTypeId(); GeometryState state = GeometryState::Normal; @@ -1357,110 +1567,150 @@ void TaskSketcherElements::slotElementsChanged(void) if (internalAligned) state = GeometryState::InternalAlignment; - else if (construction) //Caution, internalAligned geos are construction too. So the 'if' and 'else if' cannot be swapped. + else if (construction)// Caution, internalAligned geos are construction too. So the 'if' and + // 'else if' cannot be swapped. state = GeometryState::Construction; - auto IdInformation = [this,i,layerId](){ - if(sketchView->VisualLayerList.getSize() > 1) + auto IdInformation = [this, i, layerId]() { + if (sketchView->VisualLayerList.getSize() > 1) return QString::fromLatin1("(Edge%1#ID%2#VL%3)").arg(i).arg(i - 1).arg(layerId); else return QString::fromLatin1("(Edge%1#ID%2)").arg(i).arg(i - 1); }; - ElementItem* itemN = new ElementItem(i - 1, + ElementItem* itemN = new ElementItem( + i - 1, sketchView->getSketchObject()->getVertexIndexGeoPos(i - 1, Sketcher::PointPos::start), sketchView->getSketchObject()->getVertexIndexGeoPos(i - 1, Sketcher::PointPos::mid), sketchView->getSketchObject()->getVertexIndexGeoPos(i - 1, Sketcher::PointPos::end), - type, state, - type == Part::GeomPoint::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Point") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Point"))) : - type == Part::GeomLineSegment::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Line") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Line"))) : - type == Part::GeomArcOfCircle::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Arc") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Arc"))) : - type == Part::GeomCircle::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Circle") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Circle"))) : - type == Part::GeomEllipse::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Ellipse") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Ellipse"))) : - type == Part::GeomArcOfEllipse::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Elliptical Arc") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Elliptical Arc"))) : - type == Part::GeomArcOfHyperbola::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Hyperbolic Arc") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Hyperbolic Arc"))) : - type == Part::GeomArcOfParabola::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Parabolic Arc") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Parabolic Arc"))) : - type == Part::GeomBSplineCurve::getClassTypeId() ? (isNamingBoxChecked ? - (tr("BSpline") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("BSpline"))) : - (isNamingBoxChecked ? - (tr("Other") + IdInformation()) + - (construction ? (QString::fromLatin1("-") + tr("Construction")) : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) : QString::fromLatin1(""))) : - (QString::fromLatin1("%1-").arg(i) + tr("Other"))), - sketchView - ); + type, + state, + type == Part::GeomPoint::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Point") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Point"))) + : type == Part::GeomLineSegment::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Line") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Line"))) + : type == Part::GeomArcOfCircle::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Arc") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Arc"))) + : type == Part::GeomCircle::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Circle") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Circle"))) + : type == Part::GeomEllipse::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Ellipse") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Ellipse"))) + : type == Part::GeomArcOfEllipse::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Elliptical Arc") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Elliptical Arc"))) + : type == Part::GeomArcOfHyperbola::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Hyperbolic Arc") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Hyperbolic Arc"))) + : type == Part::GeomArcOfParabola::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Parabolic Arc") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Parabolic Arc"))) + : type == Part::GeomBSplineCurve::getClassTypeId() + ? (isNamingBoxChecked ? (tr("BSpline") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("BSpline"))) + : (isNamingBoxChecked ? (tr("Other") + IdInformation()) + + (construction + ? (QString::fromLatin1("-") + tr("Construction")) + : (internalAligned ? (QString::fromLatin1("-") + tr("Internal")) + : QString::fromLatin1(""))) + : (QString::fromLatin1("%1-").arg(i) + tr("Other"))), + sketchView); ui->listWidgetElements->addItem(itemN); setItemVisibility(itemN); } - const std::vector< Part::Geometry * > &ext_vals = sketchView->getSketchObject()->getExternalGeometry(); + const std::vector& ext_vals = + sketchView->getSketchObject()->getExternalGeometry(); - const std::vector linkobjs = sketchView->getSketchObject()->ExternalGeometry.getValues(); - const std::vector linksubs = sketchView->getSketchObject()->ExternalGeometry.getSubValues(); + const std::vector linkobjs = + sketchView->getSketchObject()->ExternalGeometry.getValues(); + const std::vector linksubs = + sketchView->getSketchObject()->ExternalGeometry.getSubValues(); - int j=1; - for(std::vector< Part::Geometry * >::const_iterator it= ext_vals.begin();it!=ext_vals.end();++it,++i,++j){ - Base::Type type = (*it)->getTypeId(); + int j = 1; + for (std::vector::const_iterator it = ext_vals.begin(); it != ext_vals.end(); + ++it, ++i, ++j) { + Base::Type type = (*it)->getTypeId(); - if(j>2) { // we do not want the H and V axes + if (j > 2) {// we do not want the H and V axes auto layerId = getSafeGeomLayerId(*it); - auto IdInformation = [this,j,layerId](bool link){ - if(sketchView->VisualLayerList.getSize() > 1) { - if(link) { - return QString::fromLatin1("(ExternalEdge%1#ID%2#VL%3, ").arg(j-2).arg(-j).arg(layerId); + auto IdInformation = [this, j, layerId](bool link) { + if (sketchView->VisualLayerList.getSize() > 1) { + if (link) { + return QString::fromLatin1("(ExternalEdge%1#ID%2#VL%3, ") + .arg(j - 2) + .arg(-j) + .arg(layerId); } else { - return QString::fromLatin1("(ExternalEdge%1#ID%2#VL%3)").arg(j-2).arg(-j).arg(layerId); + return QString::fromLatin1("(ExternalEdge%1#ID%2#VL%3)") + .arg(j - 2) + .arg(-j) + .arg(layerId); } } else { - if(link) { - return QString::fromLatin1("(ExternalEdge%1#ID%2, ").arg(j-2).arg(-j); + if (link) { + return QString::fromLatin1("(ExternalEdge%1#ID%2, ").arg(j - 2).arg(-j); } else { - return QString::fromLatin1("(ExternalEdge%1#ID%2)").arg(j-2).arg(-j); + return QString::fromLatin1("(ExternalEdge%1#ID%2)").arg(j - 2).arg(-j); } } }; QString linkname; - if(isNamingBoxChecked) { - if(size_t(j-3) < linkobjs.size() && size_t(j-3) < linksubs.size()) { - linkname = IdInformation(true) + - QString::fromUtf8(linkobjs[j-3]->getNameInDocument()) + - QString::fromLatin1(".") + - QString::fromUtf8(linksubs[j-3].c_str()) + - QString::fromLatin1(")"); + if (isNamingBoxChecked) { + if (size_t(j - 3) < linkobjs.size() && size_t(j - 3) < linksubs.size()) { + linkname = IdInformation(true) + + QString::fromUtf8(linkobjs[j - 3]->getNameInDocument()) + + QString::fromLatin1(".") + QString::fromUtf8(linksubs[j - 3].c_str()) + + QString::fromLatin1(")"); } else { linkname = IdInformation(false); @@ -1469,48 +1719,50 @@ void TaskSketcherElements::slotElementsChanged(void) GeometryState state = GeometryState::External; - ElementItem* itemN = new ElementItem( -j, + ElementItem* itemN = new ElementItem( + -j, sketchView->getSketchObject()->getVertexIndexGeoPos(-j, Sketcher::PointPos::start), sketchView->getSketchObject()->getVertexIndexGeoPos(-j, Sketcher::PointPos::mid), sketchView->getSketchObject()->getVertexIndexGeoPos(-j, Sketcher::PointPos::end), - type, state, - type == Part::GeomPoint::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Point") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Point"))) : - type == Part::GeomLineSegment::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Line") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Line"))) : - type == Part::GeomArcOfCircle::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Arc") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Arc"))) : - type == Part::GeomCircle::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Circle") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Circle"))) : - type == Part::GeomEllipse::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Ellipse") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Ellipse"))) : - type == Part::GeomArcOfEllipse::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Elliptical Arc") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Elliptical Arc"))) : - type == Part::GeomArcOfHyperbola::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Hyperbolic Arc") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Hyperbolic Arc"))) : - type == Part::GeomArcOfParabola::getClassTypeId() ? (isNamingBoxChecked ? - (tr("Parabolic Arc") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Parabolic Arc"))) : - type == Part::GeomBSplineCurve::getClassTypeId() ? (isNamingBoxChecked ? - (tr("BSpline") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("BSpline"))) : - (isNamingBoxChecked ? - (tr("Other") + linkname) : - (QString::fromLatin1("%1-").arg(i - 2) + tr("Other"))), - sketchView - ); + type, + state, + type == Part::GeomPoint::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Point") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Point"))) + : type == Part::GeomLineSegment::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Line") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Line"))) + : type == Part::GeomArcOfCircle::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Arc") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Arc"))) + : type == Part::GeomCircle::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Circle") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Circle"))) + : type == Part::GeomEllipse::getClassTypeId() + ? (isNamingBoxChecked ? (tr("Ellipse") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Ellipse"))) + : type == Part::GeomArcOfEllipse::getClassTypeId() + ? (isNamingBoxChecked + ? (tr("Elliptical Arc") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Elliptical Arc"))) + : type == Part::GeomArcOfHyperbola::getClassTypeId() + ? (isNamingBoxChecked + ? (tr("Hyperbolic Arc") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Hyperbolic Arc"))) + : type == Part::GeomArcOfParabola::getClassTypeId() + ? (isNamingBoxChecked + ? (tr("Parabolic Arc") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Parabolic Arc"))) + : type == Part::GeomBSplineCurve::getClassTypeId() + ? (isNamingBoxChecked ? (tr("BSpline") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("BSpline"))) + : (isNamingBoxChecked ? (tr("Other") + linkname) + : (QString::fromLatin1("%1-").arg(i - 2) + tr("Other"))), + sketchView); ui->listWidgetElements->addItem(itemN); setItemVisibility(itemN); - } } } @@ -1524,17 +1776,17 @@ void TaskSketcherElements::clearWidget() // update widget int countItems = ui->listWidgetElements->count(); - for (int i=0; i < countItems; i++) { + for (int i = 0; i < countItems; i++) { ElementItem* item = static_cast(ui->listWidgetElements->item(i)); - item->isLineSelected=false; - item->isStartingPointSelected=false; - item->isEndPointSelected=false; - item->isMidPointSelected=false; + item->isLineSelected = false; + item->isStartingPointSelected = false; + item->isEndPointSelected = false; + item->isMidPointSelected = false; } } -void TaskSketcherElements::changeEvent(QEvent *e) +void TaskSketcherElements::changeEvent(QEvent* e) { TaskBox::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -1549,7 +1801,8 @@ void TaskSketcherElements::createSettingsButtonActions() action->setCheckable(true); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/Elements"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/Elements"); { QSignalBlocker block(this); action->setChecked(hGrp->GetBool("ExtendedNaming", false)); @@ -1565,11 +1818,12 @@ void TaskSketcherElements::onSettingsExtendedInformationChanged() QList acts = ui->settingsButton->actions(); isNamingBoxChecked = acts[0]->isChecked(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/Elements"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/Elements"); hGrp->SetBool("ExtendedNaming", isNamingBoxChecked); slotElementsChanged(); } +#include "TaskSketcherElements.moc"// For Delegate as it is QOBJECT #include "moc_TaskSketcherElements.cpp" -#include "TaskSketcherElements.moc" // For Delegate as it is QOBJECT diff --git a/src/Mod/Sketcher/Gui/TaskSketcherElements.h b/src/Mod/Sketcher/Gui/TaskSketcherElements.h index 5392d0fe85..d810f05b47 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherElements.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherElements.h @@ -23,8 +23,8 @@ #ifndef GUI_TASKVIEW_TaskSketcherElements_H #define GUI_TASKVIEW_TaskSketcherElements_H -#include #include +#include #include @@ -32,22 +32,24 @@ #include -namespace App { +namespace App +{ class Property; } -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; class Ui_TaskSketcherElements; - class ElementItem; class ElementView; // Struct to identify the selection/preselection of a subelement of the item -enum class SubElementType { +enum class SubElementType +{ edge, start, end, @@ -55,17 +57,17 @@ enum class SubElementType { none }; -class ElementView : public QListWidget +class ElementView: public QListWidget { Q_OBJECT public: - explicit ElementView(QWidget *parent = nullptr); + explicit ElementView(QWidget* parent = nullptr); ~ElementView() override; ElementItem* itemFromIndex(const QModelIndex& index); protected: - void contextMenuEvent (QContextMenuEvent* event) override; + void contextMenuEvent(QContextMenuEvent* event) override; protected Q_SLOTS: // Constraints @@ -103,7 +105,7 @@ protected Q_SLOTS: void onIndexChecked(QModelIndex, Qt::CheckState state); Q_SIGNALS: - void onItemHovered(QListWidgetItem *); + void onItemHovered(QListWidgetItem*); private: void changeLayer(int layer); @@ -111,12 +113,12 @@ private: class ElementFilterList; -class TaskSketcherElements : public Gui::TaskView::TaskBox, public Gui::SelectionObserver +class TaskSketcherElements: public Gui::TaskView::TaskBox, public Gui::SelectionObserver { Q_OBJECT public: - explicit TaskSketcherElements(ViewProviderSketch *sketchView); + explicit TaskSketcherElements(ViewProviderSketch* sketchView); ~TaskSketcherElements() override; /// Observer message from the Selection @@ -133,16 +135,16 @@ private: public Q_SLOTS: void onListWidgetElementsItemPressed(QListWidgetItem* item); - void onListWidgetElementsItemEntered(QListWidgetItem *item); + void onListWidgetElementsItemEntered(QListWidgetItem* item); void onListWidgetElementsMouseMoveOnItem(QListWidgetItem* item); void onSettingsExtendedInformationChanged(); void onFilterBoxStateChanged(int val); void onListMultiFilterItemChanged(QListWidgetItem* item); protected: - void changeEvent(QEvent *e) override; - void leaveEvent ( QEvent * event ) override; - ViewProviderSketch *sketchView; + void changeEvent(QEvent* e) override; + void leaveEvent(QEvent* event) override; + ViewProviderSketch* sketchView; using Connection = boost::signals2::connection; Connection connectionElementsChanged; @@ -159,6 +161,6 @@ private: bool isNamingBoxChecked; }; -} //namespace SketcherGui +}// namespace SketcherGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif// GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/Sketcher/Gui/TaskSketcherMessages.cpp b/src/Mod/Sketcher/Gui/TaskSketcherMessages.cpp index a8eb8aa183..de341e89b3 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherMessages.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherMessages.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -30,19 +30,19 @@ #include #include -#include "ui_TaskSketcherMessages.h" #include "TaskSketcherMessages.h" #include "ViewProviderSketch.h" +#include "ui_TaskSketcherMessages.h" using namespace SketcherGui; using namespace Gui::TaskView; namespace bp = boost::placeholders; -TaskSketcherMessages::TaskSketcherMessages(ViewProviderSketch *sketchView) : - TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Solver messages"), true, nullptr), - sketchView(sketchView), - ui(new Ui_TaskSketcherMessages) +TaskSketcherMessages::TaskSketcherMessages(ViewProviderSketch* sketchView) + : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Solver messages"), true, nullptr) + , sketchView(sketchView) + , ui(new Ui_TaskSketcherMessages) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -51,25 +51,44 @@ TaskSketcherMessages::TaskSketcherMessages(ViewProviderSketch *sketchView) : this->groupLayout()->addWidget(proxy); - connectionSetUp = sketchView->signalSetUp.connect(boost::bind(&SketcherGui::TaskSketcherMessages::slotSetUp, this, bp::_1, bp::_2, bp::_3, bp::_4)); + connectionSetUp = sketchView->signalSetUp.connect(boost::bind( + &SketcherGui::TaskSketcherMessages::slotSetUp, this, bp::_1, bp::_2, bp::_3, bp::_4)); ui->labelConstrainStatus->setOpenExternalLinks(false); // Set up the possible state values for the status label - ui->labelConstrainStatus->setParameterGroup("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - ui->labelConstrainStatus->registerState(QString::fromUtf8("empty_sketch"), palette().windowText().color(), std::string("EmptySketchMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("under_constrained"), palette().windowText().color(), std::string("UnderconstrainedMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("malformed_constraints"), QColor("red"), std::string("MalformedConstraintMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("conflicting_constraints"), QColor("orangered"), std::string("ConflictingConstraintMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("redundant_constraints"), QColor("red"), std::string("RedundantConstraintMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("partially_redundant_constraints"), QColor("royalblue"), std::string("PartiallyRedundantConstraintMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("solver_failed"), QColor("red"), std::string("SolverFailedMessageColor")); - ui->labelConstrainStatus->registerState(QString::fromUtf8("fully_constrained"), QColor("green"), std::string("FullyConstrainedMessageColor")); + ui->labelConstrainStatus->setParameterGroup( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ui->labelConstrainStatus->registerState(QString::fromUtf8("empty_sketch"), + palette().windowText().color(), + std::string("EmptySketchMessageColor")); + ui->labelConstrainStatus->registerState(QString::fromUtf8("under_constrained"), + palette().windowText().color(), + std::string("UnderconstrainedMessageColor")); + ui->labelConstrainStatus->registerState(QString::fromUtf8("malformed_constraints"), + QColor("red"), + std::string("MalformedConstraintMessageColor")); + ui->labelConstrainStatus->registerState(QString::fromUtf8("conflicting_constraints"), + QColor("orangered"), + std::string("ConflictingConstraintMessageColor")); + ui->labelConstrainStatus->registerState(QString::fromUtf8("redundant_constraints"), + QColor("red"), + std::string("RedundantConstraintMessageColor")); + ui->labelConstrainStatus->registerState( + QString::fromUtf8("partially_redundant_constraints"), + QColor("royalblue"), + std::string("PartiallyRedundantConstraintMessageColor")); + ui->labelConstrainStatus->registerState( + QString::fromUtf8("solver_failed"), QColor("red"), std::string("SolverFailedMessageColor")); + ui->labelConstrainStatus->registerState(QString::fromUtf8("fully_constrained"), + QColor("green"), + std::string("FullyConstrainedMessageColor")); ui->labelConstrainStatusLink->setLaunchExternal(false); - //Set Auto Update in the 'Manual Update' button menu. - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + // Set Auto Update in the 'Manual Update' button menu. + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); bool state = hGrp->GetBool("AutoRecompute", false); sketchView->getSketchObject()->noRecomputes = !state; @@ -80,10 +99,10 @@ TaskSketcherMessages::TaskSketcherMessages(ViewProviderSketch *sketchView) : action->setChecked(state); ui->manualUpdate->addAction(action); - QObject::connect( - qAsConst(ui->manualUpdate)->actions()[0], &QAction::changed, - this, &TaskSketcherMessages::onAutoUpdateStateChanged - ); + QObject::connect(qAsConst(ui->manualUpdate)->actions()[0], + &QAction::changed, + this, + &TaskSketcherMessages::onAutoUpdateStateChanged); } TaskSketcherMessages::~TaskSketcherMessages() @@ -93,13 +112,18 @@ TaskSketcherMessages::~TaskSketcherMessages() void TaskSketcherMessages::setupConnections() { - connect(ui->labelConstrainStatusLink, &Gui::UrlLabel::linkClicked, - this, &TaskSketcherMessages::onLabelConstrainStatusLinkClicked); - connect(ui->manualUpdate, &QToolButton::clicked, - this, &TaskSketcherMessages::onManualUpdateClicked); + connect(ui->labelConstrainStatusLink, + &Gui::UrlLabel::linkClicked, + this, + &TaskSketcherMessages::onLabelConstrainStatusLinkClicked); + connect(ui->manualUpdate, + &QToolButton::clicked, + this, + &TaskSketcherMessages::onManualUpdateClicked); } -void TaskSketcherMessages::slotSetUp(const QString& state, const QString& msg, const QString& link, const QString& linkText) +void TaskSketcherMessages::slotSetUp(const QString& state, const QString& msg, const QString& link, + const QString& linkText) { ui->labelConstrainStatus->setState(state); ui->labelConstrainStatus->setText(msg); @@ -110,46 +134,48 @@ void TaskSketcherMessages::slotSetUp(const QString& state, const QString& msg, c void TaskSketcherMessages::updateToolTip(const QString& link) { - if( link == QString::fromLatin1("#conflicting")) - ui->labelConstrainStatusLink->setToolTip(tr("Click to select the conflicting constraints.")); - else - if( link == QString::fromLatin1("#redundant")) + if (link == QString::fromLatin1("#conflicting")) + ui->labelConstrainStatusLink->setToolTip( + tr("Click to select the conflicting constraints.")); + else if (link == QString::fromLatin1("#redundant")) ui->labelConstrainStatusLink->setToolTip(tr("Click to select the redundant constraints.")); - else - if( link == QString::fromLatin1("#dofs")) - ui->labelConstrainStatusLink->setToolTip(tr("The sketch has unconstrained elements giving rise to those Degrees Of Freedom. Click to select the unconstrained elements.")); - else - if( link == QString::fromLatin1("#malformed")) + else if (link == QString::fromLatin1("#dofs")) + ui->labelConstrainStatusLink->setToolTip( + tr("The sketch has unconstrained elements giving rise to those Degrees Of Freedom. " + "Click to select the unconstrained elements.")); + else if (link == QString::fromLatin1("#malformed")) ui->labelConstrainStatusLink->setToolTip(tr("Click to select the malformed constraints.")); - else - if( link == QString::fromLatin1("#partiallyredundant")) - ui->labelConstrainStatusLink->setToolTip(tr("Some constraints in combination are partially redundant. Click to select the partially redundant constraints.")); + else if (link == QString::fromLatin1("#partiallyredundant")) + ui->labelConstrainStatusLink->setToolTip( + tr("Some constraints in combination are partially redundant. Click to select the " + "partially redundant constraints.")); } -void TaskSketcherMessages::onLabelConstrainStatusLinkClicked(const QString &str) +void TaskSketcherMessages::onLabelConstrainStatusLinkClicked(const QString& str) { - if( str == QString::fromLatin1("#conflicting")) - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_SelectConflictingConstraints"); - else - if( str == QString::fromLatin1("#redundant")) - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_SelectRedundantConstraints"); - else - if( str == QString::fromLatin1("#dofs")) - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_SelectElementsWithDoFs"); - else - if( str == QString::fromLatin1("#malformed")) - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_SelectMalformedConstraints"); - else - if( str == QString::fromLatin1("#partiallyredundant")) - Gui::Application::Instance->commandManager().runCommandByName("Sketcher_SelectPartiallyRedundantConstraints"); - + if (str == QString::fromLatin1("#conflicting")) + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_SelectConflictingConstraints"); + else if (str == QString::fromLatin1("#redundant")) + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_SelectRedundantConstraints"); + else if (str == QString::fromLatin1("#dofs")) + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_SelectElementsWithDoFs"); + else if (str == QString::fromLatin1("#malformed")) + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_SelectMalformedConstraints"); + else if (str == QString::fromLatin1("#partiallyredundant")) + Gui::Application::Instance->commandManager().runCommandByName( + "Sketcher_SelectPartiallyRedundantConstraints"); } void TaskSketcherMessages::onAutoUpdateStateChanged() { bool state = qAsConst(ui->manualUpdate)->actions()[0]->isChecked(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); hGrp->SetBool("AutoRecompute", state); sketchView->getSketchObject()->noRecomputes = !state; } diff --git a/src/Mod/Sketcher/Gui/TaskSketcherMessages.h b/src/Mod/Sketcher/Gui/TaskSketcherMessages.h index 6fb99b6f1e..881d79b9a5 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherMessages.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherMessages.h @@ -31,34 +31,37 @@ class Ui_TaskSketcherMessages; using Connection = boost::signals2::connection; -namespace App { +namespace App +{ class Property; } -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; -class TaskSketcherMessages : public Gui::TaskView::TaskBox +class TaskSketcherMessages: public Gui::TaskView::TaskBox { Q_OBJECT public: - explicit TaskSketcherMessages(ViewProviderSketch *sketchView); + explicit TaskSketcherMessages(ViewProviderSketch* sketchView); ~TaskSketcherMessages() override; - void slotSetUp(const QString& state, const QString& msg, const QString& link, const QString& linkText); + void slotSetUp(const QString& state, const QString& msg, const QString& link, + const QString& linkText); private: void setupConnections(); - void onLabelConstrainStatusLinkClicked(const QString &); + void onLabelConstrainStatusLinkClicked(const QString&); void onAutoUpdateStateChanged(); void onManualUpdateClicked(bool checked); void updateToolTip(const QString& link); - + protected: - ViewProviderSketch *sketchView; + ViewProviderSketch* sketchView; Connection connectionSetUp; private: @@ -66,6 +69,6 @@ private: std::unique_ptr ui; }; -} //namespace SketcherGui +}// namespace SketcherGui -#endif // GUI_TASKVIEW_TaskSketcherMessages_H +#endif// GUI_TASKVIEW_TaskSketcherMessages_H diff --git a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp index a4c5c6daa8..595285ff3f 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp @@ -22,41 +22,42 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include #include #include -#include "ui_TaskSketcherSolverAdvanced.h" #include "TaskSketcherSolverAdvanced.h" #include "ViewProviderSketch.h" +#include "ui_TaskSketcherSolverAdvanced.h" -#define LM_EPS 1E-10 +#define LM_EPS 1E-10 #define LM_EPS1 1E-80 -#define LM_TAU 1E-3 +#define LM_TAU 1E-3 #define DL_TOLG 1E-80 #define DL_TOLX 1E-80 #define DL_TOLF 1E-10 #define CONVERGENCE 1E-10 #define MAX_ITER 100 -#define DEFAULT_SOLVER 2 // DL=2, LM=1, BFGS=0 -#define DEFAULT_RSOLVER 2 // DL=2, LM=1, BFGS=0 -#define DEFAULT_QRSOLVER 1 // DENSE=0, SPARSEQR=1 -#define QR_PIVOT_THRESHOLD 1E-13 // under this value a Jacobian value is regarded as zero -#define DEFAULT_SOLVER_DEBUG 1 // None=0, Minimal=1, IterationLevel=2 +#define DEFAULT_SOLVER 2 // DL=2, LM=1, BFGS=0 +#define DEFAULT_RSOLVER 2 // DL=2, LM=1, BFGS=0 +#define DEFAULT_QRSOLVER 1 // DENSE=0, SPARSEQR=1 +#define QR_PIVOT_THRESHOLD 1E-13// under this value a Jacobian value is regarded as zero +#define DEFAULT_SOLVER_DEBUG 1 // None=0, Minimal=1, IterationLevel=2 #define MAX_ITER_MULTIPLIER false -#define DEFAULT_DOGLEG_GAUSS_STEP 0 // FullPivLU = 0, LeastNormFullPivLU = 1, LeastNormLdlt = 2 +#define DEFAULT_DOGLEG_GAUSS_STEP 0// FullPivLU = 0, LeastNormFullPivLU = 1, LeastNormLdlt = 2 using namespace SketcherGui; using namespace Gui::TaskView; -TaskSketcherSolverAdvanced::TaskSketcherSolverAdvanced(ViewProviderSketch *sketchView) : - TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Advanced solver control"), true, nullptr), - sketchView(sketchView), - ui(new Ui_TaskSketcherSolverAdvanced) +TaskSketcherSolverAdvanced::TaskSketcherSolverAdvanced(ViewProviderSketch* sketchView) + : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Advanced solver control"), true, + nullptr) + , sketchView(sketchView) + , ui(new Ui_TaskSketcherSolverAdvanced) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -82,68 +83,107 @@ TaskSketcherSolverAdvanced::TaskSketcherSolverAdvanced(ViewProviderSketch *sketc } TaskSketcherSolverAdvanced::~TaskSketcherSolverAdvanced() -{ -} +{} void TaskSketcherSolverAdvanced::setupConnections() { - connect(ui->comboBoxDefaultSolver, qOverload(&QComboBox::currentIndexChanged), - this, &TaskSketcherSolverAdvanced::onComboBoxDefaultSolverCurrentIndexChanged); - connect(ui->comboBoxDogLegGaussStep, qOverload(&QComboBox::currentIndexChanged), - this, &TaskSketcherSolverAdvanced::onComboBoxDogLegGaussStepCurrentIndexChanged); - connect(ui->spinBoxMaxIter, qOverload(&QSpinBox::valueChanged), - this, &TaskSketcherSolverAdvanced::onSpinBoxMaxIterValueChanged); - connect(ui->checkBoxSketchSizeMultiplier, &QCheckBox::stateChanged, - this, &TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged); - connect(ui->lineEditConvergence, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditConvergenceEditingFinished); - connect(ui->comboBoxQRMethod, qOverload(&QComboBox::currentIndexChanged), - this, &TaskSketcherSolverAdvanced::onComboBoxQRMethodCurrentIndexChanged); - connect(ui->lineEditQRPivotThreshold, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditQRPivotThresholdEditingFinished); - connect(ui->comboBoxRedundantDefaultSolver, qOverload(&QComboBox::currentIndexChanged), - this, &TaskSketcherSolverAdvanced::onComboBoxRedundantDefaultSolverCurrentIndexChanged); - connect(ui->lineEditRedundantConvergence, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditRedundantConvergenceEditingFinished); - connect(ui->spinBoxRedundantSolverMaxIterations, qOverload(&QSpinBox::valueChanged), - this, &TaskSketcherSolverAdvanced::onSpinBoxRedundantSolverMaxIterationsValueChanged); - connect(ui->checkBoxRedundantSketchSizeMultiplier, &QCheckBox::stateChanged, - this, &TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged); - connect(ui->comboBoxDebugMode, qOverload(&QComboBox::currentIndexChanged), - this, &TaskSketcherSolverAdvanced::onComboBoxDebugModeCurrentIndexChanged); - connect(ui->lineEditSolverParam1, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditSolverParam1EditingFinished); - connect(ui->lineEditRedundantSolverParam1, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam1EditingFinished); - connect(ui->lineEditSolverParam2, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditSolverParam2EditingFinished); - connect(ui->lineEditRedundantSolverParam2, &Gui::PrefLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam2EditingFinished); - connect(ui->lineEditSolverParam3, &QLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditSolverParam3EditingFinished); - connect(ui->lineEditRedundantSolverParam3, &Gui::PrefLineEdit::editingFinished, - this, &TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam3EditingFinished); - connect(ui->pushButtonDefaults, &QPushButton::clicked, - this, &TaskSketcherSolverAdvanced::onPushButtonDefaultsClicked); - connect(ui->pushButtonSolve, &QPushButton::clicked, - this, &TaskSketcherSolverAdvanced::onPushButtonSolveClicked); + connect(ui->comboBoxDefaultSolver, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskSketcherSolverAdvanced::onComboBoxDefaultSolverCurrentIndexChanged); + connect(ui->comboBoxDogLegGaussStep, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskSketcherSolverAdvanced::onComboBoxDogLegGaussStepCurrentIndexChanged); + connect(ui->spinBoxMaxIter, + qOverload(&QSpinBox::valueChanged), + this, + &TaskSketcherSolverAdvanced::onSpinBoxMaxIterValueChanged); + connect(ui->checkBoxSketchSizeMultiplier, + &QCheckBox::stateChanged, + this, + &TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged); + connect(ui->lineEditConvergence, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditConvergenceEditingFinished); + connect(ui->comboBoxQRMethod, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskSketcherSolverAdvanced::onComboBoxQRMethodCurrentIndexChanged); + connect(ui->lineEditQRPivotThreshold, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditQRPivotThresholdEditingFinished); + connect(ui->comboBoxRedundantDefaultSolver, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskSketcherSolverAdvanced::onComboBoxRedundantDefaultSolverCurrentIndexChanged); + connect(ui->lineEditRedundantConvergence, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditRedundantConvergenceEditingFinished); + connect(ui->spinBoxRedundantSolverMaxIterations, + qOverload(&QSpinBox::valueChanged), + this, + &TaskSketcherSolverAdvanced::onSpinBoxRedundantSolverMaxIterationsValueChanged); + connect(ui->checkBoxRedundantSketchSizeMultiplier, + &QCheckBox::stateChanged, + this, + &TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged); + connect(ui->comboBoxDebugMode, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskSketcherSolverAdvanced::onComboBoxDebugModeCurrentIndexChanged); + connect(ui->lineEditSolverParam1, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditSolverParam1EditingFinished); + connect(ui->lineEditRedundantSolverParam1, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam1EditingFinished); + connect(ui->lineEditSolverParam2, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditSolverParam2EditingFinished); + connect(ui->lineEditRedundantSolverParam2, + &Gui::PrefLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam2EditingFinished); + connect(ui->lineEditSolverParam3, + &QLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditSolverParam3EditingFinished); + connect(ui->lineEditRedundantSolverParam3, + &Gui::PrefLineEdit::editingFinished, + this, + &TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam3EditingFinished); + connect(ui->pushButtonDefaults, + &QPushButton::clicked, + this, + &TaskSketcherSolverAdvanced::onPushButtonDefaultsClicked); + connect(ui->pushButtonSolve, + &QPushButton::clicked, + this, + &TaskSketcherSolverAdvanced::onPushButtonSolveClicked); } void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); int currentindex = ui->comboBoxDefaultSolver->currentIndex(); int redundantcurrentindex = ui->comboBoxRedundantDefaultSolver->currentIndex(); - if(redundantcurrentindex == 2 || currentindex == 2) + if (redundantcurrentindex == 2 || currentindex == 2) ui->comboBoxDogLegGaussStep->setEnabled(true); else ui->comboBoxDogLegGaussStep->setEnabled(false); - switch(currentindex) - { - case 0: // BFGS + switch (currentindex) { + case 0:// BFGS ui->labelSolverParam1->setText(QString::fromLatin1("")); ui->labelSolverParam2->setText(QString::fromLatin1("")); ui->labelSolverParam3->setText(QString::fromLatin1("")); @@ -154,7 +194,7 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() ui->lineEditSolverParam2->setDisabled(true); ui->lineEditSolverParam3->setDisabled(true); break; - case 1: // LM + case 1:// LM { ui->labelSolverParam1->setText(QString::fromLatin1("Eps")); ui->labelSolverParam2->setText(QString::fromLatin1("Eps1")); @@ -162,21 +202,36 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() ui->lineEditSolverParam1->setEnabled(true); ui->lineEditSolverParam2->setEnabled(true); ui->lineEditSolverParam3->setEnabled(true); - double eps = ::atof(hGrp->GetASCII("LM_eps",QString::number(LM_EPS).toUtf8()).c_str()); - double eps1 = ::atof(hGrp->GetASCII("LM_eps1",QString::number(LM_EPS1).toUtf8()).c_str()); - double tau = ::atof(hGrp->GetASCII("LM_tau",QString::number(LM_TAU).toUtf8()).c_str()); - ui->lineEditSolverParam1->setText(QString::number(eps).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditSolverParam2->setText(QString::number(eps1).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditSolverParam3->setText(QString::number(tau).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - // SketchObject has encapsulated write-access. The current use of const_cast just for configuration is - // deemed acceptable. Eventually this dialog should be rewritten to include only useful information and the configuration - // centralised in an individual configuration object, possibly compatible with several solvers (e.g. DeepSOIC's ConstraintSolver) - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_eps(eps); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_eps1(eps1); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_tau(tau); + double eps = ::atof(hGrp->GetASCII("LM_eps", QString::number(LM_EPS).toUtf8()).c_str()); + double eps1 = + ::atof(hGrp->GetASCII("LM_eps1", QString::number(LM_EPS1).toUtf8()).c_str()); + double tau = ::atof(hGrp->GetASCII("LM_tau", QString::number(LM_TAU).toUtf8()).c_str()); + ui->lineEditSolverParam1->setText(QString::number(eps).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditSolverParam2->setText(QString::number(eps1).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditSolverParam3->setText(QString::number(tau).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + // SketchObject has encapsulated write-access. The current use of const_cast just for + // configuration is deemed acceptable. Eventually this dialog should be rewritten to + // include only useful information and the configuration centralised in an individual + // configuration object, possibly compatible with several solvers (e.g. DeepSOIC's + // ConstraintSolver) + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_eps(eps); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_eps1(eps1); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_tau(tau); break; } - case 2: // DogLeg + case 2:// DogLeg { ui->labelSolverParam1->setText(QString::fromLatin1("Tolg")); ui->labelSolverParam2->setText(QString::fromLatin1("Tolx")); @@ -184,15 +239,30 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() ui->lineEditSolverParam1->setEnabled(true); ui->lineEditSolverParam2->setEnabled(true); ui->lineEditSolverParam3->setEnabled(true); - double tolg = ::atof(hGrp->GetASCII("DL_tolg",QString::number(DL_TOLG).toUtf8()).c_str()); - double tolx = ::atof(hGrp->GetASCII("DL_tolx",QString::number(DL_TOLX).toUtf8()).c_str()); - double tolf = ::atof(hGrp->GetASCII("DL_tolf",QString::number(DL_TOLF).toUtf8()).c_str()); - ui->lineEditSolverParam1->setText(QString::number(tolg).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditSolverParam2->setText(QString::number(tolx).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditSolverParam3->setText(QString::number(tolf).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolg(tolg); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolf(tolf); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolx(tolx); + double tolg = + ::atof(hGrp->GetASCII("DL_tolg", QString::number(DL_TOLG).toUtf8()).c_str()); + double tolx = + ::atof(hGrp->GetASCII("DL_tolx", QString::number(DL_TOLX).toUtf8()).c_str()); + double tolf = + ::atof(hGrp->GetASCII("DL_tolf", QString::number(DL_TOLF).toUtf8()).c_str()); + ui->lineEditSolverParam1->setText(QString::number(tolg).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditSolverParam2->setText(QString::number(tolx).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditSolverParam3->setText(QString::number(tolf).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolg(tolg); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolf(tolf); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolx(tolx); break; } } @@ -200,19 +270,19 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); int currentindex = ui->comboBoxDefaultSolver->currentIndex(); int redundantcurrentindex = ui->comboBoxRedundantDefaultSolver->currentIndex(); - if(redundantcurrentindex == 2 || currentindex == 2) + if (redundantcurrentindex == 2 || currentindex == 2) ui->comboBoxDogLegGaussStep->setEnabled(true); else ui->comboBoxDogLegGaussStep->setEnabled(false); - switch(redundantcurrentindex) - { - case 0: // BFGS + switch (redundantcurrentindex) { + case 0:// BFGS ui->labelRedundantSolverParam1->setText(QString::fromLatin1("")); ui->labelRedundantSolverParam2->setText(QString::fromLatin1("")); ui->labelRedundantSolverParam3->setText(QString::fromLatin1("")); @@ -223,7 +293,7 @@ void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() ui->lineEditRedundantSolverParam2->setDisabled(true); ui->lineEditRedundantSolverParam3->setDisabled(true); break; - case 1: // LM + case 1:// LM { ui->labelRedundantSolverParam1->setText(QString::fromLatin1("R.Eps")); ui->labelRedundantSolverParam2->setText(QString::fromLatin1("R.Eps1")); @@ -231,18 +301,33 @@ void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() ui->lineEditRedundantSolverParam1->setEnabled(true); ui->lineEditRedundantSolverParam2->setEnabled(true); ui->lineEditRedundantSolverParam3->setEnabled(true); - double eps = ::atof(hGrp->GetASCII("Redundant_LM_eps",QString::number(LM_EPS).toUtf8()).c_str()); - double eps1 = ::atof(hGrp->GetASCII("Redundant_LM_eps1",QString::number(LM_EPS1).toUtf8()).c_str()); - double tau = ::atof(hGrp->GetASCII("Redundant_LM_tau",QString::number(LM_TAU).toUtf8()).c_str()); - ui->lineEditRedundantSolverParam1->setText(QString::number(eps).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditRedundantSolverParam2->setText(QString::number(eps1).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditRedundantSolverParam3->setText(QString::number(tau).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_epsRedundant(eps); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_eps1Redundant(eps1); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_tauRedundant(eps1); + double eps = ::atof( + hGrp->GetASCII("Redundant_LM_eps", QString::number(LM_EPS).toUtf8()).c_str()); + double eps1 = ::atof( + hGrp->GetASCII("Redundant_LM_eps1", QString::number(LM_EPS1).toUtf8()).c_str()); + double tau = ::atof( + hGrp->GetASCII("Redundant_LM_tau", QString::number(LM_TAU).toUtf8()).c_str()); + ui->lineEditRedundantSolverParam1->setText(QString::number(eps).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditRedundantSolverParam2->setText(QString::number(eps1).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditRedundantSolverParam3->setText(QString::number(tau).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_epsRedundant(eps); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_eps1Redundant(eps1); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_tauRedundant(eps1); break; } - case 2: // DogLeg + case 2:// DogLeg { ui->labelRedundantSolverParam1->setText(QString::fromLatin1("R.Tolg")); ui->labelRedundantSolverParam2->setText(QString::fromLatin1("R.Tolx")); @@ -250,15 +335,30 @@ void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() ui->lineEditRedundantSolverParam1->setEnabled(true); ui->lineEditRedundantSolverParam2->setEnabled(true); ui->lineEditRedundantSolverParam3->setEnabled(true); - double tolg = ::atof(hGrp->GetASCII("Redundant_DL_tolg",QString::number(DL_TOLG).toUtf8()).c_str()); - double tolx = ::atof(hGrp->GetASCII("Redundant_DL_tolx",QString::number(DL_TOLX).toUtf8()).c_str()); - double tolf = ::atof(hGrp->GetASCII("Redundant_DL_tolf",QString::number(DL_TOLF).toUtf8()).c_str()); - ui->lineEditRedundantSolverParam1->setText(QString::number(tolg).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditRedundantSolverParam2->setText(QString::number(tolx).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - ui->lineEditRedundantSolverParam3->setText(QString::number(tolf).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper())); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolgRedundant(tolg); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolfRedundant(tolf); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolxRedundant(tolx); + double tolg = ::atof( + hGrp->GetASCII("Redundant_DL_tolg", QString::number(DL_TOLG).toUtf8()).c_str()); + double tolx = ::atof( + hGrp->GetASCII("Redundant_DL_tolx", QString::number(DL_TOLX).toUtf8()).c_str()); + double tolf = ::atof( + hGrp->GetASCII("Redundant_DL_tolf", QString::number(DL_TOLF).toUtf8()).c_str()); + ui->lineEditRedundantSolverParam1->setText(QString::number(tolg).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditRedundantSolverParam2->setText(QString::number(tolx).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + ui->lineEditRedundantSolverParam3->setText(QString::number(tolf).remove( + QString::fromLatin1("+") + .replace(QString::fromLatin1("e0"), QString::fromLatin1("E")) + .toUpper())); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolgRedundant(tolg); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolfRedundant(tolf); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolxRedundant(tolx); break; } } @@ -270,21 +370,22 @@ void TaskSketcherSolverAdvanced::onLineEditSolverParam1EditingFinished() double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditSolverParam1->setText(sci.toUpper()); - switch(ui->comboBoxDefaultSolver->currentIndex()) - { - case 1: // LM + switch (ui->comboBoxDefaultSolver->currentIndex()) { + case 1:// LM { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_eps(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_eps(val); ui->lineEditSolverParam1->setEntryName("LM_eps"); ui->lineEditSolverParam1->onSave(); break; } - case 2: // DogLeg + case 2:// DogLeg { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolg(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolg(val); ui->lineEditSolverParam1->setEntryName("DL_tolg"); ui->lineEditSolverParam1->onSave(); break; @@ -298,21 +399,22 @@ void TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam1EditingFinished( double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditRedundantSolverParam1->setText(sci.toUpper()); - switch(ui->comboBoxDefaultSolver->currentIndex()) - { - case 1: // LM + switch (ui->comboBoxDefaultSolver->currentIndex()) { + case 1:// LM { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_epsRedundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_epsRedundant(val); ui->lineEditRedundantSolverParam1->setEntryName("Redundant_LM_eps"); ui->lineEditRedundantSolverParam1->onSave(); break; } - case 2: // DogLeg + case 2:// DogLeg { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolgRedundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolgRedundant(val); ui->lineEditRedundantSolverParam1->setEntryName("Redundant_DL_tolg"); ui->lineEditRedundantSolverParam1->onSave(); break; @@ -326,21 +428,22 @@ void TaskSketcherSolverAdvanced::onLineEditSolverParam2EditingFinished() double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditSolverParam2->setText(sci.toUpper()); - switch(ui->comboBoxDefaultSolver->currentIndex()) - { - case 1: // LM + switch (ui->comboBoxDefaultSolver->currentIndex()) { + case 1:// LM { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_eps1(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_eps1(val); ui->lineEditSolverParam2->setEntryName("LM_eps1"); ui->lineEditSolverParam2->onSave(); break; } - case 2: // DogLeg + case 2:// DogLeg { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolx(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolx(val); ui->lineEditSolverParam2->setEntryName("DL_tolx"); ui->lineEditSolverParam2->onSave(); break; @@ -354,21 +457,22 @@ void TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam2EditingFinished( double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditRedundantSolverParam2->setText(sci.toUpper()); - switch(ui->comboBoxDefaultSolver->currentIndex()) - { - case 1: // LM + switch (ui->comboBoxDefaultSolver->currentIndex()) { + case 1:// LM { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_eps1Redundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_eps1Redundant(val); ui->lineEditRedundantSolverParam2->setEntryName("Redundant_LM_eps1"); ui->lineEditRedundantSolverParam2->onSave(); break; } - case 2: // DogLeg + case 2:// DogLeg { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolxRedundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolxRedundant(val); ui->lineEditRedundantSolverParam2->setEntryName("Redundant_DL_tolx"); ui->lineEditRedundantSolverParam2->onSave(); break; @@ -382,21 +486,22 @@ void TaskSketcherSolverAdvanced::onLineEditSolverParam3EditingFinished() double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditSolverParam3->setText(sci.toUpper()); - switch(ui->comboBoxDefaultSolver->currentIndex()) - { - case 1: // LM + switch (ui->comboBoxDefaultSolver->currentIndex()) { + case 1:// LM { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_tau(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_tau(val); ui->lineEditSolverParam3->setEntryName("LM_tau"); ui->lineEditSolverParam3->onSave(); break; } - case 2: // DogLeg + case 2:// DogLeg { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolf(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolf(val); ui->lineEditSolverParam3->setEntryName("DL_tolf"); ui->lineEditSolverParam3->onSave(); break; @@ -410,21 +515,22 @@ void TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam3EditingFinished( double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditRedundantSolverParam3->setText(sci.toUpper()); - switch(ui->comboBoxDefaultSolver->currentIndex()) - { - case 1: // LM + switch (ui->comboBoxDefaultSolver->currentIndex()) { + case 1:// LM { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setLM_tauRedundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setLM_tauRedundant(val); ui->lineEditRedundantSolverParam3->setEntryName("Redundant_LM_tau"); ui->lineEditRedundantSolverParam3->onSave(); break; } - case 2: // DogLeg + case 2:// DogLeg { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDL_tolfRedundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDL_tolfRedundant(val); ui->lineEditRedundantSolverParam3->setEntryName("Redundant_DL_tolf"); ui->lineEditRedundantSolverParam3->onSave(); break; @@ -435,32 +541,36 @@ void TaskSketcherSolverAdvanced::onLineEditRedundantSolverParam3EditingFinished( void TaskSketcherSolverAdvanced::onComboBoxDefaultSolverCurrentIndexChanged(int index) { ui->comboBoxDefaultSolver->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).defaultSolver = static_cast(index); + const_cast(sketchView->getSketchObject()->getSolvedSketch()).defaultSolver = + static_cast(index); updateDefaultMethodParameters(); } void TaskSketcherSolverAdvanced::onComboBoxDogLegGaussStepCurrentIndexChanged(int index) { ui->comboBoxDogLegGaussStep->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDogLegGaussStep((GCS::DogLegGaussStep) index); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDogLegGaussStep((GCS::DogLegGaussStep)index); updateDefaultMethodParameters(); } void TaskSketcherSolverAdvanced::onSpinBoxMaxIterValueChanged(int i) { ui->spinBoxMaxIter->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setMaxIter(i); + const_cast(sketchView->getSketchObject()->getSolvedSketch()).setMaxIter(i); } void TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged(int state) { - if(state==Qt::Checked) { + if (state == Qt::Checked) { ui->checkBoxSketchSizeMultiplier->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplier(true); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setSketchSizeMultiplier(true); } - else if (state==Qt::Unchecked) { + else if (state == Qt::Unchecked) { ui->checkBoxSketchSizeMultiplier->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplier(false); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setSketchSizeMultiplier(false); } } @@ -470,12 +580,13 @@ void TaskSketcherSolverAdvanced::onLineEditQRPivotThresholdEditingFinished() double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditQRPivotThreshold->setText(sci.toUpper()); ui->lineEditQRPivotThreshold->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setQRPivotThreshold(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setQRPivotThreshold(val); } void TaskSketcherSolverAdvanced::onLineEditConvergenceEditingFinished() @@ -484,12 +595,13 @@ void TaskSketcherSolverAdvanced::onLineEditConvergenceEditingFinished() double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditConvergence->setText(sci.toUpper()); ui->lineEditConvergence->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setConvergence(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setConvergence(val); } void TaskSketcherSolverAdvanced::onLineEditRedundantConvergenceEditingFinished() @@ -498,88 +610,96 @@ void TaskSketcherSolverAdvanced::onLineEditRedundantConvergenceEditingFinished() double val = text.toDouble(); QString sci = QString::number(val); sci.remove(QString::fromLatin1("+")); - sci.replace(QString::fromLatin1("e0"),QString::fromLatin1("E")); + sci.replace(QString::fromLatin1("e0"), QString::fromLatin1("E")); ui->lineEditRedundantConvergence->setText(sci.toUpper()); ui->lineEditRedundantConvergence->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setConvergenceRedundant(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setConvergenceRedundant(val); } void TaskSketcherSolverAdvanced::onComboBoxQRMethodCurrentIndexChanged(int index) { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setQRAlgorithm((GCS::QRAlgorithm) index); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setQRAlgorithm((GCS::QRAlgorithm)index); ui->comboBoxQRMethod->onSave(); } void TaskSketcherSolverAdvanced::onComboBoxRedundantDefaultSolverCurrentIndexChanged(int index) { ui->comboBoxRedundantDefaultSolver->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).defaultSolverRedundant = static_cast(index); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .defaultSolverRedundant = static_cast(index); updateRedundantMethodParameters(); } void TaskSketcherSolverAdvanced::onSpinBoxRedundantSolverMaxIterationsValueChanged(int i) { ui->spinBoxRedundantSolverMaxIterations->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setMaxIterRedundant(i); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setMaxIterRedundant(i); } void TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged(int state) { - if(state==Qt::Checked) { + if (state == Qt::Checked) { ui->checkBoxRedundantSketchSizeMultiplier->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplierRedundant(true); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setSketchSizeMultiplierRedundant(true); } - else if (state==Qt::Unchecked) { + else if (state == Qt::Unchecked) { ui->checkBoxRedundantSketchSizeMultiplier->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplierRedundant(true); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setSketchSizeMultiplierRedundant(true); } } void TaskSketcherSolverAdvanced::onComboBoxDebugModeCurrentIndexChanged(int index) { ui->comboBoxDebugMode->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDebugMode((GCS::DebugMode) index); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDebugMode((GCS::DebugMode)index); } -void TaskSketcherSolverAdvanced::onPushButtonSolveClicked(bool checked/* = false*/) +void TaskSketcherSolverAdvanced::onPushButtonSolveClicked(bool checked /* = false*/) { Q_UNUSED(checked); sketchView->getSketchObject()->solve(); } -void TaskSketcherSolverAdvanced::onPushButtonDefaultsClicked(bool checked/* = false*/) +void TaskSketcherSolverAdvanced::onPushButtonDefaultsClicked(bool checked /* = false*/) { Q_UNUSED(checked); // Algorithm params for default solvers - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); - hGrp->SetASCII("LM_eps",QString::number(LM_EPS).toUtf8()); - hGrp->SetASCII("LM_eps1",QString::number(LM_EPS1).toUtf8()); - hGrp->SetASCII("LM_tau",QString::number(LM_TAU).toUtf8()); - hGrp->SetASCII("DL_tolg",QString::number(DL_TOLG).toUtf8()); - hGrp->SetASCII("DL_tolx",QString::number(DL_TOLX).toUtf8()); - hGrp->SetASCII("DL_tolf",QString::number(DL_TOLF).toUtf8()); - hGrp->SetASCII("Redundant_LM_eps",QString::number(LM_EPS).toUtf8()); - hGrp->SetASCII("Redundant_LM_eps1",QString::number(LM_EPS1).toUtf8()); - hGrp->SetASCII("Redundant_LM_tau",QString::number(LM_TAU).toUtf8()); - hGrp->SetASCII("Redundant_DL_tolg",QString::number(DL_TOLG).toUtf8()); - hGrp->SetASCII("Redundant_DL_tolx",QString::number(DL_TOLX).toUtf8()); - hGrp->SetASCII("Redundant_DL_tolf",QString::number(DL_TOLF).toUtf8()); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); + hGrp->SetASCII("LM_eps", QString::number(LM_EPS).toUtf8()); + hGrp->SetASCII("LM_eps1", QString::number(LM_EPS1).toUtf8()); + hGrp->SetASCII("LM_tau", QString::number(LM_TAU).toUtf8()); + hGrp->SetASCII("DL_tolg", QString::number(DL_TOLG).toUtf8()); + hGrp->SetASCII("DL_tolx", QString::number(DL_TOLX).toUtf8()); + hGrp->SetASCII("DL_tolf", QString::number(DL_TOLF).toUtf8()); + hGrp->SetASCII("Redundant_LM_eps", QString::number(LM_EPS).toUtf8()); + hGrp->SetASCII("Redundant_LM_eps1", QString::number(LM_EPS1).toUtf8()); + hGrp->SetASCII("Redundant_LM_tau", QString::number(LM_TAU).toUtf8()); + hGrp->SetASCII("Redundant_DL_tolg", QString::number(DL_TOLG).toUtf8()); + hGrp->SetASCII("Redundant_DL_tolx", QString::number(DL_TOLX).toUtf8()); + hGrp->SetASCII("Redundant_DL_tolf", QString::number(DL_TOLF).toUtf8()); // Set other settings - hGrp->SetInt("DefaultSolver",DEFAULT_SOLVER); - hGrp->SetInt("DogLegGaussStep",DEFAULT_DOGLEG_GAUSS_STEP); + hGrp->SetInt("DefaultSolver", DEFAULT_SOLVER); + hGrp->SetInt("DogLegGaussStep", DEFAULT_DOGLEG_GAUSS_STEP); - hGrp->SetInt("RedundantDefaultSolver",DEFAULT_RSOLVER); - hGrp->SetInt("MaxIter",MAX_ITER); - hGrp->SetInt("RedundantSolverMaxIterations",MAX_ITER); - hGrp->SetBool("SketchSizeMultiplier",MAX_ITER_MULTIPLIER); - hGrp->SetBool("RedundantSketchSizeMultiplier",MAX_ITER_MULTIPLIER); - hGrp->SetASCII("Convergence",QString::number(CONVERGENCE).toUtf8()); - hGrp->SetASCII("RedundantConvergence",QString::number(CONVERGENCE).toUtf8()); - hGrp->SetInt("QRMethod",DEFAULT_QRSOLVER); - hGrp->SetASCII("QRPivotThreshold",QString::number(QR_PIVOT_THRESHOLD).toUtf8()); - hGrp->SetInt("DebugMode",DEFAULT_SOLVER_DEBUG); + hGrp->SetInt("RedundantDefaultSolver", DEFAULT_RSOLVER); + hGrp->SetInt("MaxIter", MAX_ITER); + hGrp->SetInt("RedundantSolverMaxIterations", MAX_ITER); + hGrp->SetBool("SketchSizeMultiplier", MAX_ITER_MULTIPLIER); + hGrp->SetBool("RedundantSketchSizeMultiplier", MAX_ITER_MULTIPLIER); + hGrp->SetASCII("Convergence", QString::number(CONVERGENCE).toUtf8()); + hGrp->SetASCII("RedundantConvergence", QString::number(CONVERGENCE).toUtf8()); + hGrp->SetInt("QRMethod", DEFAULT_QRSOLVER); + hGrp->SetASCII("QRPivotThreshold", QString::number(QR_PIVOT_THRESHOLD).toUtf8()); + hGrp->SetInt("DebugMode", DEFAULT_SOLVER_DEBUG); ui->comboBoxDefaultSolver->onRestore(); ui->comboBoxDogLegGaussStep->onRestore(); @@ -599,18 +719,31 @@ void TaskSketcherSolverAdvanced::onPushButtonDefaultsClicked(bool checked/* = fa void TaskSketcherSolverAdvanced::updateSketchObject() { - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDebugMode((GCS::DebugMode) ui->comboBoxDebugMode->currentIndex()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplierRedundant(ui->checkBoxRedundantSketchSizeMultiplier->isChecked()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setMaxIterRedundant(ui->spinBoxRedundantSolverMaxIterations->value()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).defaultSolverRedundant = static_cast(ui->comboBoxRedundantDefaultSolver->currentIndex()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setQRAlgorithm((GCS::QRAlgorithm) ui->comboBoxQRMethod->currentIndex()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setQRPivotThreshold(ui->lineEditQRPivotThreshold->text().toDouble()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setConvergenceRedundant(ui->lineEditRedundantConvergence->text().toDouble()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setConvergence(ui->lineEditConvergence->text().toDouble()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplier(ui->checkBoxSketchSizeMultiplier->isChecked()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setMaxIter(ui->spinBoxMaxIter->value()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).defaultSolver = static_cast(ui->comboBoxDefaultSolver->currentIndex()); - const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDogLegGaussStep((GCS::DogLegGaussStep) ui->comboBoxDogLegGaussStep->currentIndex()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDebugMode((GCS::DebugMode)ui->comboBoxDebugMode->currentIndex()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setSketchSizeMultiplierRedundant(ui->checkBoxRedundantSketchSizeMultiplier->isChecked()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setMaxIterRedundant(ui->spinBoxRedundantSolverMaxIterations->value()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .defaultSolverRedundant = + static_cast(ui->comboBoxRedundantDefaultSolver->currentIndex()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setQRAlgorithm((GCS::QRAlgorithm)ui->comboBoxQRMethod->currentIndex()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setQRPivotThreshold(ui->lineEditQRPivotThreshold->text().toDouble()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setConvergenceRedundant(ui->lineEditRedundantConvergence->text().toDouble()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setConvergence(ui->lineEditConvergence->text().toDouble()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setSketchSizeMultiplier(ui->checkBoxSketchSizeMultiplier->isChecked()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setMaxIter(ui->spinBoxMaxIter->value()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()).defaultSolver = + static_cast(ui->comboBoxDefaultSolver->currentIndex()); + const_cast(sketchView->getSketchObject()->getSolvedSketch()) + .setDogLegGaussStep((GCS::DogLegGaussStep)ui->comboBoxDogLegGaussStep->currentIndex()); updateDefaultMethodParameters(); updateRedundantMethodParameters(); diff --git a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h index 27503d6173..dfb4a2331b 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h @@ -28,20 +28,22 @@ class Ui_TaskSketcherSolverAdvanced; -namespace App { +namespace App +{ class Property; } -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; -class TaskSketcherSolverAdvanced : public Gui::TaskView::TaskBox +class TaskSketcherSolverAdvanced: public Gui::TaskView::TaskBox { Q_OBJECT public: - explicit TaskSketcherSolverAdvanced(ViewProviderSketch *sketchView); + explicit TaskSketcherSolverAdvanced(ViewProviderSketch* sketchView); ~TaskSketcherSolverAdvanced() override; private: @@ -71,14 +73,15 @@ protected: void updateDefaultMethodParameters(); void updateRedundantMethodParameters(); void updateSketchObject(); + protected: - ViewProviderSketch *sketchView; + ViewProviderSketch* sketchView; private: QWidget* proxy; std::unique_ptr ui; }; -} //namespace SketcherGui +}// namespace SketcherGui -#endif // GUI_TASKVIEW_TaskSketcherSolverAdvanced_H +#endif// GUI_TASKVIEW_TaskSketcherSolverAdvanced_H diff --git a/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp b/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp index bcb7781a46..c10b9793c7 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp @@ -22,30 +22,30 @@ #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 #include +#include #include +#include #include #include -#include -#include #include -#include "ui_TaskSketcherValidation.h" #include "TaskSketcherValidation.h" +#include "ui_TaskSketcherValidation.h" using namespace SketcherGui; @@ -54,7 +54,11 @@ using namespace Gui::TaskView; /* TRANSLATOR SketcherGui::SketcherValidation */ SketcherValidation::SketcherValidation(Sketcher::SketchObject* Obj, QWidget* parent) -: QWidget(parent), ui(new Ui_TaskSketcherValidation()), sketch(Obj), sketchAnalyser(Obj), coincidenceRoot(nullptr) + : QWidget(parent) + , ui(new Ui_TaskSketcherValidation()) + , sketch(Obj) + , sketchAnalyser(Obj) + , coincidenceRoot(nullptr) { ui->setupUi(this); setupConnections(); @@ -64,25 +68,22 @@ SketcherValidation::SketcherValidation(Sketcher::SketchObject* Obj, QWidget* par ui->fixDegenerated->setEnabled(false); ui->swapReversed->setEnabled(false); ui->checkBoxIgnoreConstruction->setEnabled(true); - double tolerances[8] = { - Precision::Confusion() / 100, - Precision::Confusion() / 10, - Precision::Confusion(), - Precision::Confusion() * 10, - Precision::Confusion() * 100, - Precision::Confusion() * 1000, - Precision::Confusion() * 10000, - Precision::Confusion() * 100000 - }; + double tolerances[8] = {Precision::Confusion() / 100, + Precision::Confusion() / 10, + Precision::Confusion(), + Precision::Confusion() * 10, + Precision::Confusion() * 100, + Precision::Confusion() * 1000, + Precision::Confusion() * 10000, + Precision::Confusion() * 100000}; QLocale loc; - for (int i=0; i<8; i++) { + for (int i = 0; i < 8; i++) { ui->comboBoxTolerance->addItem(loc.toString(tolerances[i]), QVariant(tolerances[i])); } ui->comboBoxTolerance->setCurrentIndex(5); ui->comboBoxTolerance->setEditable(true); - ui->comboBoxTolerance->setValidator(new QDoubleValidator(0,10,10,this)); - + ui->comboBoxTolerance->setValidator(new QDoubleValidator(0, 10, 10, this)); } SketcherValidation::~SketcherValidation() @@ -92,33 +93,47 @@ SketcherValidation::~SketcherValidation() void SketcherValidation::setupConnections() { - connect(ui->findButton, &QPushButton::clicked, - this, &SketcherValidation::onFindButtonClicked); - connect(ui->fixButton, &QPushButton::clicked, - this, &SketcherValidation::onFixButtonClicked); - connect(ui->highlightButton, &QPushButton::clicked, - this, &SketcherValidation::onHighlightButtonClicked); - connect(ui->findConstraint, &QPushButton::clicked, - this, &SketcherValidation::onFindConstraintClicked); - connect(ui->fixConstraint, &QPushButton::clicked, - this, &SketcherValidation::onFixConstraintClicked); - connect(ui->findReversed, &QPushButton::clicked, - this, &SketcherValidation::onFindReversedClicked); - connect(ui->swapReversed, &QPushButton::clicked, - this, &SketcherValidation::onSwapReversedClicked); - connect(ui->orientLockEnable, &QPushButton::clicked, - this, &SketcherValidation::onOrientLockEnableClicked); - connect(ui->orientLockDisable, &QPushButton::clicked, - this, &SketcherValidation::onOrientLockDisableClicked); - connect(ui->delConstrExtr, &QPushButton::clicked, - this, &SketcherValidation::onDelConstrExtrClicked); - connect(ui->findDegenerated, &QPushButton::clicked, - this, &SketcherValidation::onFindDegeneratedClicked); - connect(ui->fixDegenerated, &QPushButton::clicked, - this, &SketcherValidation::onFixDegeneratedClicked); + connect(ui->findButton, &QPushButton::clicked, this, &SketcherValidation::onFindButtonClicked); + connect(ui->fixButton, &QPushButton::clicked, this, &SketcherValidation::onFixButtonClicked); + connect(ui->highlightButton, + &QPushButton::clicked, + this, + &SketcherValidation::onHighlightButtonClicked); + connect(ui->findConstraint, + &QPushButton::clicked, + this, + &SketcherValidation::onFindConstraintClicked); + connect(ui->fixConstraint, + &QPushButton::clicked, + this, + &SketcherValidation::onFixConstraintClicked); + connect( + ui->findReversed, &QPushButton::clicked, this, &SketcherValidation::onFindReversedClicked); + connect( + ui->swapReversed, &QPushButton::clicked, this, &SketcherValidation::onSwapReversedClicked); + connect(ui->orientLockEnable, + &QPushButton::clicked, + this, + &SketcherValidation::onOrientLockEnableClicked); + connect(ui->orientLockDisable, + &QPushButton::clicked, + this, + &SketcherValidation::onOrientLockDisableClicked); + connect(ui->delConstrExtr, + &QPushButton::clicked, + this, + &SketcherValidation::onDelConstrExtrClicked); + connect(ui->findDegenerated, + &QPushButton::clicked, + this, + &SketcherValidation::onFindDegeneratedClicked); + connect(ui->fixDegenerated, + &QPushButton::clicked, + this, + &SketcherValidation::onFixDegeneratedClicked); } -void SketcherValidation::changeEvent(QEvent *e) +void SketcherValidation::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -135,9 +150,9 @@ void SketcherValidation::onFindButtonClicked() bool ok; double conv; - conv = QLocale::system().toDouble(ui->comboBoxTolerance->currentText(),&ok); + conv = QLocale::system().toDouble(ui->comboBoxTolerance->currentText(), &ok); - if(ok) { + if (ok) { prec = conv; } else { @@ -147,9 +162,11 @@ void SketcherValidation::onFindButtonClicked() } } - sketchAnalyser.detectMissingPointOnPointConstraints(prec,!ui->checkBoxIgnoreConstruction->isChecked()); + sketchAnalyser.detectMissingPointOnPointConstraints( + prec, !ui->checkBoxIgnoreConstruction->isChecked()); - std::vector & vertexConstraints = sketchAnalyser.getMissingPointOnPointConstraints(); + std::vector& vertexConstraints = + sketchAnalyser.getMissingPointOnPointConstraints(); std::vector points; points.reserve(vertexConstraints.size()); @@ -160,17 +177,17 @@ void SketcherValidation::onFindButtonClicked() hidePoints(); if (vertexConstraints.empty()) { - Gui::TranslatedNotification(*sketch, - tr("No missing coincidences"), - tr("No missing coincidences found")); + Gui::TranslatedNotification( + *sketch, tr("No missing coincidences"), tr("No missing coincidences found")); ui->fixButton->setEnabled(false); } else { showPoints(points); - Gui::TranslatedUserWarning(*sketch, - tr("Missing coincidences"), - tr("%1 missing coincidences found").arg(vertexConstraints.size())); + Gui::TranslatedUserWarning( + *sketch, + tr("Missing coincidences"), + tr("%1 missing coincidences found").arg(vertexConstraints.size())); ui->fixButton->setEnabled(true); } @@ -216,16 +233,14 @@ void SketcherValidation::onFindConstraintClicked() return; if (sketch->evaluateConstraints()) { - Gui::TranslatedNotification(*sketch, - tr("No invalid constraints"), - tr("No invalid constraints found")); + Gui::TranslatedNotification( + *sketch, tr("No invalid constraints"), tr("No invalid constraints found")); ui->fixConstraint->setEnabled(false); } else { - Gui::TranslatedUserError(*sketch, - tr("Invalid constraints"), - tr("Invalid constraints found")); + Gui::TranslatedUserError( + *sketch, tr("Invalid constraints"), tr("Invalid constraints found")); ui->fixConstraint->setEnabled(true); } @@ -246,12 +261,13 @@ void SketcherValidation::onFindReversedClicked() return; std::vector points; - const std::vector& geom = sketch->getExternalGeometry(); - for (std::size_t i=0; i& geom = sketch->getExternalGeometry(); + for (std::size_t i = 0; i < geom.size(); i++) { Part::Geometry* g = geom[i]; - //only arcs of circles need to be repaired. Arcs of ellipse were so broken there should be nothing to repair from. + // only arcs of circles need to be repaired. Arcs of ellipse were so broken there should be + // nothing to repair from. if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *segm = static_cast(g); + const Part::GeomArcOfCircle* segm = static_cast(g); if (segm->isReversed()) { points.push_back(segm->getStartPoint(/*emulateCCW=*/true)); points.push_back(segm->getEndPoint(/*emulateCCW=*/true)); @@ -259,35 +275,40 @@ void SketcherValidation::onFindReversedClicked() } } hidePoints(); - if(!points.empty()){ + if (!points.empty()) { int nc = sketch->port_reversedExternalArcs(/*justAnalyze=*/true); showPoints(points); - if(nc>0){ - Gui::TranslatedUserWarning(*sketch, - tr("Reversed external geometry"), - tr("%1 reversed external-geometry arcs were found. Their endpoints are" + if (nc > 0) { + Gui::TranslatedUserWarning( + *sketch, + tr("Reversed external geometry"), + tr("%1 reversed external-geometry arcs were found. Their endpoints are" " encircled in 3d view.\n\n" "%2 constraints are linking to the endpoints. The constraints have" " been listed in Report view (menu View -> Panels -> Report view).\n\n" "Click \"Swap endpoints in constraints\" button to reassign endpoints." - " Do this only once to sketches created in FreeCAD older than v0.15" - ).arg(points.size()/2).arg(nc) - ); + " Do this only once to sketches created in FreeCAD older than v0.15") + .arg(points.size() / 2) + .arg(nc)); ui->swapReversed->setEnabled(true); - } else { - Gui::TranslatedUserWarning(*sketch, - tr("Reversed external geometry"), - tr("%1 reversed external-geometry arcs were found. Their endpoints are " + } + else { + Gui::TranslatedUserWarning( + *sketch, + tr("Reversed external geometry"), + tr("%1 reversed external-geometry arcs were found. Their endpoints are " "encircled in 3d view.\n\n" - "However, no constraints linking to the endpoints were found.").arg(points.size()/2)); + "However, no constraints linking to the endpoints were found.") + .arg(points.size() / 2)); ui->swapReversed->setEnabled(false); } - } else { + } + else { Gui::TranslatedNotification(*sketch, - tr("Reversed external geometry"), - tr("No reversed external-geometry arcs were found.")); + tr("Reversed external geometry"), + tr("No reversed external-geometry arcs were found.")); } } @@ -300,9 +321,10 @@ void SketcherValidation::onSwapReversedClicked() doc->openTransaction("Sketch porting"); int n = sketch->port_reversedExternalArcs(/*justAnalyze=*/false); - Gui::TranslatedNotification(*sketch, - tr("Reversed external geometry"), - tr("%1 changes were made to constraints linking to endpoints of reversed arcs.").arg(n)); + Gui::TranslatedNotification( + *sketch, + tr("Reversed external geometry"), + tr("%1 changes were made to constraints linking to endpoints of reversed arcs.").arg(n)); hidePoints(); ui->swapReversed->setEnabled(false); @@ -319,11 +341,13 @@ void SketcherValidation::onOrientLockEnableClicked() doc->openTransaction("Constraint orientation lock"); int n = sketch->changeConstraintsLocking(/*bLock=*/true); - Gui::TranslatedNotification(*sketch, - tr("Constraint orientation locking"), - tr("Orientation locking was enabled and recomputed for %1 constraints. The" + Gui::TranslatedNotification( + *sketch, + tr("Constraint orientation locking"), + tr("Orientation locking was enabled and recomputed for %1 constraints. The" " constraints have been listed in Report view (menu View -> Panels ->" - " Report view).").arg(n)); + " Report view).") + .arg(n)); doc->commitTransaction(); } @@ -337,12 +361,14 @@ void SketcherValidation::onOrientLockDisableClicked() doc->openTransaction("Constraint orientation unlock"); int n = sketch->changeConstraintsLocking(/*bLock=*/false); - Gui::TranslatedNotification(*sketch, - tr("Constraint orientation locking"), - tr("Orientation locking was disabled for %1 constraints. The" + Gui::TranslatedNotification( + *sketch, + tr("Constraint orientation locking"), + tr("Orientation locking was disabled for %1 constraints. The" " constraints have been listed in Report view (menu View -> Panels ->" " Report view). Note that for all future constraints, the locking still" - " defaults to ON.").arg(n)); + " defaults to ON.") + .arg(n)); doc->commitTransaction(); } @@ -353,11 +379,15 @@ void SketcherValidation::onDelConstrExtrClicked() return; int reply; - reply = QMessageBox::question(this, - tr("Delete constraints to external geom."), - tr("You are about to delete ALL constraints that deal with external geometry. This is useful to rescue a sketch with broken/changed links to external geometry. Are you sure you want to delete the constraints?"), - QMessageBox::No|QMessageBox::Yes,QMessageBox::No); - if(reply!=QMessageBox::Yes) + reply = QMessageBox::question( + this, + tr("Delete constraints to external geom."), + tr("You are about to delete ALL constraints that deal with external geometry. This is " + "useful to rescue a sketch with broken/changed links to external geometry. Are you sure " + "you want to delete the constraints?"), + QMessageBox::No | QMessageBox::Yes, + QMessageBox::No); + if (reply != QMessageBox::Yes) return; App::Document* doc = sketch->getDocument(); @@ -367,16 +397,16 @@ void SketcherValidation::onDelConstrExtrClicked() doc->commitTransaction(); - Gui::TranslatedNotification(*sketch, - tr("Delete constraints to external geom."), - tr("All constraints that deal with external geometry were deleted.")); - + Gui::TranslatedNotification( + *sketch, + tr("Delete constraints to external geom."), + tr("All constraints that deal with external geometry were deleted.")); } void SketcherValidation::showPoints(const std::vector& pts) { - SoCoordinate3 * coords = new SoCoordinate3(); - SoDrawStyle * drawStyle = new SoDrawStyle(); + SoCoordinate3* coords = new SoCoordinate3(); + SoDrawStyle* drawStyle = new SoDrawStyle(); drawStyle->pointSize = 6; SoPointSet* pcPoints = new SoPointSet(); @@ -384,7 +414,7 @@ void SketcherValidation::showPoints(const std::vector& pts) coincidenceRoot->addChild(drawStyle); SoSeparator* pointsep = new SoSeparator(); - SoBaseColor * basecol = new SoBaseColor(); + SoBaseColor* basecol = new SoBaseColor(); basecol->rgb.setValue(1.0f, 0.5f, 0.0f); pointsep->addChild(basecol); pointsep->addChild(coords); @@ -392,10 +422,14 @@ void SketcherValidation::showPoints(const std::vector& pts) coincidenceRoot->addChild(pointsep); // Draw markers - SoBaseColor * markcol = new SoBaseColor(); + SoBaseColor* markcol = new SoBaseColor(); markcol->rgb.setValue(1.0f, 1.0f, 0.0f); SoMarkerSet* marker = new SoMarkerSet(); - marker->markerIndex=Gui::Inventor::MarkerBitmaps::getMarkerIndex("PLUS", App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")->GetInt("MarkerSize", 9)); + marker->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex( + "PLUS", + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetInt("MarkerSize", 9)); pointsep->addChild(markcol); pointsep->addChild(marker); @@ -404,7 +438,7 @@ void SketcherValidation::showPoints(const std::vector& pts) SbVec3f* c = coords->point.startEditing(); for (int i = 0; i < pts_size; i++) { const Base::Vector3d& v = pts[i]; - c[i].setValue((float)v.x,(float)v.y,(float)v.z); + c[i].setValue((float)v.x, (float)v.y, (float)v.z); } coords->point.finishEditing(); @@ -434,16 +468,14 @@ void SketcherValidation::onFindDegeneratedClicked() int count = sketchAnalyser.detectDegeneratedGeometries(prec); if (count == 0) { - Gui::TranslatedNotification(*sketch, - tr("No degenerated geometry"), - tr("No degenerated geometry found")); + Gui::TranslatedNotification( + *sketch, tr("No degenerated geometry"), tr("No degenerated geometry found")); ui->fixDegenerated->setEnabled(false); } else { - Gui::TranslatedUserWarning(*sketch, - tr("Degenerated geometry"), - tr("%1 degenerated geometry found").arg(count)); + Gui::TranslatedUserWarning( + *sketch, tr("Degenerated geometry"), tr("%1 degenerated geometry found").arg(count)); ui->fixDegenerated->setEnabled(true); } @@ -475,14 +507,13 @@ void SketcherValidation::onFixDegeneratedClicked() TaskSketcherValidation::TaskSketcherValidation(Sketcher::SketchObject* Obj) { QWidget* widget = new SketcherValidation(Obj); - Gui::TaskView::TaskBox* taskbox = new Gui::TaskView::TaskBox( - QPixmap(), widget->windowTitle(), true, nullptr); + Gui::TaskView::TaskBox* taskbox = + new Gui::TaskView::TaskBox(QPixmap(), widget->windowTitle(), true, nullptr); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } TaskSketcherValidation::~TaskSketcherValidation() -{ -} +{} #include "moc_TaskSketcherValidation.cpp" diff --git a/src/Mod/Sketcher/Gui/TaskSketcherValidation.h b/src/Mod/Sketcher/Gui/TaskSketcherValidation.h index 00c0d4c28e..8141357901 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherValidation.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherValidation.h @@ -33,12 +33,16 @@ class SoGroup; -namespace Sketcher { class SketchObject; } +namespace Sketcher +{ +class SketchObject; +} -namespace SketcherGui { +namespace SketcherGui +{ class Ui_TaskSketcherValidation; -class SketcherValidation : public QWidget +class SketcherValidation: public QWidget { Q_OBJECT @@ -47,7 +51,7 @@ public: ~SketcherValidation() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void setupConnections(); @@ -75,7 +79,7 @@ private: SoGroup* coincidenceRoot; }; -class TaskSketcherValidation : public Gui::TaskView::TaskDialog +class TaskSketcherValidation: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -83,9 +87,11 @@ public: explicit TaskSketcherValidation(Sketcher::SketchObject* Obj); ~TaskSketcherValidation() override; QDialogButtonBox::StandardButtons getStandardButtons(void) const override - { return QDialogButtonBox::Close; } + { + return QDialogButtonBox::Close; + } }; -} //namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_TASKSKETCHERVALIDATION_H +#endif// SKETCHERGUI_TASKSKETCHERVALIDATION_H diff --git a/src/Mod/Sketcher/Gui/Utils.cpp b/src/Mod/Sketcher/Gui/Utils.cpp index daf6c19b3f..17b48b0281 100644 --- a/src/Mod/Sketcher/Gui/Utils.cpp +++ b/src/Mod/Sketcher/Gui/Utils.cpp @@ -55,8 +55,8 @@ bool SketcherGui::tryAutoRecompute(Sketcher::SketchObject* obj, bool& autoremove bool autoRecompute = hGrp->GetBool("AutoRecompute", false); bool autoRemoveRedundants = hGrp->GetBool("AutoRemoveRedundants", false); - // We need to make sure the solver has right redundancy information before trying to remove the redundants. - // for example if a non-driving constraint has been added. + // We need to make sure the solver has right redundancy information before trying to remove the + // redundants. for example if a non-driving constraint has been added. if (autoRemoveRedundants && autoRecompute) obj->solve(); @@ -146,16 +146,18 @@ void SketcherGui::getIdsFromName(const std::string& name, const Sketcher::Sketch } } -std::vector SketcherGui::getGeoIdsOfEdgesFromNames(const Sketcher::SketchObject* Obj, const std::vector & names) +std::vector SketcherGui::getGeoIdsOfEdgesFromNames(const Sketcher::SketchObject* Obj, + const std::vector& names) { std::vector geoids; - for(const auto & name : names) { + for (const auto& name : names) { if (name.size() > 4 && name.substr(0, 4) == "Edge") { geoids.push_back(std::atoi(name.substr(4, 4000).c_str()) - 1); } else if (name.size() > 12 && name.substr(0, 12) == "ExternalEdge") { - geoids.push_back(Sketcher::GeoEnum::RefExt + 1 - std::atoi(name.substr(12, 4000).c_str())); + geoids.push_back(Sketcher::GeoEnum::RefExt + 1 + - std::atoi(name.substr(12, 4000).c_str())); } else if (name.size() > 6 && name.substr(0, 6) == "Vertex") { int VtId = std::atoi(name.substr(6, 4000).c_str()) - 1; @@ -163,7 +165,7 @@ std::vector SketcherGui::getGeoIdsOfEdgesFromNames(const Sketcher::SketchOb Sketcher::PointPos PosId; Obj->getGeoVertexIndex(VtId, GeoId, PosId); const Part::Geometry* geo = Obj->getGeometry(GeoId); - if (geo->getTypeId() == Part::GeomPoint::getClassTypeId()){ + if (geo->getTypeId() == Part::GeomPoint::getClassTypeId()) { geoids.push_back(GeoId); } } @@ -260,16 +262,17 @@ bool SketcherGui::isBsplineKnotOrEndPoint(const Sketcher::SketchObject* Obj, int bool SketcherGui::IsPointAlreadyOnCurve(int GeoIdCurve, int GeoIdPoint, Sketcher::PointPos PosIdPoint, Sketcher::SketchObject* Obj) { - //This func is a "smartness" behind three-element tangent-, perp.- and angle-via-point. - //We want to find out, if the point supplied by user is already on - // both of the curves. If not, necessary point-on-object constraints - // are to be added automatically. - //Simple geometric test seems to be the best, because a point can be - // constrained to a curve in a number of ways (e.g. it is an endpoint of an - // arc, or is coincident to endpoint of an arc, or it is an endpoint of an - // ellipse's major diameter line). Testing all those possibilities is way - // too much trouble, IMO(DeepSOIC). - // One exception: check for knots on their B-splines, at least until point on B-spline is implemented. (Ajinkya) + // This func is a "smartness" behind three-element tangent-, perp.- and angle-via-point. + // We want to find out, if the point supplied by user is already on + // both of the curves. If not, necessary point-on-object constraints + // are to be added automatically. + // Simple geometric test seems to be the best, because a point can be + // constrained to a curve in a number of ways (e.g. it is an endpoint of an + // arc, or is coincident to endpoint of an arc, or it is an endpoint of an + // ellipse's major diameter line). Testing all those possibilities is way + // too much trouble, IMO(DeepSOIC). + // One exception: check for knots on their B-splines, at least until point on B-spline is + // implemented. (Ajinkya) if (isBsplineKnot(Obj, GeoIdPoint)) { const Part::Geometry* geoCurve = Obj->getGeometry(GeoIdCurve); if (geoCurve->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { @@ -329,7 +332,9 @@ double SketcherGui::GetPointAngle(const Base::Vector2d& p1, const Base::Vector2d // Set the two points on circles at minimal distance // in concentric case set points on relative X axis -void SketcherGui::GetCirclesMinimalDistance(const Part::GeomCircle *circle1, const Part::GeomCircle *circle2, Base::Vector3d &point1, Base::Vector3d &point2) +void SketcherGui::GetCirclesMinimalDistance(const Part::GeomCircle* circle1, + const Part::GeomCircle* circle2, Base::Vector3d& point1, + Base::Vector3d& point2) { double radius1 = circle1->getRadius(); double radius2 = circle2->getRadius(); @@ -340,20 +345,23 @@ void SketcherGui::GetCirclesMinimalDistance(const Part::GeomCircle *circle1, con Base::Vector3d v = point2 - point1; double length = v.Length(); - if (length == 0) { //concentric case + if (length == 0) {// concentric case point1.x += radius1; point2.x += radius2; - } else { + } + else { v = v.Normalize(); - if (length <= std::max(radius1, radius2)){ //inner case - if (radius1 > radius2){ + if (length <= std::max(radius1, radius2)) {// inner case + if (radius1 > radius2) { point1 += v * radius1; point2 += v * radius2; - } else { + } + else { point1 += -v * radius1; point2 += -v * radius2; } - } else { //outer case + } + else {// outer case point1 += v * radius1; point2 += -v * radius2; } @@ -374,7 +382,8 @@ void SketcherGui::ActivateHandler(Gui::Document* doc, DrawSketchHandler* handler } } -bool SketcherGui::isSketchInEdit(Gui::Document* doc) { +bool SketcherGui::isSketchInEdit(Gui::Document* doc) +{ if (doc) { // checks if a Sketch Viewprovider is in Edit and is in no special mode auto* vp = dynamic_cast(doc->getInEdit()); @@ -385,16 +394,18 @@ bool SketcherGui::isSketchInEdit(Gui::Document* doc) { bool SketcherGui::isCommandActive(Gui::Document* doc, bool actsOnSelection) { - if(isSketchInEdit(doc)) { - auto mode = static_cast(doc->getInEdit())->getSketchMode(); + if (isSketchInEdit(doc)) { + auto mode = + static_cast(doc->getInEdit())->getSketchMode(); - if (mode == ViewProviderSketch::STATUS_NONE || - mode == ViewProviderSketch::STATUS_SKETCH_UseHandler) { + if (mode == ViewProviderSketch::STATUS_NONE + || mode == ViewProviderSketch::STATUS_SKETCH_UseHandler) { if (!actsOnSelection) { return true; } - else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0) { + else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) + > 0) { return true; } } @@ -403,9 +414,10 @@ bool SketcherGui::isCommandActive(Gui::Document* doc, bool actsOnSelection) return false; } -SketcherGui::ViewProviderSketch* SketcherGui::getInactiveHandlerEditModeSketchViewProvider(Gui::Document* doc) +SketcherGui::ViewProviderSketch* +SketcherGui::getInactiveHandlerEditModeSketchViewProvider(Gui::Document* doc) { - if(doc) { + if (doc) { return dynamic_cast(doc->getInEdit()); } @@ -414,7 +426,7 @@ SketcherGui::ViewProviderSketch* SketcherGui::getInactiveHandlerEditModeSketchVi SketcherGui::ViewProviderSketch* SketcherGui::getInactiveHandlerEditModeSketchViewProvider() { - Gui::Document *doc = Gui::Application::Instance->activeDocument(); + Gui::Document* doc = Gui::Application::Instance->activeDocument(); return getInactiveHandlerEditModeSketchViewProvider(doc); } @@ -430,44 +442,44 @@ void SketcherGui::removeRedundantHorizontalVertical(Sketcher::SketchObject* pske // we look for: // 1. Coincident to external on both endpoints // 2. Coincident in one endpoint to origin and pointonobject/tangent to an axis on the other - auto detectredundant = [psketch](std::vector& sug, - bool& ext, - bool& orig, - bool& axis) { - ext = false; - orig = false; - axis = false; + auto detectredundant = + [psketch](std::vector& sug, bool& ext, bool& orig, bool& axis) { + ext = false; + orig = false; + axis = false; - for (std::vector::const_iterator it = sug.begin(); it != sug.end(); - ++it) { - if ((*it).Type == Sketcher::Coincident && !ext) { - const std::map coincidents = - psketch->getAllCoincidentPoints((*it).GeoId, (*it).PosId); + for (std::vector::const_iterator it = sug.begin(); it != sug.end(); + ++it) { + if ((*it).Type == Sketcher::Coincident && !ext) { + const std::map coincidents = + psketch->getAllCoincidentPoints((*it).GeoId, (*it).PosId); - if (!coincidents.empty()) { - // the keys are ordered, so if the first is negative, it is coincident with external - ext = coincidents.begin()->first < 0; + if (!coincidents.empty()) { + // the keys are ordered, so if the first is negative, it is coincident + // with external + ext = coincidents.begin()->first < 0; - std::map::const_iterator geoId1iterator; + std::map::const_iterator geoId1iterator; - geoId1iterator = coincidents.find(-1); + geoId1iterator = coincidents.find(-1); - if (geoId1iterator != coincidents.end()) { - if ((*geoId1iterator).second == Sketcher::PointPos::start) - orig = true; + if (geoId1iterator != coincidents.end()) { + if ((*geoId1iterator).second == Sketcher::PointPos::start) + orig = true; + } + } + else {// it may be that there is no constraint at all, but there is external + // geometry + ext = (*it).GeoId < 0; + orig = ((*it).GeoId == -1 && (*it).PosId == Sketcher::PointPos::start); } } - else {// it may be that there is no constraint at all, but there is external geometry - ext = (*it).GeoId < 0; - orig = ((*it).GeoId == -1 && (*it).PosId == Sketcher::PointPos::start); + else if ((*it).Type == Sketcher::PointOnObject && !axis) { + axis = (((*it).GeoId == -1 && (*it).PosId == Sketcher::PointPos::none) + || ((*it).GeoId == -2 && (*it).PosId == Sketcher::PointPos::none)); } } - else if ((*it).Type == Sketcher::PointOnObject && !axis) { - axis = (((*it).GeoId == -1 && (*it).PosId == Sketcher::PointPos::none) - || ((*it).GeoId == -2 && (*it).PosId == Sketcher::PointPos::none)); - } - } - }; + }; bool firstext = false, secondext = false, firstorig = false, secondorig = false, firstaxis = false, secondaxis = false; @@ -534,7 +546,7 @@ void SketcherGui::ConstraintToAttachment(Sketcher::GeoElementId element, } -//convenience functions for cursor display +// convenience functions for cursor display bool SketcherGui::hideUnits() { Base::Reference hGrp = App::GetApplication() @@ -552,7 +564,7 @@ bool SketcherGui::showCursorCoords() .GetGroup("BaseApp") ->GetGroup("Preferences") ->GetGroup("Mod/Sketcher"); - return hGrp->GetBool("ShowCursorCoords", true);//true for testing. set to false for prod. + return hGrp->GetBool("ShowCursorCoords", true);// true for testing. set to false for prod. } bool SketcherGui::useSystemDecimals() @@ -565,12 +577,12 @@ bool SketcherGui::useSystemDecimals() return hGrp->GetBool("UseSystemDecimals", true); } -//convert value to display format %0.[digits]f. Units are displayed if -//preference "ShowUnits" is true, or if the unit schema in effect uses -//multiple units (ex. Ft/In). Digits parameter is ignored for multi-unit -//schemata -//TODO:: if the user string is delivered in 1.23e45 format, this might not work -// correctly. +// convert value to display format %0.[digits]f. Units are displayed if +// preference "ShowUnits" is true, or if the unit schema in effect uses +// multiple units (ex. Ft/In). Digits parameter is ignored for multi-unit +// schemata +// TODO:: if the user string is delivered in 1.23e45 format, this might not work +// correctly. std::string SketcherGui::lengthToDisplayFormat(double value, int digits) { Base::Quantity asQuantity; @@ -578,28 +590,28 @@ std::string SketcherGui::lengthToDisplayFormat(double value, int digits) asQuantity.setUnit(Base::Unit::Length); QString qUserString = asQuantity.getUserString(); if (Base::UnitsApi::isMultiUnitLength() || (!hideUnits() && useSystemDecimals())) { - //just return the user string + // just return the user string return Base::Tools::toStdString(qUserString); } - //find the unit of measure + // find the unit of measure double factor = 1.0; QString qUnitString; QString qtranslate = Base::UnitsApi::schemaTranslate(asQuantity, factor, qUnitString); QString unitPart = QString::fromUtf8(" ") + qUnitString; - //get the numeric part of the user string + // get the numeric part of the user string QRegularExpression rxNoUnits( QString::fromUtf8("(.*) \\D*$"));// text before space + any non digits at end of string QRegularExpressionMatch match = rxNoUnits.match(qUserString); if (!match.hasMatch()) { - //no units in userString? + // no units in userString? return Base::Tools::toStdString(qUserString); } - QString matched = match.captured(1);//matched is the numeric part of user string + QString matched = match.captured(1);// matched is the numeric part of user string int dpPos = matched.indexOf(QLocale().decimalPoint()); if (dpPos < 0) { - //no decimal separator (ie an integer), return all the digits + // no decimal separator (ie an integer), return all the digits if (hideUnits()) { return Base::Tools::toStdString(matched); } @@ -608,16 +620,16 @@ std::string SketcherGui::lengthToDisplayFormat(double value, int digits) } } - //real number + // real number if (useSystemDecimals() && hideUnits()) { - //return just the numeric part of the user string + // return just the numeric part of the user string return Base::Tools::toStdString(matched); } - //real number and not using system decimals + // real number and not using system decimals int requiredLength = dpPos + digits + 1; if (requiredLength > matched.size()) { - //just take the whole thing + // just take the whole thing requiredLength = matched.size(); } QString numericPart = matched.left(requiredLength); @@ -627,11 +639,11 @@ std::string SketcherGui::lengthToDisplayFormat(double value, int digits) return Base::Tools::toStdString(numericPart + unitPart); } -//convert value to display format %0.[digits]f. Units are always displayed for -//angles - 123.456° or 12°34'56". Digits parameter is ignored for multi-unit -//schemata. Note small differences between this method and lengthToDisplyFormat -//TODO:: if the user string is delivered in 1.23e45 format, this might not work -// correctly. +// convert value to display format %0.[digits]f. Units are always displayed for +// angles - 123.456° or 12°34'56". Digits parameter is ignored for multi-unit +// schemata. Note small differences between this method and lengthToDisplyFormat +// TODO:: if the user string is delivered in 1.23e45 format, this might not work +// correctly. std::string SketcherGui::angleToDisplayFormat(double value, int digits) { Base::Quantity asQuantity; @@ -639,47 +651,47 @@ std::string SketcherGui::angleToDisplayFormat(double value, int digits) asQuantity.setUnit(Base::Unit::Angle); QString qUserString = asQuantity.getUserString(); if (Base::UnitsApi::isMultiUnitAngle()) { - //just return the user string - //Coin SbString doesn't handle utf8 well, so we convert to ascii - QString schemeMinute = QString::fromUtf8("\xE2\x80\xB2");//prime symbol - QString schemeSecond = QString::fromUtf8("\xE2\x80\xB3");//double prime symbol - QString escapeMinute = QString::fromLatin1("\'"); //substitute ascii single quote - QString escapeSecond = QString::fromLatin1("\""); //substitute ascii double quote + // just return the user string + // Coin SbString doesn't handle utf8 well, so we convert to ascii + QString schemeMinute = QString::fromUtf8("\xE2\x80\xB2");// prime symbol + QString schemeSecond = QString::fromUtf8("\xE2\x80\xB3");// double prime symbol + QString escapeMinute = QString::fromLatin1("\'"); // substitute ascii single quote + QString escapeSecond = QString::fromLatin1("\""); // substitute ascii double quote QString displayString = qUserString.replace(schemeMinute, escapeMinute); displayString = displayString.replace(schemeSecond, escapeSecond); return Base::Tools::toStdString(displayString); } - //we always use use U+00B0 (°) as the unit of measure for angles in - //single unit schema. Will need a change to support rads or grads. + // we always use use U+00B0 (°) as the unit of measure for angles in + // single unit schema. Will need a change to support rads or grads. auto qUnitString = QString::fromUtf8("°"); auto decimalSep = QLocale().decimalPoint(); - //get the numeric part of the user string - QRegularExpression rxNoUnits( - QString::fromUtf8("(\\d*\\%1?\\d*)(\\D*)$").arg(decimalSep));// number + non digits at end of string + // get the numeric part of the user string + QRegularExpression rxNoUnits(QString::fromUtf8("(\\d*\\%1?\\d*)(\\D*)$") + .arg(decimalSep));// number + non digits at end of string QRegularExpressionMatch match = rxNoUnits.match(qUserString); if (!match.hasMatch()) { - //no units in userString? + // no units in userString? return Base::Tools::toStdString(qUserString); } - QString matched = match.captured(1);//matched is the numeric part of user string + QString matched = match.captured(1);// matched is the numeric part of user string int dpPos = matched.indexOf(decimalSep); if (dpPos < 0) { - //no decimal separator (ie an integer), return all the digits + // no decimal separator (ie an integer), return all the digits return Base::Tools::toStdString(matched + qUnitString); } - //real number + // real number if (useSystemDecimals()) { - //return just the numeric part of the user string + degree symbol + // return just the numeric part of the user string + degree symbol return Base::Tools::toStdString(matched + qUnitString); } - //real number and not using system decimals + // real number and not using system decimals int requiredLength = dpPos + digits + 1; if (requiredLength > matched.size()) { - //just take the whole thing + // just take the whole thing requiredLength = matched.size(); } QString numericPart = matched.left(requiredLength); diff --git a/src/Mod/Sketcher/Gui/Utils.h b/src/Mod/Sketcher/Gui/Utils.h index 662d9f941f..fecf4e1c3e 100644 --- a/src/Mod/Sketcher/Gui/Utils.h +++ b/src/Mod/Sketcher/Gui/Utils.h @@ -32,33 +32,38 @@ #include "ViewProviderSketchGeometryExtension.h" -namespace App { - class DocumentObject; +namespace App +{ +class DocumentObject; } -namespace Gui { - class DocumentObject; - class Document; -} +namespace Gui +{ +class DocumentObject; +class Document; +}// namespace Gui -namespace Part { - class Geometry; -} -namespace Sketcher { - enum class PointPos : int; - class SketchObject; +namespace Part +{ +class Geometry; } +namespace Sketcher +{ +enum class PointPos : int; +class SketchObject; +}// namespace Sketcher -namespace SketcherGui { - class DrawSketchHandler; - class ViewProviderSketch; +namespace SketcherGui +{ +class DrawSketchHandler; +class ViewProviderSketch; /// This function tries to auto-recompute the active document if the option /// is set in the user parameter. If the option is not set nothing will be done /// @return true if a recompute was undertaken, false if not. bool tryAutoRecompute(Sketcher::SketchObject* obj); /// Same as the other overload, but also returns whether redundants shall be removed or not -bool tryAutoRecompute(Sketcher::SketchObject* obj, bool &autoremoveredundants); +bool tryAutoRecompute(Sketcher::SketchObject* obj, bool& autoremoveredundants); /// This function tries to auto-recompute as tryAutoRecompute. If tryAutoRecompute /// is not enabled, then it solves the SketchObject. @@ -70,10 +75,12 @@ bool ReleaseHandler(Gui::Document* doc); std::string getStrippedPythonExceptionString(const Base::Exception&); -void getIdsFromName(const std::string &name, const Sketcher::SketchObject* Obj, int &GeoId, Sketcher::PointPos &PosId); +void getIdsFromName(const std::string& name, const Sketcher::SketchObject* Obj, int& GeoId, + Sketcher::PointPos& PosId); /// Returns ONLY the geometry elements when the "Edge" is selected (including GeomPoints) -std::vector getGeoIdsOfEdgesFromNames(const Sketcher::SketchObject* Obj, const std::vector & names); +std::vector getGeoIdsOfEdgesFromNames(const Sketcher::SketchObject* Obj, + const std::vector& names); bool checkBothExternal(int GeoId1, int GeoId2); @@ -81,7 +88,8 @@ bool isPointOrSegmentFixed(const Sketcher::SketchObject* Obj, int GeoId); bool areBothPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, int GeoId1, int GeoId2); -bool areAllPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, int GeoId1, int GeoId2, int GeoId3); +bool areAllPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, int GeoId1, int GeoId2, + int GeoId3); bool inline isVertex(int GeoId, Sketcher::PointPos PosId); @@ -91,17 +99,22 @@ bool isSimpleVertex(const Sketcher::SketchObject* Obj, int GeoId, Sketcher::Poin /// Checks if `GeoId` corresponds to a B-Spline knot bool isBsplineKnot(const Sketcher::SketchObject* Obj, int GeoId); -/// Checks if the (`GeoId`, `PosId`) pair corresponds to a B-Spline knot, including first and last knots -bool isBsplineKnotOrEndPoint(const Sketcher::SketchObject* Obj, int GeoId, Sketcher::PointPos PosId); +/// Checks if the (`GeoId`, `PosId`) pair corresponds to a B-Spline knot, including first and last +/// knots +bool isBsplineKnotOrEndPoint(const Sketcher::SketchObject* Obj, int GeoId, + Sketcher::PointPos PosId); -bool IsPointAlreadyOnCurve(int GeoIdCurve, int GeoIdPoint, Sketcher::PointPos PosIdPoint, Sketcher::SketchObject* Obj); +bool IsPointAlreadyOnCurve(int GeoIdCurve, int GeoIdPoint, Sketcher::PointPos PosIdPoint, + Sketcher::SketchObject* Obj); -bool isBsplinePole(const Part::Geometry * geo); +bool isBsplinePole(const Part::Geometry* geo); bool isBsplinePole(const Sketcher::SketchObject* Obj, int GeoId); -/// Checks whether there is a constraint of the given type with a First element geoid and a FirstPos PosId -bool checkConstraint(const std::vector< Sketcher::Constraint * > &vals, Sketcher::ConstraintType type, int geoid, Sketcher::PointPos pos); +/// Checks whether there is a constraint of the given type with a First element geoid and a FirstPos +/// PosId +bool checkConstraint(const std::vector& vals, Sketcher::ConstraintType type, + int geoid, Sketcher::PointPos pos); inline bool isVertex(int GeoId, Sketcher::PointPos PosId) { @@ -117,63 +130,75 @@ inline bool isEdge(int GeoId, Sketcher::PointPos PosId) /* helper functions ======================================================*/ // Return counter-clockwise angle from horizontal out of p1 to p2 in radians. -double GetPointAngle (const Base::Vector2d &p1, const Base::Vector2d &p2); +double GetPointAngle(const Base::Vector2d& p1, const Base::Vector2d& p2); // Set the two points on circles at minimal distance -void GetCirclesMinimalDistance(const Part::GeomCircle *circle1, const Part::GeomCircle *circle2, Base::Vector3d &point1, Base::Vector3d &point2); +void GetCirclesMinimalDistance(const Part::GeomCircle* circle1, const Part::GeomCircle* circle2, + Base::Vector3d& point1, Base::Vector3d& point2); -void ActivateHandler(Gui::Document *doc, DrawSketchHandler *handler); +void ActivateHandler(Gui::Document* doc, DrawSketchHandler* handler); /// Returns if a sketch is in edit mode bool isSketchInEdit(Gui::Document* doc); -/// Returns whether an edit mode command should be activated or not. It is only activated if the sketcher is no special state or a sketchHandler is active. -bool isCommandActive(Gui::Document *doc, bool actsOnSelection = false); +/// Returns whether an edit mode command should be activated or not. It is only activated if the +/// sketcher is no special state or a sketchHandler is active. +bool isCommandActive(Gui::Document* doc, bool actsOnSelection = false); -SketcherGui::ViewProviderSketch* getInactiveHandlerEditModeSketchViewProvider(Gui::Document *doc); +SketcherGui::ViewProviderSketch* getInactiveHandlerEditModeSketchViewProvider(Gui::Document* doc); SketcherGui::ViewProviderSketch* getInactiveHandlerEditModeSketchViewProvider(); void removeRedundantHorizontalVertical(Sketcher::SketchObject* psketch, - std::vector &sug1, - std::vector &sug2); + std::vector& sug1, + std::vector& sug2); -void ConstraintToAttachment(Sketcher::GeoElementId element, Sketcher::GeoElementId attachment, double distance, App::DocumentObject* obj); +void ConstraintToAttachment(Sketcher::GeoElementId element, Sketcher::GeoElementId attachment, + double distance, App::DocumentObject* obj); -//convenience functions for cursor coordinates -bool hideUnits(); -bool showCursorCoords(); -bool useSystemDecimals(); +// convenience functions for cursor coordinates +bool hideUnits(); +bool showCursorCoords(); +bool useSystemDecimals(); std::string lengthToDisplayFormat(double value, int digits); std::string angleToDisplayFormat(double value, int digits); -} +}// namespace SketcherGui /// converts a 2D vector into a 3D vector in the XY plane -inline Base::Vector3d toVector3d(const Base::Vector2d & vector2d) { +inline Base::Vector3d toVector3d(const Base::Vector2d& vector2d) +{ return Base::Vector3d(vector2d.x, vector2d.y, 0.); } -template -auto toPointerVector(const std::vector> & vector) { - std::vector vp (vector.size()); +template +auto toPointerVector(const std::vector>& vector) +{ + std::vector vp(vector.size()); - std::transform(vector.begin(), vector.end(), vp.begin(), [](auto &p) {return p.get();}); + std::transform(vector.begin(), vector.end(), vp.begin(), [](auto& p) { + return p.get(); + }); return vp; } -/** returns the visual layer id (not the one of the GeometryFacade, but the index to PropertyVisualLayerList) from a geometry or GeometryFacade. - * NOTE: If the geometry or geometryfacade does not have a corresponding ViewProviderSketchGeometryExtension, the default layer (layer 0) is returned. +/** returns the visual layer id (not the one of the GeometryFacade, but the index to + * PropertyVisualLayerList) from a geometry or GeometryFacade. NOTE: If the geometry or + * geometryfacade does not have a corresponding ViewProviderSketchGeometryExtension, the default + * layer (layer 0) is returned. * */ -template +template auto getSafeGeomLayerId(T geom) { int layerId = 0; - if(geom->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) { - auto vpext = std::static_pointer_cast( - geom->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock()); + if (geom->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) { + auto vpext = + std::static_pointer_cast( + geom->getExtension( + SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()) + .lock()); layerId = vpext->getVisualLayerId(); } @@ -181,22 +206,23 @@ auto getSafeGeomLayerId(T geom) return layerId; } -/** sets the visual layer id (not the one of the GeometryFacade, but the index to PropertyVisualLayerList) for a geometry or GeometryFacade. - * NOTE: If no ViewProviderSketchGeometryExtension is present, one is created. +/** sets the visual layer id (not the one of the GeometryFacade, but the index to + * PropertyVisualLayerList) for a geometry or GeometryFacade. NOTE: If no + * ViewProviderSketchGeometryExtension is present, one is created. * */ -template +template void setSafeGeomLayerId(T geom, int layerindex) { // create extension if none existing - if(!geom->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) { + if (!geom->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) { geom->setExtension(std::make_unique()); } auto vpext = std::static_pointer_cast( - geom->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock()); + geom->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()) + .lock()); vpext->setVisualLayerId(layerindex); } -#endif // SKETCHERGUI_Recompute_H - +#endif// SKETCHERGUI_Recompute_H diff --git a/src/Mod/Sketcher/Gui/ViewProviderPython.cpp b/src/Mod/Sketcher/Gui/ViewProviderPython.cpp index 543e5ee2f3..da2b2fee76 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderPython.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderPython.cpp @@ -22,7 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -35,12 +35,10 @@ using namespace SketcherGui; PROPERTY_SOURCE(SketcherGui::ViewProviderCustom, SketcherGui::ViewProviderSketch) ViewProviderCustom::ViewProviderCustom() -{ -} +{} ViewProviderCustom::~ViewProviderCustom() -{ -} +{} void ViewProviderCustom::onChanged(const App::Property* prop) { @@ -65,9 +63,11 @@ void ViewProviderCustom::updateData(const App::Property* prop) if (it == propView.end()) { Gui::ViewProvider* view = Gui::ViewProviderBuilder::create(prop->getTypeId()); if (view) { - if (view->getTypeId().isDerivedFrom(Gui::ViewProviderDocumentObject::getClassTypeId())) { + if (view->getTypeId().isDerivedFrom( + Gui::ViewProviderDocumentObject::getClassTypeId())) { static_cast(view)->attach(this->getObject()); - static_cast(view)->setDisplayMode(this->getActiveDisplayMode().c_str()); + static_cast(view)->setDisplayMode( + this->getActiveDisplayMode().c_str()); } propView[prop] = view; view->updateData(prop); @@ -82,7 +82,8 @@ void ViewProviderCustom::updateData(const App::Property* prop) // ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(SketcherGui::ViewProviderPython, SketcherGui::ViewProviderSketch) /// @endcond @@ -96,5 +97,4 @@ PROPERTY_SOURCE_TEMPLATE(SketcherGui::ViewProviderCustomPython, SketcherGui::Vie // explicit template instantiation template class SketcherGuiExport ViewProviderPythonFeatureT; -} - +}// namespace Gui diff --git a/src/Mod/Sketcher/Gui/ViewProviderPython.h b/src/Mod/Sketcher/Gui/ViewProviderPython.h index e00db92a3d..ba67cec9ce 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderPython.h +++ b/src/Mod/Sketcher/Gui/ViewProviderPython.h @@ -27,9 +27,10 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ -class SketcherGuiExport ViewProviderCustom : public ViewProviderSketch +class SketcherGuiExport ViewProviderCustom: public ViewProviderSketch { PROPERTY_HEADER_WITH_OVERRIDE(SketcherGui::ViewProviderCustom); @@ -48,8 +49,7 @@ protected: using ViewProviderPython = Gui::ViewProviderPythonFeatureT; using ViewProviderCustomPython = Gui::ViewProviderPythonFeatureT; -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SketcherGui_VIEWPROVIDERPYTHON_H - +#endif// SketcherGui_VIEWPROVIDERPYTHON_H diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp index 953470d59d..d224179aa4 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp @@ -22,21 +22,21 @@ #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 #endif #include @@ -60,7 +60,6 @@ #include #include -#include "ViewProviderSketch.h" #include "DrawSketchHandler.h" #include "EditDatumDialog.h" #include "EditModeCoinManager.h" @@ -68,11 +67,12 @@ #include "TaskDlgEditSketch.h" #include "TaskSketcherValidation.h" #include "Utils.h" +#include "ViewProviderSketch.h" #include "ViewProviderSketchGeometryExtension.h" #include "Workbench.h" -FC_LOG_LEVEL_INIT("Sketch",true,true) +FC_LOG_LEVEL_INIT("Sketch", true, true) using namespace SketcherGui; using namespace Sketcher; @@ -80,9 +80,11 @@ namespace bp = boost::placeholders; /************** ViewProviderSketch::ParameterObserver *********************/ -template -T getSketcherGeneralParameter(const std::string & string, T defaultvalue) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); +template +T getSketcherGeneralParameter(const std::string& string, T defaultvalue) +{ + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); if constexpr (std::is_same_v) { return static_cast(hGrp->GetUnsigned(string.c_str(), defaultvalue)); @@ -92,108 +94,136 @@ T getSketcherGeneralParameter(const std::string & string, T defaultvalue) { } } -ViewProviderSketch::ParameterObserver::ParameterObserver(ViewProviderSketch &client): Client(client) -{ -} +ViewProviderSketch::ParameterObserver::ParameterObserver(ViewProviderSketch& client) + : Client(client) +{} ViewProviderSketch::ParameterObserver::~ParameterObserver() { unsubscribeToParameters(); } -void ViewProviderSketch::ParameterObserver::updateBoolProperty(const std::string & string, App::Property * property, bool defaultvalue) +void ViewProviderSketch::ParameterObserver::updateBoolProperty(const std::string& string, + App::Property* property, + bool defaultvalue) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - auto boolprop = static_cast(property); + auto boolprop = static_cast(property); boolprop->setValue(hGrp->GetBool(string.c_str(), defaultvalue)); } -void ViewProviderSketch::ParameterObserver::updateColorProperty(const std::string & string, App::Property * property, float r, float g, float b) +void ViewProviderSketch::ParameterObserver::updateColorProperty(const std::string& string, + App::Property* property, float r, + float g, float b) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - auto colorprop = static_cast(property); + auto colorprop = static_cast(property); - colorprop->setValue(r,g,b); + colorprop->setValue(r, g, b); App::Color elementAppColor = colorprop->getValue(); unsigned long color = (unsigned long)(elementAppColor.getPackedValue()); color = hGrp->GetUnsigned(string.c_str(), color); elementAppColor.setPackedValue((uint32_t)color); - colorprop->setValue( elementAppColor); - + colorprop->setValue(elementAppColor); } -void ViewProviderSketch::ParameterObserver::updateGridSize(const std::string & string, App::Property * property) +void ViewProviderSketch::ParameterObserver::updateGridSize(const std::string& string, + App::Property* property) { - (void) property; - (void) string; + (void)property; + (void)string; - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - Client.GridSize.setValue(Base::Quantity::parse(QString::fromLatin1(hGrp->GetGroup("GridSize")->GetASCII("GridSize", "10.0").c_str())).getValue()); + Client.GridSize.setValue( + Base::Quantity::parse( + QString::fromLatin1(hGrp->GetGroup("GridSize")->GetASCII("GridSize", "10.0").c_str())) + .getValue()); } -void ViewProviderSketch::ParameterObserver::updateEscapeKeyBehaviour(const std::string & string, App::Property * property) +void ViewProviderSketch::ParameterObserver::updateEscapeKeyBehaviour(const std::string& string, + App::Property* property) { - (void) property; - (void) string; + (void)property; + (void)string; - ParameterGrp::handle hSketch = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - Client.viewProviderParameters.handleEscapeButton = !hSketch->GetBool("LeaveSketchWithEscape", true); + ParameterGrp::handle hSketch = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + Client.viewProviderParameters.handleEscapeButton = + !hSketch->GetBool("LeaveSketchWithEscape", true); } -void ViewProviderSketch::ParameterObserver::updateAutoRecompute(const std::string & string, App::Property * property) +void ViewProviderSketch::ParameterObserver::updateAutoRecompute(const std::string& string, + App::Property* property) { - (void) property; - (void) string; + (void)property; + (void)string; - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); - Client.viewProviderParameters.autoRecompute = hGrp->GetBool("AutoRecompute",false); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); + Client.viewProviderParameters.autoRecompute = hGrp->GetBool("AutoRecompute", false); } -void ViewProviderSketch::ParameterObserver::updateRecalculateInitialSolutionWhileDragging(const std::string & string, App::Property * property) +void ViewProviderSketch::ParameterObserver::updateRecalculateInitialSolutionWhileDragging( + const std::string& string, App::Property* property) { - (void) property; - (void) string; + (void)property; + (void)string; - ParameterGrp::handle hGrp2 = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp2 = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); - Client.viewProviderParameters.recalculateInitialSolutionWhileDragging = hGrp2->GetBool("RecalculateInitialSolutionWhileDragging",true); + Client.viewProviderParameters.recalculateInitialSolutionWhileDragging = + hGrp2->GetBool("RecalculateInitialSolutionWhileDragging", true); } void ViewProviderSketch::ParameterObserver::subscribeToParameters() { try { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrp->Attach(this); - ParameterGrp::handle hGrp2 = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp2 = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); hGrp2->Attach(this); - ParameterGrp::handle hGrpv = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrpv = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); hGrpv->Attach(this); } - catch(const Base::ValueError & e) { // ensure that if parameter strings are not well-formed, the exception is not propagated - Base::Console().DeveloperError("ViewProviderSketch", "Malformed parameter string: %s\n", e.what()); + catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the + // exception is not propagated + Base::Console().DeveloperError( + "ViewProviderSketch", "Malformed parameter string: %s\n", e.what()); } } void ViewProviderSketch::ParameterObserver::unsubscribeToParameters() { try { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); hGrp->Detach(this); - ParameterGrp::handle hGrp2 = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); + ParameterGrp::handle hGrp2 = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Sketcher"); hGrp2->Detach(this); - ParameterGrp::handle hGrpv = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrpv = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View"); hGrpv->Detach(this); } - catch(const Base::ValueError & e) { // ensure that if parameter strings are not well-formed, the exception is not propagated - Base::Console().DeveloperError("ViewProviderSketch", "Malformed parameter string: %s\n", e.what()); + catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the + // exception is not propagated + Base::Console().DeveloperError( + "ViewProviderSketch", "Malformed parameter string: %s\n", e.what()); } } @@ -206,60 +236,124 @@ void ViewProviderSketch::ParameterObserver::initParameters() parameterMap = { {"HideDependent", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, true);}, &Client.HideDependent }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, true); + }, + &Client.HideDependent}}, {"ShowLinks", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, true);}, &Client.ShowLinks }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, true); + }, + &Client.ShowLinks}}, {"ShowSupport", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, true);}, &Client.ShowSupport }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, true); + }, + &Client.ShowSupport}}, {"RestoreCamera", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, true);}, &Client.RestoreCamera }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, true); + }, + &Client.RestoreCamera}}, {"ForceOrtho", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, false);}, &Client.ForceOrtho }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, false); + }, + &Client.ForceOrtho}}, {"SectionView", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, false);}, &Client.SectionView }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, false); + }, + &Client.SectionView}}, {"AutoConstraints", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, true);}, &Client.Autoconstraints }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, true); + }, + &Client.Autoconstraints}}, {"AvoidRedundantAutoconstraints", - {[this](const std::string & string, App::Property * property){ updateBoolProperty(string, property, true);}, &Client.AvoidRedundant }}, + {[this](const std::string& string, App::Property* property) { + updateBoolProperty(string, property, true); + }, + &Client.AvoidRedundant}}, {"updateEscapeKeyBehaviour", - {[this](const std::string & string, App::Property * property){ updateEscapeKeyBehaviour(string, property);}, nullptr }}, + {[this](const std::string& string, App::Property* property) { + updateEscapeKeyBehaviour(string, property); + }, + nullptr}}, {"AutoRecompute", - {[this](const std::string & string, App::Property * property){ updateAutoRecompute(string, property);}, nullptr }}, + {[this](const std::string& string, App::Property* property) { + updateAutoRecompute(string, property); + }, + nullptr}}, {"RecalculateInitialSolutionWhileDragging", - {[this](const std::string & string, App::Property * property){ updateRecalculateInitialSolutionWhileDragging(string, property);}, nullptr }}, + {[this](const std::string& string, App::Property* property) { + updateRecalculateInitialSolutionWhileDragging(string, property); + }, + nullptr}}, {"GridSizePixelThreshold", - {[this](const std::string & string, [[maybe_unused]] App::Property * property){ auto v = getSketcherGeneralParameter(string, 15); Client.setGridSizePixelThreshold(v); }, nullptr }}, + {[this](const std::string& string, [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, 15); + Client.setGridSizePixelThreshold(v); + }, + nullptr}}, {"GridNumberSubdivision", - {[this](const std::string & string, [[maybe_unused]] App::Property * property){ auto v = getSketcherGeneralParameter(string, 10); Client.setGridNumberSubdivision(v); }, nullptr }}, + {[this](const std::string& string, [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, 10); + Client.setGridNumberSubdivision(v); + }, + nullptr}}, {"GridLinePattern", - {[this](const std::string & string, [[maybe_unused]] App::Property * property){ auto v = getSketcherGeneralParameter(string, 0x0f0f); Client.setGridLinePattern(v); }, nullptr }}, + {[this](const std::string& string, [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, 0x0f0f); + Client.setGridLinePattern(v); + }, + nullptr}}, {"GridDivLinePattern", - {[this](const std::string & string, [[maybe_unused]] App::Property * property){ auto v = getSketcherGeneralParameter(string, 0xffff); Client.setGridDivLinePattern(v); }, nullptr }}, + {[this](const std::string& string, [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, 0xffff); + Client.setGridDivLinePattern(v); + }, + nullptr}}, {"GridLineWidth", - {[this](const std::string & string, [[maybe_unused]] App::Property * property){ auto v = getSketcherGeneralParameter(string, 1); Client.setGridLineWidth(v); }, nullptr }}, + {[this](const std::string& string, [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, 1); + Client.setGridLineWidth(v); + }, + nullptr}}, {"GridDivLineWidth", - {[this](const std::string & string, [[maybe_unused]] App::Property * property){ auto v = getSketcherGeneralParameter(string, 2); Client.setGridDivLineWidth(v); }, nullptr }}, + {[this](const std::string& string, [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, 2); + Client.setGridDivLineWidth(v); + }, + nullptr}}, {"GridLineColor", - {[this, packedDefaultGridColor](const std::string & string, [[maybe_unused]] App::Property * property){ - auto v = getSketcherGeneralParameter(string, packedDefaultGridColor); - auto color = App::Color(v); - Client.setGridLineColor(color);}, nullptr }}, + {[this, packedDefaultGridColor](const std::string& string, + [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, packedDefaultGridColor); + auto color = App::Color(v); + Client.setGridLineColor(color); + }, + nullptr}}, {"GridDivLineColor", - {[this, packedDefaultGridColor](const std::string & string, [[maybe_unused]] App::Property * property){ - auto v = getSketcherGeneralParameter(string, packedDefaultGridColor); - auto color = App::Color(v); - Client.setGridDivLineColor(color);}, nullptr }}, + {[this, packedDefaultGridColor](const std::string& string, + [[maybe_unused]] App::Property* property) { + auto v = getSketcherGeneralParameter(string, packedDefaultGridColor); + auto color = App::Color(v); + Client.setGridDivLineColor(color); + }, + nullptr}}, }; - for( auto & val : parameterMap){ - auto string = val.first; - auto update = std::get<0>(val.second); - auto property = std::get<1>(val.second); + for (auto& val : parameterMap) { + auto string = val.first; + auto update = std::get<0>(val.second); + auto property = std::get<1>(val.second); update(string, property); } - // unsubscribed parameters which update a property on just once upon construction (and before restore if properties are being restored from a file) + // unsubscribed parameters which update a property on just once upon construction (and before + // restore if properties are being restored from a file) updateColorProperty("SketchEdgeColor", &Client.LineColor, 1.0f, 1.0f, 1.0f); updateColorProperty("SketchVertexColor", &Client.PointColor, 1.0f, 1.0f, 1.0f); updateBoolProperty("ShowGrid", &Client.ShowGrid, false); @@ -267,26 +361,26 @@ void ViewProviderSketch::ParameterObserver::initParameters() updateGridSize("GridSize", &Client.GridSize); } -void ViewProviderSketch::ParameterObserver::OnChange(Base::Subject &rCaller, const char * sReason) +void ViewProviderSketch::ParameterObserver::OnChange(Base::Subject& rCaller, + const char* sReason) { - (void) rCaller; + (void)rCaller; auto key = parameterMap.find(sReason); - if( key != parameterMap.end()) { - auto string = key->first; - auto update = std::get<0>(key->second); - auto property = std::get<1>(key->second); + if (key != parameterMap.end()) { + auto string = key->first; + auto update = std::get<0>(key->second); + auto property = std::get<1>(key->second); update(string, property); } - } /*************************** ViewProviderSketch **************************/ // Struct for holding previous click information SbTime ViewProviderSketch::DoubleClick::prvClickTime; -SbVec2s ViewProviderSketch::DoubleClick::prvClickPos; //used by double-click-detector +SbVec2s ViewProviderSketch::DoubleClick::prvClickPos;// used by double-click-detector SbVec2s ViewProviderSketch::DoubleClick::prvCursorPos; SbVec2s ViewProviderSketch::DoubleClick::newCursorPos; @@ -299,65 +393,116 @@ PROPERTY_SOURCE_WITH_EXTENSIONS(SketcherGui::ViewProviderSketch, PartGui::ViewPr ViewProviderSketch::ViewProviderSketch() - : SelectionObserver(false), - Mode(STATUS_NONE), - listener(nullptr), - editCoinManager(nullptr), - snapManager(nullptr), - pObserver(std::make_unique(*this)), - sketchHandler(nullptr), - viewOrientationFactor(1) + : SelectionObserver(false) + , Mode(STATUS_NONE) + , listener(nullptr) + , editCoinManager(nullptr) + , snapManager(nullptr) + , pObserver(std::make_unique(*this)) + , sketchHandler(nullptr) + , viewOrientationFactor(1) { PartGui::ViewProviderAttachExtension::initExtension(this); PartGui::ViewProviderGridExtension::initExtension(this); - ADD_PROPERTY_TYPE(Autoconstraints,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Create auto constraints"); - ADD_PROPERTY_TYPE(AvoidRedundant,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Avoid redundant autoconstraint"); - ADD_PROPERTY_TYPE(TempoVis,(Py::None()),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"Object that handles hiding and showing other objects when entering/leaving sketch."); - ADD_PROPERTY_TYPE(HideDependent,(true),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"If true, all objects that depend on the sketch are hidden when opening editing."); - ADD_PROPERTY_TYPE(ShowLinks,(true),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"If true, all objects used in links to external geometry are shown when opening sketch."); - ADD_PROPERTY_TYPE(ShowSupport,(true),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"If true, all objects this sketch is attached to are shown when opening sketch."); - ADD_PROPERTY_TYPE(RestoreCamera,(true),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"If true, camera position before entering sketch is remembered, and restored after closing it."); - ADD_PROPERTY_TYPE(ForceOrtho,(false),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"If true, camera type will be forced to orthographic view when entering editing mode."); - ADD_PROPERTY_TYPE(SectionView,(false),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"If true, only objects (or part of) located behind the sketch plane are visible."); - ADD_PROPERTY_TYPE(EditingWorkbench,("SketcherWorkbench"),"Visibility automation",(App::PropertyType)(App::Prop_ReadOnly),"Name of the workbench to activate when editing this sketch."); - ADD_PROPERTY_TYPE(VisualLayerList, (VisualLayer()), "Layers", (App::PropertyType)(App::Prop_ReadOnly), "Information about the Visual Representation of layers"); + ADD_PROPERTY_TYPE(Autoconstraints, + (true), + "Auto Constraints", + (App::PropertyType)(App::Prop_None), + "Create auto constraints"); + ADD_PROPERTY_TYPE(AvoidRedundant, + (true), + "Auto Constraints", + (App::PropertyType)(App::Prop_None), + "Avoid redundant autoconstraint"); + ADD_PROPERTY_TYPE( + TempoVis, + (Py::None()), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "Object that handles hiding and showing other objects when entering/leaving sketch."); + ADD_PROPERTY_TYPE( + HideDependent, + (true), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "If true, all objects that depend on the sketch are hidden when opening editing."); + ADD_PROPERTY_TYPE( + ShowLinks, + (true), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "If true, all objects used in links to external geometry are shown when opening sketch."); + ADD_PROPERTY_TYPE( + ShowSupport, + (true), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "If true, all objects this sketch is attached to are shown when opening sketch."); + ADD_PROPERTY_TYPE(RestoreCamera, + (true), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "If true, camera position before entering sketch is remembered, and restored " + "after closing it."); + ADD_PROPERTY_TYPE( + ForceOrtho, + (false), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "If true, camera type will be forced to orthographic view when entering editing mode."); + ADD_PROPERTY_TYPE( + SectionView, + (false), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "If true, only objects (or part of) located behind the sketch plane are visible."); + ADD_PROPERTY_TYPE(EditingWorkbench, + ("SketcherWorkbench"), + "Visibility automation", + (App::PropertyType)(App::Prop_ReadOnly), + "Name of the workbench to activate when editing this sketch."); + ADD_PROPERTY_TYPE(VisualLayerList, + (VisualLayer()), + "Layers", + (App::PropertyType)(App::Prop_ReadOnly), + "Information about the Visual Representation of layers"); // TODO: This is part of a naive minimal implementation to substitute rendering order // Three equally visual layers to enable/disable layer. std::vector layers; - layers.emplace_back(); // Normal layer - layers.emplace_back(0x7E7E); // Discontinuous line layer - layers.emplace_back(0xFFFF,3,false); // Hidden layer + layers.emplace_back(); // Normal layer + layers.emplace_back(0x7E7E); // Discontinuous line layer + layers.emplace_back(0xFFFF, 3, false);// Hidden layer VisualLayerList.setValues(std::move(layers)); // Default values that will be overridden by preferences (if existing) PointSize.setValue(4); - // visibility automation and other parameters: update parameter and property defaults to follow preferences + // visibility automation and other parameters: update parameter and property defaults to follow + // preferences pObserver->initParameters(); pObserver->subscribeToParameters(); sPixmap = "Sketcher_Sketch"; - //rubberband selection + // rubberband selection rubberband = std::make_unique(); cameraSensor.setFunction(&ViewProviderSketch::camSensCB); } ViewProviderSketch::~ViewProviderSketch() -{ -} +{} void ViewProviderSketch::slotUndoDocument(const Gui::Document& /*doc*/) { // Note 1: this slot is only operative during edit mode (see signal connection/disconnection) // Note 2: ViewProviderSketch::UpdateData does not generate updates during undo/redo // transactions as mid-transaction data may not be in a valid state (e.g. constraints - // may reference invalid geometry). However undo/redo notify SketchObject after the undo/redo - // and before this slot is called. + // may reference invalid geometry). However undo/redo notify SketchObject after the + // undo/redo and before this slot is called. // Note 3: Note that recomputes are no longer inhibited during the call to this slot. forceUpdateData(); } @@ -367,22 +512,23 @@ void ViewProviderSketch::slotRedoDocument(const Gui::Document& /*doc*/) // Note 1: this slot is only operative during edit mode (see signal connection/disconnection) // Note 2: ViewProviderSketch::UpdateData does not generate updates during undo/redo // transactions as mid-transaction data may not be in a valid state (e.g. constraints - // may reference invalid geometry). However undo/redo notify SketchObject after the undo/redo - // and before this slot is called. + // may reference invalid geometry). However undo/redo notify SketchObject after the + // undo/redo and before this slot is called. // Note 3: Note that recomputes are no longer inhibited during the call to this slot. forceUpdateData(); } void ViewProviderSketch::forceUpdateData() { - if(!getSketchObject()->noRecomputes) { // the sketch was already solved in SketchObject in onUndoRedoFinished + if (!getSketchObject() + ->noRecomputes) {// the sketch was already solved in SketchObject in onUndoRedoFinished Gui::Command::updateActive(); } } /***************************** handler management ************************************/ -void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler) +void ViewProviderSketch::activateHandler(DrawSketchHandler* newHandler) { assert(editCoinManager); assert(!sketchHandler); @@ -394,14 +540,14 @@ void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler) // make sure receiver has focus so immediately pressing Escape will be handled by // ViewProviderSketch::keyPressed() and dismiss the active handler, and not the entire // sketcher editor - Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); + Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView(); mdi->setFocus(); } void ViewProviderSketch::deactivateHandler() { assert(isInEditMode()); - if(sketchHandler){ + if (sketchHandler) { sketchHandler->deactivate(); sketchHandler = nullptr; } @@ -415,9 +561,9 @@ void ViewProviderSketch::purgeHandler() Gui::Selection().clearSelection(); // ensure that we are in sketch only selection mode - Gui::MDIView *mdi = Gui::Application::Instance->editDocument()->getActiveView(); - Gui::View3DInventorViewer *viewer; - viewer = static_cast(mdi)->getViewer(); + Gui::MDIView* mdi = Gui::Application::Instance->editDocument()->getActiveView(); + Gui::View3DInventorViewer* viewer; + viewer = static_cast(mdi)->getViewer(); viewer->setSelectionEnabled(false); } @@ -427,12 +573,13 @@ void ViewProviderSketch::setAxisPickStyle(bool on) editCoinManager->setAxisPickStyle(on); } -void ViewProviderSketch::moveCursorToSketchPoint(Base::Vector2d point) { +void ViewProviderSketch::moveCursorToSketchPoint(Base::Vector2d point) +{ - SbVec3f sbpoint(point.x,point.y,0.f); + SbVec3f sbpoint(point.x, point.y, 0.f); - Gui::MDIView *mdi = this->getActiveView(); - Gui::View3DInventor *view = qobject_cast(mdi); + Gui::MDIView* mdi = this->getActiveView(); + Gui::View3DInventor* view = qobject_cast(mdi); if (!view) return; @@ -441,34 +588,32 @@ void ViewProviderSketch::moveCursorToSketchPoint(Base::Vector2d point) { SbVec2s screencoords = viewer->getPointOnViewport(sbpoint); - short x,y; screencoords.getValue(x,y); + short x, y; + screencoords.getValue(x, y); - short height = viewer->getGLWidget()->height(); // Coin3D origin bottom left, QT origin top left + short height = viewer->getGLWidget()->height();// Coin3D origin bottom left, QT origin top left - QPoint newPos = viewer->getGLWidget()->mapToGlobal(QPoint(x,height-y)); + QPoint newPos = viewer->getGLWidget()->mapToGlobal(QPoint(x, height - y)); // QScreen *screen = view->windowHandle()->screen(); - //QScreen *screen = QGuiApplication::primaryScreen(); + // QScreen *screen = QGuiApplication::primaryScreen(); - //QCursor::setPos(screen, newPos); + // QCursor::setPos(screen, newPos); QCursor::setPos(newPos); } void ViewProviderSketch::preselectAtPoint(Base::Vector2d point) { - if (Mode != STATUS_SELECT_Point && - Mode != STATUS_SELECT_Edge && - Mode != STATUS_SELECT_Constraint && - Mode != STATUS_SKETCH_DragPoint && - Mode != STATUS_SKETCH_DragCurve && - Mode != STATUS_SKETCH_DragConstraint && - Mode != STATUS_SKETCH_UseRubberBand) { + if (Mode != STATUS_SELECT_Point && Mode != STATUS_SELECT_Edge + && Mode != STATUS_SELECT_Constraint && Mode != STATUS_SKETCH_DragPoint + && Mode != STATUS_SKETCH_DragCurve && Mode != STATUS_SKETCH_DragConstraint + && Mode != STATUS_SKETCH_UseRubberBand) { - SbVec3f sbpoint(point.x,point.y,0.f); + SbVec3f sbpoint(point.x, point.y, 0.f); - Gui::MDIView *mdi = this->getActiveView(); - Gui::View3DInventor *view = qobject_cast(mdi); + Gui::MDIView* mdi = this->getActiveView(); + Gui::View3DInventor* view = qobject_cast(mdi); if (!view) return; @@ -487,10 +632,8 @@ void ViewProviderSketch::preselectAtPoint(Base::Vector2d point) bool ViewProviderSketch::keyPressed(bool pressed, int key) { - switch (key) - { - case SoKeyboardEvent::ESCAPE: - { + switch (key) { + case SoKeyboardEvent::ESCAPE: { // make the handler quit but not the edit mode if (isInEditMode() && sketchHandler) { if (!pressed) @@ -505,7 +648,8 @@ bool ViewProviderSketch::keyPressed(bool pressed, int key) } if (isInEditMode() && drag.isDragCurveValid()) { if (!pressed) { - getSketchObject()->movePoint(drag.DragCurve, Sketcher::PointPos::none, Base::Vector3d(0,0,0), true); + getSketchObject()->movePoint( + drag.DragCurve, Sketcher::PointPos::none, Base::Vector3d(0, 0, 0), true); drag.DragCurve = Drag::InvalidCurve; resetPositionText(); Mode = STATUS_NONE; @@ -517,7 +661,7 @@ bool ViewProviderSketch::keyPressed(bool pressed, int key) int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(drag.DragPoint, GeoId, PosId); - getSketchObject()->movePoint(GeoId, PosId, Base::Vector3d(0,0,0), true); + getSketchObject()->movePoint(GeoId, PosId, Base::Vector3d(0, 0, 0), true); drag.DragPoint = Drag::InvalidPoint; resetPositionText(); Mode = STATUS_NONE; @@ -530,23 +674,21 @@ bool ViewProviderSketch::keyPressed(bool pressed, int key) // then ignore this one. if (!pressed && !viewProviderParameters.buttonPress) return true; - viewProviderParameters.buttonPress = pressed; + viewProviderParameters.buttonPress = pressed; // More control over Sketcher edit mode Esc key behavior // https://forum.freecad.org/viewtopic.php?f=3&t=42207 return viewProviderParameters.handleEscapeButton; } return false; - } - break; - default: - { + } break; + default: { if (isInEditMode() && sketchHandler) - sketchHandler->registerPressedKey(pressed,key); + sketchHandler->registerPressedKey(pressed, key); } } - return true; // handle all other key events + return true;// handle all other key events } void ViewProviderSketch::setAngleSnapping(bool enable, Base::Vector2d referencePoint) @@ -555,12 +697,14 @@ void ViewProviderSketch::setAngleSnapping(bool enable, Base::Vector2d referenceP snapManager->setAngleSnapping(enable, referencePoint); } -void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, const Gui::View3DInventorViewer *viewer, SbLine& line) const +void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, + const Gui::View3DInventorViewer* viewer, + SbLine& line) const { const SbViewportRegion& vp = viewer->getSoRenderManager()->getViewportRegion(); short x, y; - pnt.getValue(x,y); + pnt.getValue(x, y); SbVec2f VPsize = vp.getViewportSize(); float dX, dY; VPsize.getValue(dX, dY); @@ -581,12 +725,13 @@ void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, const Gui::View3D SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; - SbViewVolume vol = pCam->getViewVolume(); + SbViewVolume vol = pCam->getViewVolume(); vol.projectPointToLine(SbVec2f(pX, pY), line); } -Base::Placement ViewProviderSketch::getEditingPlacement() const { +Base::Placement ViewProviderSketch::getEditingPlacement() const +{ auto doc = Gui::Application::Instance->editDocument(); if (!doc || doc->getInEdit() != this) return getSketchObject()->globalPlacement(); @@ -595,7 +740,8 @@ Base::Placement ViewProviderSketch::getEditingPlacement() const { return Base::Placement(doc->getEditingTransform()); } -void ViewProviderSketch::getCoordsOnSketchPlane(const SbVec3f &point, const SbVec3f &normal, double &u, double &v) const +void ViewProviderSketch::getCoordsOnSketchPlane(const SbVec3f& point, const SbVec3f& normal, + double& u, double& v) const { // Plane form Base::Vector3d R0(0, 0, 0), RN(0, 0, 1), RX(1, 0, 0), RY(0, 1, 0); @@ -611,7 +757,7 @@ void ViewProviderSketch::getCoordsOnSketchPlane(const SbVec3f &point, const SbVe // line Base::Vector3d R1(point[0], point[1], point[2]), RA(normal[0], normal[1], normal[2]); - if (fabs(RN*RA) < FLT_EPSILON) + if (fabs(RN * RA) < FLT_EPSILON) throw Base::ZeroDivisionError("View direction is parallel to sketch plane"); // intersection point on plane Base::Vector3d S = R1 + ((RN * (R0 - R1)) / (RN * RA)) * RA; @@ -623,8 +769,8 @@ void ViewProviderSketch::getCoordsOnSketchPlane(const SbVec3f &point, const SbVe v = S.y; } -bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVec2s &cursorPos, - const Gui::View3DInventorViewer *viewer) +bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVec2s& cursorPos, + const Gui::View3DInventorViewer* viewer) { assert(isInEditMode()); @@ -640,17 +786,17 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe // Radius maximum to allow double click event const int dblClickRadius = 5; - double x,y; + double x, y; SbVec3f pos = point; if (pp) { - const SoDetail *detail = pp->getDetail(); + const SoDetail* detail = pp->getDetail(); if (detail && detail->getTypeId() == SoPointDetail::getClassTypeId()) { pos = pp->getPoint(); } } try { - getCoordsOnSketchPlane(pos,normal,x,y); + getCoordsOnSketchPlane(pos, normal, x, y); snapManager->snap(x, y); } catch (const Base::ZeroDivisionError&) { @@ -662,41 +808,48 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe if (pressed) { // Do things depending on the mode of the user interaction switch (Mode) { - case STATUS_NONE:{ - bool done=false; + case STATUS_NONE: { + bool done = false; if (preselection.isPreselectPointValid()) { - //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Point; done = true; - } else if (preselection.isPreselectCurveValid()) { - //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + } + else if (preselection.isPreselectCurveValid()) { + // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Edge; done = true; - } else if (preselection.isCrossPreselected()) { - //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + } + else if (preselection.isCrossPreselected()) { + // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Cross; done = true; - } else if (!preselection.PreselectConstraintSet.empty()) { - //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + } + else if (!preselection.PreselectConstraintSet.empty()) { + // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Constraint; done = true; } // Double click events variables - float dci = (float) QApplication::doubleClickInterval()/1000.0f; + float dci = (float)QApplication::doubleClickInterval() / 1000.0f; - if (done && - SbVec2f(cursorPos - DoubleClick::prvClickPos).length() < dblClickRadius && - (SbTime::getTimeOfDay() - DoubleClick::prvClickTime).getValue() < dci) { + if (done + && SbVec2f(cursorPos - DoubleClick::prvClickPos).length() < dblClickRadius + && (SbTime::getTimeOfDay() - DoubleClick::prvClickTime).getValue() < dci) { // Double Click Event Occurred editDoubleClicked(); // Reset Double Click Static Variables DoubleClick::prvClickTime = SbTime(); - DoubleClick::prvClickPos = SbVec2s(-16000,-16000); //certainly far away from any clickable place, to avoid re-trigger of double-click if next click happens fast. + DoubleClick::prvClickPos = SbVec2s( + -16000, + -16000);// certainly far away from any clickable place, to avoid + // re-trigger of double-click if next click happens fast. Mode = STATUS_NONE; - } else { + } + else { DoubleClick::prvClickTime = SbTime::getTimeOfDay(); DoubleClick::prvClickPos = cursorPos; DoubleClick::prvCursorPos = cursorPos; @@ -708,24 +861,27 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return done; } case STATUS_SKETCH_UseHandler: - return sketchHandler->pressButton(Base::Vector2d(x,y)); + return sketchHandler->pressButton(Base::Vector2d(x, y)); default: return false; } - } else { // Button 1 released + } + else {// Button 1 released // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_SELECT_Point: if (pp) { - //Base::Console().Log("Select Point:%d\n",this->DragPoint); - // Do selection + // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Do selection std::stringstream ss; ss << "Vertex" << preselection.getPreselectionVertexIndex(); if (isSelected(ss.str())) { - rmvSelection(ss.str()); - } else { - addSelection2(ss.str(), pp->getPoint()[0], pp->getPoint()[1],pp->getPoint()[2]); + rmvSelection(ss.str()); + } + else { + addSelection2( + ss.str(), pp->getPoint()[0], pp->getPoint()[1], pp->getPoint()[2]); drag.resetIds(); } } @@ -733,19 +889,21 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Edge: if (pp) { - //Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; if (preselection.isEdge()) ss << "Edge" << preselection.getPreselectionEdgeIndex(); - else // external geometry + else// external geometry ss << "ExternalEdge" << preselection.getPreselectionExternalEdgeIndex(); // If edge already selected move from selection - if (isSelected(ss.str()) ) { + if (isSelected(ss.str())) { rmvSelection(ss.str()); - } else { + } + else { // Add edge to the selection - addSelection2(ss.str(), pp->getPoint()[0], pp->getPoint()[1], pp->getPoint()[2]); + addSelection2( + ss.str(), pp->getPoint()[0], pp->getPoint()[1], pp->getPoint()[2]); drag.resetIds(); } } @@ -753,21 +911,30 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Cross: if (pp) { - //Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; - switch(preselection.PreselectCross){ - case Preselection::Axes::RootPoint: ss << "RootPoint" ; break; - case Preselection::Axes::HorizontalAxis: ss << "H_Axis" ; break; - case Preselection::Axes::VerticalAxis: ss << "V_Axis" ; break; - default: break; + switch (preselection.PreselectCross) { + case Preselection::Axes::RootPoint: + ss << "RootPoint"; + break; + case Preselection::Axes::HorizontalAxis: + ss << "H_Axis"; + break; + case Preselection::Axes::VerticalAxis: + ss << "V_Axis"; + break; + default: + break; } // If cross already selected move from selection - if (isSelected(ss.str()) ) { + if (isSelected(ss.str())) { rmvSelection(ss.str()); - } else { + } + else { // Add cross to the selection - addSelection2(ss.str(), pp->getPoint()[0], pp->getPoint()[1], pp->getPoint()[2]); + addSelection2( + ss.str(), pp->getPoint()[0], pp->getPoint()[1], pp->getPoint()[2]); drag.resetIds(); } } @@ -776,16 +943,20 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe case STATUS_SELECT_Constraint: if (pp) { auto sels = preselection.PreselectConstraintSet; - for(int id : sels) { + for (int id : sels) { std::stringstream ss; ss << Sketcher::PropertyConstraintList::getConstraintName(id); // If the constraint already selected remove - if (isSelected(ss.str()) ) { + if (isSelected(ss.str())) { rmvSelection(ss.str()); - } else { + } + else { // Add constraint to current selection - addSelection2(ss.str(), pp->getPoint()[0], pp->getPoint()[1], pp->getPoint()[2]); + addSelection2(ss.str(), + pp->getPoint()[0], + pp->getPoint()[1], + pp->getPoint()[2]); drag.resetIds(); } } @@ -799,11 +970,17 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe getSketchObject()->getGeoVertexIndex(drag.DragPoint, GeoId, PosId); - if (GeoId != Sketcher::GeoEnum::GeoUndef && PosId != Sketcher::PointPos::none) { + if (GeoId != Sketcher::GeoEnum::GeoUndef + && PosId != Sketcher::PointPos::none) { getDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Drag Point")); try { - Gui::cmdAppObjectArgs(getObject(), "movePoint(%d,%d,App.Vector(%f,%f,0),%d)" - ,GeoId, static_cast(PosId), x-drag.xInit, y-drag.yInit, 0); + Gui::cmdAppObjectArgs(getObject(), + "movePoint(%d,%d,App.Vector(%f,%f,0),%d)", + GeoId, + static_cast(PosId), + x - drag.xInit, + y - drag.yInit, + 0); getDocument()->commitCommand(); @@ -811,50 +988,57 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe } catch (const Base::Exception& e) { getDocument()->abortCommand(); - Base::Console().DeveloperError("ViewProviderSketch", "Drag point: %s\n", e.what()); + Base::Console().DeveloperError( + "ViewProviderSketch", "Drag point: %s\n", e.what()); } } setPreselectPoint(drag.DragPoint); drag.DragPoint = Drag::InvalidPoint; - //updateColor(); + // updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragCurve: if (drag.isDragCurveValid()) { - const Part::Geometry *geo = getSketchObject()->getGeometry(drag.DragCurve); - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() || - geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomCircle::getClassTypeId() || - geo->getTypeId() == Part::GeomEllipse::getClassTypeId()|| - geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()|| - geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()|| - geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()|| - geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::Geometry* geo = getSketchObject()->getGeometry(drag.DragCurve); + if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomCircle::getClassTypeId() + || geo->getTypeId() == Part::GeomEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId() + || geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId() + || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { getDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Drag Curve")); auto geo = getSketchObject()->getGeometry(drag.DragCurve); auto gf = GeometryFacade::getFacade(geo); - Base::Vector3d vec(x-drag.xInit,y-drag.yInit,0); + Base::Vector3d vec(x - drag.xInit, y - drag.yInit, 0); // BSpline weights have a radius corresponding to the weight value // However, in order for them proportional to the B-Spline size, // the scenograph has a size scalefactor times the weight // This code normalizes the information sent to the solver. - if(gf->getInternalType() == InternalType::BSplineControlPoint) { - auto circle = static_cast(geo); + if (gf->getInternalType() == InternalType::BSplineControlPoint) { + auto circle = static_cast(geo); Base::Vector3d center = circle->getCenter(); Base::Vector3d dir = vec - center; double scalefactor = 1.0; - if(circle->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) - { - auto vpext = std::static_pointer_cast( - circle->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock()); + if (circle->hasExtension( + SketcherGui::ViewProviderSketchGeometryExtension:: + getClassTypeId())) { + auto vpext = std::static_pointer_cast< + const SketcherGui::ViewProviderSketchGeometryExtension>( + circle + ->getExtension( + SketcherGui::ViewProviderSketchGeometryExtension:: + getClassTypeId()) + .lock()); scalefactor = vpext->getRepresentationFactor(); } @@ -863,8 +1047,13 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe } try { - Gui::cmdAppObjectArgs(getObject(), "movePoint(%d,%d,App.Vector(%f,%f,0),%d)" - ,drag.DragCurve, static_cast(Sketcher::PointPos::none), vec.x, vec.y, drag.relative ? 1 : 0); + Gui::cmdAppObjectArgs(getObject(), + "movePoint(%d,%d,App.Vector(%f,%f,0),%d)", + drag.DragCurve, + static_cast(Sketcher::PointPos::none), + vec.x, + vec.y, + drag.relative ? 1 : 0); getDocument()->commitCommand(); @@ -872,12 +1061,13 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe } catch (const Base::Exception& e) { getDocument()->abortCommand(); - Base::Console().DeveloperError("ViewProviderSketch", "Drag curve: %s\n", e.what()); + Base::Console().DeveloperError( + "ViewProviderSketch", "Drag curve: %s\n", e.what()); } } preselection.PreselectCurve = drag.DragCurve; drag.DragCurve = Drag::InvalidCurve; - //updateColor(); + // updateColor(); } resetPositionText(); Mode = STATUS_NONE; @@ -886,9 +1076,9 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe if (!drag.DragConstraintSet.empty()) { getDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Drag Constraint")); auto idset = drag.DragConstraintSet; - for(int id : idset) { + for (int id : idset) { moveConstraint(id, Base::Vector2d(x, y)); - //updateColor(); + // updateColor(); } preselection.PreselectConstraintSet = drag.DragConstraintSet; drag.DragConstraintSet.clear(); @@ -896,7 +1086,8 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe } Mode = STATUS_NONE; return true; - case STATUS_SKETCH_StartRubberBand: // a single click happened, so clear selection unless user hold control. + case STATUS_SKETCH_StartRubberBand:// a single click happened, so clear selection + // unless user hold control. if (!(QApplication::keyboardModifiers() & Qt::ControlModifier)) { Gui::Selection().clearSelection(); } @@ -907,12 +1098,12 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe rubberband->setWorking(false); // a redraw is required in order to clear the rubberband - draw(true,false); + draw(true, false); const_cast(viewer)->redraw(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_UseHandler: { - return sketchHandler->releaseButton(Base::Vector2d(x,y)); + return sketchHandler->releaseButton(Base::Vector2d(x, y)); } case STATUS_NONE: default: @@ -928,101 +1119,104 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe // make the handler quit sketchHandler->quit(); return true; - case STATUS_NONE: - { - // A right click shouldn't change the Edit Mode - if (preselection.isPreselectPointValid()) { - return true; - } else if (preselection.isPreselectCurveValid()) { - return true; - } else if (!preselection.PreselectConstraintSet.empty()) { - return true; - } else { - Gui::MenuItem geom; - geom.setCommand("Sketcher geoms"); - geom << "Sketcher_CreatePoint" - << "Sketcher_CreateArc" - << "Sketcher_Create3PointArc" - << "Sketcher_CreateCircle" - << "Sketcher_Create3PointCircle" - << "Sketcher_CreateLine" - << "Sketcher_CreatePolyline" - << "Sketcher_CreateRectangle" - << "Sketcher_CreateHexagon" - << "Sketcher_CreateFillet" - << "Sketcher_CreatePointFillet" - << "Sketcher_Trimming" - << "Sketcher_Extend" - << "Sketcher_External" - << "Sketcher_ToggleConstruction" - /*<< "Sketcher_CreateText"*/ - /*<< "Sketcher_CreateDraftLine"*/ - << "Separator"; - - Gui::Application::Instance->setupContextMenu("View", &geom); - //Create the Context Menu using the Main View Qt Widget - QMenu contextMenu(viewer->getGLWidget()); - Gui::MenuManager::getInstance()->setupContextMenu(&geom, contextMenu); - contextMenu.exec(QCursor::pos()); - - return true; - } + case STATUS_NONE: { + // A right click shouldn't change the Edit Mode + if (preselection.isPreselectPointValid()) { + return true; } - case STATUS_SELECT_Point: - break; - case STATUS_SELECT_Edge: - { + else if (preselection.isPreselectCurveValid()) { + return true; + } + else if (!preselection.PreselectConstraintSet.empty()) { + return true; + } + else { Gui::MenuItem geom; - geom.setCommand("Sketcher constraints"); - geom << "Sketcher_ConstrainVertical" - << "Sketcher_ConstrainHorizontal"; - - // Gets a selection vector - std::vector selection = Gui::Selection().getSelectionEx(); - - bool rightClickOnSelectedLine = false; - - /* - * Add Multiple Line Constraints to the menu - */ - // only one sketch with its subelements are allowed to be selected - if (selection.size() == 1) { - // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); - - // Two Objects are selected - if (SubNames.size() == 2) { - // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin(); - it!=SubNames.end();++it) { - - // If the object selected is of type edge - if (it->size() > 4 && it->substr(0,4) == "Edge") { - // Get the index of the object selected - int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; - if (preselection.PreselectCurve == GeoId) - rightClickOnSelectedLine = true; - } else { - // The selection is not exclusively edges - rightClickOnSelectedLine = false; - } - } // End of Iteration - } - } - - if (rightClickOnSelectedLine) { - geom << "Sketcher_ConstrainParallel" - << "Sketcher_ConstrainPerpendicular"; - } + geom.setCommand("Sketcher geoms"); + geom << "Sketcher_CreatePoint" + << "Sketcher_CreateArc" + << "Sketcher_Create3PointArc" + << "Sketcher_CreateCircle" + << "Sketcher_Create3PointCircle" + << "Sketcher_CreateLine" + << "Sketcher_CreatePolyline" + << "Sketcher_CreateRectangle" + << "Sketcher_CreateHexagon" + << "Sketcher_CreateFillet" + << "Sketcher_CreatePointFillet" + << "Sketcher_Trimming" + << "Sketcher_Extend" + << "Sketcher_External" + << "Sketcher_ToggleConstruction" + /*<< "Sketcher_CreateText"*/ + /*<< "Sketcher_CreateDraftLine"*/ + << "Separator"; Gui::Application::Instance->setupContextMenu("View", &geom); - //Create the Context Menu using the Main View Qt Widget + // Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(&geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } + } + case STATUS_SELECT_Point: + break; + case STATUS_SELECT_Edge: { + Gui::MenuItem geom; + geom.setCommand("Sketcher constraints"); + geom << "Sketcher_ConstrainVertical" + << "Sketcher_ConstrainHorizontal"; + + // Gets a selection vector + std::vector selection = Gui::Selection().getSelectionEx(); + + bool rightClickOnSelectedLine = false; + + /* + * Add Multiple Line Constraints to the menu + */ + // only one sketch with its subelements are allowed to be selected + if (selection.size() == 1) { + // get the needed lists and objects + const std::vector& SubNames = selection[0].getSubNames(); + + // Two Objects are selected + if (SubNames.size() == 2) { + // go through the selected subelements + for (std::vector::const_iterator it = SubNames.begin(); + it != SubNames.end(); + ++it) { + + // If the object selected is of type edge + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + // Get the index of the object selected + int GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; + if (preselection.PreselectCurve == GeoId) + rightClickOnSelectedLine = true; + } + else { + // The selection is not exclusively edges + rightClickOnSelectedLine = false; + } + }// End of Iteration + } + } + + if (rightClickOnSelectedLine) { + geom << "Sketcher_ConstrainParallel" + << "Sketcher_ConstrainPerpendicular"; + } + + Gui::Application::Instance->setupContextMenu("View", &geom); + // Create the Context Menu using the Main View Qt Widget + QMenu contextMenu(viewer->getGLWidget()); + Gui::MenuManager::getInstance()->setupContextMenu(&geom, contextMenu); + contextMenu.exec(QCursor::pos()); + + return true; + } case STATUS_SELECT_Cross: case STATUS_SELECT_Constraint: case STATUS_SKETCH_DragPoint: @@ -1038,7 +1232,8 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return false; } -bool ViewProviderSketch::mouseWheelEvent(int delta, const SbVec2s &cursorPos, const Gui::View3DInventorViewer* viewer) +bool ViewProviderSketch::mouseWheelEvent(int delta, const SbVec2s& cursorPos, + const Gui::View3DInventorViewer* viewer) { assert(isInEditMode()); @@ -1054,26 +1249,29 @@ bool ViewProviderSketch::mouseWheelEvent(int delta, const SbVec2s &cursorPos, co void ViewProviderSketch::editDoubleClicked() { if (preselection.isPreselectPointValid()) { - Base::Console().Log("double click point:%d\n",preselection.PreselectPoint); + Base::Console().Log("double click point:%d\n", preselection.PreselectPoint); } else if (preselection.isPreselectCurveValid()) { - Base::Console().Log("double click edge:%d\n",preselection.PreselectCurve); + Base::Console().Log("double click edge:%d\n", preselection.PreselectCurve); } else if (preselection.isCrossPreselected()) { - Base::Console().Log("double click cross:%d\n",static_cast(preselection.PreselectCross)); + Base::Console().Log("double click cross:%d\n", + static_cast(preselection.PreselectCross)); } else if (!preselection.PreselectConstraintSet.empty()) { // Find the constraint - const std::vector &constrlist = getSketchObject()->Constraints.getValues(); + const std::vector& constrlist = + getSketchObject()->Constraints.getValues(); auto sels = preselection.PreselectConstraintSet; - for(int id : sels) { + for (int id : sels) { - Constraint *Constr = constrlist[id]; + Constraint* Constr = constrlist[id]; // if its the right constraint if (Constr->isDimensional()) { - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Modify sketch constraints")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Modify sketch constraints")); EditDatumDialog editDatumDialog(this, id); editDatumDialog.exec(); } @@ -1081,7 +1279,7 @@ void ViewProviderSketch::editDoubleClicked() } } -bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventorViewer *viewer) +bool ViewProviderSketch::mouseMove(const SbVec2s& cursorPos, Gui::View3DInventorViewer* viewer) { // maximum radius for mouse moves when selecting a geometry before switching to drag mode const int dragIgnoredDistance = 3; @@ -1107,7 +1305,7 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor case STATUS_SKETCH_StartRubberBand: short dx, dy; (cursorPos - DoubleClick::prvCursorPos).getValue(dx, dy); - if(std::abs(dx) < dragIgnoredDistance && std::abs(dy) < dragIgnoredDistance) + if (std::abs(dx) < dragIgnoredDistance && std::abs(dy) < dragIgnoredDistance) return false; default: break; @@ -1117,9 +1315,9 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor SbLine line; getProjectingLine(cursorPos, viewer, line); - double x,y; + double x, y; try { - getCoordsOnSketchPlane(line.getPosition(),line.getDirection(),x,y); + getCoordsOnSketchPlane(line.getPosition(), line.getDirection(), x, y); snapManager->snap(x, y); } catch (const Base::ZeroDivisionError&) { @@ -1127,13 +1325,10 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor } bool preselectChanged = false; - if (Mode != STATUS_SELECT_Point && - Mode != STATUS_SELECT_Edge && - Mode != STATUS_SELECT_Constraint && - Mode != STATUS_SKETCH_DragPoint && - Mode != STATUS_SKETCH_DragCurve && - Mode != STATUS_SKETCH_DragConstraint && - Mode != STATUS_SKETCH_UseRubberBand) { + if (Mode != STATUS_SELECT_Point && Mode != STATUS_SELECT_Edge + && Mode != STATUS_SELECT_Constraint && Mode != STATUS_SKETCH_DragPoint + && Mode != STATUS_SKETCH_DragCurve && Mode != STATUS_SKETCH_DragConstraint + && Mode != STATUS_SKETCH_UseRubberBand) { std::unique_ptr Point(this->getPointOnRay(cursorPos, viewer)); @@ -1149,8 +1344,8 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor } return false; case STATUS_SELECT_Point: - if (!getSolvedSketch().hasConflicts() && - preselection.isPreselectPointValid() && drag.DragPoint != preselection.PreselectPoint) { + if (!getSolvedSketch().hasConflicts() && preselection.isPreselectPointValid() + && drag.DragPoint != preselection.PreselectPoint) { Mode = STATUS_SKETCH_DragPoint; drag.DragPoint = preselection.PreselectPoint; int GeoId; @@ -1162,59 +1357,65 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor getSketchObject()->initTemporaryMove(GeoId, PosId, false); drag.resetVector(); } - } else { + } + else { Mode = STATUS_NONE; } resetPreselectPoint(); return true; case STATUS_SELECT_Edge: - if (!getSolvedSketch().hasConflicts() && - preselection.isPreselectCurveValid() && drag.DragCurve != preselection.PreselectCurve) { + if (!getSolvedSketch().hasConflicts() && preselection.isPreselectCurveValid() + && drag.DragCurve != preselection.PreselectCurve) { Mode = STATUS_SKETCH_DragCurve; drag.DragCurve = preselection.PreselectCurve; - const Part::Geometry *geo = getSketchObject()->getGeometry(drag.DragCurve); + const Part::Geometry* geo = getSketchObject()->getGeometry(drag.DragCurve); // BSpline Control points are edge draggable only if their radius is movable // This is because dragging gives unwanted cosmetic results due to the scale ratio. // This is an heuristic as it does not check all indirect routes. - if(GeometryFacade::isInternalType(geo, InternalType::BSplineControlPoint)) { - if(geo->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) { - auto solvext = std::static_pointer_cast( - geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); + if (GeometryFacade::isInternalType(geo, InternalType::BSplineControlPoint)) { + if (geo->hasExtension(Sketcher::SolverGeometryExtension::getClassTypeId())) { + auto solvext = + std::static_pointer_cast( + geo->getExtension( + Sketcher::SolverGeometryExtension::getClassTypeId()) + .lock()); // Edge parameters are Independent, so weight won't move - if(solvext->getEdge()==Sketcher::SolverGeometryExtension::Independent) { + if (solvext->getEdge() == Sketcher::SolverGeometryExtension::Independent) { Mode = STATUS_NONE; return false; } - // The B-Spline is constrained to be non-rational (equal weights), moving produces a bad effect - // because OCCT will normalize the values of the weights. - auto grp = getSolvedSketch().getDependencyGroup(drag.DragCurve, Sketcher::PointPos::none); + // The B-Spline is constrained to be non-rational (equal weights), moving + // produces a bad effect because OCCT will normalize the values of the + // weights. + auto grp = getSolvedSketch().getDependencyGroup(drag.DragCurve, + Sketcher::PointPos::none); int bsplinegeoid = -1; std::vector polegeoids; - for( auto c : getSketchObject()->Constraints.getValues()) { - if( c->Type == Sketcher::InternalAlignment && - c->AlignmentType == BSplineControlPoint && - c->First == drag.DragCurve ) { + for (auto c : getSketchObject()->Constraints.getValues()) { + if (c->Type == Sketcher::InternalAlignment + && c->AlignmentType == BSplineControlPoint + && c->First == drag.DragCurve) { bsplinegeoid = c->Second; break; } } - if(bsplinegeoid == -1) { + if (bsplinegeoid == -1) { Mode = STATUS_NONE; return false; } - for( auto c : getSketchObject()->Constraints.getValues()) { - if( c->Type == Sketcher::InternalAlignment && - c->AlignmentType == BSplineControlPoint && - c->Second == bsplinegeoid ) { + for (auto c : getSketchObject()->Constraints.getValues()) { + if (c->Type == Sketcher::InternalAlignment + && c->AlignmentType == BSplineControlPoint + && c->Second == bsplinegeoid) { polegeoids.push_back(c->First); } @@ -1222,44 +1423,50 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor bool allingroup = true; - for( auto polegeoid : polegeoids ) { - std::pair< int, Sketcher::PointPos > thispole = std::make_pair(polegeoid,Sketcher::PointPos::none); + for (auto polegeoid : polegeoids) { + std::pair thispole = + std::make_pair(polegeoid, Sketcher::PointPos::none); - if(grp.find(thispole) == grp.end()) // not found - allingroup = false; + if (grp.find(thispole) == grp.end())// not found + allingroup = false; } - if(allingroup) { // it is constrained to be non-rational + if (allingroup) {// it is constrained to be non-rational Mode = STATUS_NONE; return false; } - } - } - if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() || - geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() + || geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { drag.relative = true; - // Since the cursor moved from where it was clicked, and this is a relative move, - // calculate the click position and use it as initial point. + // Since the cursor moved from where it was clicked, and this is a relative + // move, calculate the click position and use it as initial point. SbLine line2; getProjectingLine(DoubleClick::prvCursorPos, viewer, line2); - getCoordsOnSketchPlane(line2.getPosition(),line2.getDirection(),drag.xInit,drag.yInit); + getCoordsOnSketchPlane( + line2.getPosition(), line2.getDirection(), drag.xInit, drag.yInit); snapManager->snap(drag.xInit, drag.yInit); - } else { + } + else { drag.resetVector(); } if (geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { getSketchObject()->initTemporaryBSplinePieceMove( - drag.DragCurve, Sketcher::PointPos::none, - Base::Vector3d(drag.xInit, drag.yInit, 0.0), false); - } else { - getSketchObject()->initTemporaryMove(drag.DragCurve, Sketcher::PointPos::none, false); + drag.DragCurve, + Sketcher::PointPos::none, + Base::Vector3d(drag.xInit, drag.yInit, 0.0), + false); } - } else { + else { + getSketchObject()->initTemporaryMove( + drag.DragCurve, Sketcher::PointPos::none, false); + } + } + else { Mode = STATUS_NONE; } resetPreselectPoint(); @@ -1271,16 +1478,16 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor return true; case STATUS_SKETCH_DragPoint: if (drag.isDragPointValid()) { - //Base::Console().Log("Drag Point:%d\n",edit->DragPoint); + // Base::Console().Log("Drag Point:%d\n",edit->DragPoint); int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(drag.DragPoint, GeoId, PosId); - Base::Vector3d vec(x,y,0); + Base::Vector3d vec(x, y, 0); if (GeoId != Sketcher::GeoEnum::GeoUndef && PosId != Sketcher::PointPos::none) { if (getSketchObject()->moveTemporaryPoint(GeoId, PosId, vec, false) == 0) { - setPositionText(Base::Vector2d(x,y)); - draw(true,false); + setPositionText(Base::Vector2d(x, y)); + draw(true, false); } } } @@ -1290,24 +1497,28 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor auto geo = getSketchObject()->getGeometry(drag.DragCurve); auto gf = GeometryFacade::getFacade(geo); - Base::Vector3d vec(x-drag.xInit,y-drag.yInit,0); + Base::Vector3d vec(x - drag.xInit, y - drag.yInit, 0); // BSpline weights have a radius corresponding to the weight value // However, in order for them proportional to the B-Spline size, // the scenograph has a size scalefactor times the weight // This code normalizes the information sent to the solver. - if(gf->getInternalType() == InternalType::BSplineControlPoint) { - auto circle = static_cast(geo); + if (gf->getInternalType() == InternalType::BSplineControlPoint) { + auto circle = static_cast(geo); Base::Vector3d center = circle->getCenter(); Base::Vector3d dir = vec - center; double scalefactor = 1.0; - if(circle->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) - { - auto vpext = std::static_pointer_cast( - circle->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock()); + if (circle->hasExtension( + SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) { + auto vpext = std::static_pointer_cast< + const SketcherGui::ViewProviderSketchGeometryExtension>( + circle + ->getExtension(SketcherGui::ViewProviderSketchGeometryExtension:: + getClassTypeId()) + .lock()); scalefactor = vpext->getRepresentationFactor(); } @@ -1315,21 +1526,23 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor vec = center + dir / scalefactor; } - if (getSketchObject()->moveTemporaryPoint(drag.DragCurve, Sketcher::PointPos::none, vec, drag.relative) == 0) { - setPositionText(Base::Vector2d(x,y)); - draw(true,false); + if (getSketchObject()->moveTemporaryPoint( + drag.DragCurve, Sketcher::PointPos::none, vec, drag.relative) + == 0) { + setPositionText(Base::Vector2d(x, y)); + draw(true, false); } } return true; case STATUS_SKETCH_DragConstraint: if (!drag.DragConstraintSet.empty()) { auto idset = drag.DragConstraintSet; - for(int id : idset) - moveConstraint(id, Base::Vector2d(x,y)); + for (int id : idset) + moveConstraint(id, Base::Vector2d(x, y)); } return true; case STATUS_SKETCH_UseHandler: - sketchHandler->mouseMove(Base::Vector2d(x,y)); + sketchHandler->mouseMove(Base::Vector2d(x, y)); if (preselectChanged) { editCoinManager->drawConstraintIcons(); this->updateColor(); @@ -1341,13 +1554,15 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor return true; } case STATUS_SKETCH_UseRubberBand: { - // Here we must use the device-pixel-ratio to compute the correct y coordinate (#0003130) + // Here we must use the device-pixel-ratio to compute the correct y coordinate + // (#0003130) qreal dpr = viewer->getGLWidget()->devicePixelRatioF(); DoubleClick::newCursorPos = cursorPos; - rubberband->setCoords(DoubleClick::prvCursorPos.getValue()[0], - viewer->getGLWidget()->height()*dpr - DoubleClick::prvCursorPos.getValue()[1], - DoubleClick::newCursorPos.getValue()[0], - viewer->getGLWidget()->height()*dpr - DoubleClick::newCursorPos.getValue()[1]); + rubberband->setCoords( + DoubleClick::prvCursorPos.getValue()[0], + viewer->getGLWidget()->height() * dpr - DoubleClick::prvCursorPos.getValue()[1], + DoubleClick::newCursorPos.getValue()[0], + viewer->getGLWidget()->height() * dpr - DoubleClick::newCursorPos.getValue()[1]); viewer->redraw(); return true; } @@ -1358,14 +1573,15 @@ bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventor return false; } -void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPos) +void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d& toPos) { // are we in edit? if (!isInEditMode()) return; - const std::vector &constrlist = getSketchObject()->Constraints.getValues(); - Constraint *Constr = constrlist[constNum]; + const std::vector& constrlist = + getSketchObject()->Constraints.getValues(); + Constraint* Constr = constrlist[constNum]; #ifdef FC_DEBUG int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; @@ -1373,7 +1589,7 @@ void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPo #endif // with memory allocation - const std::vector geomlist = getSolvedSketch().extractGeometry(true, true); + const std::vector geomlist = getSolvedSketch().extractGeometry(true, true); #ifdef FC_DEBUG assert(int(geomlist.size()) == extGeoCount + intGeoCount); @@ -1381,54 +1597,66 @@ void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPo || Constr->First != GeoEnum::GeoUndef); #endif - if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY || - Constr->Type == Radius || Constr->Type == Diameter || Constr-> Type == Weight) { + if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY + || Constr->Type == Radius || Constr->Type == Diameter || Constr->Type == Weight) { - Base::Vector3d p1(0.,0.,0.), p2(0.,0.,0.); - if (Constr->SecondPos != Sketcher::PointPos::none) { // point to point distance + Base::Vector3d p1(0., 0., 0.), p2(0., 0., 0.); + if (Constr->SecondPos != Sketcher::PointPos::none) {// point to point distance p1 = getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); p2 = getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); - } else if (Constr->Second != GeoEnum::GeoUndef) { + } + else if (Constr->Second != GeoEnum::GeoUndef) { p1 = getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); - const Part::Geometry *geo = GeoList::getGeometryFromGeoId (geomlist, Constr->Second); + const Part::Geometry* geo = GeoList::getGeometryFromGeoId(geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); + const Part::GeomLineSegment* lineSeg = + static_cast(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); - if (Constr->FirstPos != Sketcher::PointPos::none) { // point to line distance + if (Constr->FirstPos != Sketcher::PointPos::none) {// point to line distance // calculate the projection of p1 onto line2 - p2.ProjectToLine(p1-l2p1, l2p2-l2p1); + p2.ProjectToLine(p1 - l2p1, l2p2 - l2p1); p2 += p1; - } else { - const Part::Geometry *geo1 = GeoList::getGeometryFromGeoId (geomlist, Constr->First); - const Part::GeomCircle *circleSeg = static_cast(geo1); - Base::Vector3d ct = circleSeg->getCenter(); - double radius = circleSeg->getRadius(); - p1.ProjectToLine(ct-l2p1, l2p2-l2p1); //project on the line translated to origin - Base::Vector3d dir = p1; - dir.Normalize(); - p1 += ct; - p2 = ct + dir * radius; - } - } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { // circle to circle distance - const Part::Geometry *geo1 = GeoList::getGeometryFromGeoId (geomlist, Constr->First); + } + else { + const Part::Geometry* geo1 = + GeoList::getGeometryFromGeoId(geomlist, Constr->First); + const Part::GeomCircle* circleSeg = static_cast(geo1); + Base::Vector3d ct = circleSeg->getCenter(); + double radius = circleSeg->getRadius(); + p1.ProjectToLine(ct - l2p1, + l2p2 - l2p1);// project on the line translated to origin + Base::Vector3d dir = p1; + dir.Normalize(); + p1 += ct; + p2 = ct + dir * radius; + } + } + else if (geo->getTypeId() + == Part::GeomCircle::getClassTypeId()) {// circle to circle distance + const Part::Geometry* geo1 = GeoList::getGeometryFromGeoId(geomlist, Constr->First); if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circleSeg1 = static_cast(geo1); - const Part::GeomCircle *circleSeg2 = static_cast(geo); + const Part::GeomCircle* circleSeg1 = static_cast(geo1); + const Part::GeomCircle* circleSeg2 = static_cast(geo); GetCirclesMinimalDistance(circleSeg1, circleSeg2, p1, p2); } - } else + } + else return; - } else if (Constr->FirstPos != Sketcher::PointPos::none) { + } + else if (Constr->FirstPos != Sketcher::PointPos::none) { p2 = getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); - } else if (Constr->First != GeoEnum::GeoUndef) { - const Part::Geometry *geo = GeoList::getGeometryFromGeoId (geomlist, Constr->First); + } + else if (Constr->First != GeoEnum::GeoUndef) { + const Part::Geometry* geo = GeoList::getGeometryFromGeoId(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); + const Part::GeomLineSegment* lineSeg = + static_cast(geo); p1 = lineSeg->getStartPoint(); p2 = lineSeg->getEndPoint(); - } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo); + } + else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + const Part::GeomArcOfCircle* arc = static_cast(geo); double radius = arc->getRadius(); Base::Vector3d center = arc->getCenter(); p1 = center; @@ -1437,72 +1665,78 @@ void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPo if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); - angle = (startangle + endangle)/2; + angle = (startangle + endangle) / 2; } else { - Base::Vector3d tmpDir = Base::Vector3d(toPos.x, toPos.y, 0) - p1; + Base::Vector3d tmpDir = Base::Vector3d(toPos.x, toPos.y, 0) - p1; angle = atan2(tmpDir.y, tmpDir.x); } - if(Constr->Type == Sketcher::Diameter) - p1 = center - radius * Base::Vector3d(cos(angle),sin(angle),0.); + if (Constr->Type == Sketcher::Diameter) + p1 = center - radius * Base::Vector3d(cos(angle), sin(angle), 0.); - p2 = center + radius * Base::Vector3d(cos(angle),sin(angle),0.); + p2 = center + radius * Base::Vector3d(cos(angle), sin(angle), 0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { - const Part::GeomCircle *circle = static_cast(geo); + const Part::GeomCircle* circle = static_cast(geo); double radius = circle->getRadius(); Base::Vector3d center = circle->getCenter(); p1 = center; - Base::Vector3d tmpDir = Base::Vector3d(toPos.x, toPos.y, 0) - p1; + Base::Vector3d tmpDir = Base::Vector3d(toPos.x, toPos.y, 0) - p1; Base::Vector3d dir = radius * tmpDir.Normalize(); - if(Constr->Type == Sketcher::Diameter) + if (Constr->Type == Sketcher::Diameter) p1 = center - dir; - if(Constr->Type == Sketcher::Weight) { + if (Constr->Type == Sketcher::Weight) { double scalefactor = 1.0; - if(circle->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) - { - auto vpext = std::static_pointer_cast( - circle->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock()); + if (circle->hasExtension( + SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) { + auto vpext = std::static_pointer_cast< + const SketcherGui::ViewProviderSketchGeometryExtension>( + circle + ->getExtension(SketcherGui::ViewProviderSketchGeometryExtension:: + getClassTypeId()) + .lock()); scalefactor = vpext->getRepresentationFactor(); } p2 = center + dir * scalefactor; - } else p2 = center + dir; } else return; - } else + } + else return; Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p2; Base::Vector3d dir; - if (Constr->Type == Distance || Constr->Type == Radius || Constr->Type == Diameter || Constr->Type == Weight) - dir = (p2-p1).Normalize(); + if (Constr->Type == Distance || Constr->Type == Radius || Constr->Type == Diameter + || Constr->Type == Weight) + dir = (p2 - p1).Normalize(); else if (Constr->Type == DistanceX) - dir = Base::Vector3d( (p2.x - p1.x >= FLT_EPSILON) ? 1 : -1, 0, 0); + dir = Base::Vector3d((p2.x - p1.x >= FLT_EPSILON) ? 1 : -1, 0, 0); else if (Constr->Type == DistanceY) dir = Base::Vector3d(0, (p2.y - p1.y >= FLT_EPSILON) ? 1 : -1, 0); if (Constr->Type == Radius || Constr->Type == Diameter || Constr->Type == Weight) { Constr->LabelDistance = vec.x * dir.x + vec.y * dir.y; Constr->LabelPosition = atan2(dir.y, dir.x); - } else { - Base::Vector3d normal(-dir.y,dir.x,0); + } + else { + Base::Vector3d normal(-dir.y, dir.x, 0); Constr->LabelDistance = vec.x * normal.x + vec.y * normal.y; - if (Constr->Type == Distance || - Constr->Type == DistanceX || Constr->Type == DistanceY) { + if (Constr->Type == Distance || Constr->Type == DistanceX + || Constr->Type == DistanceY) { vec = Base::Vector3d(toPos.x, toPos.y, 0) - (p2 + p1) / 2; Constr->LabelPosition = vec.x * dir.x + vec.y * dir.y; } @@ -1510,71 +1744,77 @@ void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPo } else if (Constr->Type == Angle) { - Base::Vector3d p0(0.,0.,0.); + Base::Vector3d p0(0., 0., 0.); double factor = 0.5; - if (Constr->Second != GeoEnum::GeoUndef) { // line to line angle + if (Constr->Second != GeoEnum::GeoUndef) {// line to line angle Base::Vector3d dir1, dir2; - if(Constr->Third == GeoEnum::GeoUndef) { //angle between two lines - const Part::Geometry *geo1 = GeoList::getGeometryFromGeoId (geomlist, Constr->First); - const Part::Geometry *geo2 = GeoList::getGeometryFromGeoId (geomlist, Constr->Second); + if (Constr->Third == GeoEnum::GeoUndef) {// angle between two lines + const Part::Geometry* geo1 = GeoList::getGeometryFromGeoId(geomlist, Constr->First); + const Part::Geometry* geo2 = + GeoList::getGeometryFromGeoId(geomlist, Constr->Second); - if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || - geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) + if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() + || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) return; - const Part::GeomLineSegment *lineSeg1 = static_cast(geo1); - const Part::GeomLineSegment *lineSeg2 = static_cast(geo2); + const Part::GeomLineSegment* lineSeg1 = + static_cast(geo1); + const Part::GeomLineSegment* lineSeg2 = + static_cast(geo2); bool flip1 = (Constr->FirstPos == Sketcher::PointPos::end); bool flip2 = (Constr->SecondPos == Sketcher::PointPos::end); - dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); - dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); + dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()); + dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { - double det = dir1.x*dir2.y - dir1.y*dir2.x; + double det = dir1.x * dir2.y - dir1.y * dir2.x; if ((det > 0 ? det : -det) < 1e-10) return;// lines are parallel - constraint unmoveable (DeepSOIC: why?..) - double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; - double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; - double x = (dir1.x*c2 - dir2.x*c1)/det; - double y = (dir1.y*c2 - dir2.y*c1)/det; + double c1 = dir1.y * pnt1.x - dir1.x * pnt1.y; + double c2 = dir2.y * pnt2.x - dir2.x * pnt2.y; + double x = (dir1.x * c2 - dir2.x * c1) / det; + double y = (dir1.y * c2 - dir2.y * c1) / det; // intersection point - p0 = Base::Vector3d(x,y,0); + p0 = Base::Vector3d(x, y, 0); Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p0; - factor = factor * Base::sgn((dir1+dir2) * vec); + factor = factor * Base::sgn((dir1 + dir2) * vec); } - } else {//angle-via-point + } + else {// angle-via-point Base::Vector3d p = getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = Base::Vector3d(p.x, p.y, 0); dir1 = getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); - dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating + dir1.RotateZ(-M_PI / 2);// convert to vector of tangency by rotating dir2 = getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); - dir2.RotateZ(-M_PI/2); + dir2.RotateZ(-M_PI / 2); Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p0; - factor = factor * Base::sgn((dir1+dir2) * vec); + factor = factor * Base::sgn((dir1 + dir2) * vec); } - - } else if (Constr->First != GeoEnum::GeoUndef) { // line/arc angle - const Part::Geometry *geo = GeoList::getGeometryFromGeoId (geomlist, Constr->First); + } + else if (Constr->First != GeoEnum::GeoUndef) {// line/arc angle + const Part::Geometry* geo = GeoList::getGeometryFromGeoId(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { - const Part::GeomLineSegment *lineSeg = static_cast(geo); - p0 = (lineSeg->getEndPoint()+lineSeg->getStartPoint())/2; + const Part::GeomLineSegment* lineSeg = + static_cast(geo); + p0 = (lineSeg->getEndPoint() + lineSeg->getStartPoint()) / 2; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { - const Part::GeomArcOfCircle *arc = static_cast(geo); + const Part::GeomArcOfCircle* arc = static_cast(geo); p0 = arc->getCenter(); } else { return; } - } else + } + else return; Base::Vector3d vec = Base::Vector3d(toPos.x, toPos.y, 0) - p0; @@ -1582,10 +1822,12 @@ void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPo } // delete the cloned objects - for (std::vector::const_iterator it=geomlist.begin(); it != geomlist.end(); ++it) - if (*it) delete *it; + for (std::vector::const_iterator it = geomlist.begin(); it != geomlist.end(); + ++it) + if (*it) + delete *it; - draw(true,false); + draw(true, false); } bool ViewProviderSketch::isSelectable() const @@ -1601,10 +1843,11 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) // are we in edit? if (isInEditMode()) { // ignore external object - if(!msg.Object.getObjectName().empty() && msg.Object.getDocument()!=getObject()->getDocument()) + if (!msg.Object.getObjectName().empty() + && msg.Object.getDocument() != getObject()->getDocument()) return; - bool handled=false; + bool handled = false; if (Mode == STATUS_SKETCH_UseHandler) { App::AutoTransaction committer; handled = sketchHandler->onSelectionChanged(msg); @@ -1615,7 +1858,8 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) std::string temp; if (msg.Type == Gui::SelectionChanges::ClrSelection) { // if something selected in this object? - if (!selection.SelPointSet.empty() || !selection.SelCurvSet.empty() || !selection.SelConstraintSet.empty()) { + if (!selection.SelPointSet.empty() || !selection.SelCurvSet.empty() + || !selection.SelConstraintSet.empty()) { // clear our selection and update the color of the viewed edges and points clearSelectPoints(); selection.SelCurvSet.clear(); @@ -1626,22 +1870,22 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) } else if (msg.Type == Gui::SelectionChanges::AddSelection) { // is it this object?? - if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 - && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { + if (strcmp(msg.pDocName, getSketchObject()->getDocument()->getName()) == 0 + && strcmp(msg.pObjectName, getSketchObject()->getNameInDocument()) == 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); - if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { + if (shapetype.size() > 4 && shapetype.substr(0, 4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; selection.SelCurvSet.insert(GeoId); this->updateColor(); } - else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { + else if (shapetype.size() > 12 && shapetype.substr(0, 12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; selection.SelCurvSet.insert(GeoId); this->updateColor(); } - else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { + else if (shapetype.size() > 6 && shapetype.substr(0, 6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; addSelectPoint(VtId); this->updateColor(); @@ -1658,8 +1902,9 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) selection.SelCurvSet.insert(Selection::VerticalAxis); this->updateColor(); } - else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { - int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); + else if (shapetype.size() > 10 && shapetype.substr(0, 10) == "Constraint") { + int ConstrId = + Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); selection.SelConstraintSet.insert(ConstrId); editCoinManager->drawConstraintIcons(); this->updateColor(); @@ -1669,24 +1914,26 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) } else if (msg.Type == Gui::SelectionChanges::RmvSelection) { // Are there any objects selected - if (!selection.SelPointSet.empty() || !selection.SelCurvSet.empty() || !selection.SelConstraintSet.empty()) { + if (!selection.SelPointSet.empty() || !selection.SelCurvSet.empty() + || !selection.SelConstraintSet.empty()) { // is it this object?? - if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 - && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { + if (strcmp(msg.pDocName, getSketchObject()->getDocument()->getName()) == 0 + && strcmp(msg.pObjectName, getSketchObject()->getNameInDocument()) == 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); - if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { + if (shapetype.size() > 4 && shapetype.substr(0, 4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; selection.SelCurvSet.erase(GeoId); this->updateColor(); } - else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { + else if (shapetype.size() > 12 + && shapetype.substr(0, 12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; selection.SelCurvSet.erase(GeoId); this->updateColor(); } - else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { + else if (shapetype.size() > 6 && shapetype.substr(0, 6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; removeSelectPoint(VtId); this->updateColor(); @@ -1703,8 +1950,10 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) selection.SelCurvSet.erase(Sketcher::GeoEnum::VAxis); this->updateColor(); } - else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { - int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); + else if (shapetype.size() > 10 && shapetype.substr(0, 10) == "Constraint") { + int ConstrId = + Sketcher::PropertyConstraintList::getIndexFromConstraintName( + shapetype); selection.SelConstraintSet.erase(ConstrId); editCoinManager->drawConstraintIcons(); this->updateColor(); @@ -1715,9 +1964,11 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) } else if (msg.Type == Gui::SelectionChanges::SetSelection) { // remove all items - //selectionView->clear(); - //std::vector objs = Gui::Selection().getSelection(Reason.pDocName); - //for (std::vector::iterator it = objs.begin(); it != objs.end(); ++it) { + // selectionView->clear(); + // std::vector objs = + // Gui::Selection().getSelection(Reason.pDocName); for + // (std::vector::iterator it = objs.begin(); it != + // objs.end(); ++it) { // // build name // temp = it->DocName; // temp += "."; @@ -1730,11 +1981,11 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) //} } else if (msg.Type == Gui::SelectionChanges::SetPreselect) { - if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 - && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { + if (strcmp(msg.pDocName, getSketchObject()->getDocument()->getName()) == 0 + && strcmp(msg.pObjectName, getSketchObject()->getNameInDocument()) == 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); - if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { + if (shapetype.size() > 4 && shapetype.substr(0, 4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; resetPreselectPoint(); preselection.PreselectCurve = GeoId; @@ -1743,7 +1994,7 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) sketchHandler->applyCursor(); this->updateColor(); } - else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { + else if (shapetype.size() > 6 && shapetype.substr(0, 6) == "Vertex") { int PtIndex = std::atoi(&shapetype[6]) - 1; setPreselectPoint(PtIndex); @@ -1763,7 +2014,7 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) } } -bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const SbVec2s &cursorPos) +bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint* Point, const SbVec2s& cursorPos) { assert(isInEditMode()); @@ -1776,8 +2027,9 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const && result.PointIndex != preselection.PreselectPoint) {// if a new point is hit std::stringstream ss; ss << "Vertex" << result.PointIndex + 1; - bool accepted = setPreselect(ss.str(), Point->getPoint()[0], Point->getPoint()[1], - Point->getPoint()[2]) + bool accepted = + setPreselect( + ss.str(), Point->getPoint()[0], Point->getPoint()[1], Point->getPoint()[2]) != 0; preselection.blockedPreselection = !accepted; if (accepted) { @@ -1793,12 +2045,13 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const std::stringstream ss; if (result.GeoIndex >= 0) ss << "Edge" << result.GeoIndex + 1; - else // external geometry + else// external geometry ss << "ExternalEdge" << -result.GeoIndex + Sketcher::GeoEnum::RefExt + 1;// convert index start from -3 to 1 - bool accepted = setPreselect(ss.str(), Point->getPoint()[0], Point->getPoint()[1], - Point->getPoint()[2]) + bool accepted = + setPreselect( + ss.str(), Point->getPoint()[0], Point->getPoint()[1], Point->getPoint()[2]) != 0; preselection.blockedPreselection = !accepted; if (accepted) { @@ -1827,8 +2080,9 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const case EditModeCoinManager::PreselectionResult::Axes::None: break;// silent warning - be explicit } - bool accepted = setPreselect(ss.str(), Point->getPoint()[0], Point->getPoint()[1], - Point->getPoint()[2]) + bool accepted = + setPreselect( + ss.str(), Point->getPoint()[0], Point->getPoint()[1], Point->getPoint()[2]) != 0; preselection.blockedPreselection = !accepted; if (accepted) { @@ -1849,16 +2103,18 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const != preselection.PreselectConstraintSet) {// if a constraint is hit bool accepted = true; for (std::set::iterator it = result.ConstrIndices.begin(); - it != result.ConstrIndices.end(); ++it) { + it != result.ConstrIndices.end(); + ++it) { std::stringstream ss; ss << Sketcher::PropertyConstraintList::getConstraintName(*it); - accepted &= setPreselect(ss.str(), Point->getPoint()[0], Point->getPoint()[1], - Point->getPoint()[2]) + accepted &= + setPreselect( + ss.str(), Point->getPoint()[0], Point->getPoint()[1], Point->getPoint()[2]) != 0; preselection.blockedPreselection = !accepted; - //TODO: Should we clear preselections that went through, if one fails? + // TODO: Should we clear preselections that went through, if one fails? } if (accepted) { resetPreselectPoint(); @@ -1866,7 +2122,7 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const if (sketchHandler) sketchHandler->applyCursor(); - return true;//Preselection changed + return true;// Preselection changed } } else if ((result.PointIndex == -1 && result.GeoIndex == -1 @@ -1883,8 +2139,8 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const sketchHandler->applyCursor(); return true; } - Gui::Selection().setPreselectCoord(Point->getPoint()[0], Point->getPoint()[1], - Point->getPoint()[2]); + Gui::Selection().setPreselectCoord( + Point->getPoint()[0], Point->getPoint()[1], Point->getPoint()[2]); } else if (preselection.isPreselectCurveValid() || preselection.isPreselectPointValid() || !preselection.PreselectConstraintSet.empty() || preselection.isCrossPreselected() @@ -1901,8 +2157,8 @@ bool ViewProviderSketch::detectAndShowPreselection(SoPickedPoint * Point, const void ViewProviderSketch::centerSelection() { - Gui::MDIView *mdi = this->getActiveView(); - Gui::View3DInventor *view = qobject_cast(mdi); + Gui::MDIView* mdi = this->getActiveView(); + Gui::View3DInventor* view = qobject_cast(mdi); if (!view || !isInEditMode()) return; @@ -1924,8 +2180,8 @@ void ViewProviderSketch::centerSelection() } } -void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s &endPos, - const Gui::View3DInventorViewer *viewer) +void ViewProviderSketch::doBoxSelection(const SbVec2s& startPos, const SbVec2s& endPos, + const Gui::View3DInventorViewer* viewer) { std::vector corners0; corners0.push_back(startPos); @@ -1941,35 +2197,40 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & Gui::ViewVolumeProjection proj(viewer->getSoRenderManager()->getCamera()->getViewVolume()); - Sketcher::SketchObject *sketchObject = getSketchObject(); + Sketcher::SketchObject* sketchObject = getSketchObject(); Base::Placement Plm = getEditingPlacement(); int intGeoCount = sketchObject->getHighestCurveIndex() + 1; int extGeoCount = sketchObject->getExternalGeometryCount(); - const std::vector geomlist = sketchObject->getCompleteGeometry(); // without memory allocation + const std::vector geomlist = + sketchObject->getCompleteGeometry();// without memory allocation assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert(int(geomlist.size()) >= 2); Base::Vector3d pnt0, pnt1, pnt2, pnt; - int VertexId = -1; // the loop below should be in sync with the main loop in ViewProviderSketch::draw - // so that the vertex indices are calculated correctly + int VertexId = + -1;// the loop below should be in sync with the main loop in ViewProviderSketch::draw + // so that the vertex indices are calculated correctly int GeoId = 0; bool touchMode = false; - //check if selection goes from the right to the left side (for touch-selection where even partially boxed objects get selected) - if(corners[0].getValue()[0] > corners[1].getValue()[0]) + // check if selection goes from the right to the left side (for touch-selection where even + // partially boxed objects get selected) + if (corners[0].getValue()[0] > corners[1].getValue()[0]) touchMode = true; - for (std::vector::const_iterator it = geomlist.begin(); it != geomlist.end()-2; ++it, ++GeoId) { + for (std::vector::const_iterator it = geomlist.begin(); + it != geomlist.end() - 2; + ++it, ++GeoId) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // ----- Check if single point lies inside box selection -----/ - const Part::GeomPoint *point = static_cast(*it); + const Part::GeomPoint* point = static_cast(*it); Plm.multVec(point->getPoint(), pnt0); pnt0 = proj(pnt0); VertexId += 1; @@ -1979,10 +2240,10 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & ss << "Vertex" << VertexId + 1; addSelection2(ss.str()); } - - } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // ----- Check if line segment lies inside box selection -----/ - const Part::GeomLineSegment *lineSeg = static_cast(*it); + const Part::GeomLineSegment* lineSeg = static_cast(*it); Plm.multVec(lineSeg->getStartPoint(), pnt1); Plm.multVec(lineSeg->getEndPoint(), pnt2); pnt1 = proj(pnt1); @@ -2008,24 +2269,25 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & ss << "Edge" << GeoId + 1; addSelection2(ss.str()); } - //check if line intersects with polygon + // check if line intersects with polygon else if (touchMode) { - Base::Polygon2d lineAsPolygon; - lineAsPolygon.Add(Base::Vector2d(pnt1.x, pnt1.y)); - lineAsPolygon.Add(Base::Vector2d(pnt2.x, pnt2.y)); - std::list resultList; - polygon.Intersect(lineAsPolygon, resultList); - if (!resultList.empty()) { - std::stringstream ss; - ss << "Edge" << GeoId + 1; - addSelection2(ss.str()); - } + Base::Polygon2d lineAsPolygon; + lineAsPolygon.Add(Base::Vector2d(pnt1.x, pnt1.y)); + lineAsPolygon.Add(Base::Vector2d(pnt2.x, pnt2.y)); + std::list resultList; + polygon.Intersect(lineAsPolygon, resultList); + if (!resultList.empty()) { + std::stringstream ss; + ss << "Edge" << GeoId + 1; + addSelection2(ss.str()); } - - } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { + } + } + else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ - ///TODO: Make it impossible to miss the circle if it's big and the selection pretty thin. - const Part::GeomCircle *circle = static_cast(*it); + /// TODO: Make it impossible to miss the circle if it's big and the selection pretty + /// thin. + const Part::GeomCircle* circle = static_cast(*it); pnt0 = circle->getCenter(); VertexId += 1; @@ -2045,15 +2307,14 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & float segment = float(2 * M_PI) / countSegments; // circumscribed polygon radius - float radius = float(circle->getRadius()) / cos(segment/2); + float radius = float(circle->getRadius()) / cos(segment / 2); bool bpolyInside = true; pnt0 = circle->getCenter(); float angle = 0.f; for (int i = 0; i < countSegments; ++i, angle += segment) { - pnt = Base::Vector3d(pnt0.x + radius * cos(angle), - pnt0.y + radius * sin(angle), - 0.f); + pnt = Base::Vector3d( + pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { @@ -2073,9 +2334,10 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & addSelection2(ss.str()); } } - } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // ----- Check if ellipse lies inside box selection -----/ - const Part::GeomEllipse *ellipse = static_cast(*it); + const Part::GeomEllipse* ellipse = static_cast(*it); pnt0 = ellipse->getCenter(); VertexId += 1; @@ -2095,8 +2357,8 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & double segment = (2 * M_PI) / countSegments; // circumscribed polygon radius - double a = (ellipse->getMajorRadius()) / cos(segment/2); - double b = (ellipse->getMinorRadius()) / cos(segment/2); + double a = (ellipse->getMajorRadius()) / cos(segment / 2); + double b = (ellipse->getMinorRadius()) / cos(segment / 2); Base::Vector3d majdir = ellipse->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); @@ -2104,7 +2366,7 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & pnt0 = ellipse->getCenter(); double angle = 0.; for (int i = 0; i < countSegments; ++i, angle += segment) { - pnt = pnt0 + (cos(angle)*a)*majdir + sin(angle)*b*mindir; + pnt = pnt0 + (cos(angle) * a) * majdir + sin(angle) * b * mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { @@ -2124,10 +2386,10 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & addSelection2(ss.str()); } } - - } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // Check if arc lies inside box selection - const Part::GeomArcOfCircle *aoc = static_cast(*it); + const Part::GeomArcOfCircle* aoc = static_cast(*it); pnt0 = aoc->getStartPoint(/*emulateCCW=*/true); pnt1 = aoc->getEndPoint(/*emulateCCW=*/true); @@ -2149,24 +2411,23 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & double startangle, endangle; aoc->getRange(startangle, endangle, /*emulateCCW=*/true); - if (startangle > endangle) // if arc is reversed + if (startangle > endangle)// if arc is reversed std::swap(startangle, endangle); - double range = endangle-startangle; + double range = endangle - startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); if (touchMode) - countSegments=countSegments*2.5; + countSegments = countSegments * 2.5; float segment = float(range) / countSegments; // circumscribed polygon radius - float radius = float(aoc->getRadius()) / cos(segment/2); + float radius = float(aoc->getRadius()) / cos(segment / 2); pnt0 = aoc->getCenter(); - float angle = float(startangle) + segment/2; + float angle = float(startangle) + segment / 2; for (int i = 0; i < countSegments; ++i, angle += segment) { - pnt = Base::Vector3d(pnt0.x + radius * cos(angle), - pnt0.y + radius * sin(angle), - 0.f); + pnt = Base::Vector3d( + pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2d(pnt.x, pnt.y))) { @@ -2174,7 +2435,7 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & if (!touchMode) break; } - else if(touchMode) { + else if (touchMode) { bpolyInside = true; break; } @@ -2204,9 +2465,10 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & ss << "Vertex" << VertexId + 1; addSelection2(ss.str()); } - } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // Check if arc lies inside box selection - const Part::GeomArcOfEllipse *aoe = static_cast(*it); + const Part::GeomArcOfEllipse* aoe = static_cast(*it); pnt0 = aoe->getStartPoint(/*emulateCCW=*/true); pnt1 = aoe->getEndPoint(/*emulateCCW=*/true); @@ -2229,25 +2491,25 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); - if (startangle > endangle) // if arc is reversed + if (startangle > endangle)// if arc is reversed std::swap(startangle, endangle); - double range = endangle-startangle; + double range = endangle - startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); if (touchMode) - countSegments=countSegments*2.5; + countSegments = countSegments * 2.5; double segment = (range) / countSegments; // circumscribed polygon radius - double a = (aoe->getMajorRadius()) / cos(segment/2); - double b = (aoe->getMinorRadius()) / cos(segment/2); + double a = (aoe->getMajorRadius()) / cos(segment / 2); + double b = (aoe->getMinorRadius()) / cos(segment / 2); Base::Vector3d majdir = aoe->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); pnt0 = aoe->getCenter(); - double angle = (startangle) + segment/2; + double angle = (startangle) + segment / 2; for (int i = 0; i < countSegments; ++i, angle += segment) { - pnt = pnt0 + cos(angle)*a*majdir + sin(angle)*b*mindir; + pnt = pnt0 + cos(angle) * a * majdir + sin(angle) * b * mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); @@ -2285,10 +2547,10 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & ss << "Vertex" << VertexId + 1; addSelection2(ss.str()); } - - } else if ((*it)->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { // Check if arc lies inside box selection - const Part::GeomArcOfHyperbola *aoh = static_cast(*it); + const Part::GeomArcOfHyperbola* aoh = static_cast(*it); pnt0 = aoh->getStartPoint(); pnt1 = aoh->getEndPoint(); pnt2 = aoh->getCenter(); @@ -2311,27 +2573,28 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & aoh->getRange(startangle, endangle, /*emulateCCW=*/true); - if (startangle > endangle) // if arc is reversed + if (startangle > endangle)// if arc is reversed std::swap(startangle, endangle); - double range = endangle-startangle; + double range = endangle - startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); if (touchMode) - countSegments=countSegments*2.5; + countSegments = countSegments * 2.5; float segment = float(range) / countSegments; // circumscribed polygon radius - float a = float(aoh->getMajorRadius()) / cos(segment/2); - float b = float(aoh->getMinorRadius()) / cos(segment/2); + float a = float(aoh->getMajorRadius()) / cos(segment / 2); + float b = float(aoh->getMinorRadius()) / cos(segment / 2); float phi = float(aoh->getAngleXU()); pnt0 = aoh->getCenter(); - float angle = float(startangle) + segment/2; + float angle = float(startangle) + segment / 2; for (int i = 0; i < countSegments; ++i, angle += segment) { - pnt = Base::Vector3d(pnt0.x + a * cosh(angle) * cos(phi) - b * sinh(angle) * sin(phi), - pnt0.y + a * cosh(angle) * sin(phi) + b * sinh(angle) * cos(phi), - 0.f); + pnt = Base::Vector3d( + pnt0.x + a * cosh(angle) * cos(phi) - b * sinh(angle) * sin(phi), + pnt0.y + a * cosh(angle) * sin(phi) + b * sinh(angle) * cos(phi), + 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); @@ -2368,12 +2631,11 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & ss << "Vertex" << VertexId + 1; addSelection2(ss.str()); } - } - - } else if ((*it)->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { + } + else if ((*it)->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { // Check if arc lies inside box selection - const Part::GeomArcOfParabola *aop = static_cast(*it); + const Part::GeomArcOfParabola* aop = static_cast(*it); pnt0 = aop->getStartPoint(); pnt1 = aop->getEndPoint(); @@ -2397,27 +2659,28 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & aop->getRange(startangle, endangle, /*emulateCCW=*/true); - if (startangle > endangle) // if arc is reversed + if (startangle > endangle)// if arc is reversed std::swap(startangle, endangle); - double range = endangle-startangle; + double range = endangle - startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); if (touchMode) - countSegments=countSegments*2.5; + countSegments = countSegments * 2.5; float segment = float(range) / countSegments; - //In local coordinate system, value() of parabola is: - //P(U) = O + U*U/(4.*F)*XDir + U*YDir - // circumscribed polygon radius - float focal = float(aop->getFocal()) / cos(segment/2); + // In local coordinate system, value() of parabola is: + // P(U) = O + U*U/(4.*F)*XDir + U*YDir + // circumscribed polygon radius + float focal = float(aop->getFocal()) / cos(segment / 2); float phi = float(aop->getAngleXU()); pnt0 = aop->getCenter(); - float angle = float(startangle) + segment/2; + float angle = float(startangle) + segment / 2; for (int i = 0; i < countSegments; ++i, angle += segment) { - pnt = Base::Vector3d(pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * sin(phi), - pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * cos(phi), - 0.f); + pnt = Base::Vector3d( + pnt0.x + angle * angle / 4 / focal * cos(phi) - angle * sin(phi), + pnt0.y + angle * angle / 4 / focal * sin(phi) + angle * cos(phi), + 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); @@ -2455,10 +2718,10 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & addSelection2(ss.str()); } } - - } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { - const Part::GeomBSplineCurve *spline = static_cast(*it); - //std::vector poles = spline->getPoles(); + } + else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { + const Part::GeomBSplineCurve* spline = static_cast(*it); + // std::vector poles = spline->getPoles(); VertexId += 2; Plm.multVec(spline->getStartPoint(), pnt1); @@ -2480,11 +2743,12 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & addSelection2(ss.str()); } - // This is a rather approximated approach. No it does not guarantee that the whole curve is boxed, specially - // for periodic curves, but it works reasonably well. Including all poles, which could be done, generally - // forces the user to select much more than the curve (all the poles) and it would not select the curve in cases - // where it is indeed comprised in the box. - // The implementation of the touch mode is also far from a desirable "touch" as it only recognizes touched points not the curve itself + // This is a rather approximated approach. No it does not guarantee that the whole curve + // is boxed, specially for periodic curves, but it works reasonably well. Including all + // poles, which could be done, generally forces the user to select much more than the + // curve (all the poles) and it would not select the curve in cases where it is indeed + // comprised in the box. The implementation of the touch mode is also far from a + // desirable "touch" as it only recognizes touched points not the curve itself if ((pnt1Inside && pnt2Inside) || (touchMode && (pnt1Inside || pnt2Inside))) { std::stringstream ss; ss << "Edge" << GeoId + 1; @@ -2517,11 +2781,14 @@ bool ViewProviderSketch::doubleClicked() float ViewProviderSketch::getScaleFactor() const { assert(isInEditMode()); - Gui::MDIView *mdi = Gui::Application::Instance->editViewOfNode(editCoinManager->getRootEditNode()); + Gui::MDIView* mdi = + Gui::Application::Instance->editViewOfNode(editCoinManager->getRootEditNode()); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { - Gui::View3DInventorViewer *viewer = static_cast(mdi)->getViewer(); + Gui::View3DInventorViewer* viewer = static_cast(mdi)->getViewer(); SoCamera* camera = viewer->getSoRenderManager()->getCamera(); - float scale = camera->getViewVolume(camera->aspectRatio.getValue()).getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) / 3; + float scale = camera->getViewVolume(camera->aspectRatio.getValue()) + .getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) + / 3; return scale; } else { @@ -2530,117 +2797,148 @@ float ViewProviderSketch::getScaleFactor() const } // This function ensures that the geometry used for drawing takes into account: -// 1. the OCC mandated weight, which is normalised for non-rational BSplines, but not normalised for rational BSplines. -// That includes properly sizing for drawing any weight constraint. -// This function ensures that both the geometry of the SketchObject and solver are updated with the new value of the scaling factor (via the extension) -// 2. the scaling factor, including inserting the scaling factor into the ViewProviderSketchGeometryExtension so as to enable -// That ensures that dragging operations on the circles of the poles of the B-Splines are properly rendered. +// 1. the OCC mandated weight, which is normalised for non-rational BSplines, but not normalised for +// rational BSplines. That includes properly sizing for drawing any weight constraint. This function +// ensures that both the geometry of the SketchObject and solver are updated with the new value of +// the scaling factor (via the extension) +// 2. the scaling factor, including inserting the scaling factor into the +// ViewProviderSketchGeometryExtension so as to enable That ensures that dragging operations on the +// circles of the poles of the B-Splines are properly rendered. // -// This function takes a reference to a vector of deep copies to delete. These deep copies are necessary to transparently perform (1) while doing (2). +// This function takes a reference to a vector of deep copies to delete. These deep copies are +// necessary to transparently perform (1) while doing (2). void ViewProviderSketch::scaleBSplinePoleCirclesAndUpdateSolverAndSketchObjectGeometry( - GeoListFacade & geolistfacade, - bool geometrywithmemoryallocation) + GeoListFacade& geolistfacade, bool geometrywithmemoryallocation) { // In order to allow to tweak geometry and insert scaling factors, this function needs to // change the geometry vector. This is highly exceptional for a drawing function and special // care needs to be taken. This is valid because: - // 1. The treatment is exceptional and no other appropriate place is available to perform this tweak - // 2. The original object needs to remain const for the benefit of all other class hierarchy of drawing functions - // 3. When referring to actual geometry, the modified pointers are short lived, as they are destroyed after drawing - auto & tempGeo = geolistfacade.geomlist; + // 1. The treatment is exceptional and no other appropriate place is available to perform this + // tweak + // 2. The original object needs to remain const for the benefit of all other class hierarchy of + // drawing functions + // 3. When referring to actual geometry, the modified pointers are short lived, as they are + // destroyed after drawing + auto& tempGeo = geolistfacade.geomlist; int GeoId = 0; - for (auto it = tempGeo.begin(); it != tempGeo.end()-2; ++it, GeoId++) { + for (auto it = tempGeo.begin(); it != tempGeo.end() - 2; ++it, GeoId++) { if (GeoId >= geolistfacade.getInternalCount()) GeoId = -geolistfacade.getExternalCount(); - if ((*it)->getGeometry()->getTypeId() == Part::GeomCircle::getClassTypeId()) { // circle - const Part::GeomCircle *circle = static_cast((*it)->getGeometry()); - auto & gf = (*it); + if ((*it)->getGeometry()->getTypeId() == Part::GeomCircle::getClassTypeId()) {// circle + const Part::GeomCircle* circle = + static_cast((*it)->getGeometry()); + auto& gf = (*it); // BSpline weights have a radius corresponding to the weight value // However, in order for them proportional to the B-Spline size, // the scenograph has a size scalefactor times the weight // // This code produces the scaled up version of the geometry for the scenograph - if(gf->getInternalType() == InternalType::BSplineControlPoint) { - for( auto c : getSketchObject()->Constraints.getValues()) { - if( c->Type == InternalAlignment && c->AlignmentType == BSplineControlPoint && c->First == GeoId) { - auto bspline = dynamic_cast(tempGeo[c->Second]->getGeometry()); + if (gf->getInternalType() == InternalType::BSplineControlPoint) { + for (auto c : getSketchObject()->Constraints.getValues()) { + if (c->Type == InternalAlignment && c->AlignmentType == BSplineControlPoint + && c->First == GeoId) { + auto bspline = dynamic_cast( + tempGeo[c->Second]->getGeometry()); - if(bspline){ + if (bspline) { auto weights = bspline->getWeights(); double weight = 1.0; - if(c->InternalAlignmentIndex < int(weights.size())) - weight = weights[c->InternalAlignmentIndex]; + if (c->InternalAlignmentIndex < int(weights.size())) + weight = weights[c->InternalAlignmentIndex]; // tentative scaling factor: // proportional to the length of the bspline // inversely proportional to the number of poles - double scalefactor = bspline->length(bspline->getFirstParameter(), bspline->getLastParameter())/10.0/weights.size(); + double scalefactor = bspline->length(bspline->getFirstParameter(), + bspline->getLastParameter()) + / 10.0 / weights.size(); - double vradius = weight*scalefactor; - if(!bspline->isRational()) { - // OCCT sets the weights to 1.0 if a bspline is non-rational, but if the user has a weight constraint on any - // pole it would cause a visual artifact of having a constraint with a different radius and an unscaled circle - // so better scale the circles. + double vradius = weight * scalefactor; + if (!bspline->isRational()) { + // OCCT sets the weights to 1.0 if a bspline is non-rational, but if + // the user has a weight constraint on any pole it would cause a + // visual artifact of having a constraint with a different radius + // and an unscaled circle so better scale the circles. std::vector polegeoids; polegeoids.reserve(weights.size()); - for ( auto ic : getSketchObject()->Constraints.getValues()) { - if( ic->Type == InternalAlignment && ic->AlignmentType == BSplineControlPoint && ic->Second == c->Second) { + for (auto ic : getSketchObject()->Constraints.getValues()) { + if (ic->Type == InternalAlignment + && ic->AlignmentType == BSplineControlPoint + && ic->Second == c->Second) { polegeoids.push_back(ic->First); } } - for ( auto ic : getSketchObject()->Constraints.getValues()) { - if( ic->Type == Weight ) { - auto pos = std::find(polegeoids.begin(), polegeoids.end(), ic->First); + for (auto ic : getSketchObject()->Constraints.getValues()) { + if (ic->Type == Weight) { + auto pos = std::find( + polegeoids.begin(), polegeoids.end(), ic->First); - if(pos != polegeoids.end()) { + if (pos != polegeoids.end()) { vradius = ic->getValue() * scalefactor; - break; // one is enough, otherwise it would not be non-rational + break;// one is enough, otherwise it would not be + // non-rational } } } } - Part::GeomCircle * tmpcircle; + Part::GeomCircle* tmpcircle; - if(geometrywithmemoryallocation) { // with memory allocation - tmpcircle = const_cast(circle); + if (geometrywithmemoryallocation) {// with memory allocation + tmpcircle = const_cast(circle); tmpcircle->setRadius(vradius); } - else { // without memory allocation - tmpcircle = static_cast(circle->clone()); + else {// without memory allocation + tmpcircle = static_cast(circle->clone()); tmpcircle->setRadius(vradius); - tempGeo[GeoId] = GeometryFacade::getFacade(tmpcircle, true); // this is the circle that will be drawn, with the updated vradius, the facade takes ownership and will deallocate. + tempGeo[GeoId] = GeometryFacade::getFacade( + tmpcircle, true);// this is the circle that will be drawn, with + // the updated vradius, the facade takes + // ownership and will deallocate. } - if(!circle->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId())) - { - // It is ok to add this kind of extension to a const geometry because: - // 1. It does not modify the object in a way that affects property state, just ViewProvider representation - // 2. If it is lost (for example upon undo), redrawing will reinstate it with the correct value - const_cast(circle)->setExtension(std::make_unique()); + if (!circle->hasExtension( + SketcherGui::ViewProviderSketchGeometryExtension:: + getClassTypeId())) { + // It is ok to add this kind of extension to a const geometry + // because: + // 1. It does not modify the object in a way that affects property + // state, just ViewProvider representation + // 2. If it is lost (for example upon undo), redrawing will + // reinstate it with the correct value + const_cast(circle)->setExtension( + std::make_unique< + SketcherGui::ViewProviderSketchGeometryExtension>()); } - auto vpext = std::const_pointer_cast( - std::static_pointer_cast( - circle->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock())); + auto vpext = std::const_pointer_cast< + SketcherGui::ViewProviderSketchGeometryExtension>( + std::static_pointer_cast< + const SketcherGui::ViewProviderSketchGeometryExtension>( + circle + ->getExtension( + SketcherGui::ViewProviderSketchGeometryExtension:: + getClassTypeId()) + .lock())); vpext->setRepresentationFactor(scalefactor); // save scale factor for any prospective dragging operation // 1. Solver must be updated, in case a dragging operation starts - // 2. if temp geometry is being used (with memory allocation), then the copy we have here must be updated. If - // no temp geometry is being used, then the normal geometry must be updated. + // 2. if temp geometry is being used (with memory allocation), then the + // copy we have here must be updated. If + // no temp geometry is being used, then the normal geometry must be + // updated. // make solver be ready for a dragging operation auto solverext = vpext->copy(); getSketchObject()->updateSolverExtension(GeoId, std::move(solverext)); - } break; } @@ -2656,40 +2954,44 @@ void ViewProviderSketch::draw(bool temp /*=false*/, bool rebuildinformationoverl // ============== Retrieve geometry to be represented ================================= - auto geolistfacade = temp ? - getSolvedSketch().extractGeoListFacade(): // with memory allocation - getSketchObject()->getGeoListFacade(); // without memory allocation + auto geolistfacade = temp ? getSolvedSketch().extractGeoListFacade() :// with memory allocation + getSketchObject()->getGeoListFacade();// without memory allocation - assert(int( geolistfacade.geomlist.size()) >= 2); + assert(int(geolistfacade.geomlist.size()) >= 2); // ============== Prepare geometry for representation ================================== // ************ Manage BSpline pole circle scaling **************************** // This function ensures that the geometry used for drawing takes into account: - // 1. the OCC mandated weight, which is normalised for non-rational BSplines, but not normalised for rational BSplines. - // That includes properly sizing for drawing any weight constraint. - // This function ensures that both the geometry of the SketchObject and solver are updated with the new value of the scaling factor (via the extension) - // 2. the scaling factor, including inserting the scaling factor into the ViewProviderSketchGeometryExtension so as to enable - // That ensures that dragging operations on the circles of the poles of the B-Splines are properly rendered. + // 1. the OCC mandated weight, which is normalised for non-rational BSplines, but not normalised + // for rational BSplines. That includes properly sizing for drawing any weight constraint. This + // function ensures that both the geometry of the SketchObject and solver are updated with the + // new value of the scaling factor (via the extension) + // 2. the scaling factor, including inserting the scaling factor into the + // ViewProviderSketchGeometryExtension so as to enable That ensures that dragging operations on + // the circles of the poles of the B-Splines are properly rendered. // - // This function takes a reference to a vector of deep copies to delete. These deep copies are necessary to transparently perform (1) while doing (2). + // This function takes a reference to a vector of deep copies to delete. These deep copies are + // necessary to transparently perform (1) while doing (2). scaleBSplinePoleCirclesAndUpdateSolverAndSketchObjectGeometry(geolistfacade, temp); - // ============== Render geometry, constraints and geometry information overlays ================================== + // ============== Render geometry, constraints and geometry information overlays + // ================================== - editCoinManager->processGeometryConstraintsInformationOverlay(geolistfacade, rebuildinformationoverlay); + editCoinManager->processGeometryConstraintsInformationOverlay(geolistfacade, + rebuildinformationoverlay); // Avoids unneeded calls to pixmapFromSvg - if(Mode==STATUS_NONE || Mode==STATUS_SKETCH_UseHandler) { - editCoinManager->drawConstraintIcons(geolistfacade); - editCoinManager->updateColor(geolistfacade); + if (Mode == STATUS_NONE || Mode == STATUS_SKETCH_UseHandler) { + editCoinManager->drawConstraintIcons(geolistfacade); + editCoinManager->updateColor(geolistfacade); } - Gui::MDIView *mdi = this->getActiveView(); + Gui::MDIView* mdi = this->getActiveView(); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { - static_cast(mdi)->getViewer()->redraw(); + static_cast(mdi)->getViewer()->redraw(); } } @@ -2708,59 +3010,64 @@ bool ViewProviderSketch::getIsShownVirtualSpace() const } -void ViewProviderSketch::drawEdit(const std::vector &EditCurve) +void ViewProviderSketch::drawEdit(const std::vector& EditCurve) { editCoinManager->drawEdit(EditCurve); } -void ViewProviderSketch::drawEdit(const std::list> &list) +void ViewProviderSketch::drawEdit(const std::list>& list) { editCoinManager->drawEdit(list); } -void ViewProviderSketch::drawEditMarkers(const std::vector &EditMarkers, unsigned int augmentationlevel) +void ViewProviderSketch::drawEditMarkers(const std::vector& EditMarkers, + unsigned int augmentationlevel) { editCoinManager->drawEditMarkers(EditMarkers, augmentationlevel); } -void ViewProviderSketch::updateData(const App::Property *prop) +void ViewProviderSketch::updateData(const App::Property* prop) { ViewProvider2DObject::updateData(prop); - // In the case of an undo/redo transaction, updateData is triggered by SketchObject::onUndoRedoFinished() in the solve() - // In the case of an internal transaction, touching the geometry results in a call to updateData. - if ( isInEditMode() && !getSketchObject()->getDocument()->isPerformingTransaction() && - !getSketchObject()->isPerformingInternalTransaction() && - (prop == &(getSketchObject()->Geometry) || prop == &(getSketchObject()->Constraints))) { + // In the case of an undo/redo transaction, updateData is triggered by + // SketchObject::onUndoRedoFinished() in the solve() In the case of an internal transaction, + // touching the geometry results in a call to updateData. + if (isInEditMode() && !getSketchObject()->getDocument()->isPerformingTransaction() + && !getSketchObject()->isPerformingInternalTransaction() + && (prop == &(getSketchObject()->Geometry) || prop == &(getSketchObject()->Constraints))) { // At this point, we do not need to solve the Sketch - // If we are adding geometry an update can be triggered before the sketch is actually solved. - // Because a solve is mandatory to any addition (at least to update the DoF of the solver), - // only when the solver geometry is the same in number than the sketch geometry an update - // should trigger a redraw. This reduces even more the number of redraws per insertion of geometry + // If we are adding geometry an update can be triggered before the sketch is actually + // solved. Because a solve is mandatory to any addition (at least to update the DoF of the + // solver), only when the solver geometry is the same in number than the sketch geometry an + // update should trigger a redraw. This reduces even more the number of redraws per + // insertion of geometry // solver information is also updated when no matching geometry, so that if a solving fails // this failed solving info is presented to the user - UpdateSolverInformation(); // just update the solver window with the last SketchObject solving information + UpdateSolverInformation();// just update the solver window with the last SketchObject + // solving information - if(getSketchObject()->getExternalGeometryCount()+getSketchObject()->getHighestCurveIndex() + 1 == - getSolvedSketch().getGeometrySize()) { - Gui::MDIView *mdi = Gui::Application::Instance->editDocument()->getActiveView(); + if (getSketchObject()->getExternalGeometryCount() + + getSketchObject()->getHighestCurveIndex() + 1 + == getSolvedSketch().getGeometrySize()) { + Gui::MDIView* mdi = Gui::Application::Instance->editDocument()->getActiveView(); if (mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) - draw(false,true); + draw(false, true); signalConstraintsChanged(); } - if(prop != &getSketchObject()->Constraints) + if (prop != &getSketchObject()->Constraints) signalElementsChanged(); } } -void ViewProviderSketch::onChanged(const App::Property *prop) +void ViewProviderSketch::onChanged(const App::Property* prop) { if (prop == &VisualLayerList) { - if(isInEditMode()) { + if (isInEditMode()) { // Configure and rebuild Coin SceneGraph editCoinManager->updateGeometryLayersConfiguration(); } @@ -2770,12 +3077,12 @@ void ViewProviderSketch::onChanged(const App::Property *prop) ViewProviderPart::onChanged(prop); } -void ViewProviderSketch::attach(App::DocumentObject *pcFeat) +void ViewProviderSketch::attach(App::DocumentObject* pcFeat) { ViewProviderPart::attach(pcFeat); } -void ViewProviderSketch::setupContextMenu(QMenu *menu, QObject *receiver, const char *member) +void ViewProviderSketch::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { menu->addAction(tr("Edit sketch"), receiver, member); // Call the extensions @@ -2788,10 +3095,10 @@ bool ViewProviderSketch::setEdit(int ModNum) // When double-clicking on the item for this sketch the // object unsets and sets its edit mode without closing // the task panel - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - TaskDlgEditSketch *sketchDlg = qobject_cast(dlg); + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); + TaskDlgEditSketch* sketchDlg = qobject_cast(dlg); if (sketchDlg && sketchDlg->getSketchView() != this) - sketchDlg = nullptr; // another sketch left open its task panel + sketchDlg = nullptr;// another sketch left open its task panel if (dlg && !sketchDlg) { QMessageBox msgBox; msgBox.setText(tr("A dialog is already open in the task panel")); @@ -2814,13 +3121,12 @@ bool ViewProviderSketch::setEdit(int ModNum) box.setInformativeText(tr("The sketch is invalid and cannot be edited.")); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); box.setDefaultButton(QMessageBox::Yes); - switch (box.exec()) - { - case QMessageBox::Yes: - Gui::Control().showDialog(new TaskSketcherValidation(getSketchObject())); - break; - default: - break; + switch (box.exec()) { + case QMessageBox::Yes: + Gui::Control().showDialog(new TaskSketcherValidation(getSketchObject())); + break; + default: + break; } return false; } @@ -2845,47 +3151,54 @@ bool ViewProviderSketch::setEdit(int ModNum) snapManager = std::make_unique(*this); auto editDoc = Gui::Application::Instance->editDocument(); - App::DocumentObject *editObj = getSketchObject(); + App::DocumentObject* editObj = getSketchObject(); std::string editSubName; - ViewProviderDocumentObject *editVp = nullptr; - if(editDoc) { - editDoc->getInEdit(&editVp,&editSubName); - if(editVp) + ViewProviderDocumentObject* editVp = nullptr; + if (editDoc) { + editDoc->getInEdit(&editVp, &editSubName); + if (editVp) editObj = editVp->getObject(); } - //visibility automation - try{ - Gui::Command::addModule(Gui::Command::Gui,"Show"); - try{ - QString cmdstr = QString::fromLatin1( - "ActiveSketch = App.getDocument('%1').getObject('%2')\n" - "tv = Show.TempoVis(App.ActiveDocument, tag= ActiveSketch.ViewObject.TypeId)\n" - "ActiveSketch.ViewObject.TempoVis = tv\n" - "if ActiveSketch.ViewObject.EditingWorkbench:\n" - " tv.activateWorkbench(ActiveSketch.ViewObject.EditingWorkbench)\n" - "if ActiveSketch.ViewObject.HideDependent:\n" - " tv.hide(tv.get_all_dependent(%3, '%4'))\n" - "if ActiveSketch.ViewObject.ShowSupport:\n" - " tv.show([ref[0] for ref in ActiveSketch.Support if not ref[0].isDerivedFrom(\"PartDesign::Plane\")])\n" - "if ActiveSketch.ViewObject.ShowLinks:\n" - " tv.show([ref[0] for ref in ActiveSketch.ExternalGeometry])\n" - "tv.sketchClipPlane(ActiveSketch, ActiveSketch.ViewObject.SectionView)\n" - "tv.hide(ActiveSketch)\n" - "del(tv)\n" - "del(ActiveSketch)\n" - ).arg(QString::fromLatin1(getDocument()->getDocument()->getName()), - QString::fromLatin1(getSketchObject()->getNameInDocument()), - QString::fromLatin1(Gui::Command::getObjectCmd(editObj).c_str()), - QString::fromLatin1(editSubName.c_str())); + // visibility automation + try { + Gui::Command::addModule(Gui::Command::Gui, "Show"); + try { + QString cmdstr = + QString::fromLatin1( + "ActiveSketch = App.getDocument('%1').getObject('%2')\n" + "tv = Show.TempoVis(App.ActiveDocument, tag= ActiveSketch.ViewObject.TypeId)\n" + "ActiveSketch.ViewObject.TempoVis = tv\n" + "if ActiveSketch.ViewObject.EditingWorkbench:\n" + " tv.activateWorkbench(ActiveSketch.ViewObject.EditingWorkbench)\n" + "if ActiveSketch.ViewObject.HideDependent:\n" + " tv.hide(tv.get_all_dependent(%3, '%4'))\n" + "if ActiveSketch.ViewObject.ShowSupport:\n" + " tv.show([ref[0] for ref in ActiveSketch.Support if not " + "ref[0].isDerivedFrom(\"PartDesign::Plane\")])\n" + "if ActiveSketch.ViewObject.ShowLinks:\n" + " tv.show([ref[0] for ref in ActiveSketch.ExternalGeometry])\n" + "tv.sketchClipPlane(ActiveSketch, ActiveSketch.ViewObject.SectionView)\n" + "tv.hide(ActiveSketch)\n" + "del(tv)\n" + "del(ActiveSketch)\n") + .arg(QString::fromLatin1(getDocument()->getDocument()->getName()), + QString::fromLatin1(getSketchObject()->getNameInDocument()), + QString::fromLatin1(Gui::Command::getObjectCmd(editObj).c_str()), + QString::fromLatin1(editSubName.c_str())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); - } catch (Base::PyException &e){ - Base::Console().DeveloperError("ViewProviderSketch","setEdit: visibility automation failed with an error: \n"); + } + catch (Base::PyException& e) { + Base::Console().DeveloperError( + "ViewProviderSketch", "setEdit: visibility automation failed with an error: \n"); e.ReportException(); } - } catch (Base::PyException &){ - Base::Console().DeveloperWarning("ViewProviderSketch", "setEdit: could not import Show module. Visibility automation will not work.\n"); + } + catch (Base::PyException&) { + Base::Console().DeveloperWarning( + "ViewProviderSketch", + "setEdit: could not import Show module. Visibility automation will not work.\n"); } // start the edit dialog @@ -2896,32 +3209,36 @@ bool ViewProviderSketch::setEdit(int ModNum) // This call to the solver is needed to initialize the DoF and solve time controls // The false parameter indicates that the geometry of the SketchObject shall not be updateData - // so as not to trigger an onChanged that would set the document as modified and trigger a recompute - // if we just close the sketch without touching anything. + // so as not to trigger an onChanged that would set the document as modified and trigger a + // recompute if we just close the sketch without touching anything. if (getSketchObject()->Support.getValue()) { if (!getSketchObject()->evaluateSupport()) getSketchObject()->validateExternalLinks(); } - // There are geometry extensions introduced by the solver and geometry extensions introduced by the viewprovider. + // There are geometry extensions introduced by the solver and geometry extensions introduced by + // the viewprovider. // 1. It is important that the solver has geometry with updated extensions. // 2. It is important that the viewprovider has up-to-date solver information // - // The decision is to maintain the "first solve then draw" order, which is consistent with the rest of the Sketcher - // for example in geometry creation. Then, the ViewProvider is responsible for updating the solver geometry when - // appropriate, as it is the ViewProvider that is introducing its geometry extensions. + // The decision is to maintain the "first solve then draw" order, which is consistent with the + // rest of the Sketcher for example in geometry creation. Then, the ViewProvider is responsible + // for updating the solver geometry when appropriate, as it is the ViewProvider that is + // introducing its geometry extensions. // - // In order to have updated solver information, solve must take "true", this cause the Geometry property to be updated - // with the solver information, including solver extensions, and triggers a draw(true) via ViewProvider::UpdateData. + // In order to have updated solver information, solve must take "true", this cause the Geometry + // property to be updated with the solver information, including solver extensions, and triggers + // a draw(true) via ViewProvider::UpdateData. getSketchObject()->solve(true); - connectUndoDocument = getDocument() - ->signalUndoDocument.connect(boost::bind(&ViewProviderSketch::slotUndoDocument, this, bp::_1)); - connectRedoDocument = getDocument() - ->signalRedoDocument.connect(boost::bind(&ViewProviderSketch::slotRedoDocument, this, bp::_1)); + connectUndoDocument = getDocument()->signalUndoDocument.connect( + boost::bind(&ViewProviderSketch::slotUndoDocument, this, bp::_1)); + connectRedoDocument = getDocument()->signalRedoDocument.connect( + boost::bind(&ViewProviderSketch::slotRedoDocument, this, bp::_1)); // Enable solver initial solution update while dragging. - getSketchObject()->setRecalculateInitialSolutionWhileMovingPoint(viewProviderParameters.recalculateInitialSolutionWhileDragging); + getSketchObject()->setRecalculateInitialSolutionWhileMovingPoint( + viewProviderParameters.recalculateInitialSolutionWhileDragging); // intercept del key press from main app listener = new ShortcutListener(this); @@ -2933,37 +3250,37 @@ bool ViewProviderSketch::setEdit(int ModNum) return true; } -QString ViewProviderSketch::appendConflictMsg(const std::vector &conflicting) +QString ViewProviderSketch::appendConflictMsg(const std::vector& conflicting) { return appendConstraintMsg(tr("Please remove the following constraint:"), - tr("Please remove at least one of the following constraints:"), - conflicting); + tr("Please remove at least one of the following constraints:"), + conflicting); } -QString ViewProviderSketch::appendRedundantMsg(const std::vector &redundant) +QString ViewProviderSketch::appendRedundantMsg(const std::vector& redundant) { return appendConstraintMsg(tr("Please remove the following redundant constraint:"), - tr("Please remove the following redundant constraints:"), - redundant); + tr("Please remove the following redundant constraints:"), + redundant); } -QString ViewProviderSketch::appendPartiallyRedundantMsg(const std::vector &partiallyredundant) +QString ViewProviderSketch::appendPartiallyRedundantMsg(const std::vector& partiallyredundant) { return appendConstraintMsg(tr("The following constraint is partially redundant:"), - tr("The following constraints are partially redundant:"), - partiallyredundant); + tr("The following constraints are partially redundant:"), + partiallyredundant); } -QString ViewProviderSketch::appendMalformedMsg(const std::vector &malformed) +QString ViewProviderSketch::appendMalformedMsg(const std::vector& malformed) { return appendConstraintMsg(tr("Please remove the following malformed constraint:"), - tr("Please remove the following malformed constraints:"), - malformed); + tr("Please remove the following malformed constraints:"), + malformed); } -QString ViewProviderSketch::appendConstraintMsg(const QString & singularmsg, - const QString & pluralmsg, - const std::vector &vector) +QString ViewProviderSketch::appendConstraintMsg(const QString& singularmsg, + const QString& pluralmsg, + const std::vector& vector) { QString msg; QTextStream ss(&msg); @@ -2974,7 +3291,7 @@ QString ViewProviderSketch::appendConstraintMsg(const QString & singularmsg, ss << pluralmsg; ss << "\n"; ss << vector[0]; - for (unsigned int i=1; i < vector.size(); i++) + for (unsigned int i = 1; i < vector.size(); i++) ss << ", " << vector[i]; ss << "\n"; @@ -2982,10 +3299,10 @@ QString ViewProviderSketch::appendConstraintMsg(const QString & singularmsg, return msg; } -inline QString intListHelper(const std::vector &ints) +inline QString intListHelper(const std::vector& ints) { QString results; - if (ints.size() < 8) { // The 8 is a bit heuristic... more than that and we shift formats + if (ints.size() < 8) {// The 8 is a bit heuristic... more than that and we shift formats for (const auto i : ints) { if (results.isEmpty()) results.append(QString::fromUtf8("%1").arg(i)); @@ -2999,7 +3316,7 @@ inline QString intListHelper(const std::vector &ints) for (int i = 0; i < numToShow; ++i) { results.append(QString::fromUtf8("%1, ").arg(ints[i])); } - results.append(QCoreApplication::translate("ViewProviderSketch","and %1 more").arg(more)); + results.append(QCoreApplication::translate("ViewProviderSketch", "and %1 more").arg(more)); } std::string testString = results.toStdString(); return results; @@ -3012,48 +3329,54 @@ void ViewProviderSketch::UpdateSolverInformation() bool hasConflicts = getSketchObject()->getLastHasConflicts(); bool hasRedundancies = getSketchObject()->getLastHasRedundancies(); bool hasPartiallyRedundant = getSketchObject()->getLastHasPartialRedundancies(); - bool hasMalformed = getSketchObject()->getLastHasMalformedConstraints(); + bool hasMalformed = getSketchObject()->getLastHasMalformedConstraints(); if (getSketchObject()->Geometry.getSize() == 0) { signalSetUp(QString::fromUtf8("empty_sketch"), tr("Empty sketch"), QString(), QString()); } - else if (dofs < 0 || hasConflicts) { // over-constrained sketch - signalSetUp(QString::fromUtf8("conflicting_constraints"), + else if (dofs < 0 || hasConflicts) {// over-constrained sketch + signalSetUp( + QString::fromUtf8("conflicting_constraints"), tr("Over-constrained: "), QString::fromUtf8("#conflicting"), QString::fromUtf8("(%1)").arg(intListHelper(getSketchObject()->getLastConflicting()))); } - else if (hasMalformed) { // malformed constraints + else if (hasMalformed) {// malformed constraints signalSetUp(QString::fromUtf8("malformed_constraints"), - tr("Malformed constraints: "), - QString::fromUtf8("#malformed"), - QString::fromUtf8("(%1)").arg(intListHelper(getSketchObject()->getLastMalformedConstraints()))); + tr("Malformed constraints: "), + QString::fromUtf8("#malformed"), + QString::fromUtf8("(%1)").arg( + intListHelper(getSketchObject()->getLastMalformedConstraints()))); } else if (hasRedundancies) { - signalSetUp(QString::fromUtf8("redundant_constraints"), + signalSetUp( + QString::fromUtf8("redundant_constraints"), tr("Redundant constraints:"), QString::fromUtf8("#redundant"), QString::fromUtf8("(%1)").arg(intListHelper(getSketchObject()->getLastRedundant()))); } else if (hasPartiallyRedundant) { signalSetUp(QString::fromUtf8("partially_redundant_constraints"), - tr("Partially redundant:"), - QString::fromUtf8("#partiallyredundant"), - QString::fromUtf8("(%1)").arg(intListHelper(getSketchObject()->getLastPartiallyRedundant()))); + tr("Partially redundant:"), + QString::fromUtf8("#partiallyredundant"), + QString::fromUtf8("(%1)").arg( + intListHelper(getSketchObject()->getLastPartiallyRedundant()))); } else if (getSketchObject()->getLastSolverStatus() != 0) { signalSetUp(QString::fromUtf8("solver_failed"), - tr("Solver failed to converge"), - QString::fromUtf8(""), - QString::fromUtf8("")); - } else if (dofs > 0) { + tr("Solver failed to converge"), + QString::fromUtf8(""), + QString::fromUtf8("")); + } + else if (dofs > 0) { signalSetUp(QString::fromUtf8("under_constrained"), - tr("Under constrained:"), - QString::fromUtf8("#dofs"), - tr("%n DoF(s)","",dofs)); + tr("Under constrained:"), + QString::fromUtf8("#dofs"), + tr("%n DoF(s)", "", dofs)); } else { - signalSetUp(QString::fromUtf8("fully_constrained"), tr("Fully constrained"), QString(), QString()); + signalSetUp( + QString::fromUtf8("fully_constrained"), tr("Fully constrained"), QString(), QString()); } } @@ -3067,7 +3390,7 @@ void ViewProviderSketch::unsetEdit(int ModNum) Workbench::leaveEditMode(); - if(listener) { + if (listener) { Gui::getMainWindow()->removeEventFilter(listener); delete listener; } @@ -3094,7 +3417,7 @@ void ViewProviderSketch::unsetEdit(int ModNum) // clear the selection and set the new/edited sketch(convenience) Gui::Selection().clearSelection(); - Gui::Selection().addSelection(editDocName.c_str(),editObjName.c_str(),editSubName.c_str()); + Gui::Selection().addSelection(editDocName.c_str(), editObjName.c_str(), editSubName.c_str()); connectUndoDocument.disconnect(); connectRedoDocument.disconnect(); @@ -3102,81 +3425,90 @@ void ViewProviderSketch::unsetEdit(int ModNum) // when pressing ESC make sure to close the dialog Gui::Control().closeDialog(); - //visibility automation - try{ - QString cmdstr = QString::fromLatin1( - "ActiveSketch = App.getDocument('%1').getObject('%2')\n" - "tv = ActiveSketch.ViewObject.TempoVis\n" - "if tv:\n" - " tv.restore()\n" - "ActiveSketch.ViewObject.TempoVis = None\n" - "del(tv)\n" - "del(ActiveSketch)\n" - ).arg(QString::fromLatin1(getDocument()->getDocument()->getName()), - QString::fromLatin1(getSketchObject()->getNameInDocument())); + // visibility automation + try { + QString cmdstr = + QString::fromLatin1("ActiveSketch = App.getDocument('%1').getObject('%2')\n" + "tv = ActiveSketch.ViewObject.TempoVis\n" + "if tv:\n" + " tv.restore()\n" + "ActiveSketch.ViewObject.TempoVis = None\n" + "del(tv)\n" + "del(ActiveSketch)\n") + .arg(QString::fromLatin1(getDocument()->getDocument()->getName()), + QString::fromLatin1(getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); - } catch (Base::PyException &e){ - Base::Console().DeveloperError("ViewProviderSketch","unsetEdit: visibility automation failed with an error: %s \n", e.what()); + } + catch (Base::PyException& e) { + Base::Console().DeveloperError( + "ViewProviderSketch", + "unsetEdit: visibility automation failed with an error: %s \n", + e.what()); } } void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int ModNum) { Q_UNUSED(ModNum); - //visibility automation: save camera - if (! this->TempoVis.getValue().isNone()){ - try{ - QString cmdstr = QString::fromLatin1( - "ActiveSketch = App.getDocument('%1').getObject('%2')\n" - "if ActiveSketch.ViewObject.RestoreCamera:\n" - " ActiveSketch.ViewObject.TempoVis.saveCamera()\n" - " if ActiveSketch.ViewObject.ForceOrtho:\n" - " ActiveSketch.ViewObject.Document.ActiveView.setCameraType('Orthographic')\n" - ).arg(QString::fromLatin1(getDocument()->getDocument()->getName()), - QString::fromLatin1(getSketchObject()->getNameInDocument())); + // visibility automation: save camera + if (!this->TempoVis.getValue().isNone()) { + try { + QString cmdstr = + QString::fromLatin1( + "ActiveSketch = App.getDocument('%1').getObject('%2')\n" + "if ActiveSketch.ViewObject.RestoreCamera:\n" + " ActiveSketch.ViewObject.TempoVis.saveCamera()\n" + " if ActiveSketch.ViewObject.ForceOrtho:\n" + " " + "ActiveSketch.ViewObject.Document.ActiveView.setCameraType('Orthographic')\n") + .arg(QString::fromLatin1(getDocument()->getDocument()->getName()), + QString::fromLatin1(getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); - } catch (Base::PyException &e){ - Base::Console().DeveloperError("ViewProviderSketch", "setEdit: visibility automation failed with an error: %s \n", e.what()); + } + catch (Base::PyException& e) { + Base::Console().DeveloperError( + "ViewProviderSketch", + "setEdit: visibility automation failed with an error: %s \n", + e.what()); } } auto editDoc = Gui::Application::Instance->editDocument(); editDocName.clear(); - if(editDoc) { - ViewProviderDocumentObject *parent=nullptr; - editDoc->getInEdit(&parent,&editSubName); - if(parent) { + if (editDoc) { + ViewProviderDocumentObject* parent = nullptr; + editDoc->getInEdit(&parent, &editSubName); + if (parent) { editDocName = editDoc->getDocument()->getName(); editObjName = parent->getObject()->getNameInDocument(); } } - if(editDocName.empty()) { + if (editDocName.empty()) { editDocName = getObject()->getDocument()->getName(); editObjName = getObject()->getNameInDocument(); editSubName.clear(); } - const char *dot = strrchr(editSubName.c_str(),'.'); - if(!dot) + const char* dot = strrchr(editSubName.c_str(), '.'); + if (!dot) editSubName.clear(); else - editSubName.resize(dot-editSubName.c_str()+1); + editSubName.resize(dot - editSubName.c_str() + 1); Base::Placement plm = getEditingPlacement(); Base::Rotation tmp(plm.getRotation()); - SbRotation rot((float)tmp[0],(float)tmp[1],(float)tmp[2],(float)tmp[3]); + SbRotation rot((float)tmp[0], (float)tmp[1], (float)tmp[2], (float)tmp[3]); // Will the sketch be visible from the new position (#0000957)? // SoCamera* camera = viewer->getSoRenderManager()->getCamera(); - SbVec3f curdir; // current view direction + SbVec3f curdir;// current view direction camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), curdir); - SbVec3f focal = camera->position.getValue() + - camera->focalDistance.getValue() * curdir; + SbVec3f focal = camera->position.getValue() + camera->focalDistance.getValue() * curdir; - SbVec3f newdir; // future view direction + SbVec3f newdir;// future view direction rot.multVec(SbVec3f(0, 0, -1), newdir); SbVec3f newpos = focal - camera->focalDistance.getValue() * newdir; @@ -3198,7 +3530,7 @@ void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int Mo viewer->setupEditingRoot(); - cameraSensor.setData(new VPRender{this, viewer->getSoRenderManager()}); + cameraSensor.setData(new VPRender {this, viewer->getSoRenderManager()}); cameraSensor.attach(viewer->getSoRenderManager()->getSceneGraph()); } @@ -3214,9 +3546,9 @@ void ViewProviderSketch::unsetEditViewer(Gui::View3DInventorViewer* viewer) viewer->setSelectionEnabled(true); } -void ViewProviderSketch::camSensCB(void *data, SoSensor *) +void ViewProviderSketch::camSensCB(void* data, SoSensor*) { - VPRender *proxyVPrdr = static_cast(data); + VPRender* proxyVPrdr = static_cast(data); if (!proxyVPrdr) return; @@ -3228,22 +3560,27 @@ void ViewProviderSketch::camSensCB(void *data, SoSensor *) void ViewProviderSketch::onCameraChanged(SoCamera* cam) { - auto rotSk = Base::Rotation(getDocument()->getEditingTransform()); //sketch orientation + auto rotSk = Base::Rotation(getDocument()->getEditingTransform());// sketch orientation auto rotc = cam->orientation.getValue().getValue(); - auto rotCam = Base::Rotation(rotc[0], rotc[1], rotc[2], rotc[3]); // camera orientation (needed because float to double conversion) + auto rotCam = + Base::Rotation(rotc[0], + rotc[1], + rotc[2], + rotc[3]);// camera orientation (needed because float to double conversion) // Is camera in the same hemisphere as positive sketch normal ? auto orientation = (rotCam.invert() * rotSk).multVec(Base::Vector3d(0, 0, 1)); auto tmpFactor = orientation.z < 0 ? -1 : 1; - if (tmpFactor != viewOrientationFactor) { // redraw only if viewing side changed - Base::Console().Log("Switching side, now %s, redrawing\n", tmpFactor < 0 ? "back" : "front"); + if (tmpFactor != viewOrientationFactor) {// redraw only if viewing side changed + Base::Console().Log("Switching side, now %s, redrawing\n", + tmpFactor < 0 ? "back" : "front"); viewOrientationFactor = tmpFactor; draw(); - QString cmdStr = QStringLiteral( - "ActiveSketch.ViewObject.TempoVis.sketchClipPlane(ActiveSketch, ActiveSketch.ViewObject.SectionView, %1)\n") - .arg(tmpFactor < 0 ? QLatin1String("True") : QLatin1String("False")); + QString cmdStr = QStringLiteral("ActiveSketch.ViewObject.TempoVis.sketchClipPlane(" + "ActiveSketch, ActiveSketch.ViewObject.SectionView, %1)\n") + .arg(tmpFactor < 0 ? QLatin1String("True") : QLatin1String("False")); Base::Interpreter().runStringObject(cmdStr.toLatin1()); } @@ -3266,20 +3603,21 @@ int ViewProviderSketch::getPreselectCurve() const int ViewProviderSketch::getPreselectCross() const { - // TODO: This function spreads over several files. It should be refactored into something less "numeric" at a second stage. + // TODO: This function spreads over several files. It should be refactored into something less + // "numeric" at a second stage. if (isInEditMode()) return static_cast(preselection.PreselectCross); return -1; } -Sketcher::SketchObject *ViewProviderSketch::getSketchObject() const +Sketcher::SketchObject* ViewProviderSketch::getSketchObject() const { - return dynamic_cast(pcObject); + return dynamic_cast(pcObject); } -const Sketcher::Sketch &ViewProviderSketch::getSolvedSketch() const +const Sketcher::Sketch& ViewProviderSketch::getSolvedSketch() const { - return const_cast(getSketchObject())->getSolvedSketch(); + return const_cast(getSketchObject())->getSolvedSketch(); } void ViewProviderSketch::deleteSelected() @@ -3289,14 +3627,16 @@ void ViewProviderSketch::deleteSelected() // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { - Base::Console().DeveloperWarning("ViewProviderSketch", "Delete: Selection not restricted to one sketch and its subelements\n"); + Base::Console().DeveloperWarning( + "ViewProviderSketch", + "Delete: Selection not restricted to one sketch and its subelements\n"); return; } // get the needed lists and objects - const std::vector &SubNames = selection[0].getSubNames(); + const std::vector& SubNames = selection[0].getSubNames(); - if(!SubNames.empty()) { + if (!SubNames.empty()) { App::Document* doc = getSketchObject()->getDocument(); doc->openTransaction("Delete sketch geometry"); @@ -3307,7 +3647,7 @@ void ViewProviderSketch::deleteSelected() } } -bool ViewProviderSketch::onDelete(const std::vector &subList) +bool ViewProviderSketch::onDelete(const std::vector& subList) { if (isInEditMode()) { std::vector SubNames = subList; @@ -3317,41 +3657,46 @@ bool ViewProviderSketch::onDelete(const std::vector &subList) std::set delInternalGeometries, delExternalGeometries, delCoincidents, delConstraints; // go through the selected subelements - for (std::vector::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { - if (it->size() > 4 && it->substr(0,4) == "Edge") { - int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; - if( GeoId >= 0 ) { + for (std::vector::const_iterator it = SubNames.begin(); it != SubNames.end(); + ++it) { + if (it->size() > 4 && it->substr(0, 4) == "Edge") { + int GeoId = std::atoi(it->substr(4, 4000).c_str()) - 1; + if (GeoId >= 0) { delInternalGeometries.insert(GeoId); } else delExternalGeometries.insert(Sketcher::GeoEnum::RefExt - GeoId); - } else if (it->size() > 12 && it->substr(0,12) == "ExternalEdge") { - int GeoId = std::atoi(it->substr(12,4000).c_str()) - 1; + } + else if (it->size() > 12 && it->substr(0, 12) == "ExternalEdge") { + int GeoId = std::atoi(it->substr(12, 4000).c_str()) - 1; delExternalGeometries.insert(GeoId); - } else if (it->size() > 6 && it->substr(0,6) == "Vertex") { - int VtId = std::atoi(it->substr(6,4000).c_str()) - 1; + } + else if (it->size() > 6 && it->substr(0, 6) == "Vertex") { + int VtId = std::atoi(it->substr(6, 4000).c_str()) - 1; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(VtId, GeoId, PosId); if (getSketchObject()->getGeometry(GeoId)->getTypeId() == Part::GeomPoint::getClassTypeId()) { - if(GeoId>=0) + if (GeoId >= 0) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(Sketcher::GeoEnum::RefExt - GeoId); } else delCoincidents.insert(VtId); - } else if (*it == "RootPoint") { + } + else if (*it == "RootPoint") { delCoincidents.insert(Sketcher::GeoEnum::RtPnt); - } else if (it->size() > 10 && it->substr(0,10) == "Constraint") { + } + else if (it->size() > 10 && it->substr(0, 10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); delConstraints.insert(ConstrId); } } // We stored the vertices, but is there really a coincident constraint? Check - const std::vector< Sketcher::Constraint * > &vals = getSketchObject()->Constraints.getValues(); + const std::vector& vals = getSketchObject()->Constraints.getValues(); std::set::const_reverse_iterator rit; @@ -3368,20 +3713,24 @@ bool ViewProviderSketch::onDelete(const std::vector &subList) int GeoId; PointPos PosId; - if (*rit == GeoEnum::RtPnt) { // RootPoint + if (*rit == GeoEnum::RtPnt) {// RootPoint GeoId = Sketcher::GeoEnum::RtPnt; PosId = Sketcher::PointPos::start; - - } else { + } + else { getSketchObject()->getGeoVertexIndex(*rit, GeoId, PosId); } if (GeoId != GeoEnum::GeoUndef) { - for (std::vector< Sketcher::Constraint * >::const_iterator it= vals.begin(); it != vals.end(); ++it) { - if (((*it)->Type == Sketcher::Coincident) && (((*it)->First == GeoId && (*it)->FirstPos == PosId) || - ((*it)->Second == GeoId && (*it)->SecondPos == PosId)) ) { + for (std::vector::const_iterator it = vals.begin(); + it != vals.end(); + ++it) { + if (((*it)->Type == Sketcher::Coincident) + && (((*it)->First == GeoId && (*it)->FirstPos == PosId) + || ((*it)->Second == GeoId && (*it)->SecondPos == PosId))) { try { - Gui::cmdAppObjectArgs(getObject(), "delConstraintOnPoint(%d,%d)", GeoId, (int)PosId); + Gui::cmdAppObjectArgs( + getObject(), "delConstraintOnPoint(%d,%d)", GeoId, (int)PosId); } catch (const Base::Exception& e) { Base::Console().DeveloperError("ViewProviderSketch", "%s\n", e.what()); @@ -3392,11 +3741,11 @@ bool ViewProviderSketch::onDelete(const std::vector &subList) } } - if(!delInternalGeometries.empty()) { + if (!delInternalGeometries.empty()) { std::stringstream stream; - // NOTE: SketchObject delGeometries will sort the array, so filling it here with a reverse iterator would - // lead to the worst case scenario for sorting. + // NOTE: SketchObject delGeometries will sort the array, so filling it here with a + // reverse iterator would lead to the worst case scenario for sorting. auto endit = std::prev(delInternalGeometries.end()); for (auto it = delInternalGeometries.begin(); it != endit; ++it) { stream << *it << ","; @@ -3423,13 +3772,13 @@ bool ViewProviderSketch::onDelete(const std::vector &subList) } } - int ret=getSketchObject()->solve(); + int ret = getSketchObject()->solve(); - if(ret!=0){ + if (ret != 0) { // if the sketched could not be solved, we first redraw to update the UI geometry as // onChanged did not update it. UpdateSolverInformation(); - draw(false,true); + draw(false, true); signalConstraintsChanged(); signalElementsChanged(); @@ -3459,49 +3808,49 @@ bool ViewProviderSketch::onDelete(const std::vector &subList) return PartGui::ViewProviderPart::onDelete(subList); } -QIcon ViewProviderSketch::mergeColorfulOverlayIcons (const QIcon & orig) const +QIcon ViewProviderSketch::mergeColorfulOverlayIcons(const QIcon& orig) const { QIcon mergedicon = orig; - if(!getSketchObject()->FullyConstrained.getValue()) { + if (!getSketchObject()->FullyConstrained.getValue()) { QPixmap px; - static const char * const sketcher_notfullyconstrained_xpm[]={ - "9 9 3 1", - ". c None", - "# c #dbaf00", - "a c #ffcc00", - "##.....##", - "#a#...#a#", - "#aa#.#aa#", - ".#a#.#a#.", - ".#a#.#a#.", - ".#a#.#a#.", - "#aa#.#aa#", - "#a#...#a#", - "##.....##"}; - px = QPixmap( sketcher_notfullyconstrained_xpm ); - - mergedicon = Gui::BitmapFactoryInst::mergePixmap(mergedicon, px, Gui::BitmapFactoryInst::BottomRight); + static const char* const sketcher_notfullyconstrained_xpm[] = {"9 9 3 1", + ". c None", + "# c #dbaf00", + "a c #ffcc00", + "##.....##", + "#a#...#a#", + "#aa#.#aa#", + ".#a#.#a#.", + ".#a#.#a#.", + ".#a#.#a#.", + "#aa#.#aa#", + "#a#...#a#", + "##.....##"}; + px = QPixmap(sketcher_notfullyconstrained_xpm); + mergedicon = Gui::BitmapFactoryInst::mergePixmap( + mergedicon, px, Gui::BitmapFactoryInst::BottomRight); } - return Gui::ViewProvider::mergeColorfulOverlayIcons (mergedicon); + return Gui::ViewProvider::mergeColorfulOverlayIcons(mergedicon); } -/*************************** functions ViewProviderSketch offers to friends such as DrawHandlerSketch ************************/ +/*************************** functions ViewProviderSketch offers to friends such as + * DrawHandlerSketch ************************/ void ViewProviderSketch::setConstraintSelectability(bool enabled /*= true*/) { editCoinManager->setConstraintSelectability(enabled); } -void ViewProviderSketch::setPositionText(const Base::Vector2d &Pos, const SbString &text) +void ViewProviderSketch::setPositionText(const Base::Vector2d& Pos, const SbString& text) { - editCoinManager->setPositionText(Pos,text); + editCoinManager->setPositionText(Pos, text); } -void ViewProviderSketch::setPositionText(const Base::Vector2d &Pos) +void ViewProviderSketch::setPositionText(const Base::Vector2d& Pos) { editCoinManager->setPositionText(Pos); } @@ -3515,7 +3864,8 @@ void ViewProviderSketch::setPreselectPoint(int PreselectPoint) { preselection.PreselectPoint = PreselectPoint; preselection.PreselectCurve = Preselection::InvalidCurve; - preselection.PreselectCross = Preselection::Axes::None;; + preselection.PreselectCross = Preselection::Axes::None; + ; preselection.PreselectConstraintSet.clear(); } @@ -3532,7 +3882,8 @@ void ViewProviderSketch::resetPreselectPoint() { preselection.PreselectPoint = Preselection::InvalidPoint; preselection.PreselectCurve = Preselection::InvalidCurve; - preselection.PreselectCross = Preselection::Axes::None;; + preselection.PreselectCross = Preselection::Axes::None; + ; preselection.PreselectConstraintSet.clear(); } @@ -3551,44 +3902,53 @@ void ViewProviderSketch::clearSelectPoints() selection.SelPointSet.clear(); } -bool ViewProviderSketch::isSelected(const std::string &subNameSuffix) const +bool ViewProviderSketch::isSelected(const std::string& subNameSuffix) const { - return Gui::Selection().isSelected(editDocName.c_str(), editObjName.c_str(), (editSubName+subNameSuffix).c_str()); + return Gui::Selection().isSelected( + editDocName.c_str(), editObjName.c_str(), (editSubName + subNameSuffix).c_str()); } -void ViewProviderSketch::rmvSelection(const std::string &subNameSuffix) +void ViewProviderSketch::rmvSelection(const std::string& subNameSuffix) { - Gui::Selection().rmvSelection(editDocName.c_str(), editObjName.c_str(), (editSubName+subNameSuffix).c_str()); + Gui::Selection().rmvSelection( + editDocName.c_str(), editObjName.c_str(), (editSubName + subNameSuffix).c_str()); } -bool ViewProviderSketch::addSelection(const std::string &subNameSuffix, float x, float y, float z) +bool ViewProviderSketch::addSelection(const std::string& subNameSuffix, float x, float y, float z) { - return Gui::Selection().addSelection(editDocName.c_str(), editObjName.c_str(), (editSubName+subNameSuffix).c_str(), x , y, z); + return Gui::Selection().addSelection( + editDocName.c_str(), editObjName.c_str(), (editSubName + subNameSuffix).c_str(), x, y, z); } -bool ViewProviderSketch::addSelection2(const std::string &subNameSuffix, float x, float y, float z) +bool ViewProviderSketch::addSelection2(const std::string& subNameSuffix, float x, float y, float z) { - return Gui::Selection().addSelection2(editDocName.c_str(), editObjName.c_str(), (editSubName+subNameSuffix).c_str(), x , y, z); + return Gui::Selection().addSelection2( + editDocName.c_str(), editObjName.c_str(), (editSubName + subNameSuffix).c_str(), x, y, z); } -bool ViewProviderSketch::setPreselect(const std::string &subNameSuffix, float x, float y, float z) +bool ViewProviderSketch::setPreselect(const std::string& subNameSuffix, float x, float y, float z) { - return Gui::Selection().setPreselect(editDocName.c_str(), editObjName.c_str(), (editSubName+subNameSuffix).c_str(), x , y, z); + return Gui::Selection().setPreselect( + editDocName.c_str(), editObjName.c_str(), (editSubName + subNameSuffix).c_str(), x, y, z); } -/*************************** private functions to decouple Attorneys and Clients ********************************************/ +/*************************** private functions to decouple Attorneys and Clients + * ********************************************/ -// Establishes a private collaboration interface with EditModeCoinManager to perform EditModeCoinManager tasks, while abstracting EditModeCoinManager -// from the specific ViewProviderSketch implementation, while allowing ViewProviderSketch to fully delegate coin management. +// Establishes a private collaboration interface with EditModeCoinManager to perform +// EditModeCoinManager tasks, while abstracting EditModeCoinManager from the specific +// ViewProviderSketch implementation, while allowing ViewProviderSketch to fully delegate coin +// management. -const std::vector ViewProviderSketch::getConstraints() const +const std::vector ViewProviderSketch::getConstraints() const { return getSketchObject()->Constraints.getValues(); } const GeoList ViewProviderSketch::getGeoList() const { - const std::vector tempGeo = getSketchObject()->getCompleteGeometry(); // without memory allocation + const std::vector tempGeo = + getSketchObject()->getCompleteGeometry();// without memory allocation int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; @@ -3605,10 +3965,11 @@ bool ViewProviderSketch::constraintHasExpression(int constrid) const std::unique_ptr ViewProviderSketch::getRayPickAction() const { assert(isInEditMode()); - Gui::MDIView *mdi = Gui::Application::Instance->editViewOfNode(editCoinManager->getRootEditNode()); + Gui::MDIView* mdi = + Gui::Application::Instance->editViewOfNode(editCoinManager->getRootEditNode()); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return nullptr; - Gui::View3DInventorViewer *viewer = static_cast(mdi)->getViewer(); + Gui::View3DInventorViewer* viewer = static_cast(mdi)->getViewer(); return std::make_unique(viewer->getSoRenderManager()->getViewportRegion()); } @@ -3621,21 +3982,21 @@ SbVec2f ViewProviderSketch::getScreenCoordinates(SbVec2f sketchcoordinates) cons Base::Rotation sketchRot(sketchPlacement.getRotation()); // get global coordinates from sketcher coordinates - Base::Vector3d pos(sketchcoordinates[0], sketchcoordinates[1],0); - sketchRot.multVec(pos,pos); + Base::Vector3d pos(sketchcoordinates[0], sketchcoordinates[1], 0); + sketchRot.multVec(pos, pos); pos = pos + sketchPos; - Gui::MDIView *mdi = this->getActiveView(); - Gui::View3DInventor *view = qobject_cast(mdi); + Gui::MDIView* mdi = this->getActiveView(); + Gui::View3DInventor* view = qobject_cast(mdi); if (!view || !isInEditMode()) - return SbVec2f(0,0); + return SbVec2f(0, 0); Gui::View3DInventorViewer* viewer = view->getViewer(); SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) - return SbVec2f(0,0); + return SbVec2f(0, 0); SbViewVolume vol = pCam->getViewVolume(); Gui::ViewVolumeProjection proj(vol); @@ -3643,23 +4004,22 @@ SbVec2f ViewProviderSketch::getScreenCoordinates(SbVec2f sketchcoordinates) cons // dimensionless [0 1] (or 1.5 see View3DInventorViewer.cpp ) Base::Vector3d screencoords = proj(pos); - int width = viewer->getGLWidget()->width(), - height = viewer->getGLWidget()->height(); + int width = viewer->getGLWidget()->width(), height = viewer->getGLWidget()->height(); if (width >= height) { // "Landscape" orientation, to square screencoords.x *= height; - screencoords.x += (width-height) / 2.0; + screencoords.x += (width - height) / 2.0; screencoords.y *= height; } else { // "Portrait" orientation screencoords.x *= width; screencoords.y *= width; - screencoords.y += (height-width) / 2.0; + screencoords.y += (height - width) / 2.0; } - SbVec2f iconCoords(screencoords.x,screencoords.y); + SbVec2f iconCoords(screencoords.x, screencoords.y); return iconCoords; } @@ -3675,22 +4035,25 @@ int ViewProviderSketch::defaultFontSizePixels() const return static_cast(metrics.height()); } -int ViewProviderSketch::getApplicationLogicalDPIX() const { +int ViewProviderSketch::getApplicationLogicalDPIX() const +{ return int(QApplication::primaryScreen()->logicalDotsPerInchX()); } -int ViewProviderSketch::getViewOrientationFactor() const { +int ViewProviderSketch::getViewOrientationFactor() const +{ return viewOrientationFactor; } double ViewProviderSketch::getRotation(SbVec3f pos0, SbVec3f pos1) const { - double x0,y0,x1,y1; + double x0, y0, x1, y1; - Gui::MDIView *mdi = Gui::Application::Instance->editViewOfNode(editCoinManager->getRootEditNode()); + Gui::MDIView* mdi = + Gui::Application::Instance->editViewOfNode(editCoinManager->getRootEditNode()); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return 0; - Gui::View3DInventorViewer *viewer = static_cast(mdi)->getViewer(); + Gui::View3DInventorViewer* viewer = static_cast(mdi)->getViewer(); SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return 0; @@ -3698,10 +4061,10 @@ double ViewProviderSketch::getRotation(SbVec3f pos0, SbVec3f pos1) const try { SbViewVolume vol = pCam->getViewVolume(); - getCoordsOnSketchPlane(pos0,vol.getProjectionDirection(),x0,y0); - getCoordsOnSketchPlane(pos1,vol.getProjectionDirection(),x1,y1); + getCoordsOnSketchPlane(pos0, vol.getProjectionDirection(), x0, y0); + getCoordsOnSketchPlane(pos1, vol.getProjectionDirection(), x1, y1); - return -atan2((y1-y0),(x1-x0))*180/M_PI; + return -atan2((y1 - y0), (x1 - x0)) * 180 / M_PI; } catch (const Base::ZeroDivisionError&) { return 0; @@ -3717,9 +4080,9 @@ GeoListFacade ViewProviderSketch::getGeoListFacade() const bool ViewProviderSketch::isSketchInvalid() const { - bool sketchinvalid = getSketchObject()->getLastHasRedundancies() || - getSketchObject()->getLastHasConflicts() || - getSketchObject()->getLastHasMalformedConstraints(); + bool sketchinvalid = getSketchObject()->getLastHasRedundancies() + || getSketchObject()->getLastHasConflicts() + || getSketchObject()->getLastHasMalformedConstraints(); return sketchinvalid; } @@ -3733,12 +4096,12 @@ bool ViewProviderSketch::haveConstraintsInvalidGeometry() const return getSketchObject()->Constraints.hasInvalidGeometry(); } -void ViewProviderSketch::addNodeToRoot(SoSeparator * node) +void ViewProviderSketch::addNodeToRoot(SoSeparator* node) { pcRoot->addChild(node); } -void ViewProviderSketch::removeNodeFromRoot(SoSeparator * node) +void ViewProviderSketch::removeNodeFromRoot(SoSeparator* node) { pcRoot->removeChild(node); } @@ -3763,9 +4126,10 @@ bool ViewProviderSketch::isConstraintSelected(int constraintId) const return selection.SelConstraintSet.find(constraintId) != selection.SelConstraintSet.end(); } -void ViewProviderSketch::executeOnSelectionPointSet(std::function && operation) const +void ViewProviderSketch::executeOnSelectionPointSet( + std::function&& operation) const { - for(const auto v : selection.SelPointSet) + for (const auto v : selection.SelPointSet) operation(v); } diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.h b/src/Mod/Sketcher/Gui/ViewProviderSketch.h index f8280420ff..86aff41e2d 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.h @@ -23,11 +23,11 @@ #ifndef SKETCHERGUI_VIEWPROVIDERSKETCH_H #define SKETCHERGUI_VIEWPROVIDERSKETCH_H -#include -#include -#include #include #include +#include +#include +#include #include #include @@ -35,8 +35,8 @@ #include #include #include -#include #include +#include #include #include "PropertyVisualLayerList.h" @@ -68,21 +68,25 @@ class SoTranslation; class SbString; class SbTime; -namespace Part { - class Geometry; +namespace Part +{ +class Geometry; } -namespace Gui { - class View3DInventorViewer; +namespace Gui +{ +class View3DInventorViewer; } -namespace Sketcher { - class Constraint; - class Sketch; - class SketchObject; -} +namespace Sketcher +{ +class Constraint; +class Sketch; +class SketchObject; +}// namespace Sketcher -namespace SketcherGui { +namespace SketcherGui +{ class EditModeCoinManager; class SnapManager; @@ -131,18 +135,18 @@ using GeoListFacade = Sketcher::GeoListFacade; * markers necessary to enable visual feedback to the user, as well as the UI interaction during * such edits. This is its exclusive responsibility under the Single Responsibility Principle. * - * A plethora of speciliased handlers derive from DrawSketchHandler for each specialised editing (see - * for example all the handlers for creation of new geometry). These derived classes do * not * have - * direct access to the ViewProviderSketchDrawSketchHandlerAttorney. This is intended to keep coupling - * under control. However, generic functionality requiring access to the Attorney can be implemented - * in DrawSketchHandler and used from its derived classes by virtue of the inheritance. This promotes a - * concentrating the coupling in a single point (and code reuse). + * A plethora of speciliased handlers derive from DrawSketchHandler for each specialised editing + * (see for example all the handlers for creation of new geometry). These derived classes do * not * + * have direct access to the ViewProviderSketchDrawSketchHandlerAttorney. This is intended to keep + * coupling under control. However, generic functionality requiring access to the Attorney can be + * implemented in DrawSketchHandler and used from its derived classes by virtue of the inheritance. + * This promotes a concentrating the coupling in a single point (and code reuse). * */ -class SketcherGuiExport ViewProviderSketch : public PartGui::ViewProvider2DObject - , public PartGui::ViewProviderGridExtension - , public PartGui::ViewProviderAttachExtension - , public Gui::SelectionObserver +class SketcherGuiExport ViewProviderSketch: public PartGui::ViewProvider2DObject, + public PartGui::ViewProviderGridExtension, + public PartGui::ViewProviderAttachExtension, + public Gui::SelectionObserver { Q_DECLARE_TR_FUNCTIONS(SketcherGui::ViewProviderSketch) @@ -155,10 +159,10 @@ private: * ViewProviderSketch, initialising the ViewProviderSketch to the current configuration * and handle in real time any change to their values. */ - class ParameterObserver : public ParameterGrp::ObserverType + class ParameterObserver: public ParameterGrp::ObserverType { public: - explicit ParameterObserver(ViewProviderSketch & client); + explicit ParameterObserver(ViewProviderSketch& client); ~ParameterObserver(); void initParameters(); @@ -168,25 +172,31 @@ private: void unsubscribeToParameters(); /** Observer for parameter group. */ - void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject& rCaller, const char* sReason) override; private: + void updateBoolProperty(const std::string& string, App::Property* property, + bool defaultvalue); + void updateGridSize(const std::string& string, App::Property* property); - void updateBoolProperty(const std::string & string, App::Property * property, bool defaultvalue); - void updateGridSize(const std::string & string, App::Property * property); + // Only for colors outside of edit mode, edit mode colors are handled by + // EditModeCoinManager. + void updateColorProperty(const std::string& string, App::Property* property, float r, + float g, float b); - // Only for colors outside of edit mode, edit mode colors are handled by EditModeCoinManager. - void updateColorProperty(const std::string & string, App::Property * property, float r, float g, float b); + void updateEscapeKeyBehaviour(const std::string& string, App::Property* property); - void updateEscapeKeyBehaviour(const std::string & string, App::Property * property); + void updateAutoRecompute(const std::string& string, App::Property* property); - void updateAutoRecompute(const std::string & string, App::Property * property); - - void updateRecalculateInitialSolutionWhileDragging(const std::string & string, App::Property * property); + void updateRecalculateInitialSolutionWhileDragging(const std::string& string, + App::Property* property); private: - ViewProviderSketch &Client; - std::map, App::Property * >> parameterMap; + ViewProviderSketch& Client; + std::map, + App::Property*>> + parameterMap; }; /** @name Classes storing the state of Dragging, Selection and Preselection @@ -212,108 +222,131 @@ private: * (2) In SketchObject.cpp, the actual document object, both {GeoId, PointPos} and VertexId * are used (see VertexId2GeoId and VertexId2GeoPosId). * - * (3) In ViewProviderSketch, both {GeoId, PointPos} an Point indices are used (see these structures) + * (3) In ViewProviderSketch, both {GeoId, PointPos} an Point indices are used (see these + * structures) * - * (4) At CoinManager level, {GeoId, PointPos}, Point indices (for selection) and MultiFieldIds (specific - * structure defining a coin multifield index and layer) are used. + * (4) At CoinManager level, {GeoId, PointPos}, Point indices (for selection) and MultiFieldIds + * (specific structure defining a coin multifield index and layer) are used. * - * Using a single index instead of a multi-index field, allows mappings to be implemented via std::vectors - * instead of std::maps. Direct mappings using std::vectors are accessed in constant time. Multi-index mappings - * relying on std::maps involve a search for the key. This leads to a drop in performance. + * Using a single index instead of a multi-index field, allows mappings to be implemented via + * std::vectors instead of std::maps. Direct mappings using std::vectors are accessed in + * constant time. Multi-index mappings relying on std::maps involve a search for the key. This + * leads to a drop in performance. * * What are these indices and how do they relate each other? - * 1. PointId, VertexId depend on the order of the geometries in the sketch. GeoList and GeoListFacade enable to - * convert between indices. + * 1. PointId, VertexId depend on the order of the geometries in the sketch. GeoList and + * GeoListFacade enable to convert between indices. * 2. CurveId is basically the GeoId assuming PointPos to be PointPos::none (edge) - * 3. Sometimes, Axes and root point are separated into a third index or enum. Legacy reasons aside, the root point - * is has GeoId=-1, which is sometimes used as invalid value in positive only indices. Additionally, root point and - * the Horizontal Axes both have GeoId=-1 (differing in PointPos only). Following the decision not to rely on PointPos, - * creating a separate index, best when enum-ed, appears justified. + * 3. Sometimes, Axes and root point are separated into a third index or enum. Legacy reasons + * aside, the root point is has GeoId=-1, which is sometimes used as invalid value in positive + * only indices. Additionally, root point and the Horizontal Axes both have GeoId=-1 (differing + * in PointPos only). Following the decision not to rely on PointPos, creating a separate index, + * best when enum-ed, appears justified. */ //@{ /** @brief Class to store vector and item Id for dragging. - * - * @details - * Ids are zero-indexed points and curves. - * - * The DragPoint indexing matches PreselectPoint indexing. - * - */ - class Drag { + * + * @details + * Ids are zero-indexed points and curves. + * + * The DragPoint indexing matches PreselectPoint indexing. + * + */ + class Drag + { public: - enum SpecialValues { + enum SpecialValues + { InvalidPoint = -1, InvalidCurve = -1 }; - Drag() { + Drag() + { resetVector(); resetIds(); } - void resetVector() { + void resetVector() + { xInit = 0; yInit = 0; relative = false; } - void resetIds() { + void resetIds() + { DragPoint = InvalidPoint; DragCurve = InvalidCurve; DragConstraintSet.clear(); } - bool isDragPointValid() { return DragPoint > InvalidPoint;} - bool isDragCurveValid() { return DragCurve > InvalidCurve;} + bool isDragPointValid() + { + return DragPoint > InvalidPoint; + } + bool isDragCurveValid() + { + return DragCurve > InvalidCurve; + } - double xInit, yInit; // starting point of the dragging operation - bool relative; // whether the dragging move vector is relative or absolute + double xInit, yInit;// starting point of the dragging operation + bool relative; // whether the dragging move vector is relative or absolute - int DragPoint; // dragged point id (only positive integers) - int DragCurve; // dragged curve id (only positive integers), negative external curves cannot be dragged. - std::set DragConstraintSet; // dragged constraints ids + int DragPoint;// dragged point id (only positive integers) + int DragCurve;// dragged curve id (only positive integers), negative external curves cannot + // be dragged. + std::set DragConstraintSet;// dragged constraints ids }; - // TODO: Selection and Preselection should use a same structure. Probably Drag should use the same structure too. To be refactored separately. + // TODO: Selection and Preselection should use a same structure. Probably Drag should use the + // same structure too. To be refactored separately. /** @brief Class to store preselected element ids. - * - * @details - * - * PreselectPoint is the positive VertexId. - * - * PreselectCurve is the GeoID, but without the Axes (indices -1 and -2). - * - * VertexN, with N = PreselectPoint + 1, same as DragPoint indexing (NOTE -1 is NOT the root point) - * - * EdgeN, with N = PreselectCurve + 1 for positive values ; ExternalEdgeN, with N = -PreselectCurve - 2 - * - * The PreselectPoint indexing matches DragPoint indexing (it further includes negative edges, which are - * not meaningful for Dragging). - * - */ - class Preselection { + * + * @details + * + * PreselectPoint is the positive VertexId. + * + * PreselectCurve is the GeoID, but without the Axes (indices -1 and -2). + * + * VertexN, with N = PreselectPoint + 1, same as DragPoint indexing (NOTE -1 is NOT the root + * point) + * + * EdgeN, with N = PreselectCurve + 1 for positive values ; ExternalEdgeN, with N = + * -PreselectCurve - 2 + * + * The PreselectPoint indexing matches DragPoint indexing (it further includes negative edges, + * which are not meaningful for Dragging). + * + */ + class Preselection + { public: - enum SpecialValues { + enum SpecialValues + { InvalidPoint = -1, InvalidCurve = -1, ExternalCurve = -3 }; - enum class Axes { + enum class Axes + { None = -1, RootPoint = 0, HorizontalAxis = 1, VerticalAxis = 2 }; - Preselection() { + Preselection() + { reset(); } - void reset(){ + void reset() + { PreselectPoint = InvalidPoint; PreselectCurve = InvalidCurve; PreselectCross = Axes::None; @@ -321,80 +354,116 @@ private: blockedPreselection = false; } - bool isPreselectPointValid() const { return PreselectPoint > InvalidPoint;} - bool isPreselectCurveValid() const { return PreselectCurve > InvalidCurve || PreselectCurve <= ExternalCurve;} - bool isCrossPreselected() const { return PreselectCross != Axes::None;} - bool isEdge() const { return PreselectCurve > InvalidCurve;} - bool isExternalEdge() const { return PreselectCurve <= ExternalCurve;} + bool isPreselectPointValid() const + { + return PreselectPoint > InvalidPoint; + } + bool isPreselectCurveValid() const + { + return PreselectCurve > InvalidCurve || PreselectCurve <= ExternalCurve; + } + bool isCrossPreselected() const + { + return PreselectCross != Axes::None; + } + bool isEdge() const + { + return PreselectCurve > InvalidCurve; + } + bool isExternalEdge() const + { + return PreselectCurve <= ExternalCurve; + } - int getPreselectionVertexIndex() const { return PreselectPoint + 1;} - int getPreselectionEdgeIndex() const { return PreselectCurve + 1;} - int getPreselectionExternalEdgeIndex() const { return -PreselectCurve - 2;} + int getPreselectionVertexIndex() const + { + return PreselectPoint + 1; + } + int getPreselectionEdgeIndex() const + { + return PreselectCurve + 1; + } + int getPreselectionExternalEdgeIndex() const + { + return -PreselectCurve - 2; + } - int PreselectPoint; // VertexN, with N = PreselectPoint + 1, same as DragPoint indexing (NOTE -1 is NOT the root point) - int PreselectCurve; // EdgeN, with N = PreselectCurve + 1 for positive values ; ExternalEdgeN, with N = -PreselectCurve - 2 - Axes PreselectCross; // 0 => rootPoint, 1 => HAxis, 2 => VAxis - std::set PreselectConstraintSet; // ConstraintN, N = index + 1 + int PreselectPoint;// VertexN, with N = PreselectPoint + 1, same as DragPoint indexing (NOTE + // -1 is NOT the root point) + int PreselectCurve;// EdgeN, with N = PreselectCurve + 1 for positive values ; + // ExternalEdgeN, with N = -PreselectCurve - 2 + Axes PreselectCross; // 0 => rootPoint, 1 => HAxis, 2 => VAxis + std::set PreselectConstraintSet;// ConstraintN, N = index + 1 bool blockedPreselection; }; /** @brief Class to store selected element ids. - * - * @details - * Selection follows yet a different mechanism than preselection. - * - * SelPointSet indices as PreselectPoint, with the addition that -1 is indeed the rootpoint. - * - * SelCurvSet indices as PreselectCurve, with the addition that -1 is the HAxis and -2 is the VAxis - * - */ - class Selection { + * + * @details + * Selection follows yet a different mechanism than preselection. + * + * SelPointSet indices as PreselectPoint, with the addition that -1 is indeed the rootpoint. + * + * SelCurvSet indices as PreselectCurve, with the addition that -1 is the HAxis and -2 is the + * VAxis + * + */ + class Selection + { public: - enum SpecialValues { + enum SpecialValues + { RootPoint = -1, HorizontalAxis = -1, VerticalAxis = -2 }; - Selection() { + Selection() + { reset(); } - void reset() { + void reset() + { SelPointSet.clear(); SelCurvSet.clear(); SelConstraintSet.clear(); } - std::set SelPointSet; // Indices as PreselectPoint (and -1 for rootpoint) - std::set SelCurvSet; // also holds cross axes at -1 and -2 - std::set SelConstraintSet; // ConstraintN, N = index + 1. + std::set SelPointSet; // Indices as PreselectPoint (and -1 for rootpoint) + std::set SelCurvSet; // also holds cross axes at -1 and -2 + std::set SelConstraintSet;// ConstraintN, N = index + 1. }; //@} /** @brief Private struct maintaining information necessary for detecting double click. */ - struct DoubleClick { + struct DoubleClick + { static SbTime prvClickTime; - static SbVec2s prvClickPos; //used by double-click-detector + static SbVec2s prvClickPos;// used by double-click-detector static SbVec2s prvCursorPos; static SbVec2s newCursorPos; }; /** @brief Private struct grouping ViewProvider parameters and internal variables */ - struct ViewProviderParameters { + struct ViewProviderParameters + { bool handleEscapeButton = false; bool autoRecompute = false; bool recalculateInitialSolutionWhileDragging = false; - bool isShownVirtualSpace = false; // indicates whether the present virtual space view is the Real Space or the Virtual Space (virtual space 1 or 2) + bool isShownVirtualSpace = false;// indicates whether the present virtual space view is the + // Real Space or the Virtual Space (virtual space 1 or 2) bool buttonPress = false; }; - /** @brief Private struct grouping ViewProvider and RenderManager node, to be used as SoNode sensor data + /** @brief Private struct grouping ViewProvider and RenderManager node, to be used as SoNode + * sensor data */ - struct VPRender { + struct VPRender + { ViewProviderSketch* vp; SoRenderManager* renderMgr; }; @@ -420,42 +489,50 @@ public: SketcherGui::PropertyVisualLayerList VisualLayerList; //@} - // TODO: It is difficult to imagine that these functions are necessary in the public interface. This requires review at a second stage and possibly - // refactor it. + // TODO: It is difficult to imagine that these functions are necessary in the public interface. + // This requires review at a second stage and possibly refactor it. /** @name handler control */ //@{ /// sets an DrawSketchHandler in control - void activateHandler(DrawSketchHandler *newHandler); + void activateHandler(DrawSketchHandler* newHandler); /// removes the active handler void purgeHandler(); //@} - // TODO: SketchMode should be refactored. DrawSketchHandler, its inheritance and free functions should access this mode via the DrawSketchHandler - // Attorney. I will not refactor this at this moment, as the refactor will be even more extensive and difficult to review. But this should be done - // in a second stage. + // TODO: SketchMode should be refactored. DrawSketchHandler, its inheritance and free functions + // should access this mode via the DrawSketchHandler Attorney. I will not refactor this at this + // moment, as the refactor will be even more extensive and difficult to review. But this should + // be done in a second stage. /** @name modus handling */ //@{ /// mode table - enum SketchMode{ - STATUS_NONE, /**< enum value View provider is in neutral. */ - STATUS_SELECT_Point, /**< enum value a point was selected. */ - STATUS_SELECT_Edge, /**< enum value an edge was selected. */ - STATUS_SELECT_Constraint, /**< enum value a constraint was selected. */ - STATUS_SELECT_Cross, /**< enum value the base coordinate system was selected. */ - STATUS_SKETCH_DragPoint, /**< enum value while dragging a point. */ - STATUS_SKETCH_DragCurve, /**< enum value while dragging a curve. */ + enum SketchMode + { + STATUS_NONE, /**< enum value View provider is in neutral. */ + STATUS_SELECT_Point, /**< enum value a point was selected. */ + STATUS_SELECT_Edge, /**< enum value an edge was selected. */ + STATUS_SELECT_Constraint, /**< enum value a constraint was selected. */ + STATUS_SELECT_Cross, /**< enum value the base coordinate system was selected. */ + STATUS_SKETCH_DragPoint, /**< enum value while dragging a point. */ + STATUS_SKETCH_DragCurve, /**< enum value while dragging a curve. */ STATUS_SKETCH_DragConstraint, /**< enum value while dragging a compatible constraint. */ - STATUS_SKETCH_UseHandler, /**< enum value a DrawSketchHandler is in control. */ + STATUS_SKETCH_UseHandler, /**< enum value a DrawSketchHandler is in control. */ STATUS_SKETCH_StartRubberBand, /**< enum value for initiating a rubber band selection */ - STATUS_SKETCH_UseRubberBand /**< enum value when making a rubber band selection */ + STATUS_SKETCH_UseRubberBand /**< enum value when making a rubber band selection */ }; /// is called by GuiCommands to set the drawing mode - void setSketchMode(SketchMode mode) {Mode = mode;} + void setSketchMode(SketchMode mode) + { + Mode = mode; + } /// get the sketch mode - SketchMode getSketchMode() const {return Mode;} + SketchMode getSketchMode() const + { + return Mode; + } //@} /** @name Drawing functions */ @@ -463,7 +540,7 @@ public: /// draw the sketch in the inventor nodes /// temp => use temporary solver solution in SketchObject /// recreateinformationscenography => forces a rebuild of the information overlay scenography - void draw(bool temp=false, bool rebuildinformationoverlay=true); + void draw(bool temp = false, bool rebuildinformationoverlay = true); /// helper change the color of the sketch according to selection and solver status void updateColor(); @@ -486,19 +563,22 @@ public: /** @name Access to Sketch and Solver objects */ //@{ /// get the pointer to the sketch document object - Sketcher::SketchObject *getSketchObject() const; + Sketcher::SketchObject* getSketchObject() const; /** returns a const reference to the last solved sketch object. It guarantees that * the solver object does not lose synchronisation with the SketchObject properties. * * NOTE: Operations requiring * write * access to the solver must be done via SketchObject * interface. See for example functions: - * -> inline void setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) + * -> inline void setRecalculateInitialSolutionWhileMovingPoint(bool + * recalculateInitialSolutionWhileMovingPoint) * -> inline int initTemporaryMove(int geoId, PointPos pos, bool fine=true) - * -> inline int moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative=false) - * -> inline void updateSolverExtension(int geoId, std::unique_ptr && ext) + * -> inline int moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool + * relative=false) + * -> inline void updateSolverExtension(int geoId, std::unique_ptr && + * ext) */ - const Sketcher::Sketch &getSolvedSketch() const; + const Sketcher::Sketch& getSolvedSketch() const; //@} /** @name miscelanea utilities */ @@ -515,7 +595,8 @@ public: //@{ /// updates the visibility of the virtual space of constraints void updateVirtualSpace(); - /// determines whether the constraints in the normal space or the ones in the virtual are to be shown + /// determines whether the constraints in the normal space or the ones in the virtual are to be + /// shown void setIsShownVirtualSpace(bool isshownvirtualspace); /// returns whether the virtual space is being shown bool getIsShownVirtualSpace() const; @@ -523,39 +604,46 @@ public: /** @name base class implementer */ //@{ - void attach(App::DocumentObject *) override; - void updateData(const App::Property *) override; + void attach(App::DocumentObject*) override; + void updateData(const App::Property*) override; - void setupContextMenu(QMenu *menu, QObject *receiver, const char *member) override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; /// is called when the Provider is in edit and a deletion request occurs - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; /// Is called by the tree if the user double clicks on the object. It returns the string /// for the transaction that will be shown in the undo/redo dialog. /// If null is returned then no transaction will be opened. - const char* getTransactionText() const override { return nullptr; } + const char* getTransactionText() const override + { + return nullptr; + } /// is called by the tree if the user double clicks on the object bool doubleClicked() override; /// is called when the Provider is in edit and the mouse is moved - bool mouseMove(const SbVec2s &pos, Gui::View3DInventorViewer *viewer) override; + bool mouseMove(const SbVec2s& pos, Gui::View3DInventorViewer* viewer) override; /// is called when the Provider is in edit and a key event ocours. Only ESC ends edit. bool keyPressed(bool pressed, int key) override; /// is called when the Provider is in edit and the mouse is clicked - bool mouseButtonPressed(int Button, bool pressed, const SbVec2s& cursorPos, const Gui::View3DInventorViewer* viewer) override; - bool mouseWheelEvent(int delta, const SbVec2s &cursorPos, const Gui::View3DInventorViewer* viewer) override; + bool mouseButtonPressed(int Button, bool pressed, const SbVec2s& cursorPos, + const Gui::View3DInventorViewer* viewer) override; + bool mouseWheelEvent(int delta, const SbVec2s& cursorPos, + const Gui::View3DInventorViewer* viewer) override; //@} /// Control the overlays appearing on the Tree and reflecting different sketcher states - QIcon mergeColorfulOverlayIcons (const QIcon & orig) const override; + QIcon mergeColorfulOverlayIcons(const QIcon& orig) const override; /** @name Signals for controlling information in Task dialogs */ //@{ /// signals if the constraints list has changed - boost::signals2::signal signalConstraintsChanged; + boost::signals2::signal signalConstraintsChanged; /// signals if the sketch has been set up - boost::signals2::signal signalSetUp; + boost::signals2::signal + signalSetUp; /// signals if the elements list has changed - boost::signals2::signal signalElementsChanged; + boost::signals2::signal signalElementsChanged; //@} /** @name Attorneys for collaboration with helper classes */ @@ -572,7 +660,7 @@ protected: void unsetEdit(int ModNum) override; void setEditViewer(Gui::View3DInventorViewer*, int ModNum) override; void unsetEditViewer(Gui::View3DInventorViewer*) override; - static void camSensCB(void *data, SoSensor *); // camera sensor callback + static void camSensCB(void* data, SoSensor*);// camera sensor callback void onCameraChanged(SoCamera* cam); //@} @@ -589,10 +677,10 @@ protected: /// update solver information based on last solving at SketchObject void UpdateSolverInformation(); - /// Auxiliary function to generate messages about conflicting, redundant and malformed constraints - static QString appendConstraintMsg( const QString & singularmsg, - const QString & pluralmsg, - const std::vector &vector); + /// Auxiliary function to generate messages about conflicting, redundant and malformed + /// constraints + static QString appendConstraintMsg(const QString& singularmsg, const QString& pluralmsg, + const std::vector& vector); //@} /** @name manage updates during undo/redo operations */ @@ -605,30 +693,28 @@ protected: /** @name base class implementer */ //@{ /// get called by the container whenever a property has been changed - void onChanged(const App::Property *prop) override; + void onChanged(const App::Property* prop) override; //@} private: /// function to handle OCCT BSpline weight calculation singularities and representation void scaleBSplinePoleCirclesAndUpdateSolverAndSketchObjectGeometry( - GeoListFacade & geolist, - bool geometrywithmemoryallocation); + GeoListFacade& geolist, bool geometrywithmemoryallocation); /** @name geometry and coordinates auxiliary functions */ //@{ /// give the coordinates of a line on the sketch plane in sketcher (2D) coordinates - void getCoordsOnSketchPlane(const SbVec3f &point, const SbVec3f &normal, double &u, double &v) const; + void getCoordsOnSketchPlane(const SbVec3f& point, const SbVec3f& normal, double& u, + double& v) const; /// give projecting line of position - void getProjectingLine(const SbVec2s&, - const Gui::View3DInventorViewer *viewer, - SbLine&) const; + void getProjectingLine(const SbVec2s&, const Gui::View3DInventorViewer* viewer, SbLine&) const; //@} /** @name preselection functions */ //@{ /// helper to detect preselection - bool detectAndShowPreselection (SoPickedPoint * Point, const SbVec2s &cursorPos); + bool detectAndShowPreselection(SoPickedPoint* Point, const SbVec2s& cursorPos); int getPreselectPoint() const; int getPreselectCurve() const; int getPreselectCross() const; @@ -636,29 +722,29 @@ private: void setPreselectRootPoint(); void resetPreselectPoint(); - bool setPreselect(const std::string &subNameSuffix, float x = 0, float y = 0, float z = 0); + bool setPreselect(const std::string& subNameSuffix, float x = 0, float y = 0, float z = 0); //@} /** @name Selection functions */ //@{ /// box selection method - void doBoxSelection(const SbVec2s &startPos, const SbVec2s &endPos, - const Gui::View3DInventorViewer *viewer); + void doBoxSelection(const SbVec2s& startPos, const SbVec2s& endPos, + const Gui::View3DInventorViewer* viewer); void addSelectPoint(int SelectPoint); void removeSelectPoint(int SelectPoint); void clearSelectPoints(); - bool isSelected(const std::string & ss) const; - void rmvSelection(const std::string &subNameSuffix); - bool addSelection(const std::string &subNameSuffix, float x = 0, float y = 0, float z = 0); - bool addSelection2(const std::string &subNameSuffix, float x = 0, float y = 0, float z = 0); + bool isSelected(const std::string& ss) const; + void rmvSelection(const std::string& subNameSuffix); + bool addSelection(const std::string& subNameSuffix, float x = 0, float y = 0, float z = 0); + bool addSelection2(const std::string& subNameSuffix, float x = 0, float y = 0, float z = 0); //@} /** @name miscelanea utilities */ //@{ /// moves a selected constraint - void moveConstraint(int constNum, const Base::Vector2d &toPos); + void moveConstraint(int constNum, const Base::Vector2d& toPos); /// returns whether the sketch is in edit mode. bool isInEditMode() const; @@ -675,7 +761,7 @@ private: bool constraintHasExpression(int constrid) const; - const std::vector getConstraints() const; + const std::vector getConstraints() const; // gets the list of geometry of the sketchobject or of the solver instance const GeoList getGeoList() const; @@ -702,15 +788,15 @@ private: bool haveConstraintsInvalidGeometry() const; - void addNodeToRoot(SoSeparator * node); + void addNodeToRoot(SoSeparator* node); - void removeNodeFromRoot(SoSeparator * node); + void removeNodeFromRoot(SoSeparator* node); bool isConstraintPreselected(int constraintId) const; bool isPointSelected(int pointId) const; - void executeOnSelectionPointSet(std::function && operation) const; + void executeOnSelectionPointSet(std::function&& operation) const; bool isCurveSelected(int curveId) const; @@ -721,15 +807,16 @@ private: //********* ViewProviderSketchDrawSketchHandlerAttorney **********// void setConstraintSelectability(bool enabled = true); - void setPositionText(const Base::Vector2d &Pos, const SbString &txt); - void setPositionText(const Base::Vector2d &Pos); + void setPositionText(const Base::Vector2d& Pos, const SbString& txt); + void setPositionText(const Base::Vector2d& Pos); void resetPositionText(); /// draw the edit curve - void drawEdit(const std::vector &EditCurve); - void drawEdit(const std::list> &list); + void drawEdit(const std::vector& EditCurve); + void drawEdit(const std::list>& list); /// draw the edit markers - void drawEditMarkers(const std::vector &EditMarkers, unsigned int augmentationlevel = 0); + void drawEditMarkers(const std::vector& EditMarkers, + unsigned int augmentationlevel = 0); /// set the pick style of the sketch coordinate axes void setAxisPickStyle(bool on); @@ -739,20 +826,21 @@ private: //@} private: - /** @name Solver message creation*/ + /** @name Solver message creation*/ //@{ /* private functions to decouple Attorneys and Clients from the internal implementation of the ViewProvider and its members, such as sketchObject (see friend attorney classes) and improve encapsulation. */ /// generates a warning message about constraint conflicts and appends it to the given message - static QString appendConflictMsg(const std::vector &conflicting); + static QString appendConflictMsg(const std::vector& conflicting); /// generates a warning message about redundant constraints and appends it to the given message - static QString appendRedundantMsg(const std::vector &redundant); - /// generates a warning message about partially redundant constraints and appends it to the given message - static QString appendPartiallyRedundantMsg(const std::vector &partiallyredundant); + static QString appendRedundantMsg(const std::vector& redundant); + /// generates a warning message about partially redundant constraints and appends it to the + /// given message + static QString appendPartiallyRedundantMsg(const std::vector& partiallyredundant); /// generates a warning message about redundant constraints and appends it to the given message - static QString appendMalformedMsg(const std::vector &redundant); + static QString appendMalformedMsg(const std::vector& redundant); //@} private: @@ -787,11 +875,10 @@ private: ViewProviderParameters viewProviderParameters; SoNodeSensor cameraSensor; - int viewOrientationFactor; // stores if sketch viewed from front or back + int viewOrientationFactor;// stores if sketch viewed from front or back }; -} // namespace PartGui +}// namespace SketcherGui -#endif // SKETCHERGUI_VIEWPROVIDERSKETCH_H - +#endif// SKETCHERGUI_VIEWPROVIDERSKETCH_H diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h b/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h index c9da259003..a99db9462a 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h @@ -23,8 +23,8 @@ #ifndef SKETCHERGUI_ViewProviderSketchCoinAttorney_H #define SKETCHERGUI_ViewProviderSketchCoinAttorney_H -#include #include +#include #include #include @@ -33,25 +33,29 @@ #include "ViewProviderSketch.h" -namespace Base { - template< typename T > - class Vector3; +namespace Base +{ +template +class Vector3; - class Vector2d; +class Vector2d; - class Placement; +class Placement; +}// namespace Base + +namespace Part +{ +class Geometry; } -namespace Part { - class Geometry; -} +namespace Sketcher +{ +class Constraint; +class PropertyConstraintList; +};// namespace Sketcher -namespace Sketcher { - class Constraint; - class PropertyConstraintList; -}; - -namespace SketcherGui { +namespace SketcherGui +{ class ViewProviderSketch; @@ -63,52 +67,58 @@ using GeoListFacade = Sketcher::GeoListFacade; * ViewProviderSketch delegates a substantial part of coin related visualisation to * ViewProviderSketchCoinAttorney during edit mode. * - * Sometimes friend classes of ViewProviderSketchCoinAttorney need to access selected functionalities only available to ViewProviderSketch. + * Sometimes friend classes of ViewProviderSketchCoinAttorney need to access selected + * functionalities only available to ViewProviderSketch. * - * This attorney class regulates which specific functionalities ViewProviderSketchCoinAttorney is able to access in - * ViewProviderSketch. + * This attorney class regulates which specific functionalities ViewProviderSketchCoinAttorney is + * able to access in ViewProviderSketch. * * The objective is: * - to preserve as much as possible ViewProviderSketch encapsulation * - to promote as much as reasonably possible loose coupling between tightly related classes. - * - to keep control over the interactions between these classes and easily identify the cooperation interface. + * - to keep control over the interactions between these classes and easily identify the + * cooperation interface. */ -class ViewProviderSketchCoinAttorney { +class ViewProviderSketchCoinAttorney +{ private: - static inline bool constraintHasExpression(const ViewProviderSketch &vp, int constrid); - static inline const std::vector getConstraints(const ViewProviderSketch & vp); - static inline const GeoList getGeoList(const ViewProviderSketch & vp); - static inline const GeoListFacade getGeoListFacade(const ViewProviderSketch & vp); - static inline Base::Placement getEditingPlacement(const ViewProviderSketch & vp); - static inline bool isShownVirtualSpace(const ViewProviderSketch & vp); - static inline std::unique_ptr getRayPickAction(const ViewProviderSketch & vp); + static inline bool constraintHasExpression(const ViewProviderSketch& vp, int constrid); + static inline const std::vector + getConstraints(const ViewProviderSketch& vp); + static inline const GeoList getGeoList(const ViewProviderSketch& vp); + static inline const GeoListFacade getGeoListFacade(const ViewProviderSketch& vp); + static inline Base::Placement getEditingPlacement(const ViewProviderSketch& vp); + static inline bool isShownVirtualSpace(const ViewProviderSketch& vp); + static inline std::unique_ptr getRayPickAction(const ViewProviderSketch& vp); - static inline float getScaleFactor(const ViewProviderSketch & vp); - static inline SbVec2f getScreenCoordinates(const ViewProviderSketch & vp, SbVec2f sketchcoordinates); - static inline QFont getApplicationFont(const ViewProviderSketch & vp); - static inline double getRotation(const ViewProviderSketch & vp, SbVec3f pos0, SbVec3f pos1); - static inline int defaultApplicationFontSizePixels(const ViewProviderSketch & vp); - static inline int getApplicationLogicalDPIX(const ViewProviderSketch & vp); - static inline int getViewOrientationFactor(const ViewProviderSketch & vp); + static inline float getScaleFactor(const ViewProviderSketch& vp); + static inline SbVec2f getScreenCoordinates(const ViewProviderSketch& vp, + SbVec2f sketchcoordinates); + static inline QFont getApplicationFont(const ViewProviderSketch& vp); + static inline double getRotation(const ViewProviderSketch& vp, SbVec3f pos0, SbVec3f pos1); + static inline int defaultApplicationFontSizePixels(const ViewProviderSketch& vp); + static inline int getApplicationLogicalDPIX(const ViewProviderSketch& vp); + static inline int getViewOrientationFactor(const ViewProviderSketch& vp); - static inline bool isSketchInvalid(const ViewProviderSketch & vp); - static inline bool isSketchFullyConstrained(const ViewProviderSketch & vp); - static inline bool haveConstraintsInvalidGeometry(const ViewProviderSketch & vp); + static inline bool isSketchInvalid(const ViewProviderSketch& vp); + static inline bool isSketchFullyConstrained(const ViewProviderSketch& vp); + static inline bool haveConstraintsInvalidGeometry(const ViewProviderSketch& vp); - static inline void addNodeToRoot(ViewProviderSketch & vp, SoSeparator * node); + static inline void addNodeToRoot(ViewProviderSketch& vp, SoSeparator* node); - static inline void removeNodeFromRoot(ViewProviderSketch & vp, SoSeparator * node); + static inline void removeNodeFromRoot(ViewProviderSketch& vp, SoSeparator* node); - static inline int getPreselectPoint(const ViewProviderSketch &vp); - static inline int getPreselectCurve(const ViewProviderSketch &vp); - static inline int getPreselectCross(const ViewProviderSketch &vp); + static inline int getPreselectPoint(const ViewProviderSketch& vp); + static inline int getPreselectCurve(const ViewProviderSketch& vp); + static inline int getPreselectCross(const ViewProviderSketch& vp); - static inline bool isConstraintPreselected(const ViewProviderSketch &vp, int constraintId); - static inline bool isPointSelected(const ViewProviderSketch &vp, int pointId); - static inline bool isCurveSelected(const ViewProviderSketch &vp, int curveId); - static inline bool isConstraintSelected(const ViewProviderSketch &vp, int constraintId); + static inline bool isConstraintPreselected(const ViewProviderSketch& vp, int constraintId); + static inline bool isPointSelected(const ViewProviderSketch& vp, int pointId); + static inline bool isCurveSelected(const ViewProviderSketch& vp, int curveId); + static inline bool isConstraintSelected(const ViewProviderSketch& vp, int constraintId); - static inline void executeOnSelectionPointSet(const ViewProviderSketch &vp, std::function && operation); + static inline void executeOnSelectionPointSet(const ViewProviderSketch& vp, + std::function&& operation); friend class EditModeCoinManager; friend class EditModeConstraintCoinManager; @@ -117,145 +127,156 @@ private: friend class EditModeGeometryCoinConverter; }; -inline bool ViewProviderSketchCoinAttorney::constraintHasExpression(const ViewProviderSketch & vp, int constrid) +inline bool ViewProviderSketchCoinAttorney::constraintHasExpression(const ViewProviderSketch& vp, + int constrid) { return vp.constraintHasExpression(constrid); }; -inline const std::vector ViewProviderSketchCoinAttorney::getConstraints(const ViewProviderSketch & vp) +inline const std::vector +ViewProviderSketchCoinAttorney::getConstraints(const ViewProviderSketch& vp) { return vp.getConstraints(); } -inline const GeoList ViewProviderSketchCoinAttorney::getGeoList(const ViewProviderSketch & vp) +inline const GeoList ViewProviderSketchCoinAttorney::getGeoList(const ViewProviderSketch& vp) { return vp.getGeoList(); } -const GeoListFacade ViewProviderSketchCoinAttorney::getGeoListFacade(const ViewProviderSketch & vp) +const GeoListFacade ViewProviderSketchCoinAttorney::getGeoListFacade(const ViewProviderSketch& vp) { - return vp.getGeoListFacade(); + return vp.getGeoListFacade(); } -inline Base::Placement ViewProviderSketchCoinAttorney::getEditingPlacement(const ViewProviderSketch & vp) +inline Base::Placement +ViewProviderSketchCoinAttorney::getEditingPlacement(const ViewProviderSketch& vp) { return vp.getEditingPlacement(); } -inline bool ViewProviderSketchCoinAttorney::isShownVirtualSpace(const ViewProviderSketch & vp) +inline bool ViewProviderSketchCoinAttorney::isShownVirtualSpace(const ViewProviderSketch& vp) { return vp.viewProviderParameters.isShownVirtualSpace; } -inline std::unique_ptr ViewProviderSketchCoinAttorney::getRayPickAction(const ViewProviderSketch & vp) +inline std::unique_ptr +ViewProviderSketchCoinAttorney::getRayPickAction(const ViewProviderSketch& vp) { return vp.getRayPickAction(); } -inline float ViewProviderSketchCoinAttorney::getScaleFactor(const ViewProviderSketch & vp) +inline float ViewProviderSketchCoinAttorney::getScaleFactor(const ViewProviderSketch& vp) { return vp.getScaleFactor(); } -inline SbVec2f ViewProviderSketchCoinAttorney::getScreenCoordinates(const ViewProviderSketch & vp, SbVec2f sketchcoordinates) +inline SbVec2f ViewProviderSketchCoinAttorney::getScreenCoordinates(const ViewProviderSketch& vp, + SbVec2f sketchcoordinates) { return vp.getScreenCoordinates(sketchcoordinates); } -inline QFont ViewProviderSketchCoinAttorney::getApplicationFont(const ViewProviderSketch & vp) +inline QFont ViewProviderSketchCoinAttorney::getApplicationFont(const ViewProviderSketch& vp) { return vp.getApplicationFont(); } -inline double ViewProviderSketchCoinAttorney::getRotation(const ViewProviderSketch & vp, SbVec3f pos0, SbVec3f pos1) +inline double ViewProviderSketchCoinAttorney::getRotation(const ViewProviderSketch& vp, + SbVec3f pos0, SbVec3f pos1) { - return vp.getRotation(pos0,pos1); + return vp.getRotation(pos0, pos1); } -inline int ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(const ViewProviderSketch & vp) +inline int +ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(const ViewProviderSketch& vp) { return vp.defaultFontSizePixels(); } -inline int ViewProviderSketchCoinAttorney::getApplicationLogicalDPIX(const ViewProviderSketch & vp) +inline int ViewProviderSketchCoinAttorney::getApplicationLogicalDPIX(const ViewProviderSketch& vp) { return vp.getApplicationLogicalDPIX(); } -inline int ViewProviderSketchCoinAttorney::getViewOrientationFactor(const ViewProviderSketch & vp) +inline int ViewProviderSketchCoinAttorney::getViewOrientationFactor(const ViewProviderSketch& vp) { return vp.getViewOrientationFactor(); } -inline bool ViewProviderSketchCoinAttorney::isSketchInvalid(const ViewProviderSketch & vp) +inline bool ViewProviderSketchCoinAttorney::isSketchInvalid(const ViewProviderSketch& vp) { return vp.isSketchInvalid(); } -inline bool ViewProviderSketchCoinAttorney::isSketchFullyConstrained(const ViewProviderSketch & vp) +inline bool ViewProviderSketchCoinAttorney::isSketchFullyConstrained(const ViewProviderSketch& vp) { return vp.isSketchFullyConstrained(); } -inline bool ViewProviderSketchCoinAttorney::haveConstraintsInvalidGeometry(const ViewProviderSketch & vp) +inline bool +ViewProviderSketchCoinAttorney::haveConstraintsInvalidGeometry(const ViewProviderSketch& vp) { return vp.haveConstraintsInvalidGeometry(); } -inline void ViewProviderSketchCoinAttorney::addNodeToRoot(ViewProviderSketch & vp, SoSeparator * node) +inline void ViewProviderSketchCoinAttorney::addNodeToRoot(ViewProviderSketch& vp, SoSeparator* node) { vp.addNodeToRoot(node); } -inline void ViewProviderSketchCoinAttorney::removeNodeFromRoot(ViewProviderSketch & vp, SoSeparator * node) +inline void ViewProviderSketchCoinAttorney::removeNodeFromRoot(ViewProviderSketch& vp, + SoSeparator* node) { vp.removeNodeFromRoot(node); } -inline int ViewProviderSketchCoinAttorney::getPreselectPoint(const ViewProviderSketch &vp) +inline int ViewProviderSketchCoinAttorney::getPreselectPoint(const ViewProviderSketch& vp) { - return vp.getPreselectPoint(); + return vp.getPreselectPoint(); } -inline int ViewProviderSketchCoinAttorney::getPreselectCurve(const ViewProviderSketch &vp) +inline int ViewProviderSketchCoinAttorney::getPreselectCurve(const ViewProviderSketch& vp) { return vp.getPreselectCurve(); } -inline int ViewProviderSketchCoinAttorney::getPreselectCross(const ViewProviderSketch &vp) +inline int ViewProviderSketchCoinAttorney::getPreselectCross(const ViewProviderSketch& vp) { return vp.getPreselectCross(); } -inline bool ViewProviderSketchCoinAttorney::isConstraintPreselected(const ViewProviderSketch &vp, int constraintId) +inline bool ViewProviderSketchCoinAttorney::isConstraintPreselected(const ViewProviderSketch& vp, + int constraintId) { return vp.isConstraintPreselected(constraintId); } -inline bool ViewProviderSketchCoinAttorney::isPointSelected(const ViewProviderSketch &vp, int pointId) +inline bool ViewProviderSketchCoinAttorney::isPointSelected(const ViewProviderSketch& vp, + int pointId) { return vp.isPointSelected(pointId); } -inline bool ViewProviderSketchCoinAttorney::isCurveSelected(const ViewProviderSketch &vp, int curveId) +inline bool ViewProviderSketchCoinAttorney::isCurveSelected(const ViewProviderSketch& vp, + int curveId) { return vp.isCurveSelected(curveId); } -inline bool ViewProviderSketchCoinAttorney::isConstraintSelected(const ViewProviderSketch &vp, int constraintId) +inline bool ViewProviderSketchCoinAttorney::isConstraintSelected(const ViewProviderSketch& vp, + int constraintId) { return vp.isConstraintSelected(constraintId); } -inline void ViewProviderSketchCoinAttorney::executeOnSelectionPointSet(const ViewProviderSketch &vp, std::function && operation) +inline void ViewProviderSketchCoinAttorney::executeOnSelectionPointSet( + const ViewProviderSketch& vp, std::function&& operation) { vp.executeOnSelectionPointSet(std::move(operation)); } -} // namespace SketcherGui - - -#endif // SKETCHERGUI_ViewProviderSketchCoinAttorney_H - +}// namespace SketcherGui +#endif// SKETCHERGUI_ViewProviderSketchCoinAttorney_H diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp index 68851a217d..2b6f5185b8 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp @@ -34,19 +34,21 @@ using namespace SketcherGui; //---------- Geometry Extension -TYPESYSTEM_SOURCE(SketcherGui::ViewProviderSketchGeometryExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE(SketcherGui::ViewProviderSketchGeometryExtension, + Part::GeometryPersistenceExtension) -ViewProviderSketchGeometryExtension::ViewProviderSketchGeometryExtension():RepresentationFactor(1.0), VisualLayerId(0) -{ +ViewProviderSketchGeometryExtension::ViewProviderSketchGeometryExtension() + : RepresentationFactor(1.0) + , VisualLayerId(0) +{} -} - -void ViewProviderSketchGeometryExtension::copyAttributes(Part::GeometryExtension * cpy) const +void ViewProviderSketchGeometryExtension::copyAttributes(Part::GeometryExtension* cpy) const { Part::GeometryExtension::copyAttributes(cpy); - static_cast(cpy)->RepresentationFactor = this->RepresentationFactor; - static_cast(cpy)->VisualLayerId = this->VisualLayerId; + static_cast(cpy)->RepresentationFactor = + this->RepresentationFactor; + static_cast(cpy)->VisualLayerId = this->VisualLayerId; } std::unique_ptr ViewProviderSketchGeometryExtension::copy() const @@ -55,30 +57,31 @@ std::unique_ptr ViewProviderSketchGeometryExtension::co copyAttributes(cpy.get()); -#if defined (__GNUC__) && (__GNUC__ <=4) +#if defined(__GNUC__) && (__GNUC__ <= 4) return std::move(cpy); #else return cpy; #endif } -void ViewProviderSketchGeometryExtension::restoreAttributes(Base::XMLReader &reader) +void ViewProviderSketchGeometryExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); - if(reader.hasAttribute("visualLayerId")) + if (reader.hasAttribute("visualLayerId")) VisualLayerId = reader.getAttributeAsInteger("visualLayerId"); } -void ViewProviderSketchGeometryExtension::saveAttributes(Base::Writer &writer) const +void ViewProviderSketchGeometryExtension::saveAttributes(Base::Writer& writer) const { Part::GeometryPersistenceExtension::saveAttributes(writer); - writer.Stream() << "\" visualLayerId=\"" << VisualLayerId; + writer.Stream() << "\" visualLayerId=\"" << VisualLayerId; } -PyObject * ViewProviderSketchGeometryExtension::getPyObject() +PyObject* ViewProviderSketchGeometryExtension::getPyObject() { - return new ViewProviderSketchGeometryExtensionPy(new ViewProviderSketchGeometryExtension(*this)); + return new ViewProviderSketchGeometryExtensionPy( + new ViewProviderSketchGeometryExtension(*this)); } diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h index 63f4b66aa3..ba1753232e 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h @@ -27,38 +27,52 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ -class SketcherGuiExport ViewProviderSketchGeometryExtension : public Part::GeometryPersistenceExtension +class SketcherGuiExport ViewProviderSketchGeometryExtension + : public Part::GeometryPersistenceExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: +public: ViewProviderSketchGeometryExtension(); ~ViewProviderSketchGeometryExtension() override = default; std::unique_ptr copy() const override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; // Data Members // Representation factor // Provides a mechanism to store a factor associated with the representation of a geometry - // This is only useful when a geometry must be scaled only for representation, while keeping its value - // Applicability: General abstract concepts embodied in a geometry, in practice B-Spline poles. - // Why not in SketchGeometryExtension? Because it is merely representation related. It has no place in - // a console application. - double getRepresentationFactor() const {return RepresentationFactor;} - void setRepresentationFactor(double representationFactor) {RepresentationFactor = representationFactor;} + // This is only useful when a geometry must be scaled only for representation, while keeping its + // value Applicability: General abstract concepts embodied in a geometry, in practice B-Spline + // poles. Why not in SketchGeometryExtension? Because it is merely representation related. It + // has no place in a console application. + double getRepresentationFactor() const + { + return RepresentationFactor; + } + void setRepresentationFactor(double representationFactor) + { + RepresentationFactor = representationFactor; + } - int getVisualLayerId() const {return VisualLayerId;} - void setVisualLayerId(int visuallayerid) {VisualLayerId = visuallayerid;} + int getVisualLayerId() const + { + return VisualLayerId; + } + void setVisualLayerId(int visuallayerid) + { + VisualLayerId = visuallayerid; + } protected: - void copyAttributes(Part::GeometryExtension * cpy) const override; - void restoreAttributes(Base::XMLReader &reader) override; - void saveAttributes(Base::Writer &writer) const override; + void copyAttributes(Part::GeometryExtension* cpy) const override; + void restoreAttributes(Base::XMLReader& reader) override; + void saveAttributes(Base::Writer& writer) const override; private: ViewProviderSketchGeometryExtension(const ViewProviderSketchGeometryExtension&) = default; @@ -68,7 +82,7 @@ private: int VisualLayerId; }; -} //namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHER_VIEWPROVIDERSKETCHGEOMETRYEXTENSION_H +#endif// SKETCHER_VIEWPROVIDERSKETCHGEOMETRYEXTENSION_H diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp index 7bc868be17..b236c3b426 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" #include "ViewProviderSketchGeometryExtensionPy.h" + #include "ViewProviderSketchGeometryExtensionPy.cpp" @@ -38,7 +39,8 @@ std::string ViewProviderSketchGeometryExtensionPy::representation() const return str.str(); } -PyObject *ViewProviderSketchGeometryExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ViewProviderSketchGeometryExtensionPy::PyMake(struct _typeobject*, PyObject*, + PyObject*)// Python wrapper { // create a new instance of PointPy and the Twin object return new ViewProviderSketchGeometryExtensionPy(new ViewProviderSketchGeometryExtension); @@ -60,9 +62,10 @@ int ViewProviderSketchGeometryExtensionPy::PyInit(PyObject* args, PyObject* /*kw return 0; } - PyErr_SetString(PyExc_TypeError, "ViewProviderSketchGeometryExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- int\n"); + PyErr_SetString(PyExc_TypeError, + "ViewProviderSketchGeometryExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- int\n"); return -1; } @@ -76,13 +79,13 @@ void ViewProviderSketchGeometryExtensionPy::setVisualLayerId(Py::Long Id) this->getViewProviderSketchGeometryExtensionPtr()->setVisualLayerId(Id); } -PyObject *ViewProviderSketchGeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ViewProviderSketchGeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } -int ViewProviderSketchGeometryExtensionPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) +int ViewProviderSketchGeometryExtensionPy::setCustomAttributes(const char* /*attr*/, + PyObject* /*obj*/) { return 0; } - diff --git a/src/Mod/Sketcher/Gui/VisualLayer.cpp b/src/Mod/Sketcher/Gui/VisualLayer.cpp index 075a49f715..f44acb4719 100644 --- a/src/Mod/Sketcher/Gui/VisualLayer.cpp +++ b/src/Mod/Sketcher/Gui/VisualLayer.cpp @@ -31,7 +31,10 @@ using namespace SketcherGui; //**************** VisualClassConfig **************************************// -VisualLayer::VisualLayer(unsigned int linePattern, float lineWidth, bool visible): linePattern(linePattern), lineWidth(lineWidth), visible(visible) +VisualLayer::VisualLayer(unsigned int linePattern, float lineWidth, bool visible) + : linePattern(linePattern) + , lineWidth(lineWidth) + , visible(visible) {} unsigned int VisualLayer::getLinePattern() const @@ -64,23 +67,22 @@ void VisualLayer::setVisible(bool show) visible = show; } -void VisualLayer::Save(Base::Writer &writer) const +void VisualLayer::Save(Base::Writer& writer) const { - writer.Stream() << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; } -void VisualLayer::Restore(Base::XMLReader &reader) +void VisualLayer::Restore(Base::XMLReader& reader) { reader.readElement("VisualLayer"); std::string str = reader.getAttribute("visible"); - visible = ( str == "true"); + visible = (str == "true"); linePattern = reader.getAttributeAsUnsigned("linePattern"); lineWidth = reader.getAttributeAsFloat("lineWidth"); } - diff --git a/src/Mod/Sketcher/Gui/VisualLayer.h b/src/Mod/Sketcher/Gui/VisualLayer.h index 53e5b686e3..587a835ddd 100644 --- a/src/Mod/Sketcher/Gui/VisualLayer.h +++ b/src/Mod/Sketcher/Gui/VisualLayer.h @@ -30,13 +30,15 @@ namespace SketcherGui { /** Provides the visual layer configuration for a class of geometry. - * A class of geometry can be any grouping of geometry, for - * which the user wants to provide a per coin layer specific - * configuration. - */ -class VisualLayer { + * A class of geometry can be any grouping of geometry, for + * which the user wants to provide a per coin layer specific + * configuration. + */ +class VisualLayer +{ public: - explicit VisualLayer(unsigned int linePattern = 0xFFFF, float lineWidth = 3.0, bool visible = true); + explicit VisualLayer(unsigned int linePattern = 0xFFFF, float lineWidth = 3.0, + bool visible = true); unsigned int getLinePattern() const; float getLineWidth() const; @@ -47,8 +49,8 @@ public: bool isVisible() const; void setVisible(bool show); - void Save(Base::Writer &/*writer*/) const; - void Restore(Base::XMLReader &/*reader*/); + void Save(Base::Writer& /*writer*/) const; + void Restore(Base::XMLReader& /*reader*/); private: unsigned int linePattern; @@ -60,12 +62,11 @@ private: bool operator==(VisualLayer const& lhs, VisualLayer const& rhs) { - return ( lhs.linePattern == rhs.linePattern ) && - ( lhs.lineWidth == rhs.lineWidth ) && - ( lhs.visible == rhs.visible ); + return (lhs.linePattern == rhs.linePattern) && (lhs.lineWidth == rhs.lineWidth) + && (lhs.visible == rhs.visible); } -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHERGUI_VisualLayer_H +#endif// SKETCHERGUI_VisualLayer_H diff --git a/src/Mod/Sketcher/Gui/Workbench.cpp b/src/Mod/Sketcher/Gui/Workbench.cpp index 46cfdc4d92..c107f14052 100644 --- a/src/Mod/Sketcher/Gui/Workbench.cpp +++ b/src/Mod/Sketcher/Gui/Workbench.cpp @@ -22,15 +22,15 @@ #include "PreCompiled.h" -#include #include "Utils.h" #include "Workbench.h" #include #include +#include using namespace SketcherGui; -#if 0 // needed for Qt's lupdate utility +#if 0// needed for Qt's lupdate utility qApp->translate("CommandGroup", "Sketcher"); qApp->translate("Workbench","P&rofiles"); qApp->translate("Workbench","S&ketch"); @@ -46,28 +46,26 @@ using namespace SketcherGui; TYPESYSTEM_SOURCE(SketcherGui::Workbench, Gui::StdWorkbench) Workbench::Workbench() -{ -} +{} Workbench::~Workbench() -{ -} +{} Gui::MenuItem* Workbench::setupMenuBar() const { Gui::MenuItem* root = StdWorkbench::setupMenuBar(); Gui::MenuItem* item = root->findItem("&Windows"); -// == Profile menu ========================================== -/* TODO: implement profile menu with different profiles - Gui::MenuItem* profile = new Gui::MenuItem; - root->insertItem(item, profile); - profile->setCommand("P&rofiles"); + // == Profile menu ========================================== + /* TODO: implement profile menu with different profiles + Gui::MenuItem* profile = new Gui::MenuItem; + root->insertItem(item, profile); + profile->setCommand("P&rofiles"); - *profile << "Sketcher_ProfilesHexagon1"; -*/ + *profile << "Sketcher_ProfilesHexagon1"; + */ -// == Sketcher menu ========================================== + // == Sketcher menu ========================================== Gui::MenuItem* geom = new Gui::MenuItem(); geom->setCommand("Sketcher geometries"); @@ -94,11 +92,7 @@ Gui::MenuItem* Workbench::setupMenuBar() const sketch->setCommand("S&ketch"); addSketcherWorkbenchSketchActions(*sketch); addSketcherWorkbenchSketchEditModeActions(*sketch); - *sketch << geom - << cons - << consaccel - << bsplines - << virtualspace; + *sketch << geom << cons << consaccel << bsplines << virtualspace; return root; } @@ -111,7 +105,8 @@ Gui::ToolBarItem* Workbench::setupToolBars() const sketcher->setCommand("Sketcher"); addSketcherWorkbenchSketchActions(*sketcher); - Gui::ToolBarItem* sketcherEditMode = new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); + Gui::ToolBarItem* sketcherEditMode = + new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); sketcherEditMode->setCommand("Sketcher Edit Mode"); addSketcherWorkbenchSketchEditModeActions(*sketcherEditMode); @@ -123,7 +118,8 @@ Gui::ToolBarItem* Workbench::setupToolBars() const cons->setCommand("Sketcher constraints"); addSketcherWorkbenchConstraints(*cons); - Gui::ToolBarItem* consaccel = new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); + Gui::ToolBarItem* consaccel = + new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); consaccel->setCommand("Sketcher tools"); addSketcherWorkbenchTools(*consaccel); @@ -131,15 +127,17 @@ Gui::ToolBarItem* Workbench::setupToolBars() const bspline->setCommand("Sketcher B-spline tools"); addSketcherWorkbenchBSplines(*bspline); - Gui::ToolBarItem* virtualspace = new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); + Gui::ToolBarItem* virtualspace = + new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); virtualspace->setCommand("Sketcher virtual space"); addSketcherWorkbenchVirtualSpace(*virtualspace); - Gui::ToolBarItem* edittools = new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); + Gui::ToolBarItem* edittools = + new Gui::ToolBarItem(root, Gui::ToolBarItem::HideStyle::FORCE_HIDE); edittools->setCommand("Sketcher edit tools"); addSketcherWorkbenchEditTools(*edittools); - return root; + return root; } Gui::ToolBarItem* Workbench::setupCommandBars() const @@ -151,7 +149,7 @@ Gui::ToolBarItem* Workbench::setupCommandBars() const void Workbench::activated() { - Gui::Document *doc = Gui::Application::Instance->activeDocument(); + Gui::Document* doc = Gui::Application::Instance->activeDocument(); if (isSketchInEdit(doc)) { enterEditMode(); } @@ -159,29 +157,29 @@ void Workbench::activated() namespace { - inline const QStringList editModeToolbarNames() - { - return QStringList{ QString::fromLatin1("Sketcher Edit Mode"), - QString::fromLatin1("Sketcher geometries"), - QString::fromLatin1("Sketcher constraints"), - QString::fromLatin1("Sketcher tools"), - QString::fromLatin1("Sketcher B-spline tools"), - QString::fromLatin1("Sketcher virtual space"), - QString::fromLatin1("Sketcher edit tools")}; - } - - inline const QStringList nonEditModeToolbarNames() - { - return QStringList{ QString::fromLatin1("Structure"), - QString::fromLatin1("Sketcher") }; - } +inline const QStringList editModeToolbarNames() +{ + return QStringList {QString::fromLatin1("Sketcher Edit Mode"), + QString::fromLatin1("Sketcher geometries"), + QString::fromLatin1("Sketcher constraints"), + QString::fromLatin1("Sketcher tools"), + QString::fromLatin1("Sketcher B-spline tools"), + QString::fromLatin1("Sketcher virtual space"), + QString::fromLatin1("Sketcher edit tools")}; } +inline const QStringList nonEditModeToolbarNames() +{ + return QStringList {QString::fromLatin1("Structure"), QString::fromLatin1("Sketcher")}; +} +}// namespace + void Workbench::enterEditMode() { /*Modify toolbars dynamically. - First save state of toolbars in case user changed visibility of a toolbar but he's not changing the wb. - This happens in someone works directly from sketcher, changing from edit mode to not-edit-mode*/ + First save state of toolbars in case user changed visibility of a toolbar but he's not changing + the wb. This happens in someone works directly from sketcher, changing from edit mode to + not-edit-mode*/ Gui::ToolBarManager::getInstance()->saveState(); Gui::ToolBarManager::getInstance()->setToolbarVisibility(true, editModeToolbarNames()); @@ -191,276 +189,280 @@ void Workbench::enterEditMode() void Workbench::leaveEditMode() { /*Modify toolbars dynamically. - First save state of toolbars in case user changed visibility of a toolbar but he's not changing the wb. - This happens in someone works directly from sketcher, changing from edit mode to not-edit-mode*/ + First save state of toolbars in case user changed visibility of a toolbar but he's not changing + the wb. This happens in someone works directly from sketcher, changing from edit mode to + not-edit-mode*/ Gui::ToolBarManager::getInstance()->saveState(); Gui::ToolBarManager::getInstance()->setToolbarVisibility(false, editModeToolbarNames()); Gui::ToolBarManager::getInstance()->setToolbarVisibility(true, nonEditModeToolbarNames()); } -namespace SketcherGui { +namespace SketcherGui +{ -template +template void SketcherAddWorkbenchSketchActions(T& sketch); -template <> +template<> inline void SketcherAddWorkbenchSketchActions(Gui::MenuItem& sketch) { - sketch << "Sketcher_NewSketch" - << "Sketcher_EditSketch" - << "Sketcher_MapSketch" - << "Sketcher_ReorientSketch" - << "Sketcher_ValidateSketch" - << "Sketcher_MergeSketches" - << "Sketcher_MirrorSketch"; + sketch << "Sketcher_NewSketch" + << "Sketcher_EditSketch" + << "Sketcher_MapSketch" + << "Sketcher_ReorientSketch" + << "Sketcher_ValidateSketch" + << "Sketcher_MergeSketches" + << "Sketcher_MirrorSketch"; } -template <> +template<> inline void SketcherAddWorkbenchSketchActions(Gui::ToolBarItem& sketch) { - sketch << "Sketcher_NewSketch" - << "Sketcher_EditSketch" - << "Sketcher_MapSketch" - << "Sketcher_ReorientSketch" - << "Sketcher_ValidateSketch" - << "Sketcher_MergeSketches" - << "Sketcher_MirrorSketch"; + sketch << "Sketcher_NewSketch" + << "Sketcher_EditSketch" + << "Sketcher_MapSketch" + << "Sketcher_ReorientSketch" + << "Sketcher_ValidateSketch" + << "Sketcher_MergeSketches" + << "Sketcher_MirrorSketch"; } -template +template void SketcherAddWorkbenchSketchEditModeActions(T& sketch); -template <> +template<> inline void SketcherAddWorkbenchSketchEditModeActions(Gui::MenuItem& sketch) { - sketch << "Sketcher_LeaveSketch" - << "Sketcher_ViewSketch" - << "Sketcher_ViewSection" - << "Sketcher_StopOperation"; + sketch << "Sketcher_LeaveSketch" + << "Sketcher_ViewSketch" + << "Sketcher_ViewSection" + << "Sketcher_StopOperation"; } -template <> +template<> inline void SketcherAddWorkbenchSketchEditModeActions(Gui::ToolBarItem& sketch) { - sketch << "Sketcher_LeaveSketch" - << "Sketcher_ViewSketch" - << "Sketcher_ViewSection"; + sketch << "Sketcher_LeaveSketch" + << "Sketcher_ViewSketch" + << "Sketcher_ViewSection"; } -template +template void SketcherAddWorkbenchGeometries(T& geom); -template +template void SketcherAddWorkspaceArcs(T& geom); -template <> +template<> inline void SketcherAddWorkspaceArcs(Gui::MenuItem& geom) { - geom << "Sketcher_CreateArc" - << "Sketcher_Create3PointArc" - << "Sketcher_CreateCircle" - << "Sketcher_Create3PointCircle" - << "Sketcher_CreateEllipseByCenter" - << "Sketcher_CreateEllipseBy3Points" - << "Sketcher_CreateArcOfEllipse" - << "Sketcher_CreateArcOfHyperbola" - << "Sketcher_CreateArcOfParabola" - << "Sketcher_CreateBSpline" - << "Sketcher_CreatePeriodicBSpline" - << "Sketcher_CreateBSplineByInterpolation" - << "Sketcher_CreatePeriodicBSplineByInterpolation"; + geom << "Sketcher_CreateArc" + << "Sketcher_Create3PointArc" + << "Sketcher_CreateCircle" + << "Sketcher_Create3PointCircle" + << "Sketcher_CreateEllipseByCenter" + << "Sketcher_CreateEllipseBy3Points" + << "Sketcher_CreateArcOfEllipse" + << "Sketcher_CreateArcOfHyperbola" + << "Sketcher_CreateArcOfParabola" + << "Sketcher_CreateBSpline" + << "Sketcher_CreatePeriodicBSpline" + << "Sketcher_CreateBSplineByInterpolation" + << "Sketcher_CreatePeriodicBSplineByInterpolation"; } -template <> +template<> inline void SketcherAddWorkspaceArcs(Gui::ToolBarItem& geom) { - geom << "Sketcher_CompCreateArc" - << "Sketcher_CompCreateCircle" - << "Sketcher_CompCreateConic" - << "Sketcher_CompCreateBSpline"; + geom << "Sketcher_CompCreateArc" + << "Sketcher_CompCreateCircle" + << "Sketcher_CompCreateConic" + << "Sketcher_CompCreateBSpline"; } -template +template void SketcherAddWorkspaceRegularPolygon(T& geom); -template <> +template<> inline void SketcherAddWorkspaceRegularPolygon(Gui::MenuItem& geom) { - geom << "Sketcher_CreateTriangle" - << "Sketcher_CreateSquare" - << "Sketcher_CreatePentagon" - << "Sketcher_CreateHexagon" - << "Sketcher_CreateHeptagon" - << "Sketcher_CreateOctagon" - << "Sketcher_CreateRegularPolygon"; + geom << "Sketcher_CreateTriangle" + << "Sketcher_CreateSquare" + << "Sketcher_CreatePentagon" + << "Sketcher_CreateHexagon" + << "Sketcher_CreateHeptagon" + << "Sketcher_CreateOctagon" + << "Sketcher_CreateRegularPolygon"; } -template <> +template<> inline void SketcherAddWorkspaceRegularPolygon(Gui::ToolBarItem& geom) { - geom << "Sketcher_CompCreateRegularPolygon"; + geom << "Sketcher_CompCreateRegularPolygon"; } -template +template void SketcherAddWorkspaceRectangles(T& geom); -template <> +template<> inline void SketcherAddWorkspaceRectangles(Gui::MenuItem& geom) { - geom << "Sketcher_CreateRectangle" - << "Sketcher_CreateRectangle_Center" - << "Sketcher_CreateOblong"; + geom << "Sketcher_CreateRectangle" + << "Sketcher_CreateRectangle_Center" + << "Sketcher_CreateOblong"; } -template <> +template<> inline void SketcherAddWorkspaceRectangles(Gui::ToolBarItem& geom) { geom << "Sketcher_CompCreateRectangles"; } -template +template void SketcherAddWorkspaceFillets(T& geom); -template <> +template<> inline void SketcherAddWorkspaceFillets(Gui::MenuItem& geom) { - geom << "Sketcher_CreateFillet" - << "Sketcher_CreatePointFillet"; + geom << "Sketcher_CreateFillet" + << "Sketcher_CreatePointFillet"; } -template <> +template<> inline void SketcherAddWorkspaceFillets(Gui::ToolBarItem& geom) { - geom << "Sketcher_CompCreateFillets"; + geom << "Sketcher_CompCreateFillets"; } -template +template inline void SketcherAddWorkbenchGeometries(T& geom) { - geom << "Sketcher_CreatePoint" - << "Sketcher_CreateLine"; + geom << "Sketcher_CreatePoint" + << "Sketcher_CreateLine"; SketcherAddWorkspaceArcs(geom); - geom << "Separator" - << "Sketcher_CreatePolyline"; + geom << "Separator" + << "Sketcher_CreatePolyline"; SketcherAddWorkspaceRectangles(geom); SketcherAddWorkspaceRegularPolygon(geom); - geom << "Sketcher_CreateSlot" - << "Separator"; + geom << "Sketcher_CreateSlot" + << "Separator"; SketcherAddWorkspaceFillets(geom); - geom << "Sketcher_Trimming" - << "Sketcher_Extend" - << "Sketcher_Split" - << "Sketcher_External" - << "Sketcher_CarbonCopy" - << "Sketcher_ToggleConstruction" - /*<< "Sketcher_CreateText"*/ - /*<< "Sketcher_CreateDraftLine"*/; + geom << "Sketcher_Trimming" + << "Sketcher_Extend" + << "Sketcher_Split" + << "Sketcher_External" + << "Sketcher_CarbonCopy" + << "Sketcher_ToggleConstruction" + /*<< "Sketcher_CreateText"*/ + /*<< "Sketcher_CreateDraftLine"*/; } -template +template inline void SketcherAddWorkbenchConstraints(T& cons); -template <> +template<> inline void SketcherAddWorkbenchConstraints(Gui::MenuItem& cons) { - cons << "Sketcher_ConstrainCoincident" - << "Sketcher_ConstrainPointOnObject" - << "Sketcher_ConstrainVertical" - << "Sketcher_ConstrainHorizontal" - << "Sketcher_ConstrainParallel" - << "Sketcher_ConstrainPerpendicular" - << "Sketcher_ConstrainTangent" - << "Sketcher_ConstrainEqual" - << "Sketcher_ConstrainSymmetric" - << "Sketcher_ConstrainBlock" - << "Separator" - << "Sketcher_ConstrainLock" - << "Sketcher_ConstrainDistanceX" - << "Sketcher_ConstrainDistanceY" - << "Sketcher_ConstrainDistance" - << "Sketcher_ConstrainRadius" - << "Sketcher_ConstrainDiameter" - << "Sketcher_ConstrainRadiam" - << "Sketcher_ConstrainAngle" - << "Sketcher_ConstrainSnellsLaw" - << "Separator" - << "Sketcher_ToggleDrivingConstraint" - << "Sketcher_ToggleActiveConstraint"; + cons << "Sketcher_ConstrainCoincident" + << "Sketcher_ConstrainPointOnObject" + << "Sketcher_ConstrainVertical" + << "Sketcher_ConstrainHorizontal" + << "Sketcher_ConstrainParallel" + << "Sketcher_ConstrainPerpendicular" + << "Sketcher_ConstrainTangent" + << "Sketcher_ConstrainEqual" + << "Sketcher_ConstrainSymmetric" + << "Sketcher_ConstrainBlock" + << "Separator" + << "Sketcher_ConstrainLock" + << "Sketcher_ConstrainDistanceX" + << "Sketcher_ConstrainDistanceY" + << "Sketcher_ConstrainDistance" + << "Sketcher_ConstrainRadius" + << "Sketcher_ConstrainDiameter" + << "Sketcher_ConstrainRadiam" + << "Sketcher_ConstrainAngle" + << "Sketcher_ConstrainSnellsLaw" + << "Separator" + << "Sketcher_ToggleDrivingConstraint" + << "Sketcher_ToggleActiveConstraint"; } -template <> +template<> inline void SketcherAddWorkbenchConstraints(Gui::ToolBarItem& cons) { - cons << "Sketcher_ConstrainCoincident" - << "Sketcher_ConstrainPointOnObject" - << "Sketcher_ConstrainVertical" - << "Sketcher_ConstrainHorizontal" - << "Sketcher_ConstrainParallel" - << "Sketcher_ConstrainPerpendicular" - << "Sketcher_ConstrainTangent" - << "Sketcher_ConstrainEqual" - << "Sketcher_ConstrainSymmetric" - << "Sketcher_ConstrainBlock" - << "Separator" - << "Sketcher_ConstrainLock" - << "Sketcher_ConstrainDistanceX" - << "Sketcher_ConstrainDistanceY" - << "Sketcher_ConstrainDistance" - << "Sketcher_CompConstrainRadDia" - << "Sketcher_ConstrainAngle" - // << "Sketcher_ConstrainSnellsLaw" // Rarely used, show only in menu - << "Separator" - << "Sketcher_ToggleDrivingConstraint" - << "Sketcher_ToggleActiveConstraint"; + cons << "Sketcher_ConstrainCoincident" + << "Sketcher_ConstrainPointOnObject" + << "Sketcher_ConstrainVertical" + << "Sketcher_ConstrainHorizontal" + << "Sketcher_ConstrainParallel" + << "Sketcher_ConstrainPerpendicular" + << "Sketcher_ConstrainTangent" + << "Sketcher_ConstrainEqual" + << "Sketcher_ConstrainSymmetric" + << "Sketcher_ConstrainBlock" + << "Separator" + << "Sketcher_ConstrainLock" + << "Sketcher_ConstrainDistanceX" + << "Sketcher_ConstrainDistanceY" + << "Sketcher_ConstrainDistance" + << "Sketcher_CompConstrainRadDia" + << "Sketcher_ConstrainAngle" + // << "Sketcher_ConstrainSnellsLaw" // Rarely used, show only in menu + << "Separator" + << "Sketcher_ToggleDrivingConstraint" + << "Sketcher_ToggleActiveConstraint"; } -template +template inline void SketcherAddWorkbenchTools(T& consaccel); -template <> +template<> inline void SketcherAddWorkbenchTools(Gui::MenuItem& consaccel) { - consaccel << "Sketcher_SelectElementsWithDoFs" - << "Sketcher_SelectConstraints" - << "Sketcher_SelectElementsAssociatedWithConstraints" - << "Sketcher_SelectRedundantConstraints" - << "Sketcher_SelectConflictingConstraints" - << "Sketcher_RestoreInternalAlignmentGeometry" - << "Separator" - << "Sketcher_SelectOrigin" - << "Sketcher_SelectHorizontalAxis" - << "Sketcher_SelectVerticalAxis" - << "Separator" - << "Sketcher_Symmetry" - << "Sketcher_Clone" - << "Sketcher_Copy" - << "Sketcher_Move" - << "Sketcher_RectangularArray" - << "Sketcher_RemoveAxesAlignment" - << "Separator" - << "Sketcher_DeleteAllGeometry" - << "Sketcher_DeleteAllConstraints"; + consaccel << "Sketcher_SelectElementsWithDoFs" + << "Sketcher_SelectConstraints" + << "Sketcher_SelectElementsAssociatedWithConstraints" + << "Sketcher_SelectRedundantConstraints" + << "Sketcher_SelectConflictingConstraints" + << "Sketcher_RestoreInternalAlignmentGeometry" + << "Separator" + << "Sketcher_SelectOrigin" + << "Sketcher_SelectHorizontalAxis" + << "Sketcher_SelectVerticalAxis" + << "Separator" + << "Sketcher_Symmetry" + << "Sketcher_Clone" + << "Sketcher_Copy" + << "Sketcher_Move" + << "Sketcher_RectangularArray" + << "Sketcher_RemoveAxesAlignment" + << "Separator" + << "Sketcher_DeleteAllGeometry" + << "Sketcher_DeleteAllConstraints"; } -template <> +template<> inline void SketcherAddWorkbenchTools(Gui::ToolBarItem& consaccel) { - consaccel //<< "Sketcher_SelectElementsWithDoFs" //rarely used, it is usually accessed by solver message. - << "Sketcher_SelectConstraints" - << "Sketcher_SelectElementsAssociatedWithConstraints" - //<< "Sketcher_SelectRedundantConstraints" //rarely used, it is usually accessed by solver message. - //<< "Sketcher_SelectConflictingConstraints" - << "Sketcher_RestoreInternalAlignmentGeometry" - << "Sketcher_Symmetry" - << "Sketcher_CompCopy" - << "Sketcher_RectangularArray" - << "Sketcher_RemoveAxesAlignment" - << "Sketcher_DeleteAllConstraints"; + consaccel//<< "Sketcher_SelectElementsWithDoFs" //rarely used, it is usually accessed by solver + // message. + << "Sketcher_SelectConstraints" + << "Sketcher_SelectElementsAssociatedWithConstraints" + //<< "Sketcher_SelectRedundantConstraints" //rarely used, it is usually accessed by solver + // message. + //<< "Sketcher_SelectConflictingConstraints" + << "Sketcher_RestoreInternalAlignmentGeometry" + << "Sketcher_Symmetry" + << "Sketcher_CompCopy" + << "Sketcher_RectangularArray" + << "Sketcher_RemoveAxesAlignment" + << "Sketcher_DeleteAllConstraints"; } -template +template inline void SketcherAddWorkbenchBSplines(T& bspline); -template <> +template<> inline void SketcherAddWorkbenchBSplines(Gui::MenuItem& bspline) { bspline << "Sketcher_BSplineDegree" @@ -477,7 +479,7 @@ inline void SketcherAddWorkbenchBSplines(Gui::MenuItem& bspline) << "Sketcher_JoinCurves"; } -template <> +template<> inline void SketcherAddWorkbenchBSplines(Gui::ToolBarItem& bspline) { bspline << "Sketcher_CompBSplineShowHideGeometryInformation" @@ -489,30 +491,30 @@ inline void SketcherAddWorkbenchBSplines(Gui::ToolBarItem& bsp << "Sketcher_JoinCurves"; } -template +template inline void SketcherAddWorkbenchVirtualSpace(T& virtualspace); -template <> +template<> inline void SketcherAddWorkbenchVirtualSpace(Gui::MenuItem& virtualspace) { virtualspace << "Sketcher_SwitchVirtualSpace"; } -template <> +template<> inline void SketcherAddWorkbenchVirtualSpace(Gui::ToolBarItem& virtualspace) { virtualspace << "Sketcher_SwitchVirtualSpace"; } -template +template inline void SketcherAddWorkbenchEditTools(T& virtualspedittoolsace); -template <> +template<> inline void SketcherAddWorkbenchEditTools(Gui::ToolBarItem& edittools) { - edittools << "Sketcher_Grid" - << "Sketcher_Snap" - << "Sketcher_RenderingOrder"; + edittools << "Sketcher_Grid" + << "Sketcher_Snap" + << "Sketcher_RenderingOrder"; } void addSketcherWorkbenchSketchActions(Gui::MenuItem& sketch) diff --git a/src/Mod/Sketcher/Gui/Workbench.h b/src/Mod/Sketcher/Gui/Workbench.h index c5384fe952..4345806bb8 100644 --- a/src/Mod/Sketcher/Gui/Workbench.h +++ b/src/Mod/Sketcher/Gui/Workbench.h @@ -30,12 +30,13 @@ #include -namespace SketcherGui { +namespace SketcherGui +{ /** * @author Werner Mayer */ -class SketcherGuiExport Workbench : public Gui::StdWorkbench +class SketcherGuiExport Workbench: public Gui::StdWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -70,6 +71,6 @@ SketcherGuiExport void addSketcherWorkbenchBSplines(Gui::ToolBarItem& bspline); SketcherGuiExport void addSketcherWorkbenchVirtualSpace(Gui::ToolBarItem& virtualspace); SketcherGuiExport void addSketcherWorkbenchEditTools(Gui::ToolBarItem& edittools); -} // namespace SketcherGui +}// namespace SketcherGui -#endif // SKETCHER_WORKBENCH_H +#endif// SKETCHER_WORKBENCH_H